Sha256: 287f68fe7fa91d48c5267a9f437b1913fc5fe24f3e4a7304f6f35803ac23620d

Contents?: true

Size: 1.34 KB

Versions: 4

Compression:

Stored size: 1.34 KB

Contents

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 do |ws|
          ws.on :message do |event|
            begin
              on_message event, @bot
            rescue StandardError => e
              logger.error "Message #{event} could not be processed. #{e.message}"
            end
          end
        end
      end
      self
    end

    private

    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"], self).tap { |bot|
        block.call ScriptDSL.new(bot) if block_given?
        logger.debug { "bot is configured and ready to go!" }
      }
    end

    def on_message(event, bot)
      logger.debug { "message arrived #{event.data}" }
      bot.event JSON.parse(event.data)
    end

    def on_close
      logger.debug { "bye byeb." }
    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
      yield ws if block_given?
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
boty-0.0.17.1 lib/boty/session.rb
boty-0.0.17 lib/boty/session.rb
boty-0.0.16 lib/boty/session.rb
boty-0.0.15 lib/boty/session.rb