Class: KHL::WebSocket::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/khl/web_socket/client.rb

Overview

Client for the KHL WebSocket API client = KHL::WebSocket.new(token: “bot_token”) Thread.new { client.run } client.message.pop # Get message from queue

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Client

Returns a new instance of Client.

Parameters:

  • config (String)

    :token Bot token

Options Hash (config):

  • :token_type (String)

    Token type

  • :language (String)

    Language

  • :compress (Boolean)

    Compress



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/khl/web_socket/client.rb', line 26

def initialize(config)
  config[:compress] ||= false

  @config = config
  @http_gateway = HTTP::Gateway.new(config)
  @url = gateway_url
  @messages = Queue.new
  @sn = 0
  @state = :disconnected
  @ping_signal = false
  @resume_signal = false
  @ws = nil
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



20
21
22
# File 'lib/khl/web_socket/client.rb', line 20

def config
  @config
end

#messagesObject (readonly)

Returns the value of attribute messages.



20
21
22
# File 'lib/khl/web_socket/client.rb', line 20

def messages
  @messages
end

#stateObject (readonly)

Returns the value of attribute state.



20
21
22
# File 'lib/khl/web_socket/client.rb', line 20

def state
  @state
end

#urlObject (readonly)

Returns the value of attribute url.



20
21
22
# File 'lib/khl/web_socket/client.rb', line 20

def url
  @url
end

Instance Method Details

#runObject

Only receive messages from the server



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/khl/web_socket/client.rb', line 41

def run
  EM.run {
    Signal.trap("INT") { EventMachine.stop }
    Signal.trap("TERM") { EventMachine.stop }

    @ws = Faye::WebSocket::Client.new(gateway_url)
    @state = :connecting

    EventMachine.add_periodic_timer(30) do
      EventMachine.add_timer(6) do
        if @ping_signal
          @state = :timeout

          unless reconnect
            unless resume
              @state = :disconnected
              EventMachine.stop
              rerun
            end
          end
        end
      end

      # Send ping message
      @ws.send({s: 2, sn: @sn}.to_json)
      @ping_signal = true
    end

    @ws.on :message do |event|
      raw = config[:compress] ? Zlib::Inflate.inflate(event.data.pack("C*")) : event.data
      msg = Message.parse(raw)

      if msg.hello?
        @state = :connected
      elsif msg.pong?
        @ping_signal = false
      elsif msg.resume_ack?
        @resume_signal = false
      elsif msg.reconnect?
        @state = :reconnecting
        rerun
      elsif msg.event?
        messages << msg
        @sn = msg.sn
      end
    end
  }
end