mot.la

How to Build a Facebook Messenger Bot with Ruby on Rails

The other day I learned how to build a Facebook Messenger Bot using Ruby on Rails. Here is how to do it.

What you'll need:


Configure Rails

Begin by generating your rails application.

$ rails new your-app --database postgresql

Next, we need a way to accept messages. Hypersolo's facebook-messenger gem is a strong choice for this. Add it to your Gemfile. Also add dotenv-rails. We'll need it later.

# Gemfile
...
gem 'dotenv-rails', :groups => [:development, :test]
gem 'facebook-messenger'
...

Install it.

$ bundle install

Then follow the instructions here. When you are done, proceed to the next step.


Configure Facebook App

1. Page

Create a facebook page. You'll need this so you can subscribe your messenger app to your facebook page.

2. App

Create the application at developers.facebook.com.

3. Webhook

Create a new webhook for the app you previously created.

It will ask you for a domain and a verification token of your choosing. Choose whatever you want for the verification token. But the domain will have to match up with your ngrok server.

Note: Don't subscribe to message_echoes

3.1 ngrok

Start your Rails server.

$ rails server

Start your ngrok tunnel server.

$ ngrok http 3000

Ngrok creates a unique URL mapping to your local Rails server. It will look something like this: https://e4a6dbae.ngrok.io

Test it out by visiting http://REPLACE.ngrok.io/bot. You should see Error; wrong verify token, just as you would if you visited http://localhost:3000.

Great! Now paste that url into the Webhook form.

Lastly, subscribe the webhook to the page you created previously. The location for this is hard to find and moves locations. Look for the text "Select a page to subscribe your webhook to the page events" on the Messenger > Settings page under your Facebook developers account.

You are almost done.


Configure Token ENVs

Create a .env file in the root of your Rails project.

$ touch .env

Configure it using the VERIFY_TOKEN and ACCESS_TOKEN. You created these when setting up your Facebook page and messenger application.

# .env
VERIFY_TOKEN=verify
ACCESS_TOKEN=EAADsuzGN4pMBAHlSKyqnZBEZBKo39ZEAADsuzGN4pMBAHlSKyqnZBEZBKo39Z

Restart your Rails server.

$ rails server

Test it out

Visit the facebook page you created. Scroll about halfway down and look in the right hand sidebar. You will see a Message Now link.

Click Message Now and test out your app! You should see your bot reply with "Hello, human!".

Debugging: If you are not getting a response from your bot, double check that your webhook URL matches your ngrok server URL. Also, make sure your ngrok server is still running.