Class: Clacky::Channel::Adapters::Discord::GatewayClient

Inherits:
Object
  • Object
show all
Defined in:
lib/clacky/server/channel/adapters/discord/gateway_client.rb

Overview

WebSocket client for the Discord Gateway (v10, JSON, no compression). Implements identify, heartbeat, resume, and intent-aware error handling.

Defined Under Namespace

Classes: AuthError

Constant Summary collapse

GATEWAY_URL =
"wss://gateway.discord.gg/?v=10&encoding=json"
INTENTS =

GUILDS | GUILD_MESSAGES | GUILD_MESSAGE_REACTIONS | DIRECT_MESSAGES | MESSAGE_CONTENT

(1 << 0) | (1 << 9) | (1 << 10) | (1 << 12) | (1 << 15)
FATAL_CLOSE_CODES =
[4004, 4010, 4011, 4012, 4013, 4014].freeze
RECONNECT_DELAY =
5
READ_TIMEOUT_S =
90

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bot_token:) ⇒ GatewayClient

Returns a new instance of GatewayClient.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/clacky/server/channel/adapters/discord/gateway_client.rb', line 27

def initialize(bot_token:)
  @bot_token = bot_token
  @running   = false
  @on_event  = nil

  @session_id          = nil
  @resume_gateway_url  = nil
  @last_seq            = nil
  @heartbeat_interval  = nil
  @heartbeat_acked     = true
  @heartbeat_thread    = nil

  @ws_socket  = nil
  @ws_open    = false
  @ws_version = nil
  @incoming   = nil
end

Class Method Details

.client_identifierObject



211
212
213
214
215
# File 'lib/clacky/server/channel/adapters/discord/gateway_client.rb', line 211

def self.client_identifier
  name = Clacky::BrandConfig.load.product_name
  name = "OpenClacky" if name.nil? || name.strip.empty?
  "#{name.strip}/#{Clacky::VERSION}"
end

Instance Method Details

#start(&on_event) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/clacky/server/channel/adapters/discord/gateway_client.rb', line 45

def start(&on_event)
  @running  = true
  @on_event = on_event

  while @running
    begin
      connect_and_listen
    rescue AuthError
      @running = false
      raise
    rescue => e
      Clacky::Logger.error("[DiscordGW] error: #{e.message}")
      sleep RECONNECT_DELAY if @running
    end
  end
end

#stopObject



62
63
64
65
66
67
# File 'lib/clacky/server/channel/adapters/discord/gateway_client.rb', line 62

def stop
  @running = false
  @heartbeat_thread&.kill
  send_raw_frame(:close, "") rescue nil
  @ws_socket&.close rescue nil
end