How to build Facebook Messenger Chat Bot using PHP

Nowadays, Chat Bot is very demanding topic. There are several platforms which enable us to interact with people through conversations. Facebook Messenger Platform is one of them. With Messenger Platform, we can personalize conversation with Users or Customers of Facebook Page. Instead of using traditional auto response message, we use Facebook Messenger Chat Bot.

By using Messenger Chat Bot, we have possibilities to enhance user experience by communicating one to one with tailored and useful message. Furthermore, we can provide different type of messages like texts, images, audios, videos and so on according to the conversation.

This is step by step guide to build a simple Facebook Messenger Chat Bot using PHP.

Getting started with Facebook Messenger Chat Bot

First of all, we need to create a Facebook App and a Facebook Page. We  can create a Facebook App by going to developer’s app page and clicking Add a New App Button. This will display a pop up box to create a New Facebook App.

Creating FB App for Messenger Chat Bot
Creating a Facebook App

Fill the fields with appropriate values and hit the Create App ID button. And then click Get Started button next to Messenger on Product Setup page.

After creating App, we need a Facebook page. If we already have a Facebook page, we can use it otherwise we have to create a new page.

In addition to having Facebook App and Facebook Page, we need page token so that our Page can start using the APIs. Select a Page to generate an access token.

FB Page Token Generation
Page Token Generation for Facebook Messenger Bot

So far, we have a Facebook App, a Facebook page and a Page Access Token to connect App with Page. In addition to this, we need to Setup Webhook to receive messages and other events sent by Messenger users.

Setup Webhooks

To setup the webhook, click Setup Webhooks button inside the Webhooks section. The following Pop Up appears:

webhook setup screen
Facebook Messenger webhook setup

Page at Callback URL should look for the Verify Token and respond with the challenge sent in the verification request. All callbacks will be made to this Callback URL aslo called as webhook. The following PHP code verifies the Verify Token and respond back with the challenge:

$verify_token = 'your_verify_token';
if(isset($_REQUEST['hub_mode']) && $_REQUEST['hub_mode'] == 'subscribe') {
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];

if ($hub_verify_token === $verify_token) {
header("HTTP/1.1 200 OK");
echo $challenge;
die;
}
}

After filling ‘Callback URL’ and ‘Verify Token’ fields with proper values, select Subscription Fields and then Click Verify and Save button to call your webhook with a GET request. Upon successful verification, success icon is shown as follows:

successful webhook setup
Webhook setup successful

In the above screenshot, we can see “Select a page to subscribe your webhook to the page events” at the bottom. Select the page and click the Subscribe button to subscribe the webhook for a specific page.

So far, we have setup background for Facebook Messenger Chatbot. As a result of this, the Webhook URL can receive callback from Facebook. We need to listen for POST calls at our webhook.

Listening POST calls

At our Webhook URL, we use php://input to read raw data from the request body as follows:

$input = json_decode(file_get_contents('php://input'), true);

The incoming messages from Facebook is in JSON format and it follows the following structure:

{  
   "object":"page",
   "entry":[  
      {  
         "id":"111998675571667",
         "time":1484326151343,
         "messaging":[  
            {  
               "sender":{  
                  "id":"12267537747884"
               },
               "recipient":{  
                  "id":"111998675571667"
               },
               "timestamp":1484326151290,
               "message":{  
                  "mid":"mid.1484326151290:f182b81009",
                  "seq":53593,
                  "text":"hi"
               }
            }
         ]
      }
   ]
}

We can save this response to a file for debugging and other purposes using the following PHP code:

file_put_contents('fb_response.txt', file_get_contents("php://input") . PHP_EOL, FILE_APPEND);

Reply with a text message

Once we receive incoming message at our Webhook URL, we read the message and decode the JSON string using json_decode. After decoding, we have the message in array format. From this array, can retrieve the following:

$input = json_decode(file_get_contents('php://input'), true);

// Page ID of Facebook page which is sending message
$page_id = $input['entry'][0]['id'];

// User Scope ID of sender.
$sender_id = $input['entry'][0]['messaging'][0]['sender']['id'];

// Get Message text if available
$message = isset($input['entry'][0]['messaging'][0]['message']['text']) ? $input['entry'][0]['messaging'][0]['message']['text']: '' ;

// Get Postback payload if available
$postback = isset($input['entry'][0]['messaging'][0]['postback']['payload']) ? $input['entry'][0]['messaging'][0]['postback']['payload']: '' ;

If a Message or Postback is received, we will reply with the message. We have to analyze the message/postback and prepare appropriate reply to send. We can lookup keywords or use preg_match to the received message and respond accordingly.

For the sake of learning, we will respond back with the message typed by the user in the following illustration.

if($message) {
	
	$reply = 'Message received: ' . $message;

 	$responseJSON = '{
		"recipient":{
			"id":"'. $sender_id .'"
		},
		"message": {
		        "text":"'. $reply .'"
		    }
	}';

	$access_token = 'your_page_access_token';
	
	//Graph API URL
	$url = 'https://graph.facebook.com/v2.7/me/messages?access_token='.$access_token;

	// Using cURL to send a JSON POST data
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $responseJSON);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
	$result = curl_exec($ch);
	curl_close($ch);
	
}

When we send any message to our bot, it will respond back with the same message.

fb-chat-bot-demo
Facebook Messenger Bot Demo

In this way, we build a simple Chat Bot using Facebook Messenger Platform. Our Bot can now respond with text messages. Apart from text messages, we can also send images, links, buttons, generic templates, audios as well as videos. Furthermore, we can make Chat Bot more intelligent by integrating APIs for Natural Language Processing (NLP) so that the Bot can better understand users message and respond back with appropriate reply.

Further Readings

Personalize your Messenger Bot by Adding Persistent Menu and Get Started Buttons

Nested Persistent Menu using Messenger Profile API

10 Comments

Leave a Reply