Class: Rubord::Gateway
- Inherits:
-
Object
- Object
- Rubord::Gateway
- Defined in:
- lib/rubord/structs/gateway.rb
Constant Summary collapse
- GATEWAY_URL =
"wss://gateway.discord.gg/?v=10&encoding=json"- OPCODE_DISPATCH =
0- OPCODE_HEARTBEAT =
1- OPCODE_IDENTIFY =
2- OPCODE_HELLO =
10- OPCODE_HEARTBEAT_ACK =
11- OPCODE_RECONNECT =
7- OPCODE_INVALID_SESSION =
9
Instance Attribute Summary collapse
-
#latency ⇒ Object
readonly
Returns the value of attribute latency.
-
#seq ⇒ Object
readonly
Returns the value of attribute seq.
-
#session_id ⇒ Object
readonly
Returns the value of attribute session_id.
Instance Method Summary collapse
- #cleanup_connection ⇒ Object
- #connect(&block) ⇒ Object
- #connected? ⇒ Boolean
- #disconnect ⇒ Object
- #handle_close(event) ⇒ Object
- #handle_dispatch(event_type, data, &block) ⇒ Object
- #handle_error(e) ⇒ Object
- #handle_heartbeat_ack ⇒ Object
- #handle_hello(data) ⇒ Object
- #handle_invalid_session(resumable) ⇒ Object
- #handle_message(event, &block) ⇒ Object
- #handle_open ⇒ Object
- #identify ⇒ Object
-
#initialize(token, intents) ⇒ Gateway
constructor
A new instance of Gateway.
- #reconnect ⇒ Object
- #resume_connection ⇒ Object
- #schedule_reconnect ⇒ Object
- #send_payload(payload) ⇒ Object
- #start_heartbeat ⇒ Object
Constructor Details
#initialize(token, intents) ⇒ Gateway
Returns a new instance of Gateway.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/rubord/structs/gateway.rb', line 20 def initialize(token, intents) @token = token @intents = intents @seq = nil @session_id = nil @ws = nil @stopping = false @connected = false @heartbeat_interval = nil @last_heartbeat_at = nil @latency = 0 @heartbeat_thread = nil @event_handlers = {} @mutex = Mutex.new end |
Instance Attribute Details
#latency ⇒ Object (readonly)
Returns the value of attribute latency.
18 19 20 |
# File 'lib/rubord/structs/gateway.rb', line 18 def latency @latency end |
#seq ⇒ Object (readonly)
Returns the value of attribute seq.
18 19 20 |
# File 'lib/rubord/structs/gateway.rb', line 18 def seq @seq end |
#session_id ⇒ Object (readonly)
Returns the value of attribute session_id.
18 19 20 |
# File 'lib/rubord/structs/gateway.rb', line 18 def session_id @session_id end |
Instance Method Details
#cleanup_connection ⇒ Object
328 329 330 331 332 333 334 335 336 337 338 339 |
# File 'lib/rubord/structs/gateway.rb', line 328 def cleanup_connection @connected = false @heartbeat_thread&.kill rescue nil @heartbeat_thread = nil begin @ws&.close if @ws.respond_to?(:close) rescue end @ws = nil end |
#connect(&block) ⇒ Object
38 39 40 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 |
# File 'lib/rubord/structs/gateway.rb', line 38 def connect(&block) @mutex.synchronize do return if @connected && !@stopping if @token.nil? || @token.strip.empty? raise InvalidTokenError, "Discord token cannot be empty" end @stopping = false @connected = false begin @ws = WebSocket::Client::Simple.connect(GATEWAY_URL, headers: { "User-Agent" => "DiscordBot (https://github.com/kauzxx00/rubord, 1.0.0)", }) rescue => e Rubord::Logger.error "[Rubord:Gateway] Failed to connect to Discord Gateway: #{e.}" schedule_reconnect return end gateway_instance = self @ws.on(:open) do gateway_instance.handle_open end @ws.on(:message) do |event| gateway_instance.(event, &block) end @ws.on(:close) do |event| gateway_instance.handle_close(event) end @ws.on(:error) do |e| gateway_instance.handle_error(e) end end sleep 1 while !@stopping end |
#connected? ⇒ Boolean
357 358 359 |
# File 'lib/rubord/structs/gateway.rb', line 357 def connected? @connected && !@stopping end |
#disconnect ⇒ Object
346 347 348 349 350 351 352 353 354 355 |
# File 'lib/rubord/structs/gateway.rb', line 346 def disconnect Rubord::Logger.warn "[Rubord:Gateway] Disconnecting..." @mutex.synchronize do @stopping = true @connected = false cleanup_connection end end |
#handle_close(event) ⇒ Object
130 131 132 133 134 |
# File 'lib/rubord/structs/gateway.rb', line 130 def handle_close(event) Rubord::Logger.warn "[Rubord:Gateway] WebSocket connection closed: code=#{event.code}, reason=#{event.reason}" cleanup_connection schedule_reconnect unless @stopping end |
#handle_dispatch(event_type, data, &block) ⇒ Object
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/rubord/structs/gateway.rb', line 177 def handle_dispatch(event_type, data, &block) if event_type == "READY" @session_id = data["session_id"] @connected = true end event_map = { "READY" => :ready, "RESUMED" => :resumed, "MESSAGE_CREATE" => :message_create, "MESSAGE_UPDATE" => :message_update, "MESSAGE_DELETE" => :message_delete, "GUILD_CREATE" => :guild_create, "GUILD_DELETE" => :guild_delete, "CHANNEL_CREATE" => :channel_create, "CHANNEL_DELETE" => :channel_delete, "INTERACTION_CREATE" => :interaction_create, "MESSAGE_REACTION_ADD" => :reaction_add, "MESSAGE_REACTION_REMOVE" => :reaction_remove, "TYPING_START" => :typing_start, "PRESENCE_UPDATE" => :presence_update, } event_symbol = event_map[event_type] if event_symbol && block_given? begin block.call(event_symbol, data) rescue => e Rubord::Logger.warn "[Rubord:Gateway] Error in event handler for #{event_type}: #{e.}" Rubord::Logger.warn e. end end end |
#handle_error(e) ⇒ Object
136 137 138 139 140 141 |
# File 'lib/rubord/structs/gateway.rb', line 136 def handle_error(e) Rubord::Logger.warn "[Rubord:Gateway] WebSocket error: #{e.}" Rubord::Logger.warn e.backtrace.join("\n") if e.backtrace cleanup_connection schedule_reconnect unless @stopping end |
#handle_heartbeat_ack ⇒ Object
155 156 157 158 159 |
# File 'lib/rubord/structs/gateway.rb', line 155 def handle_heartbeat_ack if @last_heartbeat_at @latency = ((Time.now - @last_heartbeat_at) * 1000).round end end |
#handle_hello(data) ⇒ Object
143 144 145 146 147 148 149 150 151 152 153 |
# File 'lib/rubord/structs/gateway.rb', line 143 def handle_hello(data) @heartbeat_interval = data["heartbeat_interval"].to_f / 1000.0 @connected = true if @session_id && @seq resume_connection else start_heartbeat identify end end |
#handle_invalid_session(resumable) ⇒ Object
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
# File 'lib/rubord/structs/gateway.rb', line 161 def handle_invalid_session(resumable) Rubord::Logger.warn "[Rubord:Gateway] Invalid session (resumable: #{resumable})" if resumable && @session_id && @seq Rubord::Logger.warn "[Rubord:Gateway] Attempting to resume session" sleep rand(1..3) identify else Rubord::Logger.warn "[Rubord:Gateway] Starting new session" @session_id = nil @seq = nil sleep rand(1..5) identify end end |
#handle_message(event, &block) ⇒ Object
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'lib/rubord/structs/gateway.rb', line 85 def (event, &block) data = event.data.to_s if data.nil? || data.strip.empty? Rubord::Logger.warn "[Rubord:Gateway] Received empty payload" return end begin payload = JSON.parse(data) rescue JSON::ParserError => e Rubord::Logger.warn "[Rubord:Gateway] Failed to parse JSON: #{e.}" Rubord::Logger.warn "[Rubord:Gateway] Raw data: #{data.inspect[0..100]}" if data && data.length > 0 return end op = payload["op"] t = payload["t"] d = payload["d"] s = payload["s"] @mutex.synchronize do @seq = s if s && s > 0 case op when OPCODE_HELLO handle_hello(d) when OPCODE_HEARTBEAT_ACK handle_heartbeat_ack when OPCODE_RECONNECT Rubord::Logger.warn "[Rubord:Gateway] Discord requested reconnect" schedule_reconnect when OPCODE_INVALID_SESSION handle_invalid_session(d) when OPCODE_DISPATCH handle_dispatch(t, d, &block) else Rubord::Logger.warn "[Rubord:Gateway] Unhandled opcode: #{op}" end end rescue => e Rubord::Logger.warn "[Rubord:Gateway] Error processing message: #{e.}" Rubord::Logger.warn e.backtrace.join("\n") if e.backtrace end |
#handle_open ⇒ Object
81 82 83 |
# File 'lib/rubord/structs/gateway.rb', line 81 def handle_open @latency = 0 end |
#identify ⇒ Object
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
# File 'lib/rubord/structs/gateway.rb', line 212 def identify payload = { op: OPCODE_IDENTIFY, d: { token: @token, intents: @intents, properties: { "$os": "linux", "$browser": "Rubord", "$device": "Rubord", }, compress: false, large_threshold: 250, shard: [0, 1], }, } send_payload(payload) end |
#reconnect ⇒ Object
341 342 343 344 |
# File 'lib/rubord/structs/gateway.rb', line 341 def reconnect Rubord::Logger.warn "[Rubord:Gateway] Manual reconnect requested" schedule_reconnect end |
#resume_connection ⇒ Object
232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
# File 'lib/rubord/structs/gateway.rb', line 232 def resume_connection Rubord::Logger.warn "[Rubord:Gateway] Attempting to resume session #{@session_id} at seq #{@seq}" payload = { op: 6, d: { token: @token, session_id: @session_id, seq: @seq, }, } send_payload(payload) end |
#schedule_reconnect ⇒ Object
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
# File 'lib/rubord/structs/gateway.rb', line 301 def schedule_reconnect return if @stopping Thread.new do @mutex.synchronize do cleanup_connection delay = 1 max_delay = 30 while !@stopping Rubord::Logger.warn "[Rubord:Gateway] Reconnecting in #{delay}s..." sleep delay begin connect break if @connected rescue => e Rubord::Logger.warn "[Rubord:Gateway] Reconnect failed: #{e.}" end delay = [delay * 2, max_delay].min end end end end |
#send_payload(payload) ⇒ Object
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 |
# File 'lib/rubord/structs/gateway.rb', line 279 def send_payload(payload) return if @stopping || !@ws begin json = payload.to_json @ws.send(json) if ENV["DEBUG"] opcode_name = case payload[:op] || payload["op"] when 1 then "HEARTBEAT" when 2 then "IDENTIFY" when 6 then "RESUME" else "OP#{payload[:op] || payload["op"]}" end Rubord::Logger.warn "[Rubord:Gateway] Sent #{opcode_name}" end rescue => e Rubord::Logger.warn "[Rubord:Gateway] Failed to send payload: #{e.}" schedule_reconnect end end |
#start_heartbeat ⇒ Object
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 |
# File 'lib/rubord/structs/gateway.rb', line 247 def start_heartbeat return unless @heartbeat_interval && @heartbeat_interval > 0 @heartbeat_thread&.kill rescue nil @heartbeat_thread = Thread.new do while !@stopping && @connected begin sleep @heartbeat_interval break if @stopping || !@connected if @last_heartbeat_at && (Time.now - @last_heartbeat_at) > (@heartbeat_interval * 3) Rubord::Logger.warn "[Rubord:Gateway] No heartbeat ACK received, reconnecting..." schedule_reconnect break end heartbeat_payload = { op: OPCODE_HEARTBEAT, d: @seq } @last_heartbeat_at = Time.now send_payload(heartbeat_payload) Rubord::Logger.warn "[Rubord:Gateway] Sent heartbeat (seq: #{@seq})" if ENV["DEBUG"] rescue => e Rubord::Logger.warn "[Rubord:Gateway] Heartbeat error: #{e.}" schedule_reconnect break end end end end |