Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / Node.js

Developing Chatbots for Facebook Messenger Platform

4.67/5 (6 votes)
11 Jan 2017CPOL6 min read 23K  
Explaining the new Facebook messenger platform for developing chatbots, with a live example.
This article gives a live example to explain the new Facebook messenger platform for developing chatbots.

Introduction

Before e-commerce online shops were invented, we always had an opportunity to talk to a sales representative or distributor when choosing goods or services. After moving to the digital world, this area became silent. Is that convenient for customers? I think not. It is much easier to ask a question to a sales rep or dealer about the desired product or service instead of searching through multiple catalogs and stores. Today, almost every 'modern' person is using messenger application - WhatsApp, Facebook messenger, Slack, Yahoo, etc. Facebook gives a wonderful ability for developers to make e-commerce, online shops, services and other distribution agency more friendly to their customers - enabling live dialogs - talking with a simple AI representative like with a real dealer at the shop.

Background

Apparently, most Internet users have negative associations with the word 'chatbot'. This article has nothing to with spam bots, it's only about useful tiny programs which are designed to simplify life for customers by making online sales and goods distribution interactive.

Designing a Chatbot

Normally, chatbot is a tiny application, in case of Facebook messenger (this article concerns only Facebook chatbots), it is called webhook. It's basically a web endpoint, which accepts messages sent from Facebook. The webhook processes incoming message - which is a chat message received from the Facebook page, analyses it and sends back a response based on the message content. The response could be just a string - message chatbot reply or extended content like images, web links, audio, video, etc. Basically, we can define major steps to develop a Facebook messenger chatbot:

  1. Creating a Facebook page which will use chatbot webhook for chatting with customers. (when developing chatbot for existing page, this step should be obviously omitted). For example: https://www.facebook.com/sskotugoroshko
  2. Registering Facebook app for the messenger chatbot https://developers.facebook.com/apps
  3. Building or renting hosting place for the webhook with some DNS name, for example: http://fbwebhookbotsem.herokuapp.com. The webhook can be done using .NET, PHP, Java or Node.Js whichever you like, the hosting environment should be appropriate.
  4. Preparing flow cases or chat diagrams in format of message - response for constructing a dialog.
  5. Choosing which Artificial Intelligence engine to use. The possible options are as follows:
    • Self coded string parsing with primitive if-else logic. The advantage is that it's highly customizable.
    • Using self-coded chatbot core based on ELIZA AI architecture. The eliza is epic, basic AI architecture for any chatbot. It defines the basic principles and turnovers to support a human like conversation ( chat ).
    • Building own Artificial Intelligence engine, using NLP or similar, which requires strong, advanced knowledge in developing human like intellect (neural networks, machine learning, etc.).
    • The most popular nowadays is using external Artificial Intelligence engine - through web API, for example Wit.AI, or RecastAI there are many others open, modern AI APIs coming on the way.
  6. Implementing the webhook using selected AI engine.
  7. Doing live tests, to make sure that the bot is supporting conversation as desired. Adding and monitoring chat logs, to identify and fix difficult chat cases.

For me, the best technology for implementing webhook is Node.Js, it's very intuitive, simple, easy to deploy and hosting is cheap or even free. In this article, I'm going to use code sample provided by Facebook when explaining the chatbot webhook behaviour. The code sample can be downloaded from the official GitHub page: https://github.com/fbsamples/messenger-platform-samples. This example is done using Node.Js, it supports very simple commands to show capabilities of FB messenger platform. In case Node.Js is chosen for the webhook backend, Heroku can be used for hosting. Heroku provides free hosting plans with limited traffic for different platforms, including Node.Js.

Creating a Page

Facebook chatbots are designed to operate in page chats, that's why when starting new chatbot needs to set out which page it will be running on. Page Create menu is in the right top corner of the Facebook page. If page already exists, one just needs to know that page ID.

To find Page ID:

  1. Go to your page.
  2. Click "Settings".
  3. Click "Page Info".
  4. You can see "Facebook Page ID".

facebook page id

For example, I've created a page, for shoes online shop https://www.facebook.com/sskotugoroshko

create facebook page

When page ID is ready, the next step is to create a Facebook app. It should be done on the following page: https://developers.facebook.com/apps.

create facebook app

When the app is created, it needs to configure connection between webhook endpoint and page, called 'Subscribe App to Page'. It's well explained in the following document https://developers.facebook.com/docs/messenger-platform/guides/quick-start. When this is done, the app settings screen should look like this:

subscribe app to page

webhook setup fb app

Very important! After the setup is done, after implementing the webhook and passing all chat tests, don't forget to turn your app ON for public access. Facebook App page -> Settings tab. Otherwise, no one from public would be able to chat with your bot.

make it live

Creating Account on heroku for NodeJs.

The following article describes in details how to create heroku account and deploy NodeJs application https://scotch.io/tutorials/how-to-deploy-a-node-js-app-to-heroku. Account setup and deployment are fairly easy, I did it in less than one hour, should take about 30 minutes. Heroku account is free to use.

Conversation Flow Chart or Chat Cases

This is the starting point when writing code for the chatbot. Your customer have to provide chart diagram of chat cases to describe desired behaviour of the chatbot. Example of the chat cases can be found on my intro page at http://fbwebhookbotsem.herokuapp.com/.

Writing the Chatbot Webhook Code

Now, the page is ready, Facebook App is completely setup, hosting environment is created, chat cases are considered, it's time to write code of the chatbot itself. To implement the bot, you would need to follow the chat cases provided by your customer. I'd recommend to use Eliza core, it's available on Github OR Wit.AI web interface. On the webhook side, the app should listen for posted data at the appropriate address, for example Node.Js code of the server running process:

JavaScript
/*
 * All callbacks for Messenger are POST-ed. They will be sent to the same
 * webhook. Be sure to subscribe your app to your page to receive callbacks
 * for your page. 
 * https://developers.facebook.com/docs/messenger-platform/
 *         product-overview/setup#subscribe_app
 *
 */
app.post('/webhook', function (req, res) {
  var data = req.body;

  // Make sure this is a page subscription
  if (data.object == 'page') {
    // Iterate over each entry
    // There may be multiple if batched
    data.entry.forEach(function(pageEntry) {
      var pageID = pageEntry.id;
      var timeOfEvent = pageEntry.time;

      // Iterate over each messaging event
      pageEntry.messaging.forEach(function(messagingEvent) {
        if (messagingEvent.optin) {
          receivedAuthentication(messagingEvent);
        } else if (messagingEvent.message) {
          receivedMessage(messagingEvent);
        } else if (messagingEvent.delivery) {
          receivedDeliveryConfirmation(messagingEvent);
        } else if (messagingEvent.postback) {
          receivedPostback(messagingEvent);
        } else if (messagingEvent.read) {
          receivedMessageRead(messagingEvent);
        } else if (messagingEvent.account_linking) {
          receivedAccountLink(messagingEvent);
        } else {
          console.log("Webhook received unknown messagingEvent: ", messagingEvent);
        }
      });
    });

    // Assume all went well.
    //
    // You must send back a 200, within 20 seconds, to let us know you've 
    // successfully received the callback. Otherwise, the request will time out.
    res.sendStatus(200);
  }
});

For more details, please check the official tutorial repository at https://github.com/fbsamples/messenger-platform-samples

Testing the Chatbot

When the chatbot is implemented, it needs to make sure that it behaves according to the requested flow. For that, you can configure test users, who can chat with bot, while it's in development or test stage, but not live yet (Facebook app settings page, Roles tab, Roles menu):

add test users before app is live

Working example of a chatbot can be found on my Facebook page: https://www.facebook.com/sskotugoroshko/messages or directly on the messenger page https://messenger.com/t/sskotugoroshko.

The introduction page of the bot: http://fbwebhookbotsem.herokuapp.com/

chat with bot sample

History

  • 11th January, 2017: Published by Sem

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)