Sha256: 2a74dcf2622261551986f907d4c33a60ce07fd343ad2f90093fb130ea9e55651

Contents?: true

Size: 1.31 KB

Versions: 6

Compression:

Stored size: 1.31 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
    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 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

6 entries across 6 versions & 1 rubygems

Version Path
boty-0.0.14 lib/boty/session.rb
boty-0.0.13 lib/boty/session.rb
boty-0.0.12 lib/boty/session.rb
boty-0.0.11 lib/boty/session.rb
boty-0.0.10 lib/boty/session.rb
boty-0.0.9 lib/boty/session.rb