Axway AMPLIFY Blogs

The Leading Resource for All THings Mobile & Data Integration

API Builder: Facebook Chatbot Example

34 Flares 34 Flares ×

In a prior post, we described how to use API Builder to implement a Twitter Bot that posted tweets, retweeted and also followed anyone that followed the bot.

In this blog post, we describe how to use API Builder to create a Facebook chatbot. A Facebook chatbot can be used to engage employees or clients who visit your page and allow them to discover information about your company and products in a more natural chat format.

This post will not dive into the AI aspect of chatbots, but focus more on the mechanics of setting up API Builder for implementing a Facebook chatbot.

You can view and interact with the chatbot here.

You can expect an experience similar to the screenshot below where I am interacting with the chatbot in the lower right hand corner of the page:

Background

The basic idea is to create the bot in Facebook and then create the Facebook-required API’s (webhooks) in API Builder. API Builder will also be used to implement the artificial intelligence (AI) required to make the bot (seemingly) intelligent.

I found the Facebook Messenger Platform Quick Start Guide to be a great place to get started with the creation of a Facebook chatbot. I only followed steps 1 – 6 of this guide to get the basics implemented.

How to Build a Facebook Bot App Using Node.js was also a useful resource.

I’m not going to cover the Facebook chatbot creation as it’s well documented in the Quick Start guide, so let’s dive into API Builder.

API Builder Webhook for Subscription

In step 2 of the Facebook Messenger Platform Quick Start Guide, we need to provide the URL of an API endpoint that can take a GET request. The Quick Start Guide provides the Express code for this.

In API Builder, I chose to implement this as a Custom API. My Custom API, in the file /api/fbwebhook.js, is shown below:


var Arrow = require('arrow');
var fbwebhook = Arrow.API.extend({
    group: 'webhooks',
    path: '/api/fbwebhook',
    method: 'GET',
    description: 'this is an api that shows how to handle requests from the FB chatbot',
    parameters: {
        'hub.mode': {
            description: 'hub.mode',
            optional: true
        },
        'hub.challenge': {
            description: 'hub.challenge',
            optional: true
        },
        'hub.verify_token': {
            description: 'hub.verify_token',
            optional: true
        }
    },
    action: function(req, resp, next) {
        if (req.query['hub.mode'] === 'subscribe' &&
            req.query['hub.verify_token'] === '') {
          resp.response.status(200);
          resp.send(req.query['hub.challenge']);
        } else {
          resp.response.status(403);
        }
        next();
    }
});
module.exports = fbwebhook;

Here is where I faced the first challenge.

Facebook does not allow me to change the webhook URL once I enter it into the Facebook developer portal. With API Builder, you are typically developing and testing the API Builder project locally and then publishing it when you are done. So, you need to publish the API Builder project and then use that URL for the Facebook chatbot. But that poses a development conundrum, since it is very slow to make changes, and then publish to production after each change.

My solution was to create two bots, one for dev and one for production.

During development, I use the dev chatbot and ngrok, so that Facebook can actually call an API Builder API running locally in dev mode.

The production Facebook chatbot will use the API Builder production API for its webhook.

The one issue using this method is that I need to manage two Facebook page access tokens. This is covered in the next section.

Another issue that I faced following the Quick Start Guide is that the instructions mention to select messages and messaging_postbacks under Subscription Fields. Another guide I found suggested also subscribing to messaging_optins and message_deliveries as well. I found that I needed these additional two subscription fields checked in order to get the chatbot approved by Facebook. See the screen shot below:

API Builder Webhook for Chatting

When a user types into the chatbot, Facebook will make a POST request to the same endpoint described above. This is described in section 5 of the Facebook Messenger Platform Quick Start Guide. In this step, you will also generate a Page Access Token.

The express code in the Facebook guide simply echoes back what the user typed.

Again, we’ll create an API Builder Custom API with the same endpoint, but it will be a POST this time. My custom API, in the file, /api/fbwebhookp.js, is shown below. Note that all the methods – like receivedMessage() – are not shown below but are included in the github link at the end of this post.


var Arrow = require('arrow');

.
.
.

var fbwebhookp = Arrow.API.extend({
    group: 'webhooks',
    path: '/api/fbwebhook',
    method: 'POST',
    description: 'this is an api that shows how to handle requests from the FB chatbot',
    parameters: {
        'object': {
            description: 'object',
            optional: true
        },
        'entry': {
            description: 'entry',
            optional: true
        }
    },
    action: function(req, resp, next) {
      var data = req.body;
      if (data.object === 'page') {
        data.entry.forEach(function(entry) {
          var pageID = entry.id;
          var timeOfEvent = entry.time;
          entry.messaging.forEach(function(event) {
            if (event.message) {
              receivedMessage(event);
            } else {
              console.log("Webhook received unknown event: ", event);
            }
          });
        });
        resp.response.status(200);
        next();
      } else {
        resp.response.status(200);
        next();
      }

    }
});
module.exports = fbwebhookp;

At this point, you have a chatbot that you can send messages to and the message will be echoed back to you. However, Facebook will not approve such a bot. It needs to provide some useful response. We’ll cover adding AI in a future blog post. Stay tuned. In the meantime, you can find the code for this project here.

34 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 34 Email -- 34 Flares ×

3 Comments

  1. Miguel Espeso

    Hi, first congratulate them for their work.
    My question is have some example of including facebook in my application to share content, I’ve been trying for days and I’m not able to get it.
    I am new and looking for your blog I can not find anything like it.
    Thank you, and once again, congratulations on your work.

Comments are closed.

computer and tablet showing Appcelerator software
Start free, grow from there.
34 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 34 Email -- 34 Flares ×