Facebook now has the Messenger Platform which allows us to build bots which can accept messages from users and respond to them. In this tutorial, we shall see how we can build a bot and add it to one of our pages so that the users can interact with the bot by sending messages to the page.
To get started, we have three requirements to fulfill:
- We need a Facebook Page
- We need a Facebook App
- We need a webhook / callback URL to accept incoming messages
I am assuming you already have a Facebook Page. If you don’t, go ahead and create one. It’s very simple.
Creating and Configuring The Facebook App
(1) First, we create a generic facebook app. We need to provide the name, namespace, category, contact email. Simple and straightforward. This is how it looks for me:
.
(2) Now we have to browse the “Add Product” section and add “Messenger”.
(3) Generate access token for a Page you manage. A popup will open asking you for permissions. Grant the permission and you will soon see the access token for that page. Please take a note of this token. We shall use it later send messages to the users on behalf of the page.
Next, click the “Webhooks” section.
(4) Before we can setup a webhook, we need to setup an URL which is publicly accessible on the internet. The URL must have SSL (that is it needs to be https). To meet this requirement and set up a local dev environment, we setup a quick flask app on our local machine.
Install Flask from PyPi using pip
:
1 |
pip install Flask |
Facebook will send a GET
request to the callback URL we provide. The request will contain a custom secret we can add (while setting up the webhook) and a challenge code from Facebook. They expect us to output the challenge code to verify ourselves. To do so, we write a quick GET
handler using Flask.
1 2 3 4 5 6 7 8 9 10 11 12 |
## Filename: server.py from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET']) def handle_verification(): return request.args['hub.challenge'] if __name__ == '__main__': app.run(debug=True) |
We run the local server using python server.py
. The app will launch at port 5000 by default. Next we use ngrok
to expose the server to the internet. ngrok is a fantastic tool and you should seriously give it a try for running and debugging webhooks/callback urls on your local machine.
1 |
ngrok http 5000 |
With that command, we will get an address like https://ac433506.ngrok.io
. Copy that url and paste it in the Webhook setup popup. Checkmark the events we’re interested in. I check them all. Then we input a secret, which our code doesn’t care about much. So just add anything you like. The popup now looks like this:
Click “Verify and Save”. If the verification succeeds, the popup will close and you will be back to the previous screen.
Select a Page again and click “Subscribe”. Now our app should be added to the page we selected. Please note, if we haven’t generated an access token for that page in the earlier step, the subscription will fail. So make sure we have an access token generated for that page.
Handling Messages
Now every time someone sends a message to the “Masnun” page, Facebook will make a POST
request to our callback url. So we need to write a POST
handler for that url. We also need respond back to the user using the Graph API. For that we would need to use the awesome requests
module.
1 |
pip install requests |
Here’s the code for accepting incoming messages and sending them a reply:
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 |
from flask import Flask, request import requests app = Flask(__name__) ACCESS_TOKEN = "EAAP9MMaGh1cBAHS7jZCnuQgm2GWx5grLraIElFlWlIw2r3Afb34m2c2rP0xdkkkKEeiBOykGINAP0tScwmL5NNBJQN9ayPCuq13syvWocmbYZA7BXL86FsZCyZBxTmkgYYp8MDulLc1Tx70FGdU5ebQZAJV28nMkZD" def reply(user_id, msg): data = { "recipient": {"id": user_id}, "message": {"text": msg} } resp = requests.post("https://graph.facebook.com/v2.6/me/messages?access_token=" + ACCESS_TOKEN, json=data) print(resp.content) @app.route('/', methods=['POST']) def handle_incoming_messages(): data = request.json sender = data['entry'][0]['messaging'][0]['sender']['id'] message = data['entry'][0]['messaging'][0]['message']['text'] reply(sender, message[::-1]) return "ok" if __name__ == '__main__': app.run(debug=True) |
The code here accepts a message, retrieves the user id and the message content. It reverses the message and sends back to the user. For this we use the ACCESS_TOKEN
we generated before hand. The incoming request must be responded with a status code 200 to acknowledge the message. Otherwise Facebook will try the message a few more times and then disable the webhook. So sending a http status code 200 is important. We just output “ok” to do so.
You can now send a message to your page and see if it responds correctly. Check out Flask’s and ngrok’s logs to debug any issues you might face.
You can download the sample code from here: https://github.com/masnun/fb-bot