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 directorymkdir testbot

Change your working directory to the directory you just createdcd testbot

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.

4. Install packagesnpm install express body-parser request --save

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

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.

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

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.

Follow these steps to create a git repository:

1. git init

2. git add .

3. git commit -m "Register Facebook Webhook"

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.

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

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

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“.

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.

6. Select “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

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

Akshay has been a gadget freak since longer than he cares to admit and loves everything to do with technology. When he's not fanboying over the latest and greatest in the tech universe, he watches Game of Thrones and Silicon Valley.