require "json" require "net/http" module Boty class Session attr_reader :bot attr_writer :verbose def initialize(verbose: false) @verbose = verbose end def start(&block) EM.run do login bot = initialize_bot(&block) stablish_connection do |ws| ws.on :message do |event| on_message event, bot end end end end private def verbose?; @verbose; end def debug(message, *stuff) return unless verbose? $stdout.puts message method = $stdout.respond_to?(:pp) ? :pp : :p talker = $stdout.method method stuff.each do |printable| talker.call printable end end def login debug "logging in against slack right now" @slack_info = Slack.rtm.start debug "yep! logged in!" @session_url = @slack_info["url"] end def initialize_bot(&block) Bot.new(@slack_info["self"], self).tap { |bot| block.call bot if block_given? debug "bot is configured and ready to go!" } end def on_message(event, bot) debug "message arrived", event.data bot.event JSON.parse(event.data) end def on_close debug "bye byeb." end def stablish_connection debug "starting to listen on #{@session_url}" ws = Faye::WebSocket::Client.new @session_url ws.on :close do on_close end yield ws if block_given? end end end