Create sample FB bot with ruby

If you are better at js, just follow this official article.

If not you are, after creating following app, you follow the article above and set up fb bot account and fb page.

here’s my code -> mmyoji/fb-bot-sample

Precondition

  • Ruby 2.3
  • rails-api
  • on Heroku

Create sample rails-api app

$ cd ~/path/to/workspace
$ gem install rails-api
$ rails-api new fb-bot -d postgresql # but we're not use database
$ cd ./fb-bot

Use faraday

In order to send a request to facebook endpoints, I use faraday.

If you want to another HTTP client library, it’s up to you.

$ echo "gem 'faraday'" >> Gemfile
$ bundle install

Create controller and routing

$ rails g controller webhooks show create
$ emacs config/routes.rb # or use vim
# config/routes.rb
Rails.application.routes.draw do
  get  "webhook", to: "webhooks#show"
  post "webhook", to: "webhooks#create"
end

and edit controller

# app/controllers/webhooks_controller.rb
class WebhooksController < ApplicationController
  # you can get your fb page access token after finishing the article.
  # and set it as heroku environment variable.
  ACCESS_TOKEN = ENV.fetch("PAGE_ACCESST_TOKEN")

  def show
    # actually, it's better to compare `verify_token` on this action.
    render json: params["hub.challenge"]
  end

  def create
    events = params[:entry].first.fetch(:messaging, [])
    events.each do |ev|
      sender_id = ev[:sender][:id]
      next unless (text = ev[:message].try(:fetch, :text, nil))

      res_json = {
        recipient: {
          id: sender_id
        },
        message: {
          text: text
        }
      }.to_json
      fb_conn.post("/v2.6/me/messages?access_token=#{ACCESS_TOKEN}") do |req|
        req.headers["Content-Type"] = "application/json; charset=utf-8"
        req.body = res_json
      end
    end
    head :ok
  end

  private

  def fb_conn
    @fb_conn ||= Faraday.new(url: "https://graph.facebook.com") do |builder|
      builder.request  :url_encoded
      builder.response :logger
      builder.adapter  :net_http
    end
  end
end

That’s all.

Then you just finish the tutorial article. Easy.

Contents