How to Create a Facebook Messenger Bot

April 18, 2016


Last Wednesday, Facebook released its hotly anticipated Facebook Messenger Bot API, allowing developers to, for the first time, create bots that can respond automatically to messages on Facebook. After a few days of trial and error and scrounging around the Facebook Bugs forum, I successfully got a bot up and running (and even picked up two hackathon prizes along the way)! This tutorial will lead you through the process of creating a messenger bot from start to finish, using the Facebook Messenger API, node.js, and ngrok.

1. Create a Facebook App and Facebook Page. As the first step in the Facebook Getting Started walkthrough explains, the name and profile picture of the page you create will be the name profile picture of your bot. It's alright if your page is unpublished and your app is in sandbox mode, but you will only be able to message app admins. Note that my Facebook Developer dashboard looks a little different from that in the screenshots of the official getting started guide, since those in the official guide seems to be from a newer version that hasn't been rolled out universally yet.

Create a new page Click "Create Page" to create a new Facebook page

To create a Facebook App, go to your app dashboard and click "Add a New App." From the dashboard of your new app, select "Messenger" on the left hand menu bar, then click the "Get Started" button. In the "Token Generation Section" at the top, select the page you just created. This will generate a "Page Access Token" that you will need later. messenger bot dashboard Dashboard for creating a Messenger Bot

2. Install messenger-bot, a node client for sending and receiving messages. First, make sure you have node.js >= 4.0.0 installed. Then, open up terminal, navigate to the directory you want to host your project in, and run: npm install messenger-bot. messenger-bot is an excellent, lightweight node client that will save you the hassle of setting up a node server from scratch. Even so, the code for messenger-bot is only 131 lines, making it extremely easy to understand and further customize, if you wish.

Create a new file called app.js and copy-paste in this code, originally taken and modified from messenger-bot's examples directory (Note: if you copy-paste directly from github, it won't work!).

'use strict'
const http = require('http')
const Bot = require('messenger-bot')

let bot = new Bot({
  token: 'PAGE_TOKEN',
  verify: 'VERIFY_TOKEN'
})

bot.on('error', (err) => {
  console.log(err.message)
})

bot.on('message', (payload, reply) => {
  let text = payload.message.text

  bot.getProfile(payload.sender.id, (err, profile) => {
    if (err) throw err

    reply({ text }, (err) => {
      if (err) throw err

      console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
    })
  })
})

http.createServer(bot.middleware()).listen(3000)

Go back to your Facebook app page and replace PAGE_TOKEN in your app.js file with your actual token. Feel free to leave VERIFY_TOKEN as is; if you change it, be sure to use the same token in step 4, when you set up your bot's webhook subscription. To run your server, type node app.js in your terminal. If there are no error messages, that means your server is working!

3. Use ngrok to set up a secure tunnel to your localhost server. ngrok is a tool that allows you to easily expose your localhost server to the outside world, and I'm including it in this tutorial because it's the fastest way to get your bot up and running*. If you don't already have ngrok installed, download it here. Then open up a new tab in terminal and run ./ngrok http 3000. You should see a screen displaying information about the tunnel; for this tutorial, you'll need the https url forwarding to your localhost, which in my case is "https://a1db04f5.ngrok.io". Copy this link to your clipboard, as Facebook will ask for it in the next step. ngrok server running screen ngrok server screen

*Of course, if you want your bot to be available 24/7 even when your computer's not running, you'll eventually want to deploy your server to a third-party hosting service like Heroku, AWS, or Azure. Just don't forget to update webhooks and run the curl command (steps 4 and 5) from that server as well!

4. Set up your Facebook Messenger webhooks. Return to your app page and click the "Setup Webhooks" button in the "Webhooks" section. Paste your ngrok url into the callback url, use "VERIFY_TOKEN" as your verify token (it's the default in your app.js file; feel free to change both if you wish), select all the subscription fields, and press "Verify and Save." Setup webhooks screen Setup webhooks screen

5. Subscribe your app to the page. This step is both super important and easy to miss! Open up your terminal and run

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

replacing <token> with your Page Access token (from the Token Generation section of your app's messenger dashboard).

6. Message your bot! Go to your bot's Facebook page, click "Message," and say hello! It should echo back whatever you send it.
MediatorBot demo Demo of starting a mediation session with MediatorBot!

And there you have it: your very own messenger bot! Try editing app.js and looking over messenger-bot's README documentation to customize your bot. At Copenhacks, Harrison and I built MediatorBot, a bot that mediates disputes between two parties (Github link). We've temporarily unpublished our Facebook page to give us a chance to refactor some code and make our logic more robust before releasing back into the wild.

If you're looking to develop an intelligent, adaptive bot, it might be worth looking into bot engines such as wit.ai and api.ai, which allow you to train your bot using examples and stories. Although these engines ended up being too limited and inconsistent for what we had in mind for MediatorBot, they could serve businesses with a more formulaic service-oriented goal well. Additionally, I'm sure both of these engines will continue to undergo rapid improvement, as they both have robust development teams behind them (wit.ai is reportedly developing Facebook Messenger's M, a personal bot assistant that's currently only available in the San Francisco Bay Area).

Best of luck with your bots, thanks for reading, and feel free to post your questions, comments and feedback below!


   FACEBOOK    MESSENGER    BOT    HACKATHON    TUTORIAL    TECH