Facebook Messenger Bot Tutorial

 

Facebook Messenger Bot Tutorial: Step-by-Step Instructions for Building a Basic Facebook Chat Bot




First there were desktop software products, then it all moved to the web. Then there were the email based products and even the SMS based ones. The latest craze for software interfaces is in messaging bots, and Facebook has the biggest chat platform by far.

facebook-chatbot

In this tutorial, I will show you how to create your own Facebook Messenger chat bot in python. We will be using Flask for the basic processing of web requests. 

 

 Let's start. 

 

 Step 1: Create a working webhook endpoint 

 We'll cover sending and receiving messages shortly, but first you need to have a working endpoint that returns a 200 response code and returns information in order to verify your bot with Facebook.

fb-chat-bot-github

cod 

 

 First, git clone the Github repository I configured for this project: 

 

 git clone git@github.com: hartleybrody / fbmessengerbot.git 

 

 pip install r requirements.txt 

 

 For more simplicity, we'll implement this on Heroku, but you can also deploy this Flask web app to any server you have access to. 

 

 Assuming the Heroku CLI Toolbelt is already installed, you can run 

 

 heroku create 

 

 to get the new configuration of the application. 

 

 We also use the Heroku convention for the Procfile to tell it how to run the application, but you can configure it on your server with something like nginx in front of one or more gunicorn processes. 

 

 To verify that Heroku can run things locally on your machine, start your local server with: 

 

 local heroku 

 

 Then in your browser visit http: // localhost: 5000 / and you should see "Hello world" .

localhost

Kill the local server with Ctrl + C. To deploy this endpoint on Heroku 

 

 git push heroku master 

 

 And to open it in your browser 

 

 heroku open 

 

 You now have a working webhook url "which you can use to configure your bot. Make sure you get the full URL https: //*.herokuapp.com from your browser as we'll need that in a moment. 

 

 Step 2: Create a Facebook page 

 If you don't already have one, you need to create a Facebook page. The Facebook Page is your bot's “identity”, including the name and image that appears when someone is chatting with them in Facebook Messenger. 

 

 If you're just creating a dummy template for your chatbot, it doesn't matter what you call it or how you categorize it. You can skip most of the configuration steps. 

 

 To communicate with your bot, people will need to go through your Page, which we'll see in a moment. 

 

 Step 3: Create a Facebook App 

 Go to the Facebook developer's quick start page and click “Skip and Create App ID” at the top right.Then create a new Facebook app for your bot and give your app a name, category, and contact email address.

create-fb-app

You’ll see your new App ID at the top right on the next page. Scroll down and click “Get Started” next to Messenger.

setup-fb-messenger-app

Step 4: Configure your 

 messaging application You are now in the Messenger settings of your Facebook application. You'll need to fill in a few things here for your chatbot to connect to the Heroku endpoint that we configured earlier. 

 

 Generate page access token 

 Using the page you created earlier (or an existing page), click on the authentication flow and you will receive an access token to the page for your application.

page-access-token-generation

Click the page access token to copy it to the clipboard. You will need to set it as an environment variable for your Heroku app. On the command line, in the same folder where you cloned the application, run: 

 

 heroku config: add PAGE_ACCESS_TOKEN = your_page_token_here 

 

 This token will be used to authenticate your requests every time you try to send a message or respond to someone. 

 

 Configure the Webhook 

 When you are going to configure your webhook, you will need some information:

setup-webhook-annotated

  • Callback URL The Heroku (or whatever) URL we defined earlier. 
  •  Verification Token A secret value that will be sent to your bot, to verify that the request comes from Facebook. Whatever value is set here, be sure to add it to your Heroku environment using the heroku configuration: add VERIFY_TOKEN = your_verification_token_here 
  •  Subscription fields This tells Facebook which email events you are interested in and which ones that you want your webhook to notify. If you are not sure, start with "messages", as you can change it later 
  •  After setting up your webhook, you will need to subscribe to the specific page for which you want to receive message notifications.

subscribe-to-page

Once you have the page access token and configured the webhook, be sure to set both the PAGE_ACCESS_TOKEN and VERIFY_TOKEN configuration values ​​in your Heroku app and you should be good to go!

Step #5: Start Chatting with Your Bot

Go to the Facebook Page you created and click on “Message” button, next to the “Like” button near the top of the page. This should open a message pane with your Page.

fb-page-chat-bot

Start sending your Page messages and the bot should reply!

To see what’s happening, check the logs of your application

heroku logs -t

You should see the POST data that Facebook is sending to your endpoint whenever a new message is sent to your Page’s bot.

Here’s an example JSON POST body that I got when I sent “does this work?” to my bot

        {
            "object":"page",
            "entry":[
                {
                    "messaging":[
                        {
                            "message":{
                                "text":"does this work?",
                                "seq":20,
                                "mid":"mid.1466015596912:7348aba4de4cfddf91"
                            },
                            "timestamp":1466015596919,
                            "sender":{
                                "id":"885721401551027"
                            },
                            "recipient":{
                                "id":"260317677677806"
                            }
                        }
                    ],
                    "time":1466015596947,
                    "id":"260317677677806"
                }
            ]
        }

By default, the bot should respond to everything with “got it, thanks!”

Step #6: Customize Your Bot’s Behavior

Here’s where we finally start to dive into the code.

There are really only two key parts to a messaging bot: receiving and sending messages

Receiving Messages
We handle incoming messages starting on line 24 inside app.py, in our webhook() view function.

First we load in the JSON POST data that’s sent to the webhook from Facebook whenever a new messaging event is triggered, usually when someone sends a message to our Page.

Then we loop over each entry – in my testing experience, there’s only ever been one entry sent to the webhook at a time.

Then we loop over each of the messaging events. Here, there may be several messaging events.

In step #4, we told Facebook what message types we want our webhook to be notified about. If you followed my advice, then our endpoint will only receive “message” events, but we could also receive delivery confirmations, optins and postbacks (more on those later). I left some code in place for detecting those other types of messaging events, but I don’t actually handle them.

The messaging event that will be most useful to most applications will be the “message” event, meaning someone has sent your Page a new message. I wrote some basic code to handle that event, parsing out the sender’s ID, and simply responding back to them.

Sending Messages
In order to send a simple text message, you only need two things:

  • the recipient's Facebook ID
  • the text of the message you want to send

I’ve created a simple send_message() function that automatically hits the Facebook API and sends those pieces of information.

Remember that the request is authenticated using the PAGE_ACCESS_TOKEN environment variable that we got back in step #4.

There are many more complex message types you can send, including messages with images and buttons. More information on those message types here.

Important to note is the ability to send a “postback” button in a message. These are essentially buttons that, when tapped by a user, send a postback messaging event to your webhook.

This essentially allows users to “press buttons” in your app, all while inside Facebook Messenger. You could use this for placing an order, confirming a request or lots of other things.

Whenever a user taps a postback button, your webhook is notified and can perform any sort of subsequent follow-up action necessary.

Step #7: Submit Your App to be Reviewed

While you’re testing your bot, only you and other Page admins can message with the bot directly. You have to go through a review process before your bot is open to the world, ready to chat with anyone.

Facebook seems to be very thorough in their review process, and with good reason. The code for a messaging bot runs on your own servers and could change at any time, without Facebook knowing.

They seem to be trying hard to make sure you’re a good actor, and not submitting a simple dummy app to get approved, only to change it to some spam bot down the road.

Obviously, they could still revoke your API access tokens if you did that, but they’d rather not have any abuse on the Messenger platform at all.

Go back to your Messenger App Settings page that we used in Step #4. Scroll down to “App Review for Messenger” and click “Request Permissions.”

chat-bot-approval

Request the permissions that you need, and then you’ll be taken to the “Review Status” page. This page requires a ton of information to ensure that developers aren’t going to abuse the platform.

It requires you to

  • check several boxes verifying that you've read their policies and guidelines
  • promise you won't engage in unsolicited, outbound messaging
  • describe how you're going to interact with users through your bot
  • provide a test user that the review team can use to interact with your bot
  • upload a screencast of you interacting with your bot via Messenger
  • have a privacy policy
  • verify that you're explaining the bot and setting expectations with users

On this page, you can also ask to be granted extra information about users, like their email or profile information.

Then it all goes to the Facebook review team to sign off and give you full access to the Messenger platform. More information about the approval process here.


Even if you don’t intend to go all the way through the review process, hopefully you’ve learned a thing or two about how to build a simple chat bot for Facebook Messenger.

facebook-messenger

Post a Comment

0 Comments