我认为更好的解决方案是使用 Microsoft Bot Framework 并使用它的 /firstRun 发送信使开始按钮
function firstRun(session) {
console.log('This user is running our bot the first time')
createUser(session)
platforms.firstRun(session.message.user.id, session.message.address.channelId)
.then((values) => {
for (let value of values) {
if (value.data.firstName && value.data.lastName) {
session.userData.user.profile = value.data
}
}
})
.catch((errors => {
console.log(errors);
}))
reply(session)
session.endDialog()
}
platforms.firstRun 如下图所示
platforms.firstRun = function (userId, channel) {
switch (channel) {
case platforms.channels.emulator:
return Promise.reject('none')
case platforms.channels.facebook:
return platforms.facebook.firstRun(userId)
case platforms.channels.skype:
return Promise.reject('none')
default:
return Promise.reject('none')
}
}
这又会调用platforms.facebook.firstRun
platforms.facebook.firstRun = function (userId) {
return Promise.all([
platforms.facebook.sendThread(facebookTemplates.greet(), 'Greeting'),
platforms.facebook.sendThread(facebookTemplates.getStarted(), 'Get Started'),
platforms.facebook.sendThread(facebookTemplates.getPersistentMenu(), 'Persistent Menu'),
platforms.facebook.sendThread(facebookTemplates.getDomainWhitelisting(), 'Domain Whitelisting'),
platforms.facebook.getProfile(userId)
])
}
platforms.facebook.sendThread 如下所示
// 调用 Facebook graph api 来改变 bot 设置
platforms.facebook.sendThread = function (template, cmd) {
return new Promise((resolve, reject) => {
// Start the request
request({
url: platforms.facebook.GRAPH_BASE_URI + '/me/thread_settings?access_token=' + endpoints.FACEBOOK_PAGE_ACCESS_TOKEN,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
form: template
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
resolve({ status: response.statusCode, data: body })
} else {
// TODO: Handle errors
reject({ status: response.statusCode, data: error })
}
});
})
}
请注意 facebookTemplates.getStarted(),它实际上具有用于入门的 json,如下所示
templates.getStarted = function () {
return {
setting_type: "call_to_actions",
thread_state: "new_thread",
call_to_actions: [
{
payload: payloads.FACEBOOK_GET_STARTED
}
]
}
}
完全可插入的代码架构,用于在所有聊天机器人平台上执行首次运行操作。在我的机器人上完美运行 HERE