I'm trying to create a Facebook chatbot using NodeJS, Express, and a Heroku server.
I created my webhook on Heroku and had it verified and saved by Facebook. I then ran this code to connect my webhook to Facebook.
curl -ik -X POST "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=<token>"
this returned {success:true}.
So then I started adding code that would reply to incoming messages but I can't seem to get it to receive the sent information. Whenever I send a message I get no reply.
Everything is connected and running but this error I am getting "TypeError: Cannot read property '0' of undefined" is because I'm not getting the message information sent to my webhook from facebook. This is the line of code that is empty:
messaging_events = req.body.entry[0].messaging;
Here is my full code:
var express = require('express');
var bodyParser = require('body-parser');
var request = require("request")
var app = express();
var port = process.env.PORT || 3000;
// body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function (req, res) {
if (req.query['hub.verify_token'] === '8FKU9XWeSjnZN4ae') {
res.send(req.query['hub.challenge']);
console.log("app.get ran")
res.sendStatus(200)
}
console.log("Error: wrong validation token")
})
app.post('/', function (req, res) {
messaging_events = req.body.entry[0].messaging;
console.log("app.post ran")
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));
}
}
res.sendStatus(200);
});
app.listen(port, function () {
console.log('Listening on port ' + port);
});
var token = "<myToken>";
function sendTextMessage(sender, text) {
messageData = {
text:text
}
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 message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
Here are my Heroku Logs:
So I'm confused as to why I'm not getting the message data when my webhook is connected to Facebook and they are communicating. I also made sure I had all the subscription fields necessary checked.
Anyone see the problem? Any help is appreciated. Thanks!
Edit: I'm following this guide by the way - https://developers.facebook.com/docs/messenger-platform/quickstart
I had the same problem. Can you add app.use(bodyParser.json()) before bodyParser.urlencoded() ) ?