Class: Slatan::Heart

Inherits:
Object
  • Object
show all
Defined in:
lib/slatan/heart.rb

Instance Method Summary collapse

Instance Method Details

#beatObject



11
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/slatan/heart.rb', line 11

def beat()
  Signal.trap(:INT)  { EM.stop }
  Signal.trap(:TERM) { EM.stop }

  req = Net::HTTP.post_form URI("#{Spirit.slack_api_url}/rtm.start"), token: Spirit.slack_token
  parsed_body = JSON.parse(req.body, symbolize_names: true)
  Buttocks.fatal "failed rtm.start (#{parsed_body[:error]})" if !parsed_body[:ok]
  set_affiliation parsed_body
  ws_url = parsed_body[:url]
  EM.run {
    @ws = Faye::WebSocket::Client.new(ws_url)

    @ws.on :open do |event|
      Buttocks.info('open')
    end

    @ws.on :message do |event|
      Buttocks.debug("message: #{event.data}")
      data = JSON.parse(event.data, symbolize_names: true)
      Ear.hear(data) if enable_dispatch data
    end

    @ws.on :close do |event|
      Buttocks.warn("close: #{event.code}(#{event.reason})")
      @ws = nil
      EM.stop
    end
  }
end