I'm trying to build a FB messenger bot using messenger-bot module. Here's my sample code
bot.on('message', (payload, reply) => {
let userData = payload.message.text;
bot.getProfile(payload.sender.id, (err, profile) => {
if (err) {
console.log(err);
// throw err
}
else {
text = {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Pick an option?",
"buttons":[
{
"type":"postback",
"title":"Option 1",
"payload":"first_option"
},
{
"type":"postback",
"title":"Option 2",
"payload":"second_option"
}
]
}
}
};
postBack(text, payload.sender.id, profile);
}
});
});
bot.on('postback', (payload, reply) => {
let text = payload.postback.payload;
bot.getProfile(payload.sender.id, (err, profile) => {
//Do something with the userData and the selected option
});
})
Now how do I access userData
in the event callback for "postback"
? I could think of only the following solution
Pass the userData
as part of the payload of the options, something like
"buttons":[
{
"type":"postback",
"title":"Option 1",
"payload":"first_option||"+userData
}
and parse it again in the "postback"
callback.
Is there a better way to do this? In other words how to share variables across callbacks in NodeJS/ JavaScript?
假设这需要服务多个用户,因此无法将userData的范围扩大,那么您要么将其持久化在数据库/缓存中,然后从“回发”中进行查询,要么使用将其作为有效内容的一部分的想法。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.