require "json" require "net/http" module Boty class Session include Boty::Logger attr_reader :bot def start(&block) EM.run do login @bot = initialize_bot(&block) stablish_connection end self end private def on_connect(ws) ws.on :message do |event| begin on_message event, @bot rescue StandardError => e logger.error "Message #{event} could not be processed. #{e.message}" logger.debug e.backtrace.reduce("") { |msg, line| msg << "#{line}\n" } end end end def login logger.debug { "Logging in against slack right now" } @slack_info = Slack.rtm.start logger.debug { "yep! logged in!" } @session_url = @slack_info["url"] end def initialize_bot(&block) Bot.new(@slack_info["self"]).tap { |bot| DSL.new(bot).instance_eval(&block) if block_given? logger.debug { "Bot is configured and ready to go!" } } end def on_message(event, bot) logger.debug { "Message arrived. Creating bot event" } bot.event JSON.parse(event.data) end def on_close logger.debug { "bye bye" } #todo try to reconnect (stablish_connection) unless is an em interrupt end def stablish_connection logger.debug { "Starting to listen on #{@session_url}" } ws = Faye::WebSocket::Client.new @session_url ws.on :close do on_close end on_connect ws end end end