# Messenger Bot: Echo Bot 💬🤖 ###### tags: `MessengerBot` ### Open Source @ UCSD --- In this tutorial, we will be using Glitch to create a simple Messenger Bot, the Echo Bot! Some tools that will be utilized: * [Flask](http://flask.pocoo.org/docs/1.0/) * A "microframework" that allows you to make web services and applications * [PyMessager](https://github.com/eceusc/PyMessager) * Python Wrapper for the Facebook Messenger API * [Glitch](https://glitch.com/) * Offers hassle-free web hosting --- ## The Big Picture ![](http://res.cloudinary.com/dyd911kmh/image/upload/f_auto,q_auto:best/v1519812384/chatbot_2x_gj3ga0.png =500x) 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: 1. Set up hosting and deployment (using Glitch) 2. Create a server which listens to messages from Facebook (using flask) 3. Define a function for sending messages back to users (using requests and PyMessager) Let's dive right in! 👉 --- ## Step 1: Make a Facebook App and Facebook Page Create a Facebook App for your bot: - Go to https://developers.facebook.com/ - Log in (top right corner) - Follow instructions to create app (make sure to choose the first option for App Type) We also need to create a Facebook Page for the app you just created: https://www.facebook.com/pages/creation/ --- ## Step 2: Environment Setup Click this button to remix the Messenger Bot template on Glitch. Make sure you're signed into Glitch to save your progress. <!-- Remix Button --> <a href="https://glitch.com/edit/#!/remix/messenger-bot-template"> <img src="https://cdn.glitch.com/2bdfb3f8-05ef-4035-a06e-2043962a3a13%2Fremix%402x.png?1513093958726" alt="remix this" height="50"> </a> ---- 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. ![](https://i.imgur.com/Qsh1Bwn.png =250x) ``` pip3 install --user flask requests ``` --- ## Step 3: Set up Webhooks Webhook - a way for an app to provide other applications with real-time information Go to Dashboard on your Facebook App (top left) ![](https://i.imgur.com/f6BeA9K.png =130x130) Scroll down until you see "Add a Product" section Look for Messenger ![](https://i.imgur.com/YPQzVVb.png =200x150) ---- Scroll to the Webhook section and select Set Up. Select **Page** from the dropdown. ![](https://i.imgur.com/oKDMAM4.png =500x) 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!! :tada: 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" ![](https://i.imgur.com/DopyRyW.png) 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: ![](https://i.imgur.com/j347Wxl.png=500px) 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") ![](https://i.imgur.com/iQ7ht7O.png) Tick all of the boxes EXCEPT 'message_echoes'. We're all set! :+1: Check to see you have completed all the steps above. ---- 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 :white_check_mark: : (don't worry too much about the details ) This just ensures that your verification token matches with your Facebook app's verification token. ``` python @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 ``` --- ## Step 4: Receive messages from Facebook Now that we're all set up, we should be able to receive information! In the webhook() method in server.py: ``` python @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 👇 ---- ``` python @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 ![](https://i.imgur.com/MXsgkPX.png =150x150) Now, we can message our bot and test it out! Click View as Visitor and you should see the option to Send Message. ![](https://i.imgur.com/e1RAkuk.png) ![](https://i.imgur.com/6UT9NNq.png) ---- Once you send a message, take a look at your Logs. Something like this should be printed out. ![](https://i.imgur.com/3w4Ilqs.png) ---- If you have the weird u', add this line after `data = request.get_json()`. If you don't, ignore this. ``` python data = dict([(str(k), v) for k, v in data.items()]) ``` --- ## Step 5: Let's Reply! :speech_balloon: 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: 1. Who the sender is (who we should reply to) 2. What the sender said (what we should send back) Those information are provided in our "data" variable! In my example here, I messaged my bot 'HELLO' and receive this back: ![](https://i.imgur.com/068LtMs.png) 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](https://www.pluralsight.com/guides/manipulating-lists-dictionaries-python). First, to make sure that the message we received is a page subscription, do: ``` python 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). ![](https://i.imgur.com/kM5e06x.png) (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 :+1: ): ``` python 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 :smile:) **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](https://github.com/eceusc/PyMessager/blob/master/pymessager/message.py), 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: ``` python 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 ``` python 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. ![](https://i.imgur.com/Fi73Swg.png) [Source code](https://github.com/enginebai/PyMessager/blob/master/pymessager/message.py#L148-L150) 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 :bug: Check your console log to see if there are any errors. Here's my code as a reference if you need: [Echo Bot Example](https://glitch.com/edit/#!/chau-messenger-bot?path=server.py) --- 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". [Instructions to do that here](https://www.nukesuite.com/support/social-applications/adding-someone-as-a-tester/) --- ## Congrats! You made your first Messenger Bot! 🤖💬🎉😎🚀