(Credit: Independent.co.uk)

Facebook recently announced a Bot platform for it’s Messenger which provides businesses and individuals another way to communicate with people.

What is a Chat bot?

A computer program designed to simulate conversation with human users, especially over the Internet.

Chat bot in PHP

When I heard of it, my very first thought was to a bot in PHP. I started to find some SDK in this regard released by Facebook but none was present. I headed over to documentation which provided good information for starters.

Ok! so without wasting further time, let’s build our first Bot

Timebot

In order to create an Fb bot you will need two things to host your bot: A Facebook Page which will be like Home of Bot, People will visit the page, click on Message option to Interact with your bot. For example, suppose Pizza Hut introduce a bot for order related operations. What could they do that they integrate or host their bot on their official page, a fan can just click on Message button and send messages to order a Pizza, get new deals etc and they will get messages as if some human representatives is responding to them. It all depends how efficient a bot is. Facebook puts no limitation in this regard.

I am going to create a Time bot which will tell you current time Time API that provides different options to retrieve time. For our bot, we are just fetching latest(NOW) time. I will go step by step:

Step 1: Create Facebook Page:

I am going to create Bot’s Page first, this page will actually be the entry point for communication for the bot to interact with your page fans/users. Do note that it is not necessary to create a separate page only for Bot purpose. You may use existing Fan page for this purpose. For sake of this tutorial I am assuming that you never created a page before. Visit https://www.facebook.com/pages/create/ and you will see something like this(as of April, 2016):

I picked Entertainment option. In next steps it asks different options which you can always skip.

Alright! so my page is ready and something like should be visible for you as well:

Step 2: Create Facebook App:

Alright, go to https://developers.facebook.com/apps and click on Add a New App button. Make sure you have a developer account otherwise you will not be able to access developer dashboard.

When you click on it it shows a window and asks you what kind of app are you going to make. I picked Basic Setup given at bottom. I entered required information; Display Name & Contact Email and hit Create App ID button.

After Captcha you will be redirected to your App Page where you will be seeing details.

On left side bar you will see an option of Messenger. When you click on it, it shows introduction of Messenger Platform and why and how these bots will be helpful.

Click on Get Started and it will show a New Dashboard page related to your newly created app that’s going to be hooked with Messenger platform.

Now we need to do a few things for setting up the bot. As you can see, you are being asked a few things; Access Token/Page Token so that Facebook can know where do you want to host bot, Webhooks, your script URL that will be receiving messages from your users and responding them. It will also be hold the logic of your bot and Permissions that is, what this bot should be able to perform when communicating with users. Ok first, set the page which you just created. I am selecting TimBot. Since I, as a normal Facebook User going to use this page very first time, it will ask for Permissions as it normally asks.

Once all goes well you would get your Page Token like this, save it somewhere as this will be used as access_token while sending messages.

Now we have to set our Webhook. Facebook asks you to setup an https:// URL which means, you simply can’t use localhost while developing. You can either upload your script somewhere which allows SSL based requests or.. you can use some tunneling tool that will pass on your localhost message to outer world. Luckily such tools are available and they are FREE as well. I’d recommend nGrok for this purpose. Once it’s unzipped, go to the folder and run the command:

./ngrok http 80 1 . / ngrok http 80

As a free user you are not allowed to give your own subdomain. Once it starts working, it shows something like this:

As you can see, it gives you two forwarded URLs. Since we re interested about https one so we will focus on that. nGrok also provides you an interface to view requests on your newly created domain. It will help you to debug how your webhook page is being accessed by Messenger Platform. For that purpose, open a separate tab with the URL http://localhost:4040/inspect/http and here you can see all details related to that request.



Now I have the URL, all I have to do is to setup my Webhook for Time Bot. Click on Setup Webhooks option and you’d see something like that.

Here I entered the nGrok based URL, Verify Token which could be ANY string and checked subscription fields. If you hit verify and save, you will get error:

What does it mean? Webhook when access the URL, it first verification token before doing anything further, if not present or incorrect, it gives the error you are seeing above.

It’s time to open IDE and write some code. Create a file, in my case it’s index.php, in your case it could be any other file. Write the code that verify your Webhook.

$access_token = "EAAH5qCyWCdcBAP0ddTZBNbVRdmqd43TZCnBJGFEwRZAmO76hlrXfWmVzBXO5xEsochEnlrQ88Tkrwm2B63KzXctLxXQ8RU6KKM9sWEFsGZAaBzmmMUoqVjfir1n5ufXgW8btvZAL41bNJ5S0IceHKUCioOLTqCLZCZCOOMlNz5fRAZDZD"; $verify_token = "fb_time_bot"; $hub_verify_token = null; if(isset($_REQUEST['hub_challenge'])) { $challenge = $_REQUEST['hub_challenge']; $hub_verify_token = $_REQUEST['hub_verify_token']; } if ($hub_verify_token === $verify_token) { echo $challenge; } 1 2 3 4 5 6 7 8 9 10 11 12 13 $access_token = "EAAH5qCyWCdcBAP0ddTZBNbVRdmqd43TZCnBJGFEwRZAmO76hlrXfWmVzBXO5xEsochEnlrQ88Tkrwm2B63KzXctLxXQ8RU6KKM9sWEFsGZAaBzmmMUoqVjfir1n5ufXgW8btvZAL41bNJ5S0IceHKUCioOLTqCLZCZCOOMlNz5fRAZDZD" ; $verify_token = "fb_time_bot" ; $hub_verify_token = null ; if ( isset ( $_REQUEST [ 'hub_challenge' ] ) ) { $challenge = $_REQUEST [ 'hub_challenge' ] ; $hub_verify_token = $_REQUEST [ 'hub_verify_token' ] ; } if ( $hub_verify_token === $verify_token ) { echo $challenge ; }

$verify_token holds the value you in Verify Token field.

Now all seems set, let’s try again! Hurray! if all goes well you would see something like this:



Now all seems set. How about we test our Webhook by sending message to our bot.

Step 3: Sending and Receiving Messages

Before you start sending/receiving messages, you need to subscribe your page. Go to Command prompt, assuming cURL is installed,run the following command.

curl -X POST "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=EAAH5qCyWCdcBAOGIHVjWL7TGTYHFYYTr1RZAxc0bXZCK9pBaqqFEJPn9ctdZCSgzbJbJIdTcEHScfIxJ2zWku2sn8AUSOEqktL5VmTqYhYrC0NXbJEMY3EpsshZAFCd484PEBcyK4hN3H2ZAaiQLowoZAbRSx5aNAihIVsjbCKggZDZD" 1 curl - X POST "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=EAAH5qCyWCdcBAOGIHVjWL7TGTYHFYYTr1RZAxc0bXZCK9pBaqqFEJPn9ctdZCSgzbJbJIdTcEHScfIxJ2zWku2sn8AUSOEqktL5VmTqYhYrC0NXbJEMY3EpsshZAFCd484PEBcyK4hN3H2ZAaiQLowoZAbRSx5aNAihIVsjbCKggZDZD"

Where access_token is the code I got in earlier step for the page Time Bot Page which I asked you to save somewhere. If works perfectly you should success message on console:

{"success":true} 1 { "success" : true }

Now go to your bot page and send message.

If hooks and subscription works fine, on your nGrok Web Interface(http://localhost:4040/inspect/http), you should see a request hit:

Now you will know the power of nGrok Web Interface, here we are receiving message from Bot in a structure. In next step we will convert this message structure by decoding JSON into array and fetch sender Id and message.

$input = json_decode(file_get_contents('php://input'), true); $sender = $input['entry'][0]['messaging'][0]['sender']['id']; $message = $input['entry'][0]['messaging'][0]['message']['text']; 1 2 3 4 $input = json_decode ( file_get_contents ( 'php://input' ) , true ) ; $sender = $input [ 'entry' ] [ 0 ] [ 'messaging' ] [ 0 ] [ 'sender' ] [ 'id' ] ; $message = $input [ 'entry' ] [ 0 ] [ 'messaging' ] [ 0 ] [ 'message' ] [ 'text' ] ;

First line using to get message from Facebook and then convert the JSON into PHP Associative Array.

In next couple of lines I am getting senderID, the ID of the person messaging to bot and the message itself.

Wait.. while you are debugging requests on nGrok, you could find an error:

<span class="hljs-tag"><<span class="hljs-title">br</span> /></span> <span class="hljs-tag"><<span class="hljs-title">b</span>></span>Deprecated<span class="hljs-tag"></<span class="hljs-title">b</span>></span>: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in <span class="hljs-tag"><<span class="hljs-title">b</span>></span>Unknown<span class="hljs-tag"></<span class="hljs-title">b</span>></span> on line <span class="hljs-tag"><<span class="hljs-title">b</span>></span>0<span class="hljs-tag"></<span class="hljs-title">b</span>></span><span class="hljs-tag"><<span class="hljs-title">br</span> /></span> <span class="hljs-tag"><<span class="hljs-title">br</span> /></span> <span class="hljs-tag"><<span class="hljs-title">b</span>></span>Warning<span class="hljs-tag"></<span class="hljs-title">b</span>></span>: Cannot modify header information - headers already sent in <span class="hljs-tag"><<span class="hljs-title">b</span>></span>Unknown<span class="hljs-tag"></<span class="hljs-title">b</span>></span> on line <span class="hljs-tag"><<span class="hljs-title">b</span>></span>0<span class="hljs-tag"></<span class="hljs-title">b</span>></span><span class="hljs-tag"><<span class="hljs-title">br</span> /></span> <span class="hljs-tag"><<span class="hljs-title">br</span> /></span> <span class="hljs-tag"><<span class="hljs-title">b</span>></span>Notice<span class="hljs-tag"></<span class="hljs-title">b</span>></span>: Undefined variable: data in <span class="hljs-tag"><<span class="hljs-title">b</span>></span>/Applications/MAMP/htdocs/Facebook-Chat-Bot/index.php<span class="hljs-tag"></<span class="hljs-title">b</span>></span> on line <span class="hljs-tag"><<span class="hljs-title">b</span>></span>30<span class="hljs-tag"></<span class="hljs-title">b</span>></span><span class="hljs-tag"><<span class="hljs-title">br</span> /></span> Invalid 1 2 3 4 5 6 7 < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > br < / span > / & gt ; < / span > < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > b < / span > & gt ; < / span > Deprecated < span class = "hljs-tag" > & lt ; / < span class = "hljs-title" > b < / span > & gt ; < / span > : Automatically populating $ HTTP_RAW_POST_DATA is deprecated and will be removed in a future version . To avoid this warning set 'always_populate_raw_post_data' to '-1' in php . ini and use the php : //input stream instead. in <span class="hljs-tag"><<span class="hljs-title">b</span>></span>Unknown<span class="hljs-tag"></<span class="hljs-title">b</span>></span> on line <span class="hljs-tag"><<span class="hljs-title">b</span>></span>0<span class="hljs-tag"></<span class="hljs-title">b</span>></span><span class="hljs-tag"><<span class="hljs-title">br</span> /></span> < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > br < / span > / & gt ; < / span > < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > b < / span > & gt ; < / span > Warning < span class = "hljs-tag" > & lt ; / < span class = "hljs-title" > b < / span > & gt ; < / span > : Cannot modify header information - headers already sent in < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > b < / span > & gt ; < / span > Unknown < span class = "hljs-tag" > & lt ; / < span class = "hljs-title" > b < / span > & gt ; < / span > on line < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > b < / span > & gt ; < / span > 0 < span class = "hljs-tag" > & lt ; / < span class = "hljs-title" > b < / span > & gt ; < / span > < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > br < / span > / & gt ; < / span > < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > br < / span > / & gt ; < / span > < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > b < / span > & gt ; < / span > Notice < span class = "hljs-tag" > & lt ; / < span class = "hljs-title" > b < / span > & gt ; < / span > : Undefined variable : data in < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > b < / span > & gt ; < / span > / Applications / MAMP / htdocs / Facebook - Chat - Bot / index . php < span class = "hljs-tag" > & lt ; / < span class = "hljs-title" > b < / span > & gt ; < / span > on line < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > b < / span > & gt ; < / span > 30 < span class = "hljs-tag" > & lt ; / < span class = "hljs-title" > b < / span > & gt ; < / span > < span class = "hljs-tag" > & lt ; < span class = "hljs-title" > br < / span > / & gt ; < / span > Invalid

This issue arises if you are using PHP5.6. The best bet to create an .htaccess file with the content.

<IfModule mod_php5.c> php_value always_populate_raw_post_data -1 </IfModule> 1 2 3 < IfModule mod_php5 . c > php_value always_populate_raw_post_data - 1 < / IfModule >

Now the error should be gone away. This particular will not go away by using ini_set().

I am setting some basic rules for my bot. It should only tell if it contains certain words.

/** * Some Basic rules to validate incoming messages */ if(preg_match('[time|current time|now]', strtolower($message))) { // Make request to Time API ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); $result = file_get_contents("http://www.timeapi.org/utc/now?format=%25a%20%25b%20%25d%20%25I:%25M:%25S%20%25Y"); if($result != '') { $message_to_reply = $result; } } else { $message_to_reply = 'Huh! what do you mean?'; } print $message_to_reply; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 /** * Some Basic rules to validate incoming messages */ if ( preg_match ( '[time|current time|now]' , strtolower ( $message ) ) ) { // Make request to Time API ini_set ( 'user_agent' , 'Mozilla/4.0 (compatible; MSIE 6.0)' ) ; $result = file_get_contents ( "http://www.timeapi.org/utc/now?format=%25a%20%25b%20%25d%20%25I:%25M:%25S%20%25Y" ) ; if ( $result != '' ) { $message_to_reply = $result ; } } else { $message_to_reply = 'Huh! what do you mean?' ; } print $message_to_reply ;

Jus to check all going well, the message going to be printed should be able to watch on nGrok debugger.

Ok, now we have to message back to user. We have sender’s Id, we prepared the message, it’s time to send.

//API Url $url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token; //Initiate cURL. $ch = curl_init($url); //The JSON data. $jsonData = '{ "recipient":{ "id":"'.$sender.'" }, "message":{ "text":"'.$message_to_reply.'" } }'; //Encode the array into JSON. $jsonDataEncoded = $jsonData; //Tell cURL that we want to send a POST request. curl_setopt($ch, CURLOPT_POST, 1); //Attach our encoded JSON string to the POST fields. curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); //Set the content type to application/json curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); //Execute the request if(!empty($input['entry'][0]['messaging'][0]['message'])){ $result = curl_exec($ch); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 //API Url $url = 'https://graph.facebook.com/v2.6/me/messages?access_token=' . $access_token ; //Initiate cURL. $ch = curl_init ( $url ) ; //The JSON data. $jsonData = '{ "recipient":{ "id":"' . $sender . '" }, "message":{ "text":"' . $message_to_reply . '" } }' ; //Encode the array into JSON. $jsonDataEncoded = $jsonData ; //Tell cURL that we want to send a POST request. curl_setopt ( $ch , CURLOPT_POST , 1 ) ; //Attach our encoded JSON string to the POST fields. curl_setopt ( $ch , CURLOPT_POSTFIELDS , $jsonDataEncoded ) ; //Set the content type to application/json curl_setopt ( $ch , CURLOPT_HTTPHEADER , array ( 'Content-Type: application/json' ) ) ; //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); //Execute the request if ( ! empty ( $input [ 'entry' ] [ 0 ] [ 'messaging' ] [ 0 ] [ 'message' ] ) ) { $result = curl_exec ( $ch ) ; }

First, we will create a JSON structure of the message as given by Facebook platform and then will make POST call via cURL. If all things coded correctly, you should see bot in action!

As you can see it covers bot valid and invalid messages here as per our rules.

Alright! It’s your time to show your creativity and create your first awesome bot. if you bot goes public you can add a little code on your Website to invite others. Check the documentation for that.

Code is available on Github

Do you have an existing Web app or Facebook page and wants to integrate a bot with it? Let me know and I could help you in this regard. Contact me at kadnan(at)gmail.com







