项目作者: jw84

项目描述 :
Facebook Messenger bot 15分钟教程
高级语言: JavaScript
项目地址: git://github.com/jw84/messenger-bot-tutorial.git
创建时间: 2016-04-14T01:59:44Z
项目社区:https://github.com/jw84/messenger-bot-tutorial

开源协议:MIT License

下载


🤖 Creating your own Facebook Messenger bot

Alt text

Facebook recently opened up their Messenger platform to enable bots to converse with users through Facebook Apps and on Facebook Pages.

You can read the documentation the Messenger team prepared but it’s not very clear for beginners and intermediate hackers.

So instead here is how to create your own messenger bot in 15 minutes.

🙌 Get set

Messenger bots uses a web server to process messages it receives or to figure out what messages to send. You also need to have the bot be authenticated to speak with the web server and the bot approved by Facebook to speak with the public.

You can also skip the whole thing by git cloning this repository, running npm install, and run a server somewhere.

Build the server

  1. Install the Heroku toolbelt from here https://toolbelt.heroku.com to launch, stop and monitor instances. Sign up for free at https://www.heroku.com if you don’t have an account yet.

  2. Install Node from here https://nodejs.org, this will be the server environment. Then open up Terminal or Command Line Prompt and make sure you’ve got the very most recent version of npm by installing it again:

    1. sudo npm install npm -g
  3. Create a new folder somewhere and let’s create a new Node project. Hit Enter to accept the defaults.

    1. npm init
  4. Install the additional Node dependencies. Express is for the server, request is for sending out messages and body-parser is to process messages.

    1. npm install express request body-parser --save
  5. Create an index.js file in the folder and copy this into it. We will start by authenticating the bot.

    1. 'use strict'
    2. const express = require('express')
    3. const bodyParser = require('body-parser')
    4. const request = require('request')
    5. const app = express()
    6. app.set('port', (process.env.PORT || 5000))
    7. // Process application/x-www-form-urlencoded
    8. app.use(bodyParser.urlencoded({extended: false}))
    9. // Process application/json
    10. app.use(bodyParser.json())
    11. // Index route
    12. app.get('/', function (req, res) {
    13. res.send('Hello world, I am a chat bot')
    14. })
    15. // for Facebook verification
    16. app.get('/webhook/', function (req, res) {
    17. if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
    18. res.send(req.query['hub.challenge'])
    19. }
    20. res.send('Error, wrong token')
    21. })
    22. // Spin up the server
    23. app.listen(app.get('port'), function() {
    24. console.log('running on port', app.get('port'))
    25. })
  6. Make a file called Procfile and copy this. This is so Heroku can know what file to run.

    1. web: node index.js
  7. Commit all the code with Git then create a new Heroku instance and push the code to the cloud.

    1. git init
    2. git add .
    3. git commit --message "hello world"
    4. heroku create
    5. git push heroku master

Setup the Facebook App

  1. Create or configure a Facebook App or Page here https://developers.facebook.com/apps/

    Alt text

  2. In the app go to Messenger tab then click Setup Webhook. Here you will put in the URL of your Heroku server and a token. Make sure to check all the subscription fields.

    Alt text

  3. Get a Page Access Token and save this somewhere.

    Alt text

  4. Go back to Terminal and type in this command to trigger the Facebook app to send messages. Remember to use the token you requested earlier.

    1. curl -X POST "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=<PAGE_ACCESS_TOKEN>"

Setup the bot

Now that Facebook and Heroku can talk to each other we can code out the bot.

  1. Add an API endpoint to index.js to process messages. Remember to also include the token we got earlier.

    1. app.post('/webhook/', function (req, res) {
    2. let messaging_events = req.body.entry[0].messaging
    3. for (let i = 0; i < messaging_events.length; i++) {
    4. let event = req.body.entry[0].messaging[i]
    5. let sender = event.sender.id
    6. if (event.message && event.message.text) {
    7. let text = event.message.text
    8. sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200))
    9. }
    10. }
    11. res.sendStatus(200)
    12. })
    13. const token = "<PAGE_ACCESS_TOKEN>"

    Optional, but recommended: keep your app secrets out of version control!

    • On Heroku, its easy to create dynamic runtime variables (known as config vars). This can be done in the Heroku dashboard UI for your app or from the command line:
      Alt text

      1. heroku config:set FB_PAGE_ACCESS_TOKEN=fake-access-token-dhsa09uji4mlkasdfsd
      2. # view
      3. heroku config
    • For local development: create an environmental variable in your current session or add to your shell config file.

      1. # create env variable for current shell session
      2. export FB_PAGE_ACCESS_TOKEN=fake-access-token-dhsa09uji4mlkasdfsd
      3. # alternatively, you can add this line to your shell config
      4. # export FB_PAGE_ACCESS_TOKEN=fake-access-token-dhsa09uji4mlkasdfsd
      5. echo $FB_PAGE_ACCESS_TOKEN
    • config var access at runtime

      1. const token = process.env.FB_PAGE_ACCESS_TOKEN
  1. Add a function to echo back messages

    1. function sendTextMessage(sender, text) {
    2. let messageData = { text:text }
    3. request({
    4. url: 'https://graph.facebook.com/v2.6/me/messages',
    5. qs: {access_token:token},
    6. method: 'POST',
    7. json: {
    8. recipient: {id:sender},
    9. message: messageData,
    10. }
    11. }, function(error, response, body) {
    12. if (error) {
    13. console.log('Error sending messages: ', error)
    14. } else if (response.body.error) {
    15. console.log('Error: ', response.body.error)
    16. }
    17. })
    18. }
  2. Commit the code again and push to Heroku

    1. git add .
    2. git commit -m 'updated the bot to speak'
    3. git push heroku master
  3. Go to the Facebook Page and click on Message to start chatting!

Alt text

⚙ Customize what the bot says

Send a Structured Message

Facebook Messenger can send messages structured as cards or buttons.

Alt text

  1. Copy the code below to index.js to send a test message back as two cards.

    1. function sendGenericMessage(sender) {
    2. let messageData = {
    3. "attachment": {
    4. "type": "template",
    5. "payload": {
    6. "template_type": "generic",
    7. "elements": [{
    8. "title": "First card",
    9. "subtitle": "Element #1 of an hscroll",
    10. "image_url": "http://messengerdemo.parseapp.com/img/rift.png",
    11. "buttons": [{
    12. "type": "web_url",
    13. "url": "https://www.messenger.com",
    14. "title": "web url"
    15. }, {
    16. "type": "postback",
    17. "title": "Postback",
    18. "payload": "Payload for first element in a generic bubble",
    19. }],
    20. }, {
    21. "title": "Second card",
    22. "subtitle": "Element #2 of an hscroll",
    23. "image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
    24. "buttons": [{
    25. "type": "postback",
    26. "title": "Postback",
    27. "payload": "Payload for second element in a generic bubble",
    28. }],
    29. }]
    30. }
    31. }
    32. }
    33. request({
    34. url: 'https://graph.facebook.com/v2.6/me/messages',
    35. qs: {access_token:token},
    36. method: 'POST',
    37. json: {
    38. recipient: {id:sender},
    39. message: messageData,
    40. }
    41. }, function(error, response, body) {
    42. if (error) {
    43. console.log('Error sending messages: ', error)
    44. } else if (response.body.error) {
    45. console.log('Error: ', response.body.error)
    46. }
    47. })
    48. }
  2. Update the webhook API to look for special messages to trigger the cards

    1. app.post('/webhook/', function (req, res) {
    2. let messaging_events = req.body.entry[0].messaging
    3. for (let i = 0; i < messaging_events.length; i++) {
    4. let event = req.body.entry[0].messaging[i]
    5. let sender = event.sender.id
    6. if (event.message && event.message.text) {
    7. let text = event.message.text
    8. if (text === 'Generic') {
    9. sendGenericMessage(sender)
    10. continue
    11. }
    12. sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200))
    13. }
    14. }
    15. res.sendStatus(200)
    16. })

Act on what the user messages

What happens when the user clicks on a message button or card though? Let’s update the webhook API one more time to send back a postback function.

  1. app.post('/webhook/', function (req, res) {
  2. let messaging_events = req.body.entry[0].messaging
  3. for (let i = 0; i < messaging_events.length; i++) {
  4. let event = req.body.entry[0].messaging[i]
  5. let sender = event.sender.id
  6. if (event.message && event.message.text) {
  7. let text = event.message.text
  8. if (text === 'Generic') {
  9. sendGenericMessage(sender)
  10. continue
  11. }
  12. sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200))
  13. }
  14. if (event.postback) {
  15. let text = JSON.stringify(event.postback)
  16. sendTextMessage(sender, "Postback received: "+text.substring(0, 200), token)
  17. continue
  18. }
  19. }
  20. res.sendStatus(200)
  21. })

Git add, commit, and push to Heroku again.

Now when you chat with the bot and type ‘Generic’ you can see this.

Alt text

📡 How to share your bot

Add a chat button to your webpage

Go here to learn how to add a chat button your page.

You can use https://m.me/ to have someone start a chat.

💡 What’s next?

You can learn how to get your bot approved for public use here.

You can also connect an AI brain to your bot here

Read about all things chat bots with the ChatBots Magazine here

You can also design Messenger bots in Sketch with the Bots UI Kit!

How I can help

I build and design bots all day. Email me for help!