我開始使用messenger bot並獲取上述錯誤。我有以下代碼:Messenger Bot:TypeError:無法讀取未定義的屬性「文本」
app.post('/webhook', (req, res) => {
console.log(req.body);
if (req.body.object === 'page') {
req.body.entry.forEach((entry) => {
entry.messaging.forEach((event) => {
if (event.message.text === 'buy') {
sendGenericMessage(event)
} else if (event.postback) {
processPostback(event)}
});
});
res.status(200).end();
}
});
function sendGenericMessage(event) {
const senderID = event.sender.id;
var messageData = {
"attachment":{
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
...
"buttons":[
{
"type":"postback",
"title":"Purchase",
"payload":"PURCHASE_PAYLOAD"
},{
"type":"postback",
"title":"Start Chatting",
"payload":"DEVELOPER_DEFINED_PAYLOAD"
}
]
}, {
"title":"Welcome to Peter\'s Hats",
"image_url":"https://static.pexels.com/photos/177809/pexels-photo-177809.jpeg",
"subtitle":"We\'ve got the right hat for everyone.",
"buttons":[
{
...
}
]
}
]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
method: 'POST',
json: {
recipient: {id: senderID},
message: messageData
}
}, function (error, response) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
function processPostback(event) {
const senderID = event.sender.id;
const payload = event.postback.payload;
if (payload === "PURCHASE_PAYLOAD") {
var message = event.message.text + " payment"
sendMessage(event, message)
}
}
當我鍵入「買入」,機器人將與通用模板答覆,並按下按鈕「購買」時,機器人墜毀。我的錯誤日誌如下:
我已經搜查,發現像這樣類似的問題,但我從回傳,而不是短信發起相比,他們的。 How to avoid 'cannot read property of undefined' errors?
這裏有些幫助將是巨大的,謝謝。
您好@christos,感謝您的回覆。我試過你的解決方案,但它會拋出一個錯誤(#100)無效的數據。參考上面的錯誤日誌,似乎表明「無法讀取文本屬性」的錯誤發生在entry.messaging.forEach。這是否意味着「購買」按鈕不被識別爲消息? – Koh
我編輯了我的回覆,在代碼中添加了另一個更改重要更改。 :) –
我在代碼中也犯了一個小錯誤。複製粘貼代碼;) –