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 = Bot.new @slack_info["self"], self block.call bot if block_given? debug "bot is configured and ready to go!" debug "starting to listen on #{@session_url}" @ws = Faye::WebSocket::Client.new @session_url @ws.on :message do |event| debug "message arrived", event.data bot.event JSON.parse(event.data) end @ws.on :close do debug "bye bye" 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"] @logged = true end end end