Facebook Messenger Bot With Node.js

Facebook is the biggest social network in the world and they also involved in various research process to give power for the people to share and make the world more open and connected. Facebook started developing artificial intelligence in order to have computer software programs called bots, take over sales and customer service functions on Facebook messenger platform. It will gives you the ability to have conversations with people on messenger and they also added new tools for you to build and promote your bot so you can create a custom experience for your unique audience. Let’s we get into few configuration and few line of program to create our bot

Create a Facebook Page
  • Go to facebook.com/pages/create.
  • Click to choose a Page category.
  • Select a more specific category from the dropdown menu and fill out the required information.
  • Click Get Started and follow the on-screen instructions to complete the process.
Register and Configure an App
  • Developer Account :

    You’ll need Facebook developer account to get started. If you don’t have one upgrade your personal Facebook account to a Facebook Developer account now. Skip this step, if you already have a developer account.

  • Create new Facebook app :

    Choose Apps in the header navigation and select Add a New App and then select Platform, Name as well as follow some other quick steps to complete your App creation

  • App ID :

    Your app will have a unique app ID. You can find your app ID in your app’s dashboard. Now, You need to add a contact email, Go to your app’s dashboard and select the navigation item Settings in the left sidebar and provide a valid contact email.

  • Add Messenger Product :

    Select the Add Product on the left sidebar to add messenger for your app.

  • Page Access Token :

    Create a page access token by providing the callback URL
    and your token to authorize callback URL. While creating select all service like message_deliveries, messages, etc..,

Note: Callback URL is the URL where we hosted bot program and token is the one which we created. In our case the URL is https://xxxx.herokuapp.com/webhook and Token is webhooktoken

Deploy your Application on Cloud Server

Now you have to choose the place where we need to launch our application, We have a lot of service provider to launch our application, I used Heroku to launch my application. After launching the application your bot is ready to interact with Facebook messenger. Now confirm Once the webhook callback URL is verified and active.

Here is the simple Node.js program to act as a bot, Which interact facebook messenger platform and reply for your customer/client.

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
var token = "EAAFAb0qoKxgBAJWMyGYINDYRDM7cGRrqVDBFNopMl2SaM34FEzweSzJZBGdGtj6wbEZBLtkpV1QlkpfZCBRlGZAmz0bwWcZBRa1WejtxQ5ZCq2HhTGRWZB700paRKXnBIBQr5VQah6hTEIEH2hy4hDvdnQe26TZCnOoZBSSuupGqN1wZDZD";

app.set('port', (process.env.PORT || 1000))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.get('/', function (req, res) {
  res.send('Facebook Bot')
});

/*
 * Use your own validation token. Check that the token used in the Webhook 
 * setup is the same token used here.
 *
 */
app.get('/webhook', function (req, res) {
  if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === 'webhooktoken') {
    console.log("Validating webhook");
    res.status(200).send(req.query['hub.challenge']);
  } else {
    console.error("Failed validation. Make sure the validation tokens match.");
    res.sendStatus(403);
  }
});

/*
 * All callbacks for Messenger are POST-ed. They will be sent to the same webhook.
 *
 */
app.post('/webhook', function (req, res) {
  var data = req.body;
  if (data.object == 'page') {
    data.entry.forEach(function (pageEntry) {
      var pageID = pageEntry.id;
      var timeOfEvent = pageEntry.time;
      pageEntry.messaging.forEach(function (event) {
        if (event.message && event.message.text) {
          receivedMessage(event);
        }
      });
    });
    res.sendStatus(200);
  }
});

function receivedMessage(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfMessage = event.timestamp;
  var message = event.message.text;

  var messageText = "I'm Siva, How can I help you ?";

  var messageData = {
    recipient: { id: senderID },
    message: { text: messageText }
  };

  callSendAPI(messageData);
}

/*
 * Call the Send API. The message data goes in the body. If successful, we'll 
 * get the message id in a response 
 *
 */
function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: token },
    method: "POST",
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;
      console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

app.listen(app.get('port'), function () {
  console.log('running on port', app.get('port'))
})

You can download the source code via GitHub. Downloaded source code can be run/executed with the following commands,

npm install #Install packages dependencies
node app    #Start the Server/Application

Here is the Facebook official documentation to develop your bot with more advance feature or you can use this as a reference for developing your bot. Please leave your valuable comments/suggestions/feedback on below comment box if any.

Thank You !!

Leave a Reply

Your email address will not be published. Required fields are marked *