How to make Messenger Chat Bot using NodeJs

Akarsh Barar
4 min readNov 19, 2019

Hey there everyone in this blog we are going to learn how to create a messenger chat bot using Nodejs. So lets get started:

First Step

Install latest version of Node in your System. You can test node by running

node -v

npm -v

this should give you the version of node and npm installed in your system.

Second Step

Go tho the facebook developer site and login with your facebook credentials or click link below.

Third Step

Click on the create new app and give display name and email id to your project. It will look something like this

After that you will be redirected to you dashboard.

Fourth Step

Now open terminal and follow the steps given below to make folder and make code ready for deployment.

(1):: mkdir MessengerChatBotFolder

(2):: cd MessengerChatBotFolder

(3):: npm init

(4):: npm install express body-parser request

(5):: make file name index.js this will contain all our code of node js

(6):: Now go the developer dashboard and in Access token section add your Facebook page if you don’t have a page try to make a page select it.

(7):: Click on the generate token button for your page it will be a long string that will be unique for your app. PLEASE KEEP THIS TOKEN SECRET WITH YOU.

(8):: Now go to the index.js and paste the following code in it

‘use strict’;

const bodyParser = require(‘body-parser’);
const config = require(‘config’);
const crypto = require(‘crypto’);
const express = require(‘express’);
const https = require(‘https’);
const request = require(‘request’);

var app = express();
app.set(‘port’, process.env.PORT || 5555);
app.set(‘view engine’, ‘ejs’);
app.use(bodyParser.json({ verify: verifyRequestSignature }));
app.use(express.static(‘public’));

app.listen(app.get(‘port’), function() {
console.log(‘Node app is running on port’, app.get(‘port’));
});

This will start the server at port 5555. set your own port as per your system.

(9):: Append following code in it

app.get(‘/webhook’, function(req, res) {

if (req.query[‘hub.mode’] === ‘subscribe’ &&

req.query[‘hub.verify_token’] === VALIDATION_TOKEN) {

console.log(“Validating webhook”);

res.status(200).send(req.query[‘hub.challenge’]);

} else {

console.error(“Failed validation. Make sure the validation tokens match.”);

res.sendStatus(403);

}

});

VALIDATION_TOKEN will be a string that will be unique for your app this is different from access token. Access Token is generated by facebook but validation token can be set by you. Let say we keep VALIDATION_TOKEN as “chatbot”

(10):: Then we will create a function that will reply to user

function sendTextMessage(recipientId, messageText) {

var messageData = {

recipient: {

id: recipientId

},

message: {

text: messageText,

metadata: “DEVELOPER_DEFINED_METADATA”

}

};

callSendAPI(messageData);

}

function callSendAPI(messageData) {

request({

uri: ‘https://graph.facebook.com/v2.6/me/messages',

qs: { access_token: PAGE_ACCESS_TOKEN },

method: ‘POST’,

json: messageData

}, function (error, response, body) {

if (!error && response.statusCode == 200) {

var recipientId = body.recipient_id;

var messageId = body.message_id;

if (messageId) {

console.log(“Successfully sent message with id %s to recipient %s”,

messageId, recipientId);

} else {

console.log(“Successfully called Send API for recipient %s”,

recipientId);

}

} else {

console.error(“Failed calling Send API”, response.statusCode, response.statusMessage, body.error);

}

});

}

(11):: Now at last we just have to go for route that will take input from user and brings it to server

app.post(‘/webhook’, function (req, res) {

var data = req.body;

if (data.object == ‘page’) {

data.entry.forEach(function(pageEntry) {

var pageID = pageEntry.id;

var timeOfEvent = pageEntry.time;

pageEntry.messaging.forEach(function(messagingEvent) {

if (messagingEvent.message) {

receivedMessage(messagingEvent);

} else if (messagingEvent.delivery) {

receivedDeliveryConfirmation(messagingEvent);

} else if (messagingEvent.read) {

receivedMessageRead(messagingEvent);

} else {

console.log(“Webhook received unknown messagingEvent: “, messagingEvent);

}

});

});

res.sendStatus(200);

}

});

I am showing only one function ie readMessage() otherwise this blog will be very long and boring.

function receivedMessage(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;

console.log(“Received message for user %d and page %d at %d with message:”,senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var isEcho = message.is_echo;
var messageId = message.mid;
var appId = message.app_id;
var metadata = message.metadata;
var messageText = message.text;
var messageAttachments = message.attachments;
var quickReply = message.quick_reply;

if (isEcho) {
console.log(“Received echo for message %s and app %d with metadata %s”,messageId, appId, metadata);
return;
} else if (quickReply) {
var quickReplyPayload = quickReply.payload;
console.log(“Quick reply for message %s with payload %s”, messageId, quickReplyPayload);
sendTextMessage(senderID, “Quick reply tapped”);
return;
}
if (messageText) {
sendTextMessage(senderID, messageText);
}
}

(12):: At last deploy the app in the server and give the server link the webhook callback url part along with VALIDATION_TOKEN(as mentioned above we have set the VALIDATION_TOKEN as “chatbot”) then set the permissions.

And thats it. Try to run your app and test it.

If you want to ask any question or want to suggest any topic ping me on instagram.

Make sure to subscribe to my YouTube Channel :

https://youtu.be/yWSdXqf_2k4

And follow on instagram:

@mycodecave

Also on Facebook :

https://www.facebook.com/CodeCave-299370007293562

--

--