require "sinbotra" require "sinatra" require "json" require "sinbotra/messenger/middleware/facebook_signature" require "sinbotra/messenger/middleware/parse_message" module Sinbotra class Server < Sinatra::Base use Sinbotra::Messenger::Middleware::FacebookSignature use Sinbotra::Messenger::Middleware::ParseMessage configure do raise ArgumentError, "You need to set a FACEBOOK_CHALLENGE environmental variable to run the server!" unless ENV["FACEBOOK_CHALLENGE"] set :facebook_handler, Sinbotra::MessageHandler.new(:facebook) Sinbotra::Bot::UserRepo.connect end helpers do def match_facebook_challenge(params) matching = params["hub.mode"] == "subscribe" && params["hub.verify_token"] == ENV.fetch("FACEBOOK_CHALLENGE") matching ? params["hub.challenge"] : nil end end get "/facebook/webhook" do if challenge = match_facebook_challenge(params) challenge else status 403 end end post "/facebook/webhook" do begin msgs = request.env["facebook.messages"] settings.facebook_handler.receive_messages(msgs) status 200 "OK" rescue Exception => e STDERR.puts e.message STDERR.puts e.backtrace status 200 "ERROR" end end end end