Last active
November 1, 2016 11:18
-
-
Save kskomori/f2c2935454333aa7c0a4ac758f5f8baa to your computer and use it in GitHub Desktop.
今更ながらFacebook「Messenger Platform(Beta)」を使ったEchoサーバをRails4で書いてみる ref: http://qiita.com/kskomori/items/d12ba058eb738e3326bf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FbBotController < ApplicationController | |
protect_from_forgery except: :callback | |
FB_WEBHOOK_VERIFY_TOKEN="WebHook登録時に入力したトークン" | |
FB_PAGE_ACCESS_TOKEN="フェイスブックページのページアクセストークン" | |
# WebHooks登録時コールバックURL | |
def subscribe | |
if params["hub.mode".to_sym] != "subscribe" | |
render text: "Error. wrong mode" and return | |
end | |
if params["hub.verify_token".to_sym] != FB_WEBHOOK_VERIFY_TOKEN | |
render text: "Error. wrong verify_token" and return | |
end | |
render text: params["hub.challenge".to_sym] | |
end | |
# コールバックURL | |
def callback | |
messaging = params[:entry][0][:messaging] | |
messaging.each do |event| | |
# post_text() で送ったものもコールバックされるので判別してる | |
# if event.include?(:delivery) でもいいかもしれないがどうだろう | |
unless event.include?(:message) | |
logger.info("NO MESSAGE(maybe from BOT):sender=#{event[:sender][:id]}") | |
next | |
end | |
from = event[:sender][:id] | |
to = event[:recipient][:id] | |
msg = event[:message][:text] | |
post_text(from, msg) | |
end | |
render text: '' | |
end | |
private | |
def post_text(to, text) | |
msg = { | |
recipient: { id: to }, | |
message: { text: text }, | |
} | |
conn = Faraday.new(url: 'https://graph.facebook.com') do |builder| | |
builder.request :url_encoded | |
builder.response :logger | |
builder.adapter Faraday.default_adapter | |
end | |
endpoint = '/v2.6/me/messages?access_token=' << FB_PAGE_ACCESS_TOKEN | |
res = conn.post endpoint do |req| | |
req.headers['Content-type'] = 'application/json; charset=UTF-8' | |
req.body = msg.to_json | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment