require "json" require "net/http" module Boty class Session SLACK_RTM_START_URL = "https://%{domain}.slack.com/api/rtm.start?"+ "token=%{token}&"+ "simple_latest=true&no_unreads=true" private_constant :SLACK_RTM_START_URL attr_reader :bot attr_writer :verbose def initialize(slack_domain = ENV["SLACK_COMPANY"], verbose: false) @rtm_start_url = SLACK_RTM_START_URL.sub "%{domain}", slack_domain @rtm_start_url = @rtm_start_url.sub "%{token}", ENV["SLACK_BOT_API_TOKEN"] @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 = JSON.parse Net::HTTP.get(URI @rtm_start_url) 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