DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

Related

  • Unleashing the Power of GPT: A Comprehensive Guide To Implementing OpenAI’s GPT in ReactJS
  • How To Use IBM App Connect To Build Flows
  • Effective Code Reviews For Remote Teams
  • DocRaptor vs. WeasyPrint: A PDF Export Showdown

Trending

  • DZone's Article Submission Guidelines
  • From Monolith to Containers: Real-World Migration Blueprint
  • How You Can Use Few-Shot Learning In LLM Prompting To Improve Its Performance
  • Kung Fu Code: Master Shifu Teaches Strategy Pattern to Po – The Functional Way
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Create Facebook Messenger Bot With Structured Messages in PHP

Create Facebook Messenger Bot With Structured Messages in PHP

In this article, learn how to create a simple Facebook chatbot that can carry out effective conversation with your users.

By 
shahroze nawaz user avatar
shahroze nawaz
·
Nov. 22, 16 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
30.5K Views

Join the DZone community and get the full member experience.

Join For Free

Chatbots are the latest sensation in social media communication channels. These automated chat systems are especially employed to receive visitors on social media chats and provide basic information to the visitors. 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 reduce 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 CSRs.

In this article, I will create a simple Facebook chatbot that can carry out effective conversation with 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.

cloudways school facebook page

Create a Facebook Application

The second step is the creation of a 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.

facebook app

The app will appear in the developer dashboard. Open the application and add messenger platform to the app.

Image title

Next, add the webhook that connects the app with the website. To add the webhook, generate the page access token.

Image title

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.

Image title

Create Bot.php File

The Facebook app is now active. I will now create the file for the bot.

<?php
// 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 $senderIdand 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 to the public_html folder using Filezilla.

At this point, when you say hi on the facebook page, you will get hello in reply.

Image title

Send Structured Messages in Bot

In addition to Hello, in reply to Hi, Facebook Messenger also provides several interesting template messages that cover the latest news, images, 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 to you some of the templates here to kickstart your first 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:

Image title

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

Image title

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
];}

Button Messages

Facebook Messenger could also send actionable buttons as a response. For example, if the user asks for more the response would be:

Image title

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 set up 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.

If you have a question about the code or would like to add to the discussion, leave a comment below.

Facebook Messenger PHP app Template Chatbot Webhook code style

Opinions expressed by DZone contributors are their own.

Related

  • Unleashing the Power of GPT: A Comprehensive Guide To Implementing OpenAI’s GPT in ReactJS
  • How To Use IBM App Connect To Build Flows
  • Effective Code Reviews For Remote Teams
  • DocRaptor vs. WeasyPrint: A PDF Export Showdown

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: