I am bulding a messenger bot with node js express.I am trying to split my index.js file into two files. Here is the code for msg.js which is the new file
'const
express = require('express'),
bodyParser = require('body-parser'),
request = require('request'),
PAGE_ACCESS_TOKEN ="",
app = express().use(bodyParser.json());
//functions
module.exports = {
//hangles messages
handleMessage:function (sender_psid, received_message) {
let response;
// Checks if the message contains text
if (received_message.text) {
// Create the payload for a basic text message, which
// will be added to the body of our request to the Send API
response = {
"text": `You sent the message: "${received_message.text}". Now send me an attachment!`
}
} else if (received_message.attachments) {
// Get the URL of the message attachment
let attachment_url = received_message.attachments[0].payload.url;
response = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [{
"title": "Is this the right picture?",
"subtitle": "Tap a button to answer.",
"image_url": attachment_url,
"buttons": [
{
"type": "postback",
"title": "Yes!",
"payload": "yes",
},
{
"type": "postback",
"title": "No!",
"payload": "no",
}
],
}]
}
}
}
}
// Send the response message
module.exports.callSendAPI(sender_psid, response);
},
// Handles messaging_postbacks events
handlePostback:function (sender_psid, received_postback) {
let response;
// Get the payload for the postback
if (received_postback) {
let payload = received_postback.payload;
}
// Send the message to acknowledge the postback
module.exports.callSendAPI(sender_psid, response);
},
// Sends response messages via the Send API
callSendAPI:function (sender_psid, response) {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
}
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
}
};
I have the following code at the bottom of my index.js file.
//Imports functions from other files
let msg = require('./msg.js'),
handleMessage = msg.handleMessage(),
handlePostback = msg.handlePostback(),
callSendAPI = msg.callSendAPI();
I am getting the following error:
msg.js:14 if (received_message.text) { ^
TypeError: Cannot read property 'text' of undefined
The problem is this line:
if (received_message.text) {
When this gets called, received_message
which is passed in is undefined, so when you try to get the text
field from the received_message
variable it will throw an error since received_message
is undefined and thus would not have any fields you could call from it. Check to see if received_message is ever set properly before being passed into your handleMessage function.