Click here to Skip to main content
15,742,377 members
Articles / Web Development / Node.js
Posted 11 Jan 2017


8 bookmarked

Developing Chatbots for Facebook Messenger Platform

Rate me:
Please Sign up or sign in to vote.
4.67/5 (6 votes)
11 Jan 2017CPOL6 min read
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.


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.


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:
  2. Registering Facebook app for the messenger chatbot
  3. Building or renting hosting place for the webhook with some DNS name, for example: 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: 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

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:

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

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:

 * 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. 
 *         product-overview/setup#subscribe_app
 */'/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 =;
      var timeOfEvent = pageEntry.time;

      // Iterate over each messaging event
      pageEntry.messaging.forEach(function(messagingEvent) {
        if (messagingEvent.optin) {
        } else if (messagingEvent.message) {
        } else if ( {
        } else if (messagingEvent.postback) {
        } else if ( {
        } else if (messagingEvent.account_linking) {
        } 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.

For more details, please check the official tutorial repository at

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: or directly on the messenger page

The introduction page of the bot:

chat with bot sample


  • 11th January, 2017: Published by Sem


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

Written By
Software Developer (Senior)
Ukraine Ukraine
Individual software developer, good experience with PHP, Java, .Net, NodeJs, Ruby on Rails, JavaScript, LESS, CSS3, HTML5, jQuery, CoffeeScript, ExtJS, Backbone, AngularJS, AJAX, Amazon s3 services, Azure. Programming is not just my work, but more like a hobby. I'm glad to learn new pattern and technologies, making research and study new things. I work remotely for couple of years. More than nine years I'm writing commercial projects.

Comments and Discussions

-- No messages could be retrieved (timeout) --