MessengerBot
In this tutorial, we will be using Glitch to create a simple Messenger Bot, the Echo Bot!
Some tools that will be utilized:
Instead of ngrok (like shown in the image above), we'll replace it with Glitch to host our Flask app.
There are 3 main stages of creating a Messenger Bot:
Let's dive right in! ๐
Create a Facebook App for your bot:
We also need to create a Facebook Page for the app you just created:
https://www.facebook.com/pages/creation/
Click this button to remix the Messenger Bot template on Glitch. Make sure you're signed into Glitch to save your progress.
Set up your working environment by installing flask, requests, and pymessenger. These are libraries that we will be using.
Open the console (look for Tools at the bottom left corner) and enter the pip commands below.
pip3 install --user flask requests
Webhook - a way for an app to provide other applications with real-time information
Go to Dashboard on your Facebook App (top left)
Scroll to the Webhook section and select Set Up. Select Page from the dropdown.
Here, Facebook asks for a Callback URL. A callback URL is basically a URL for Facebook to deliver requests to in order to communicate with our bot.
Where do we get that? From Glitch!!
Glitch will hosts your Flask App using its server and provide you a unique URL.
On the top left corner, press "Show" and select "In a New Window"
You should see "Yeehaw ๐ค "! The URL of this page is the Callback URL we're looking for. Copy and paste it in the Callback URL field.
Next, we need to provide Facebook a Verify Token. The Verify Token is a string you make up (kind of like your bot's password) - it's just used to make sure it is your Facebook app that your server is interacting with. Put that in the VERFIFICATION_TOKEN variable in the .env file.
The .env file contains all confidential information that you might not want other people to access! We can define any variable in .env and access it in our code with os.environ.get("<VARIABLE_NAME>")
To summarize:
Use your Glitch's URL as the Callback URL
Verify Token should be your VERIFICATION_TOKEN (in .env)
Go up to the Access Tokens section, should look something like this:
Select "Add or Remove Pages" and select the page you made earlier. Once your app is linked, press "Generate Token".
Paste the Token into the PAGE_ACCESS_TOKEN variable in .env
Scroll back down to the Webhook section and subscribe the webhook to your Facebook Page (click "Add Subscriptions")
Tick all of the boxes EXCEPT 'message_echoes'.
We're all set!
To explain the existing code in server.py a little bit:
Import tools & dependencies
import os, sys
from dotenv import load_dotenv
from flask import Flask, request
from pymessager import Messager
from pprint import pprint
Make the Flask app
app = Flask(__name__)
Run the app
if __name__ == "__main__":
app.run()
Webhook Validation
@app.route('/', methods=['GET'])
# Webhook validation
def verify():
if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
# Check if the verification token matches
if not request.args.get("hub.verify_token") == VERIFICATION_TOKEN:
return "Verification token mismatch", 403
return request.args["hub.challenge"], 200
return "Yeehaw ๐ค ", 200
Now that we're all set up, we should be able to receive information!
In the webhook() method in server.py:
@app.route('/', methods=['POST'])
def webhook():
# TODO
pass
Delete the line with 'pass'. That's just a placeholder.
When Facebook sends your bot a POST request to indicate that a message was received, you can retrieve that information as a JSON object with request.get_json(). Use pprint to display the data to the console.
Make sure to return 200
to let Facebook know that we received the POST request. Else, Facebook will keep prompting webhook() until it receives the 200 code.
It'll look something like this ๐
@app.route('/', methods=['POST'])
def webhook():
data = request.get_json()
pprint(data)
return 'OK', 200
Open your Console Logs. At the bottom left, press Tools -> Logs
Now, we can message our bot and test it out! Click View as Visitor and you should see the option to Send Message.
Once you send a message, take a look at your Logs. Something like this should be printed out.
If you have the weird u', add this line after data = request.get_json()
. If you don't, ignore this.
data = dict([(str(k), v) for k, v in data.items()])
Our goal is to create a simple Echo Bot, and an Echo Bot's only job is to reply back whatever the user messaged it.
To do so, we need to know:
Those information are provided in our "data" variable!
In my example here, I messaged my bot 'HELLO' and receive this back:
The underlined portions are what we need! To get to those, we'll need to traverse through this complicated JSON object.
Wait, that looks familiarโฆ
That's right, this is basically just a dictionary with nested lists and strings! If you're unfamiliar with Python dictionaries and lists, this might help.
First, to make sure that the message we received is a page subscription, do:
if data['object'] == 'page':
Now, to get to the sender's id, we have to get the key 'messaging' within 'entry' (1), get 'sender' from 'messaging' (2), and finally get the value of 'id' (3).
(1)
Be careful, if you do data['entry'], the value is actually a list. To get to the inner dictionary, you can either use access the first element of the list like data['entry'][0], OR use a for loop to assign it to a variable like so:
for entry in data['entry']:
(2)
Again, the value inside of 'messaging' is another list, we can do the same thing as above:
for messaging_event in entry['messaging']:
(3)
Within 'messaging', what we want is the sender's id. Note that 'sender' is a key within 'messaging', and 'id' is a key within 'sender'.
To access the value of the id, we can do:
sender_id = messaging_event['sender']['id']
My version looks like this so far (yours might be different but as long as you get the right value
if data['object'] == 'page':
for entry in data['entry']:
for messaging_event in entry['messaging']:
# Retrieve the sender id
sender_id = messaging_event['sender']['id']
Try print(sender_id) to check if you're getting the correct value.
Awesome, we're almost done. Now the second thing we need is the message itself.
We can check if the user sent a message, and if what they sent is text by doing this:
if messaging_event.get('message'):
if messaging_event['message'].get('text'):
This is just to make sure that what we get is text because if the user sends something like an attachment or a picture, we won't be able to echo that (actually you can but that's for a future workshop
Challenge:
Retrieve the sender's message and assign it to a variable called 'response'.
# Retrieve the message
response = #TODO
Refer to how we got the sender_id for some guidance. Still stuck? Ask for help on Discord (#ss-help channel or chau#7639)!
Now we have everything we need to message the sender back! The sender's id is stored in the variable 'sender_id' and the message we want to send back is stored in 'response'.
We can use pymessager to make the API easier to use.
If you take a look at the source code, PyMessager has different classes to perform different actions.
In our case, we'll be using the Messager class for the Echo Bot.
First, import the class at the top:
from PyMessager.pymessager.message import Messager
Make a Messager object to use the messenging methods in the library. Note that the constructor (__init__ method) requires an access token
messager = Messager(PAGE_ACCESS_TOKEN)
Now we can just tell the bot to send the message to the sender's id. We can do that with the send_text method declared in the Pymessager library.
Note that it takes in user_id and text as the arguments, which is our sender_id and response.
# Echo the message
messager.send_text(sender_id, response)
And that's it, your bot is ready! Try messaging it and it should echo back!
If it doesn't work, it's just a matter of debugging
Check your console log to see if there are any errors.
Here's my code as a reference if you need:
Echo Bot Example
Quick Note: Your Bot is not approved by Facebook yet, so it is not publically available for other people to message it.
If you want your friends to be able to message your bot, you have to add them as "Testers".