Home New Business How To Create Facebook Messenger Bots?

How To Create Facebook Messenger Bots?

by Mariya Parackal

Creating Facebook Messenger Bots

A chat-bot synonymous known as talk-bot, chatter-bot, Bot, chatterbox, IM bot, interactive agent, or Artificial Conversational Entity) is a computer program designed to simulate a conversation with human users, especially over the Internet. Chat-bots are often integrated into the dialog system of virtual assistants to give them the ability to engaging in casual conversation unrelated to the scope of their primary expert systems. A chat-bot can be considered as a service that runs on certain rules/AI, with which you can’t interact with a chat interface(FB Messenger/Slack/Telegram/Apple iMessage).

Some of the most common use cases of chat-bots include customer support, sales, personal assistants, concierge etc.

Facebook Messenger bots: How many are there? As per Bot-list, the app store for bots, some of the bots include Trivia Blast, Complex, Operator, theScore, NBA, Hangman, Mealou, Digg, Emoji News, etc. Messenger bots provide endless possibilities and enable users to play hangman and trivia, or you can buy stuff online or seek customer support. Designed to make it easier for the users, Bots also enhances the chat experience.

The Configuration and Setup Process

In order to make things easier for you, we have simplified the whole process in a few steps as given below:

1) Create an FB page: https://www.facebook.com/pages/create

2) Create an FB apphttps://developers.facebook.com/apps

3) Install & configure nodejs on your server, if it isn’t already available.

(nodejs based example).

4) Once you have created your app, let’s add messenger to it. Go to the App Dashboard and under Product Settings click “Add Product” and select “Messenger.”

5) Now, link your page with the messenger and get the page access token. The below screenshot gives an idea of this:

6) Set Up webhooks

The below screenshot gives an idea of how webhooks are set up.

In the sample app, this method is defined in app.js:

app.get('/webhook', function(req, res) {
if (req.query['hub.mode'] === 'subscribe' &&
req.query['hub.verify_token'] === ) {
console.log("Validating webhook");
} else {
console.error("Failed validation. Make sure the validation tokens match.");

since FB requires a valid SSL certificate, we need to make some minor changes to the script. before we start, note the path of the SSL files on your server.

Now change the following lines:-

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


const fs = require('fs');
var privateKey = fs.readFileSync('path_to_key.pem');
var certificate = fs.readFileSync('path_to_cert.pem');
var certificateAuth = fs.readFileSync('path_to_ca.crt');
var credentials = {
key: privateKey,
cert: certificate,
ca: certificateAuth
https.createServer(credentials, app).listen(app.get('port'), function(){
console.log('Node app updated running on port', app.get('port'));

This allows FB to verify the SSL issued to your domain (without this change, the setup webhooks step won’t be completed) and hence its mandatory.

7) Subscribe the App to the Page

In the Web-hooks section, subscribe the web-hook for your page. The below screenshot would help you get a clearer picture of how it’s done.

8) The chatbot can now be accessed from the messenger section within your FB profile with the below-mentioned URL,


eg:- if your FB page ID is PAGENAME-119052895406724, {FB_PAGE_MSG_ID} would be 119052895406724

9) Now that the configuration is completed, let us listen for incoming messages & echo back the same to the user.

In the sample app, this method is also defined in app.js:-

function receivedMessage(event) {
var senderID = event.sender.id;
var message = event.message;
var messageText = message.text;
sendTextMessage(senderID, messageText);

sendTextMessage formats the data in the request:-

function sendTextMessage(recipientId, messageText) {
var messageData = {
recipient: {
id: recipientId
message: {
text: messageText

callSendAPI calls the Send API:-

function callSendAPI(messageData) {
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;
console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId);
} else {
console.error("Unable to send message.");

11) Right now our chat-bot just echoes back whatever the user sends to it. So the next step would be to process the messages received & send back appropriate responses.

api.ai would help us out with this. You can use your Google account to sign up for a new api.ai account:-


12) Once your account is ready, use the ‘Create Agent’ link in the dashboard. The below screenshot will give you an idea of the same.

13) Now, go to the settings section of your agent and copy the ‘Client access token’ as shown in the below screenshot.

14) Since intents & Entities form the backbone of the api.ai agent. proper manipulation of these would help in training the agent to handle different types of client queries you would expect for your business.

Since the details of these are beyond the scope of this article. please refer to the docs link for more info:- https://api.ai/docs/getting-started/basics.

15) Besides training our agent, api.ai comes with a set of predefined query/responses. Then navigate to ‘Small Talk’ section in the left menu and enable it.

This would let the agent answer the usual banter with the user (eg:- how are you?/what are you? etc).

16) Next, install the apiai package for nodejs on your server. then add the following lines to app.js –

const apiai = require('apiai');
var srv = apiai(CLIENT_ACCESS_TOKEN);
function receivedMessage(event) {
var senderID = event.sender.id;
var message = event.message;
var messageText = message.text;
var requestAPI = srv.textRequest(messageText, {
sessionId: Math.floor((Math.random() * 100000) + 1)
requestAPI.on('response', function(response) {
//check the response type from api.ai
if(response.result.fulfillment.speech != '') {
sendTextMessage(senderID, response.result.fulfillment.speech);
} else {
sendTextMessage(senderID, "I'm sorry, could you be more specific?");
requestAPI.on('error', function(error) {
sendTextMessage(senderID, "Sorry, but I just couldn't figure that out!");

17) Now that it’s all done, you can head over to your FB Messenger and indulge in some small talk with your chat-bot.

Case Study of FB Messenger & api.ai

Now we will see how FB Messenger would provide us with the chat interface & api.ai would work as the agent to analyze the user input and generate the corresponding responses. The casual messages would be answered by the AI, for other queries, the Bot uses Google’s search API to look it up in stack-overflow & provide some suggestions (so it would be accurate only in case of technical questions, in other cases the answer might not be spot on). The level of interaction can be improved by further training the AI.




Click the button below to download the sample code used to create the sample above. You can use it to clone for your purpose

Download Sample Bot Code


  • The chatbot would work out of FB Messenger & is linked to the FB page, so you can’t have it integrated within your website.
  • You would also need a domain name with SSL provided by any authorized 3rd party (Go-daddy/VeriSign etc) to set up the Messenger back-end.



Chatbots are immensely used by instant messaging platforms like Facebook Messenger, Kik, and We-chat for marketing, customer service entertainment purposes. The bots often appear as one among the participants in a group chat or as one of the user’s contacts. Some IM bots are able to connect to outside databases and provide the users with weather reports, movie timings, driving directions, stock quotes, and other details. Renowned eateries like Domino’s, Disney, Yamato’s line, Pizza Hut, nerdify, have launched their own chat-bots to promote user engagement and to promote their services and products, making it easier for customers to order food. In the travel industry, many airlines and agencies took the aid of Messenger and introduced chat-bot services. Using AI, Aeromexico’s sold tickets and answered questions and both KLM’s and Aeroméxico’s provided flight status updates, allowing users to check in for flights, provided hotel recommendations, recreational activities and deliver mobile boarding passes. China is one of the countries who has been providing services via We-chat.

If you want the code sample used to create the bot above, then you can get it for free to start your own or bot or we could design something for you.

You can get in touch with us for more information @ https://www.armia.com


Leave a Comment