Chau Vu
  • NEW!
    NEW!  Connect Ideas Across Notes
    Save time and share insights. With Paragraph Citation, you can quote others’ work with source info built in. If someone cites your note, you’ll see a card showing where it’s used—bringing notes closer together.
    Got it
      • Create new note
      • Create a note from template
        • Sharing URL Link copied
        • /edit
        • View mode
          • Edit mode
          • View mode
          • Book mode
          • Slide mode
          Edit mode View mode Book mode Slide mode
        • Customize slides
        • Note Permission
        • Read
          • Only me
          • Signed-in users
          • Everyone
          Only me Signed-in users Everyone
        • Write
          • Only me
          • Signed-in users
          • Everyone
          Only me Signed-in users Everyone
        • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invite by email
        Invitee

        This note has no invitees

      • Publish Note

        Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

        Your note will be visible on your profile and discoverable by anyone.
        Your note is now live.
        This note is visible on your profile and discoverable online.
        Everyone on the web can find and read all notes of this public team.

        Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Explore these features while you wait
        Complete general settings
        Bookmark and like published notes
        Write a few more notes
        Complete general settings
        Write a few more notes
        See published notes
        Unpublish note
        Please check the box to agree to the Community Guidelines.
        View profile
      • Commenting
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Suggest edit
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
      • Emoji Reply
      • Enable
      • Versions and GitHub Sync
      • Note settings
      • Note Insights New
      • Engagement control
      • Make a copy
      • Transfer ownership
      • Delete this note
      • Save as template
      • Insert from template
      • Import from
        • Dropbox
        • Google Drive
        • Gist
        • Clipboard
      • Export to
        • Dropbox
        • Google Drive
        • Gist
      • Download
        • Markdown
        • HTML
        • Raw HTML
    Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
    Create Create new note Create a note from template
    Menu
    Options
    Engagement control Make a copy Transfer ownership Delete this note
    Import from
    Dropbox Google Drive Gist Clipboard
    Export to
    Dropbox Google Drive Gist
    Download
    Markdown HTML Raw HTML
    Back
    Sharing URL Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    Customize slides
    Note Permission
    Read
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Write
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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! 🤖💬🎉😎🚀

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully