New to our community ?

Discover a world of possibilities! Join us and explore a vibrant community where ideas flourish and connections thrive.

One of Our Valued Members

Thank you for being part of our community. Your presence enriches our shared experiences. Let's continue this journey together!

Home php codes How To Build A Facebook Messenger Chatbot In PHP

How To Build A Facebook Messenger Chatbot In PHP

0

Hello Learners, Welcome back to short learner, today we will see that how we can build a fully functional facebook messenger chat using php.Before proceeding further I would like to give a brief knowledge about Chatbot.

facebook messenger chat bot

What is Chat Bot?

A Chabot is a computer program or an artificial intelligence which conducts a conversation via auditory or textual methods.Chatbots are typically used in dialog systems for various practical purposes including customer service or information acquisition. Many brands use chatbots to receive incoming queries on social media channels.

Importance of chatbots

The objective of chat bots is to support and expand business teams in their relations with clients.

Chatbots can be competent in many aspects of the customer experience, including providing customer service, presenting product recommendations and engaging customers through targeted marketing campaigns.
Steps To Build a Facebook Messenger Chatbot in PHP

    1. Create A Facebook Page
  1. Create the Facebook Application
  2. Create Required Class and Methods
  3. Conclusion

Create A Facebook Page

The first step of the process is to create a Facebook page (requires an active Facebook account). Login facebook and then create a page. Select the desired category and fill in the required information including the name of the page, address and contact information

Create the Facebook Application

The second step is to create the Facebook application that provides communication between the chatbot app and the Facebook page chat. To create the facebookapplication, go to Facebook Developers page and click Add New App. Add all thenecessary information and click Create App ID button.

The application will appear in the Developer Dashboard. Open the application and add the facebook messenger platform to your app. Now, we will add the web hook that will connect the app with your website. To add the web hook, generate the page access token.

In the next step we will define the callback URL and the access token generated from the dashboard of your app. Now go to the Web hook tab and click Setup Web hooks. Insert the URL. Note that, in order for this to work, the URL must be in https format.

Create Required Class and Methods

Now for creating required classes and method, we will use Guzzle, to install Guzzle, run the following command:

composer require guzzlehttp/guzzle

This command will create a vendor directory and install Guzzle in the project’s folder. Create two more files in the directory FbBot.php (for the main class) and bot.php (for handling messages via class methods).

fbBot.php

<?php
require 'vendor/autoload.php';

useGuzzleHttpClient;
useGuzzleHttpExceptionRequestException;
useGuzzleHttpPsr7Request;
classFbBot
{
private $hubVerifyToken = null;
private $accessToken = null;
private $tokken = false;
protected $client = null;
function __construct()
    {
    }

public function setHubVerifyToken($value)
    {
        $this->hubVerifyToken = $value;
    }

public function setAccessToken($value)
    {
        $this->accessToken = $value;
    }

public function verifyTokken($hub_verify_token, $challange)
    {
try
        {
if ($hub_verify_token === $this->hubVerifyToken)
            {
return $challange;
            }
else
            {
throw new Exception("Tokken not verified");
            }
        }
catch(Exception $ex)
        {
return $ex->getMessage();
        }
    }

public function readMessage($input)
    {
try
        {
            $payloads = null;
            $senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
            $messageText = $input['entry'][0]['messaging'][0]['message']['text'];
            $postback = $input['entry'][0]['messaging'][0]['postback'];
            $loctitle = $input['entry'][0]['messaging'][0]['message']['attachments'][0]['title'];
if (!empty($postback))
            {
                $payloads = $input['entry'][0]['messaging'][0]['postback']['payload'];
return ['senderid' => $senderId, 'message' => $payloads];
            }
if (!empty($loctitle))
            {
                $payloads = $input['entry'][0]['messaging'][0]['postback']['payload'];
return ['senderid' => $senderId, 'message' => $messageText, 'location' => $loctitle];
            }
            // file_put_contents('abc.txt', $payloads);
            // var_dump($senderId,$messageText,$payload);
            //   $payload_txt = $input['entry'][0]['messaging'][0]['message']['quick_reply']['payload'];
return ['senderid' => $senderId, 'message' => $messageText];
        }
catch(Exception $ex)
        {
return $ex->getMessage();
        }
    }

public function sendMessage($input)
    {
try
        {
            $client = new GuzzleHttpClient();
            $url = "https://graph.facebook.com/v2.6/me/messages";
            $messageText = strtolower($input['message']);
            $senderId = $input['senderid'];
            $msgarray = explode(' ', $messageText);

            $response = null;
            $header = array(
                'content-type' => 'application/json'
            );
if (in_array('hi', $msgarray))
            {
                $answer = "Hello! how may I help you today?";
                $response = ['recipient' => ['id' => $senderId], 'message' => ['text' => $answer], 'access_token' => $this->accessToken];
            }
elseif (in_array('blog', $msgarray))
            {
                $answer = ["attachment" => ["type" => "template", "payload" => ["template_type" => "generic", "elements" => [["title" => "Migrate your symfony application", "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" => "Migrate your symfony application from Cpanel to Cloud.", "buttons" => [["type" => "web_url", "url" => "www.cloudways.com", "title" => "View Website"], ["type" => "postback", "title" => "Start Chatting", "payload" => "get started"]]]]]]];
                $response = ['recipient' => ['id' => $senderId], 'message' => $answer, 'access_token' => $this->accessToken];

                // file_put_contents('abc.txt', print_r($response));
            }
elseif (in_array('list', $msgarray))
            {
                $answer = ["attachment" => ["type" => "template", "payload" => ["template_type" => "list", "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://cloudways.com", "title" => "View Website"], ]], ["title" => "Multipurpose Theme Design and Versatility", "item_url" => "https://www.cloudways.com/blog/multipurpose-wordpress-theme-for-agency/", "image_url" => "https://www.cloudways.com/blog/wp-content/uploads/How-a-multipurpose-WordPress-theme-can-help-your-agency-Banner.jpg", "subtitle" => "We've got the right theme for everyone.", "buttons" => [["type" => "web_url", "url" => "https://cloudways.com", "title" => "View Website"], ]], ["title" => "Add Custom Discount in Magento 2", "item_url" => "https://www.cloudways.com/blog/add-custom-discount-magento-2/", "image_url" => "https://www.cloudways.com/blog/wp-content/uploads/M2-Custom-Discount-Banner.jpg", "subtitle" => "Learn adding magento 2 custom discounts.", "buttons" => [["type" => "web_url", "url" => "https://cloudways.com", "title" => "View Website"], ]]]]]];
                $response = ['recipient' => ['id' => $senderId], 'message' => $answer, 'access_token' => $this->accessToken];
            }
elseif ($messageText == 'get started')
            {
                $answer = ["text" => "Please share your location:", "quick_replies" => [["content_type" => "location", ]]];
                $response = ['recipient' => ['id' => $senderId], 'message' => $answer, 'access_token' => $this->accessToken];
            }
elseif (!empty($input['location']))
            {
                $answer = ["text" => 'great you are at' . $input['location'], ];
                $response = ['recipient' => ['id' => $senderId], 'message' => $answer, 'access_token' => $this->accessToken];
            }
elseif (!empty($messageText))
            {
                $answer = 'I can not Understand you ask me about blogs';
                $response = ['recipient' => ['id' => $senderId], 'message' => ['text' => $answer], 'access_token' => $this->accessToken];
            }
            $response = $client->post($url, ['query' => $response, 'headers' => $header]);

            // file_put_contents("payytorrrr.json", json_encode($response));
return true;
        }
catch(RequestException $e)
        {
            $response = json_decode($e->getResponse()->getBody(true)->getContents());
file_put_contents("payytorrrre.json", json_encode($response));
return $response;
        }
    }
}
?>

bot.php

<?php
include 'FbBot.php';

$tokken = $_REQUEST['hub_verify_token'];
$hubVerifyToken = 'your page name goes here’;
$challange = $_REQUEST['hub_challenge'];
$accessToken = 'your access token for your facebook page goes here';
$bot = new FbBot();
$bot->setHubVerifyToken($hubVerifyToken);
$bot->setaccessToken($accessToken);
$bot->verifyTokken($tokken, $challange);
$message = $bot->readMessage($input);
$botmessage = $bot->sendMessage($message);
?>

The result of tall this activity is that when I go to the Facebook page and say Hi, the bot will reply Hello.
You should now have a simple chatbot and a perfect setup for building your own, Developing a Facebook Messenger chat bot is a relatively straight forward process and much exciting. Using PHP and Facebook’s native tools, you could have a very functional chatbot up and running in no time.