Class: Websocket::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/edi/websocket/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



8
9
10
# File 'lib/edi/websocket/client.rb', line 8

def initialize
  self.id = 1
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



6
7
8
# File 'lib/edi/websocket/client.rb', line 6

def client
  @client
end

#idObject

Returns the value of attribute id.



6
7
8
# File 'lib/edi/websocket/client.rb', line 6

def id
  @id
end

#ws_urlObject

Returns the value of attribute ws_url.



6
7
8
# File 'lib/edi/websocket/client.rb', line 6

def ws_url
  @ws_url
end

Instance Method Details

#connectObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/edi/websocket/client.rb', line 12

def connect
  self.ws_url = EDI.get("https://slack.com/api/rtm.start?token=#{EDI.bot_token}").response["url"]
  EM.run {

    self.client = Faye::WebSocket::Client.new(ws_url)

    client.on :open do |event|
      puts "EDI is now online"
    end

    # Respond to Messages
    client.on :message do |event|
      incoming_message = Slack::WebsocketIncomingMessage.new(event.data)
      if incoming_message.should_respond?
        response_text = ""
        service = Proc.new { response_text = EDI.runner.new(message: incoming_message).execute }
        response = Proc.new { client.send Slack::WebsocketOutgoingMessage.new(text: response_text, channel: incoming_message.channel, id: id).to_json }
        EM.defer service, response
        increment_id
      end
    end

    # Kepp Websocket Connection Alive
    EM.add_periodic_timer(1) do
      client.ping
    end
  }
end