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:
Begin by generating your rails application.
$ rails new your-app --database postgresql
# Gemfile ... gem 'dotenv-rails', :groups => [:development, :test] gem 'facebook-messenger' ...
$ bundle install
Then follow the instructions here. When you are done, proceed to the next step.
Configure Facebook App
Create a facebook page. You'll need this so you can subscribe your messenger app to your facebook page.
Create the application at developers.facebook.com.
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
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:
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
.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.