Charles Lee
    • 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
    # Lab 1 - Messenger Platform ## Step 0 - Set up Facebook Account > https://developers.facebook.com/docs/messenger-platform/getting-started/app-setup You'll need the first three things, which will be self-explanatory. > 1. Facebook Page: A Facebook Page will be used as the identity of your Messenger experience. When people chat with your app, they will see the Page name and the Page profile picture. To create a new Page, visit https://www.facebook.com/pages/create > 1. Facebook Developer Account: Your developer account is required to create new apps, which are the core of any Facebook integration. You can create a new developer account by going to the Facebook Developers website and clicking the 'Get Started' button. > 1. Facebook App: The Facebook app contains the settings for your Messenger experience, including access tokens. To create a new app, visit your app dashboard The fourth, we'll set up here. ## Step 1 - Setting up Vercel / Ngrok / HTTP Endpoint The first step is to just simply create and deploy something to the internet, that returns "Hello World". In the next step, we will make it respond correctly to Facebook's webhooks. We'll use two services here, [ngrok](www.ngrok.com) and [Vercel](www.vercel.com) to aid us in our mission. We'll start by installing Vercel - [detailed instructions here](https://vercel.com/download). `npm i -g vercel` 1. Create a new directory for your project, and inside the project, create a directory called `api` and a file called `hello.js`. `npm init -y` `mkdir api` `touch api/hello.js` As mentioned above, we'll simply return "Hello World". ``` export default (req, res) => { res.send("Hello World") } ``` This is using Vercel's serverless Node runtime, which is based off of Express / NodeJS. You can find [documentation here](https://vercel.com/docs/serverless-functions/introduction). If you aren't familiar with Express, don't worry, we won't use any advanced features of the framework here. But if you're curious [you can explore express documentation here](https://expressjs.com/en/starter/hello-world.html). Make sure you're in the root directory (not in `/api`): ![](https://i.imgur.com/nWCBHko.png) The basic settings should be fine: ![](https://i.imgur.com/Plq4C99.png) You can now go to the URL, in my case: https://msngr-hl-wrld.vercel.app/api/hello This is important to get a real address on the internet, because Facebook needs to be able to call our bot, so "localhost" won't be sufficient. We could stop here and keep uploading each time (`npx vercel` will deploy a new version) but this is pretty inconvenient, because it's quite slow to deploy each time. This may not seem like a big deal but over time this will be super frustrating and slow us down too much. Instead, let's develop on localhost. First step is to run vercel in development mode, by typing: ``` vercel dev ``` ![](https://i.imgur.com/Blm2ZpT.png) This starts at a local port, 3000. But now we need a way for Facebook to reach our local port, 3000. There are many options here, but let's start with a service called https://ngrok.com/. You'll want to sign up (don't worry, we'll stay on free tier) and https://dashboard.ngrok.com/get-started/setup. You'll download this, and then you'll unzip it - it's just an executable. After you download it, you just need to run: ``` ./ngrok http 3000 ``` This will give you an externally available address that _forwards_ to your local computer: ![](https://i.imgur.com/OxhIhMX.png) Verify that going to your ngrok URL successfully returns "Hello World". ## Step 2 - Setting the Verify webhook callback for Facebook Now we can go to the next steps in the Facebook setup: https://developers.facebook.com/docs/messenger-platform/getting-started/app-setup. Add Webhooks and Messenger to your Facebook App, and you'll be prompted for a callback URL. Use your ngrok from the previous step. **NOTE**: every time you restart ngrok, you'll need to update this URL because your ngrok url will change. (In production, you can point it at your Vercel production instance.) ![](https://i.imgur.com/Ylpx0rV.png) You can set the Verify Token to whatever you like. It is your personal password, and just remember it. Your callback url needs to come back with the right parameters - if you haven't coded your server correctly (which we haven't), when you try to put "Verify and Save", you'll get an error like this: ![](https://i.imgur.com/MypcZBx.png) or possibly like this: ![](https://i.imgur.com/4rhXjTO.png) We actually need to fix two things - our path, and our code. * Create a new file, let's call it `webhook.js`. That file looks like this: ``` module.exports = (req, res) => { if (req.method == "GET") { return verifyWebhook(req, res); } return handlePost(req, res); }; const verifyWebhook = ({ query }, res) => { // Your verify token. let VERIFY_TOKEN = "ToiYeuDevC"; // Parse the query params let mode = query["hub.mode"]; let token = query["hub.verify_token"]; let challenge = query["hub.challenge"]; // Checks if a token and mode is in the query string of the request if (mode && token) { // Checks the mode and token sent is correct if (mode === "subscribe" && token === VERIFY_TOKEN) { // Responds with the challenge token from the request console.log("WEBHOOK_VERIFIED"); res.status(200).send(challenge); } else { // Responds with '403 Forbidden' if verify tokens do not match res.status(403).send(); } } }; const handlePost = (req, res) => {}; ``` Note that I wrote `ToiYeuDevC`; that can be anything (but just make it the same as what you put in the Facebook dialog). Now change your url to `xxx.ngrok.io/api/webhook`, and then clicking "Verify and Save" will succeed and you've made it to the next step! Now click on the Messenger Tab and make sure to subscribe to `messages` and `messaging_postbacks`. ![](https://i.imgur.com/e9Tazik.png) ## Step 3: Receive Messages! The `verifyWebhook` code is just to let Facebook know that our server is indeed, the right one (so nobody else can take over our chatbot). The real magic happens in `handlePost`; that's where our subscriptions will trigger. Here, we'll share code that's a highly simplified version of the official facebook samples at https://github.com/fbsamples/messenger-platform-samples/tree/master/quick-start and https://github.com/fbsamples/original-coast-clothing. Please read those! But I think you'll find that CoderSchool's version is simpler ;). For `handlePost`: ``` const handlePost = (req, res) => { let body = req.body; // Checks if this is an event from a page subscription if (body.object === "page") { // Returns a '200 OK' response to all requests res.status(200).send("EVENT_RECEIVED"); // Iterates over each entry - there may be multiple if batched for ({messaging} of body.entry) { const { sender, message } = messaging[0]; console.log('sender', sender); console.log('message', message) } } }; ``` Now send your bot a message. You won't see a response, but you _will_ see something pop up in your local terminal (where you ran `vercel dev`). ![](https://i.imgur.com/k26kHkA.png) **Hooray**, messages are getting through to your program. ## Step 3: Respond with a Simple Text Message Now it's time to make your robot come to life. We'll need to reply to the `post` requests. To make things easier, let's install the popular `axios` library that makes HTTP requests easier: ``` npm install axios ``` Now we'll need At the top of webhook.js ``` const axios = require('axios'); ``` Now, in the handlePost, after the `console.log`s of the previous step: ``` const token = <INSERT TOKEN HERE> const handlePost = (req, res) => { let body = req.body; // Checks if this is an event from a page subscription if (body.object === "page") { // Returns a '200 OK' response to all requests res.status(200).send("EVENT_RECEIVED"); // Iterates over each entry - there may be multiple if batched for ({ messaging } of body.entry) { const { sender, message } = messaging[0]; console.log("sender", sender); console.log("message", message); if(!message) { return; } axios.post( `https://graph.facebook.com/v8.0/me/messages?access_token=${token}`, { recipient: { id: sender.id }, message: { text: `Hi! I've received your message ${message.text}` } } ); } } }; ``` You'll see we need a token. Where did this come from? Well, it comes from your "Page access tokens" on Facebook settings. ![](https://i.imgur.com/9xFFnO7.png) Click the generate token, and you'll get a token. Replace `<YOUR TOKEN HERE>` with your token. Make sure you keep this token secret (don't upload it into git). For full credit, you should set this as an environment variable - you [can consult vercel documentation here](https://vercel.com/docs/build-step#environment-variables) but we won't cover that here. Now we've set up our "parrot" bot, which will repeat what you say. ![](https://i.imgur.com/uy0Tyb3.png) ## Step 4: Send a Structured Message Plain text responses already open up a lot of possibilities, but here's one more: using what's called a "message template". Instead of simply replying with `{text: blahblah}` we can respond with a "structured" message, with buttons. Create a message: ``` const response = { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": [{ "title": "Do you love DevC?", "subtitle": "Tap a button to answer.", "image_url": 'https://www.techsignin.com/wp-content/uploads/2019/05/facebook-developer-circles-vietnam-innovation-challenge-22.jpg', "buttons": [ { "type": "postback", "title": "Yes!", "payload": "yes", }, { "type": "postback", "title": "No!", "payload": "no", } ], }] } } } ``` Now, from the previous step, replace sending ``` message: { text: `Hi! I've received your message ${message.text}` }, ``` with: ``` message: response, ``` and you should get something like this: ![](https://i.imgur.com/uDLmJR8.png) ## Step 5: Responding to the Button Click (postback) Note that responding to the message doesn't do anything. Buttons come in the form of `messaging_postbacks`, which we subscribed to earlier. To handle this, let's refactor our code to read the `postback` field, and separate our handling. ``` for ({ messaging } of body.entry) { const { sender, message, postback } = messaging[0]; console.log("sender", sender); console.log("message", message); console.log("postback", postback); if(postback) { return handlePostback(sender, postback); } if(message) { return handleMessage(sender, message); } ``` Copy the previous code into handleMessage. Let's now implement `handlePostback`. We will read the `payload` we specified above: ``` const handlePostback = (sender, postback) => { console.log('postback2', postback); if(postback.payload == "yes") { axios.post( `https://graph.facebook.com/v8.0/me/messages?access_token=${token}`, { recipient: { id: sender.id }, message: {text: "thanks! devc loves you too"}, } ); } if(postback.payload == "no") { axios.post( `https://graph.facebook.com/v8.0/me/messages?access_token=${token}`, { recipient: { id: sender.id }, message: {text: "it's okay, we can still be friends"}, } ); } } ``` ![](https://i.imgur.com/PZ9wwzm.png) **NOTE**: It looks like the user is just typing "Yes!" but it's from clicking on the button. Let's do a little refactoring on the `axios.post` and everything, so here's the cleaner final code: ``` const sendMsg = (recipient, message) => { axios.post( `https://graph.facebook.com/v8.0/me/messages?access_token=${token}`, { recipient, message, } ); }; const handlePostback = (sender, postback) => { if (postback.payload == "yes") { sendMsg(sender, { text: "thanks! devc loves you too!" }); } if (postback.payload == "no") { sendMsg(sender, { text: "it's okay we can still be friends!" }); } }; ```

    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 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