How-to-Make-a-Facebook-Messenger-Bot.jpg

How to Make a Facebook Messenger Bot


Chat bots are computer programs that mimic conversation with people using artificial intelligence. They can transform the way you interact with the internet from a series of self-initiated tasks to a quasi-conversation.(Source)

These chatbots can help you to create the personalized experience for your business without hiring additional staff.

If you have Facebook Business Page you can easily integrate bot messenger to your page, or here you can learn how to create Facebook Business Page (How to Create a Facebook Business Page in 5 Simple Steps).

You can develop Facebook messenger bot in any language like PHP, Python, Android etc.

I am assuming that you have a Facebook Business Page.

Step-1 Creating Facebook App

  • To create Facebook app go to this link https://developers.facebook.com/apps to create a developers account, if you already have developers account then just login to that account.

  • Click register now to create a developer account.

  • Now select the platform in which you want to create the Facebook messenger. Here I am selecting Android platform.
  • After selecting platform you have to create a New App ID. Now fill the required information like Display Name, Contact Email & Category.

  • Then filling the captcha you will be redirected to your app dashboard.

Step-2 Page Access Token

  • Now in the left sidebar click on “Add Products” then click on “Messenger”. Then you will redirect to the page like this:

 

  • To get your Page access token “Select a Page” to generate page access token

Step-3 Set Up Webhooks

  • Now our next step is to create Webhooks

In the Webhooks section click on “setup Webhooks”

 

  • To setup your webhooks Facebook ask you to call back URL, you can’t use localhost while developing Facebook chat bot messenger or you can use any free tunneling tools.
  • Now add your callback URL, Verify Token can be any string and checked the subscription fields.

  • In your webhook URL, you have to add code for verification to verify token.

This is the sample code for Javascript.

app.get('/webhook', function(req, res) {
 if (req.query['hub.mode'] === 'subscribe' &&
     req.query['hub.verify_token'] === <VERIFY_TOKEN>) {
   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);          
 }  
});

http://www.seopros.co.in/wp-content/uploads/2017/05/8.png

Step-4 Receiving Message

Now we have to receive the messages we need to make POST calls to Facebook webhooks and all callback will be made to this webhook.

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(entry) {
     var pageID = entry.id;
     var timeOfEvent = entry.time;

     // Iterate over each messaging event
     entry.messaging.forEach(function(event) {
       if (event.message) {
         receivedMessage(event);
       } else {
         console.log("Webhook received unknown event: ", event);
       }
     });
   });

   // 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 and we will keep trying to resend.
   res.sendStatus(200);
 }
});
 function receivedMessage(event) {
 // Putting a stub for now, we'll expand it in the following steps
 console.log("Message data: ", event.message);
}

Step-5 Sending Message

  • Now we have to send the message back to the user,

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

 console.log("Received message for user %d and page %d at %d with message:",
   senderID, recipientID, timeOfMessage);
 console.log(JSON.stringify(message));

 var messageId = message.mid;

 var messageText = message.text;
 var messageAttachments = message.attachments;

 if (messageText) {

   // If we receive a text message, check to see if it matches a keyword
   // and send back the example. Otherwise, just echo the text we received.
   switch (messageText) {
     case 'generic':
       sendGenericMessage(senderID);
       break;

     default:
       sendTextMessage(senderID, messageText);
   }
 } else if (messageAttachments) {
   sendTextMessage(senderID, "Message with attachment received");
 }

}

Now your Facebook Messenger Bot is ready. If you have any doubts and queries while implementing this do let us know in comment section. 

 


Comments

Your message has been sent. Thank you!