Class: Ruboty::SlackRTM::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/ruboty/slack_rtm/client.rb

Constant Summary collapse

CONNECTION_CLOSED =
Object.new

Instance Method Summary collapse

Constructor Details

#initialize(websocket_url:) ⇒ Client

Returns a new instance of Client.



9
10
11
12
# File 'lib/ruboty/slack_rtm/client.rb', line 9

def initialize(websocket_url:)
  @queue = Queue.new
  @client = create_client(websocket_url.to_s)
end

Instance Method Details

#main_loopObject



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/ruboty/slack_rtm/client.rb', line 35

def main_loop
  keep_connection

  loop do
    message = @queue.deq
    if message.equal?(CONNECTION_CLOSED)
      break
    end
    @client.send(message)
  end
end

#on_text(&block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ruboty/slack_rtm/client.rb', line 19

def on_text(&block)
  @client.on(:message) do |message|
    case message.type
    when :ping
      Ruboty.logger.debug("#{Client.name}: Received ping message")
      send('', type: 'pong')
    when :pong
      Ruboty.logger.debug("#{Client.name}: Received pong message")
    when :text
      block.call(JSON.parse(message.data))
    else
      Ruboty.logger.warn("#{Client.name}: Received unknown message type=#{message.type}: #{message.data}")
    end
  end
end

#send_message(data) ⇒ Object



14
15
16
17
# File 'lib/ruboty/slack_rtm/client.rb', line 14

def send_message(data)
  data[:id] = (Time.now.to_i * 10 + rand(10)) % (1 << 31)
  @queue.enq(data.to_json)
end