我是编程的新手,我已成功运行Facebook Messenger Platform - quick start案例中的示例。但是,在对原始示例进行一些小改动时,我遇到了一个问题:
我想制作一个回发按钮点击事件来触发另一个结构化消息。当用户点击菜单页面内的“咖啡”按钮时,它将显示另一个结构消息,即咖啡页面。
我使用if condiction来检查
JSON.stringify(event.postback.payload)
是特定的字符串(应该是'coffee'),但是当我点击菜单页面中的'coffee'按钮时,它没有显示另一个结构化的信使。
以下是我的webhook代码:
app.post('/webhook/', function (req, res) {
let messaging_events = req.body.entry[0].messaging
for (let i = 0; i < messaging_events.length; i++) {
let event = req.body.entry[0].messaging[i]
let sender = event.sender.id
if (event.message && event.message.text) {
let text = event.message.text
if (text === 'menu') {
sendMenuMessage(sender)
continue
} else if (text === 'coffee') {
sendCoffeeMessage(sender)
continue
}
sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200))
}
if (event.postback) {
let text = JSON.stringify(event.postback.payload)
sendTextMessage(sender, "Postback.payload received: " + text.substring(0, 200), token)
if (text === 'coffee') {
sendCoffeeMessage(sender)
}
continue
}
}
res.sendStatus(200)})
还有2个结构化信使,其中包括: 1.菜单页面(显示各种产品) 2.咖啡页面(仅显示咖啡)
1.Menu页面 要打开菜单页面,有一个函数调用sendMenuMessage:
function sendMenuMessage(sender) {
let messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [{
"title": "Our Menu",
"subtitle": "Click buttons to see more",
"image_url": "img.jpg",
"buttons": [{
"type": "postback",
"title": "Coffee",
"payload": "coffee",
}, {
"type": "postback",
"title": "Tea",
"payload": "tea",
}],
}]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: token
},
method: 'POST',
json: {
recipient: {
id: sender
},
message: messageData,
}
}, function (error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})}
2.Coffee页面 要打开咖啡页面,有一个函数调用sendCoffeeMessage:
function sendCoffeeMessage(sender) {
let messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [{
"title": "Americano",
"subtitle": "5$",
"image_url": "img2.jpg",
"buttons": [{
"type": "postback",
"title": "Detail",
"payload": "americano_detail",
}],
}, {
"title": "Latte",
"subtitle": "5.5$",
"image_url": "img3.jpg",
"buttons": [{
"type": "postback",
"title": "Detail",
"payload": "latte_detail",
}],
}]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: token
},
method: 'POST',
json: {
recipient: {
id: sender
},
message: messageData,
}
}, function (error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})}
答案 0 :(得分:0)
您应该检查以下代码
console.log(JSON.stringify('coffee') === 'coffee')
//false
区别在于
console.log(JSON.stringify('coffee'))
//'"coffee"'
console.log('coffee')
//'coffee'
这意味着第一个是包含双引号的字符串。因为那是json格式的字符串表达式。