How to Create A Facebook Messenger Bot (Guide)

Facebook’s “messenger bots” feature is nothing new, and a lot of awesome bots already exist. However, the resources regarding exactly how to build your very own bot are scarce, and lacking in explanation for people who are new to the Facebook Graph API. Messenger bots now also require you to use a SSL secured webhook callback URL (more on that later), and setting up SSL is not for everyone, and also costs money.

In this article, I’ll walk you through the entire process of creating a simple Facebook messenger bot, because Facebook’s own documentation is rather poorly explained. We will set up a cloud app that uses https protocol, code the bot in Node.js (which is a javascript, server-side language), use git to push the code to the cloud application, and test it out on Facebook Messenger.

Setup Bot

You will need Node installed on your laptop. If you don’t, go to the Node website to download and install it.

Once you are done, you can continue with the setup for the bot. Follow the steps below:

1. Launch Terminal.

2. You need a separate directory for holding your code.

  • Make a new directory
    mkdir testbot
  • Change your working directory to the directory you just created
    cd testbot

facebook messenger bot create_and_cd_testbot_directory

3. Next, initialise the Node application.
npm init

  • You will be asked to enter information about your application, just use the defaults by pressing Enter for everything.

facebook messenger bot npm_init

4. Install packages
npm install express body-parser request --save

  • The command will run, and give some warnings; ignore them.

facebook messenger bot npm_install_packages

5. In Finder, open the directory “testbot” that you created, and find the file named “package.json“; open this in an editor like Sublime Text.

6. In this file, we need to add a line
"start": "node index.js"

  • Don’t forget to append a “,” at the end of the previous line.

facebook messenger bot package_json_edits

7. Next, create a new file in Sublime Text, and put in the following code inside it:

[js]

var express = require(‘express’);
var bodyParser = require(‘body-parser’);
var request = require(‘request’);
var app = express();

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 3000));
app.get(‘/’, function (req, res) {
res.send(‘This is TestBot Server’);
});
app.get(‘/webhook’, function (req, res) {
if (req.query[‘hub.verify_token’] === ‘testbot_verify_token’) {
res.send(req.query[‘hub.challenge’]);
} else {
res.send(‘Invalid verify token’);
}
});

[/js]

Save this file as index.js

Note: In Line 13, the value of ‘hub.verify_token’ is set as ‘testbot_verify_token’, remember this value as it will be used when creating the webhook in Facebook.

Create Git Repository

Now that we have set up our bot’s callback handling, we need to push the code to Heroku. For that, we need to create a git repository in our directory.

Note: “git” is a version control system for files and software code. You can read more about it on Wikipedia.

Creating a git repository is easy, and only takes a couple of Terminal commands.

Note: Make sure you are inside the “testbot” directory in the Terminal. You can do this by typing the command pwd into the Terminal.

facebook messenger bot pwd_check

Follow these steps to create a git repository:

1. git init

2. git add .

3. git commit -m "Register Facebook Webhook"

facebook messenger bot git_commit

Setup Heroku

Before we even go into Facebook’s developer pages, we need a callback URL that Facebook can talk to. This URL needs to use the https protocol, which means we need to install an SSL certificate on our website; but, this is a beginner’s guide to Facebook messenger bots, so let’s not complicate things. We’ll use Heroku to deploy our code. Heroku gives you https URLs for your applications and has a free plan which meets our (very basic) demands.

Go to the Heroku website and register yourself.

Note: In the field that says “Pick Your Primary Development Language”, use “I use another Language”.

Once you’re done with that, install the Heroku toolbelt for your OS (Mac, for me), and install it. This will give you access to Heroku on your Terminal (or command prompt, on Windows).

Next, we will create an app on Heroku, which will hold the entire code for our bot. Follow the steps below:

1. Launch Terminal

2. Type heroku login

  • You will be asked to enter your email and password.
  • Type your email, hit Enter; then, type your password, hit Enter.
  • You will be logged in to heroku

3. Type heroku create

  • This will create an app on Heroku and provide you with a hyperlink. Note that the link is using the https protocol. Easy, right?

facebook messenger bot heroku create

4. Now you can push your app code to Heroku
git push heroku master

facebook messenger bot heroku push

5. Once this is done, your app is basically live, and you can visit the link in your browser to check that everything is working fine. It should open a webpage saying “This is TestBot Server“.

Facebook Setup

It’s time to connect our bot to Facebook! You will need to create a new Facebook Page or use an existing one that you own. I’ll show you how to proceed by creating a new Facebook Page.

1. Go to Facebook and create a new page.

  • You can create a page in whichever category you want. I’m opting for Company/Organisation, for no particular reason.

facebook messenger bot create new page

2. The next steps that Facebook shows are optional, and can be skipped.

3. Next, head over to the Facebook Developers’ Website.

  • On the top-right, hover your mouse on “My Apps” and then click on “Add a New App” from the drop-down menu.

facebook messenger bot facebook developers new app

  • Click on “basic setup” when Facebook prompts you to choose a platform.

facebook messenger bot basic setup

4. Fill up the details for your App Name and contact email address.

  • Select “Apps for Pages” in the Category.
  • Click on “Create App ID“.

facebook messenger bot create app id

5. You will be taken to the dashboard for your app. On the sidebar, navigate to “+Add Products” and select “Messenger” by clicking on the “Get Started” button.

facebook messenger bot add platforms

6. Select “Setup Webhooks“.

facebook messenger bot setup webhooks

7. Fill up the required fields, replacing the “Callback URL” with the URL of the Heroku app, Verify Token with the token used in the index.js file, and select the following Subscription Fields:

  • message_deliveries
  • messages
  • message_optins
  • messaging_postbacks

facebook messenger bot webhook fields

Note: Make sure you append “/webhook” to the Callback URL so that index.js executes the required function when Facebook tries to ping the URL, it can verify the “Verify Token”.

8. Click on “Verify and Save“.

9. In the “Token Generation” section, click on “Select a Page” and select the page you created earlier.

This will generate a “Page Access Token“, save it somewhere; you will need it later.

facebook messenger bot select page access

10. Next, you will have to make a POST query to your app, using the Page Access Token generated in the last step. This can be easily done in the Terminal. Just run the following command, replacing PAGE_ACCESS_TOKEN with the Page Access Token you generated.

curl -X POST “https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=PAGE_ACCESS_TOKEN”

You should receive a “success” response in the Terminal.

More Heroku Setup

Yeah, we’re not done, yet. Not nearly.

1. Go to the Heroku website and log in with your email ID.

2. Locate your app in the “dashboard” and click on it.

3. Navigate to the Settings tab.

facebook messenger bot heroku app settings_

4. Click on “Reveal Config Vars

facebook messenger bot reveal_configs

5. Add the PAGE_ACCESS_TOKEN as a “config var“, and click “Add“.

facebook messenger bot config var add

Coding the Actual Bot

Now that we’re done with the grunt work, we can focus on what really matters: making the bot respond to messages. To start off, we’ll just design a bot that simply echoes the messages it receives. As it turns out, this simple task requires a considerable bit of code to function.

1. Coding the Message Listener

Before the bot can echo back the message, it needs to be able to listen for messages. Let’s do that first.

In the index.js file, add the following code:

[js]

app.post(‘/webhook’, function (req, res) {
var events = req.body.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {
sendMessage(event.sender.id, {text: "Echo: " + event.message.text});
}
}
res.sendStatus(200);
});

[/js]

What this function does, is it checks for received messages, and then checks if there is text in the message. If it finds text in the received message, it calls the sendMessage (shown later) function, passing the sender’s ID and the text to send back. It’s important to understand the following values and what they mean:

  • event.message.text is the text received in the message. For example, if someone sends the message “Hello” to our bot, the value of event.message.text will be “Hello”.
  • event.sender.id is the id of the person who sent the message to the bot. This is required so that the bot knows whom to address the response to.

2. Coding the sendMessage Function

Lets code the “sendMessage” function, now.

[js]

function sendMessage(recipientId, message) {
request({
url: ‘https://graph.facebook.com/v2.6/me/messages’,
qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
method: ‘POST’,
json: {
recipient: {id: recipientId},
message: message,
}
}, function(error, response, body) {
if (error) {
console.log(‘Error sending message: ‘, error);
} else if (response.body.error) {
console.log(‘Error: ‘, response.body.error);
}
});
};

[/js]

The “sendMessage” function takes two parameters:

  • recipientId
  • message

The recipientId is required so that the message can be addressed to the correct user.

The message is the actual text that is to be sent in the response.

3. Pushing the Changes to Heroku

If you have completed the steps above, your bot should be able to echo back the received text. But first, you have to push the changes to the application hosted on Heroku. To do this, follow the steps given below:

1. Launch Terminal.

2. Change directory to your testbot directory
cd testbot

3. Do the following steps:

  • git add .
  • Note: There is a “.” at the end of “git add”
  • git commit -m “First commit”
  • git push heroku master

4. Now send a message to your page, and the bot will echo the message back to you.

facebook messenger bot echo_responses

Conditional Responses aka Making the Bot Smarter

We can use text matching to allow our Facebook messenger bot to respond according to certain special keywords.

To achieve this, we need to add another function. I’m naming it “conditionalResponses”, but you can choose whatever name you prefer.

1. Coding the conditionalResponses Function

[js]

function conditionalResponses(recipientId, text) {
text = text || "";

var what = text.match(/what/gi); //check if text string contains the word "what"; ignore case
var beebom = text.match(/beebom/gi); //check if text string contains the word "beebom"; ignore case
var who = text.match(/who/gi); //check if text string contains the word "who"; ignore case
var you = text.match(/you/gi); //check if text string contains the word "you"; ignore case

//if text contains both "what" and "beebom", do this:

if(what != null &&; beebom != null) {
message = {
text: "Beebom is a website offering tech resources. Welcome."
}
sendMessage(recipientId, message);
return true;
}

//if text contains both "who" and "you", do this:
if(who != null && you != null) {
message = {
text: "I have been asked not to discuss my identity online."
}
sendMessage(recipientId, message);
return true;
}

//if nothing matched, return false to continue execution of inner function.
return false;
};

[/js]

In lines 4 to 7, we have defined variables depending on matching the received string against particular words. The best part about using “text.match()” is that it uses Regular Expressions (usually called regex, read more here.). It is good for us, because this means that as long as even a part of a word in the received text matches with either of the words we mentioned in text.match(), the variable will not be null. This means, that if the received message was “What’s Beebom?”, “var what” and “var beebom” will not be null, because the word “What’s” contains the word “what”. So we are saved from creating extra statements for every variation in which someone might say “What”.

2. Editing the Message Listener

We also need to edit the Message Listener we coded, to ensure that it tries to match the received text with the “conditionalResponses” function as well.

[js]

app.post(‘/webhook’, function (req, res) {
var events = req.body.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {

//first try to check whether received message qualifies for conditional response.
if(!conditionalResponses(event.sender.id, event.message.text)) {

//if it doesn’t, simply echo the received message back to the sender.
sendMessage(event.sender.id, {text: "Echo: " + event.message.text});
}
}
}
res.sendStatus(200);
});

[/js]

The changes in the listener might not look very drastic, but their effects sure are. Now, the listener first tries to respond with conditional responses, and if there is no valid condition for the received message, it simply echoes the message back to the user.

3. Pushing the Changes to Heroku

Before you can try out the new features, you will have to push the updated code to the app hosted on Heroku. Follow the steps below to do this:

1. Launch Terminal.

2. Change directory to your testbot directory
cd testbot

3. Do the following steps:

  • git add .
  • Note: There is a “.” at the end of “git add”
  • git commit -m “Adding conditional capabilities”
  • git push heroku master

4. Now send a message to your page, and the bot will echo the message back to you.

facebook messenger bot conditional responses

Even More Functionality

Our bot now responds to a small set of commands in nice, well structured responses. But it’s still not very useful. Let’s make some more changes to the code to make our bot a more “functional” piece of software. We’ll be revamping a lot of functions, and adding a couple more, so get excited.

1. Editing the Message Listener

Our message listener, at this stage, works just ok. However, it’s not very nicely formatted and if we were to keep increasing the nested if statements to add extra “condition checks“, it will quickly become ugly to look at, difficult to understand and slower at execution. We don’t want that, now, do we? Let’s make some changes.

Note: There’s a line of code in the message listener that reads “res.sendStatus(200)”, this line sends a status 200 code to Facebook, telling it that the function successfully executed. According to Facebook’s documentation, Facebook waits for a maximum of 20 seconds to receive a 200 status, before it decides that the message didn’t go through and stops execution of the code.

Our new message listener looks like this. We use the “res.sendStatus(200)” command to stop execution of the function as soon as a condition is matched and executed.

[js]

app.post(‘/webhook’, function (req, res) {
var events = req.body.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {

//first check message text against introResponse conditions
if(introResponse(event.sender.id, event.message.text)) {
res.sendStatus(200);
}

//for lack of a better name, I called this newResponse :p; check this next
else if(newResponse(event.sender.id, event.message.text)) {
res.sendStatus(200);
}

//else, just echo back the original message
else {
//replace echo with valid command list
sendMessage(event.sender.id, {text: "Echo: " + event.message.text});
}
}
}
res.sendStatus(200);
});

[/js]

2. Coding the newResponse Function

Our message listener now checks the message text against a set of conditions in “newResponse” as well, but first, we need to code the newResponse function. We will be using this function to check if the user asked for article suggestions from the Beebom website, search the query term on the website, and present the link to the user. Once again, we will use regular expressions to match text with specific keywords.

[js]

function newResponse(recipientId, text) {
text = text || "";
var suggest = text.match(/suggest/gi);
var random = text.match(/random/gi);
var article = text.match(/article/gi);
var iphone = text.match(/iphone/gi);
var android = text.match(/android/gi);
var mac = text.match(/mac/gi);
var browser = text.match(/browser/gi);
var vpn = text.match(/vpn/gi);

//check if user is asking for article suggestions at all
if(suggest != null && article != null) {
var query = "";
//if article suggestions are queried, check the topic the user is looking for
if(android != null) {
query = "Android";
} else if (mac != null) {
query = "Mac";
} else if (iphone != null) {
query = "iPhone";
} else if (browser != null) {
query = "Browser";
} else if (vpn != null) {
query = "VPN";
}
sendButtonMessage(recipientId, query);
return true
}
return false;
};

[/js]

We are using another custom function called “sendButtonMessage” to send the message in case the user is asking for article suggestions. We will create this next.

3. Coding the sendButtonMessage Function

The sendButtonMessage function takes two parameters, a recipient ID and a query. The recipient ID is used to identify the user to whom the message must be sent, and the query is used to identify the topic on which the user wants article suggestions.

[js]

function sendButtonMessage(recipientId, query) {
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "button",
text: "This is what I found for "+query,
buttons:[{
type: "web_url",
url: "https://beebom.com/?s="+query,
title: "Beebom: " + query
}]
}
}
}
};

callSendAPI(messageData);
}

[/js]

Once again, we are using a custom function; this time to send the final message, with the article links, to the user. The function is, in many ways, similar to the “sendMessage” function we coded earlier, but is more generic in the way it takes the message data, which suits us, because our message data changes with the query that the user makes.

4. Coding the callSendAPI Function

The “callSendAPI” function takes a single parameter, the “messageData”. This parameter contains the entire message data, formatted properly according to Facebook rules, so that the messenger can display it properly to the user.

[js]

function callSendAPI(messageData) {
request({
uri: ‘https://graph.facebook.com/v2.6/me/messages’,
qs: { access_token: process.env.PAGE_ACCESS_TOKEN },
method: ‘POST’,
json: messageData

}, function (error, response, body) {
if (!error &amp;&amp; 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.");
console.error(response);
console.error(error);
}
});
}

[/js]

5. Pushing the Changes to Heroku

We’re at the final step towards making our upgraded bot live. We just need to push all the code changes to Heroku. The process is the same as before, and is outlined below:

1. Launch Terminal.

2. Change directory to the testbot directory.
cd testbot

3. Do the following:

  • git add .
  • Note: There is a “.” at the end of that command.
  • git commit -m “improving condition checks and formatting”
  • git push heroku master

4. Now send a message such as “Suggest an article on Android”, or “Beebom, suggest me any article on the topic Android”; and the bot will send a nicely formatted message with a link that you can tap on to open the articles related to your query.

article_android

article_mac

SEE ALSO: 16 Facebook Messenger Tips And Tricks You Should Know

Dig Deeper

Now that you know how to get started with developing Facebook messenger bots, go through the Facebook documentation on how to develop Facebook messenger bots. While the documentation is not good for beginners, you’re not a beginner anymore. You should check out the official documentation and try to figure out how to make your bot even smarter. Teaser: You can send messages with images and buttons as well! It’s also possible to use services such as Wit.ai and Api.ai to code your bot and then integrate it with Facebook, but in my feeble attempts to use those services, Wit.ai doesn’t work too well, and Api.ai has a sharp learning curve for beginners.

Have you ever developed a Facebook messenger bot? If you have, how did you go about developing it, and what can it do? Did you use services like Wit.ai and Api.ai to create your bot? If you haven’t ever tried your hands on coding a bot, go and develop your own Facebook messenger bot, make it smarter and better, and let us know about your experience in the comments below.

comment Comments 1
  • Anirudh Datta says:

    Akshay, My Code isn’t pushing to heroku.. i tried to merge local branch with the master
    “git push -f heroku local-topic-branch:refs/heads/master”
    but still now working

Leave a Reply