class Gateway
WebSocket client for the Discord Gateway (v10).
Connects to Discord's WebSocket gateway, authenticates with a bot token, manages heartbeating, and dispatches incoming events to registered handlers.
Supports session resumption on reconnect.
gateway = Async::Discord::Gateway.new(token: "MTk...", intents: 0x30001)
gateway.on("MESSAGE_CREATE") |data| puts data["content"]
gateway.on("READY") |data| puts "Connected as #{data["user"]["username"]" }
gateway.run # blocks, runs inside Async reactor
Definitions
DISPATCH = 0
Discord Gateway opcodes
def on(event_type, &block)
Register a handler for a Discord event type.
gateway.on("MESSAGE_CREATE") |data| ...
gateway.on("READY") |data| ...
Implementation
def on(event_type, &block)
@handlers[event_type] << block
end
def run
Connect to the gateway and run the event loop. Blocks until the connection is closed or an unrecoverable error occurs. Must be called inside an Async reactor.
Implementation
def run
@running = true
while @running
begin
connect_and_run
rescue => e
Console.error(self) { "Gateway error: #{e.class}: #{e.message}" }
break unless @running
sleep(5)
end
end
end
def stop
Gracefully stop the gateway.
Implementation
def stop
@running = false
@connection&.close
end
def send_payload(op:, d: nil)
Send a raw payload to the gateway.
Implementation
def send_payload(op:, d: nil)
return unless @connection
payload = {op: op, d: d}
@connection.write(payload.to_json)
@connection.flush
end