blog

  • Home
  • blog
  • Building a Facebook Chat Bot with Node and Heroku

Building a Facebook Chat Bot with Node and Heroku

A man and his Facebook chat bot, sat on the sofa watching Metropolis on a large TV

At last year’s f8 conference, Facebook launched the Messenger Platform, giving developers the ability to create bots that could have a conversation with people on Messenger or from a Facebook Page. With bots, app owners can better engage with their users by providing personalized and interactive communication that can scale for the masses. Since the launch, businesses and app owners have shown great interest in the chat bots. Just three months after the announcement, there was an estimated 11,000 bots built on the platform.

Businesses and app owners aren’t the only ones benefiting from chatbots. Users of these bots can enjoy a myriad of services such as:

The current interest in and appeal of chatbots is obvious and as the technology in artificial intelligence improves, the bots will get better at interacting with users.

In this article, we’ll look at how to create a Facebook chat bot that can interact with users via Messenger on behalf of a Facebook Page. We’ll build a bot that gives the user different details regarding a movie that they specified.

Do I Need to Know AI to Build a Bot?

Being skilled in AI will certainly help, especially in building sophisticated bots, but is not required. You can certainly build a bot without knowing machine learning.

There are two types of bots you can build. One is based on a set of rules and the other uses machine learning. The former is limited in the interactions it can offer. It can only respond to specific commands. This is the type of bot we’ll be building.

With bots that use machine learning, you get better interaction with the user. The user can interact with the bot in a more natural way as they would in a human to human interaction, as opposed to just using commands. The bot also gets smarter as it learns from the conversations it has with people. We’ll leave building this type of bot for a future article. Machine learning knowledge will not be necessary, though. Lucky for us, there are services such as wit.ai and Api.ai that enable developers to integrate machine learning (specifically Natural Language Processing – NLP) into their apps.

Getting Started

You can download the code for the completed demo app here.

For your chat bot to communicate with Facebook users, we’ll need to set up a server that will receive, process and send back messages. The server will make use of the Facebook Graph API for this. The Graph API is the primary way to get data in and out of Facebook’s platform. The server must have an endpoint URL that is accessible from Facebook’s servers, therefore deploying the web application on your local machine won’t work, you have to put it online. Also, as of version 2.5 of the Graph API, new subscriptions to the service have to use a secure HTTPS callback URL. In the tutorial, we’ll deploy the app to Heroku as all default appname.herokuapp.com domains are already SSL-enabled. We’ll use Node.js to build the web application.

To get started, first make sure Node is installed on your computer. You can check this by typing node -v in the Terminal. If installed, it will output the version number. Then install the Heroku Command Line Interface (CLI). We’ll use this later to push the app to Heroku. Use heroku --version to verify that the CLI is installed.

Create the project directory and initialize a package.json file with the following commands.

$ mkdir spbot
$ cd spbot
$ npm init

Follow the prompts to set your preferences for the project.

After the package.json file has been generated, open it and add a start property to the scripts object. This lets Heroku know what command to execute to start the app. During project setup, I defined app.js as the entry point of the app, thus I’m using node app.js as the value of start. Change this according to your project’s settings.

{
  "name": "spbot",
  "version": "1.0.0",
  "description": "SPBot Server",
  "main": "app.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node app.js"
  },
  "author": "Joyce Echessa",
  "license": "ISC"
}

Install the following Node packages.

$ npm install express request body-parser mongoose --save

Create a .gitignore file in your project’s root directory and include the node_modules folder, to prevent it from being committed.

node_modules

In your project’s root directory, create a file labeled app.js (or index.js, if you went with the default name). Modify it as shown:

var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");

var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 5000));

// Server index page
app.get("/", function (req, res) {
  res.send("Deployed!");
});

// Facebook Webhook
// Used for verification
app.get("/webhook", function (req, res) {
  if (req.query["hub.verify_token"] === "this_is_my_token") {
    console.log("Verified webhook");
    res.status(200).send(req.query["hub.challenge"]);
  } else {
    console.error("Verification failed. The tokens do not match.");
    res.sendStatus(403);
  }
});

The first GET handler will be for our own testing – to know if the app has been successfully deployed. The second GET handler is the endpoint that Facebook will use to verify the app. The code should look for the verify_token and respond with the challenge sent in the verification request.

You can paste your own token into the code. Such data is best saved in an environment variable, which we’ll do shortly after we create a project on Heroku.

Deploying to Heroku

For the Facebook platform to connect with our backend application, we first need to put it online.

Create a Git repository and commit the project’s files with the following commands:

$ git init
$ git add .
$ git commit -m "Initial commit"

Register for a free Heroku account if you don’t already have one.

From your terminal, login to Heroku and create an application.

$ heroku login
$ heroku create
$ git push heroku master
$ heroku open

On running the heroku open command, the link to the running app will be opened in your default browser. If everything went well, you will get a page with the text Deployed! on it.

Creating Environment Variables

Before we continue, let’s create an environment variable on Heroku to hold the app’s Verify Token.

Open your Heroku Dashboard and select the app that you just deployed. Go to the app’s Settings and click on the Reveal Config Vars button. Enter VERIFICATION_TOKEN as the Key and your token as the Value and click Add.

Create Heroku Config Var

In your code, modify your token string ("this_is_my_token") to process.env.VERIFICATION_TOKEN. Commit your changes and push them to Heroku.

Create a Facebook Page and App

With the server up and running, we’ll now create a Facebook app and the Page it will be associated with. You can create a new Page or use an existing one.

To create a Facebook Page, log in to Facebook and head over to Create a Page. Select a Page Type from the given options. I chose Entertainment.

Screenshot of the Create a Page options, showing the six different types of page

Then select a Category and Name for the Page.

Screenshot of the dropdown menu prompting for a category and page name

Ater clicking on Get Started, the Page will be created and you will be asked for more details regarding your app (description, website, profile picture, target audience, e.t.c). You can skip these setup steps for now.

screenshot of the newly created Facebook page

To create a Facebook App, head over to the Add a New App page and click on the basic setup link below the other platform choices.

Screenshot of the 'Add a New App' page, prompting to select a platform

Fill in the necessary details. Select Apps for Pages as the Category.

Screenshot of the 'Create a New App ID' form

On clicking Create App ID, the app’s dashboard will be opened.

Screenshot of the App Dashboard

From the Product Setup on the right, click on Get Started in the Messenger section. You will then be taken to the Messenger Settings page shown below.

Screenshot of the Facebook Messenger Settings page

To receive messages and other events sent by Messenger users, the app should enable webhooks integration. We’ll do this next. Webhooks (formerly Real Time Updates) let you subscribe to changes you want to track and receive updates in real time without having to call the API.

In the Webhooks section, click Setup Webhooks

Enter a callback URL where the updates will be sent (the endpoint URL defined in the backend app i.e. <your-app-url>/webhook), enter a Verify Token (the token used in the backend app, i.e. the value stored in process.env.VERIFICATION_TOKEN) and check all the checkboxes. These specify which events the app will be subscribed to. We’ll see what these do a little later on.

Webhook Settings

On successfully enabling webhooks, you should see Complete in the Webhooks section and a list of the events subscribed to. If you get an error, make sure you have entered the correct URL for the webhook endpoint (ending with /webhook) and also make sure the token used here is the same one you used in the Node app.

Continue reading %Building a Facebook Chat Bot with Node and Heroku%

LEAVE A REPLY