Skip to main content

Create facebook messenger chatbot using PHP

Chatbots are the latest sensation in social media communication channels. These automated chat systems are especially build to receive vistiors on social media chats and provide basic information to the visitors about your business. This information could include event schedules, product information, latest deals, store offers and general information about the brand.
Entrepreneurs and brand marketers employ chatbots to handle the bulk of chats queries. This way, a large number of queries could be easily handled with minimum costs. Chatbots help reduces the dependence on human customer service representatives (CSR). These chatbots vet out common queries so that the human CSR cold focus on queries that require processing of multiple information sources. Since chatbots steer all conversation toward a pre-set direction, it is easy and time-efficient to use these chatbots instead of human CSR.
In this article, I will create a simple Facebook chatbot that could carry out an effective conversation with the users. The process of creating the chatbot comprises of several interconnected steps.
Create a Page on Facebook
The first step is the creation of a Facebook page. This requires an active account. Login and then create a page. Select the appropriate category and then fill in required information including page name, address and contact information. Complete the process of page creation. For the purpose of this tutorial, I have created a page named Cloudways School.

Create a Facebook Application

The second step is the creation of the Facebook application that interfaces between the chatbot and the facebook page chat. To create the app, go to Facebook Developers page and click Add New App. Add all required information and click Create App ID button. Facebook might ask you to verify a CAPTCHA code.

The app will appear in the developer dashboard. Open the application and add messenger platform to the app.
Next, add the webhook that connects the app to the website. To add the webhook, generate the page access token.

Next, define the callback URL and the access token. Right below the token generation tab, go to the Webhook tab and click Setup Webhooks.Insert the URL. note that, in order for this to work, the URL must be in https format.

Create bot.php File

The Facebook app is now active. I will now create the file for the bot.
Create a new file named bot.php and add the following code to it. This code is based on Remy Mellet’s code of a simple Facebook Messenger bot. I have added more code that handle structured messages sent to the bot. The basic code is:

// parameters
$hubVerifyToken = 'cloudwaysschool';
$accessToken =   "EAxxxxxxxxxxxqgBAKWAgizvoHnQLZBR7ZxxxxxxxxxxxxxxxxxxxxxxxxxxxxxptYSymSdocFFCp1ink3EHRVMrCSxxxxxxxxxxxxxxxxxxxxwMZApStyA8GbqAxxxxxxxxxxxxxxxxxxxxxxxxxxx9R6QttFVyNS4ZBurwZDZD";

// check token at setup
if ($_REQUEST['hub_verify_token'] === $hubVerifyToken) {
  echo $_REQUEST['hub_challenge'];
  exit;
}

// handle bot's anwser
$input = json_decode(file_get_contents('php://input'), true);

$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$response = null;

//set Message
if($messageText == "hi") {
    $answer = "Hello";
}

//send message to facebook bot
$response = [
    'recipient' => [ 'id' => $senderId ],
    'message' => [ 'text' => $answer ]
];

$ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token='.$accessToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
if(!empty($input)){
$result = curl_exec($ch);
}
curl_close($ch);
 
The $hubVerifyToken should contain the same value as the value provided in the webhook token value. In this case, I have set up both values to cloudwaysschool in both the code and the webhook. Once the challenge has been successfully validated, the incoming message is collected in $input. From this, sender ID is extracted into $senderId and the message text in $messageText. Next, the string in messageText is matched with exact keywords and a pre-selected response is sent.
For instance, if the user sends Hi, the keyword is matched and triggers a reply. The code that executes this function is:

if($messageText == "hi") {
    $answer = "Hello";
}

//send message to facebook bot
$response = [
    'recipient' => [ 'id' => $senderId ],
    'message' => [ 'text' => $answer ]
];
Finally, the message is sent using CURL by passing $response as the response..

Upload and Test bot.php

Since the Facebook webhooks supports only https, bot.php could only be tested on a hosting platform that supports SSL. Fortunately, all top hosting providers offer some form of SSL. For the purpose of this tutorial, I am using Cloudways. I have installed Letsencrypt for my application and point it to the domain. A staging URL is always provided with every Cloudways app. However, I have pointed my domain to symfonyfeed.com. Simply upload bot.php in public_html folder using Filezilla.
At this point, when you say hi on the facebook page, you will get hello in reply.

Send Structured Messages

In addition to Hello , in reply to hi, Facebook Messenger also provides several interesting template messages that cover latest news, image and list messages. Button links could also be sent in response. Some common message templates are:
-Button Template
-Generic Template
-List Template
-Receipt Template
I will explain you some of the templates here to kickstart your 1st messenger bot in php. You can see the complete documentation for the message templates could be found here.

Generic Message

Facebook Messenger provides several templates that could be used to send responses to the users. For example, if a user wishes to inquire about the latest blog on your website, they could send a blog. The generic response would be like:

Let’s make a new condition for this message. Try out the following code:
if($messageText == "blog"){
     $answer = ["attachment"=>[
      "type"=>"template",
      "payload"=>[
        "template_type"=>"generic",
        "elements"=>[
          [
            "title"=>"Welcome to Peter\'s Hats",
            "item_url"=>"https://www.cloudways.com/blog/migrate-symfony-from-cpanel-to-cloud-hosting/",
            "image_url"=>"https://www.cloudways.com/blog/wp-content/uploads/Migrating-Your-Symfony-Website-To-Cloudways-Banner.jpg",
            "subtitle"=>"We\'ve got the right hat for everyone.",
            "buttons"=>[
              [
                "type"=>"web_url",
                "url"=>"https://petersfancybrownhats.com",
                "title"=>"View Website"
              ],
              [
                "type"=>"postback",
                "title"=>"Start Chatting",
                "payload"=>"DEVELOPER_DEFINED_PAYLOAD"
              ]              
            ]
          ]
        ]
      ]
    ]];

     $response = [
    'recipient' => [ 'id' => $senderId ],
    'message' => $answer 
];}

List Messages

Facebook Messenger bot could also send lists in response to the users’ queries. For instance, if the user wishes to see the list of all the latest blogs published, all the user could send today. In response, the bot sends a list.

Add this code to bot.php to test this option:
if($messageText == "today"){

 $answer = ["attachment"=>[
      "type"=>"template",
      "payload"=>[
        "template_type"=>"list",
        "elements"=>[
          [
             "title"=> "Classic T-Shirt Collection",
                    "image_url"=> "https://www.cloudways.com/blog/wp-content/uploads/Migrating-Your-Symfony-Website-To-Cloudways-Banner.jpg",
                    "subtitle"=> "See all our colors",
                    "default_action"=> [
                        "type"=> "web_url",
                        "url"=> "https://www.cloudways.com/blog/migrate-symfony-from-cpanel-to-cloud-hosting/",                       
                        "webview_height_ratio"=> "tall",
                        // "messenger_extensions"=> true,
                        // "fallback_url"=> "https://peterssendreceiveapp.ngrok.io/"
                    ],
            "buttons"=>[
              [
                "type"=>"web_url",
                "url"=>"https://petersfancybrownhats.com",
                "title"=>"View Website"
              ],
            ]
          ],
            [
            "title"=>"Welcome to Peter\'s Hats",
            "item_url"=>"https://www.cloudways.com/blog/migrate-symfony-from-cpanel-to-cloud-hosting/",
            "image_url"=>"https://www.cloudways.com/blog/wp-content/uploads/Migrating-Your-Symfony-Website-To-Cloudways-Banner.jpg",
            "subtitle"=>"We\'ve got the right hat for everyone.",
            "buttons"=>[
              [
                "type"=>"web_url",
                "url"=>"https://petersfancybrownhats.com",
                "title"=>"View Website"
              ],
            ]
          ],
            [
            "title"=>"Welcome to Peter\'s Hats",
            "item_url"=>"https://www.cloudways.com/blog/migrate-symfony-from-cpanel-to-cloud-hosting/",
            "image_url"=>"https://www.cloudways.com/blog/wp-content/uploads/Migrating-Your-Symfony-Website-To-Cloudways-Banner.jpg",
            "subtitle"=>"We\'ve got the right hat for everyone.",
            "buttons"=>[
              [
                "type"=>"web_url",
                "url"=>"https://petersfancybrownhats.com",
                "title"=>"View Website"
              ],
            ]
          ]

        ]
      ]
    ]];

  $response = [
    'recipient' => [ 'id' => $senderId ],
    'message' => $answer
];


}
elseif($messageText == "hi") {
    $answer = "Hello";
      $response = [
    'recipient' => [ 'id' => $senderId ],
    'message' => [ 'text' => $answer ]
];
}

Button Messages

Facebook Messenger could also send actionable buttons as a response. For example, if the user asks for more the response would be:
To send buttons as response, try out the following code:
if($messageText == "more") {

  $answer = ["attachment"=>[
      "type"=>"template",
      "payload"=>[
        "template_type"=>"button",
        "text"=>"What do you want to do next?",
        "buttons"=>[
          [
            "type"=>"web_url",
            "url"=>"https://petersapparel.parseapp.com",
            "title"=>"Show Website"
          ],
          [
            "type"=>"postback",
            "title"=>"Start Chatting",
            "payload"=>"USER_DEFINED_PAYLOAD"
          ]
        ]
      ]
      ]];

      $response = [
    'recipient' => [ 'id' => $senderId ],
    'message' => $answer
];
}

Conclusion

In this tutorial, I discussed how to setup a basic Facebook Messenger to cater to your visitors. I highlighted how to use both generic and structured responses that add a lot to the volume of the conversation. I hope you are able to follow the code and implementation of various messages via PHP.

Comments

Post a Comment

Popular posts from this blog

Build chatbot with node js and react js

User Experience is given a lot of attention while building any application these days. More and more brands are leveraging chatbots to service their customers, market their brand, and even sell their products. There are a lot of awesome tools out there which helps in building an intelligent bot very easily like Google’s DialogFlow, Amazon Lex, etc, most of which implement their own Natural Language Processing (NLP) logic. However, in some cases, we don’t really need an intelligent bot. Whenever we have a small application having a limited set of options to choose from, it’s not really necessary to use NLP based tools like Google’s DialogFlow. You need to integrate with them (which is pretty easy though), and you need to make a network call to get the results. Instead, you would want to define your rules locally in those cases. Here we will build a simple chatbot using React Simple Chatbot library and add it to our pizza-builder app using which we can build ou...

PHP Image Upload with Size Type Dimension Validation

File upload feature requires basic validations to  make clean and hygienic  the user input. There is a huge chance of exploiting a file upload option with malicious intent. Improper implementation of a file upload input increases security vulnerability. We need to validate the uploaded files before saving them on the server to reduce the vulnerability. I have created a HTML form and provided an option to upload files. When the form is submitted, the file binaries are sent to the PHP and validated in the server side. I have checked if the uploaded file is an image and I have specified the allowed image extension, size and dimension based on which the validation is taking place. After all these validations have passed, the image file is saved in the target location as specified. The server-side image file validation takes place in the following aspects. If the file is not empty. If the file extension is one of .jpg, .png, .jpeg. If the file size is le...

Arrays In PHP

Have you ever heard about Array.A n Array is a   PHP datatype  used to store a group of data into a variable. Each array item is stored as a key and value pair. Arrays are classified as “indexed array” and “associative array” based on the key specification. The Indexed array has default index starts with ‘0’ and the associative array contains the user-defined key index. The array can also be classified as “one-dimensional array” and “multi-dimensional array” based on the level of the array index. In this tutorial, we are going to see some of the important array functions in PHP. PHP Array Functions In this section, we are going to see some of the widely used PHP array functions. I explain the purpose of the array functions, the parameter it requires and the default values of the parameter. This section includes small and simple PHP code snippets to explain the usage of each array function.  range(start, end) PHP  range()  fu...