I am getting started on a messenger bot and am getting the above error. I have the following code:
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)
}
}
When I type 'buy', the bot will reply with a generic template, and when the button 'purchase' is pressed, the bot crashed. My error logs are as follows:
I have searched and found similar problems like so, but mine originates from postbacks instead of text message as compared to theirs. How to avoid 'cannot read property of undefined' errors?
Some help here would be great, thanks.