onyxcord 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. checksums.yaml +7 -0
  2. data/.devcontainer/Dockerfile +13 -0
  3. data/.devcontainer/devcontainer.json +29 -0
  4. data/.devcontainer/postcreate.sh +4 -0
  5. data/.github/CONTRIBUTING.md +13 -0
  6. data/.github/ISSUE_TEMPLATE/bug_report.md +38 -0
  7. data/.github/ISSUE_TEMPLATE/feature_request.md +24 -0
  8. data/.github/pull_request_template.md +37 -0
  9. data/.github/workflows/ci.yml +78 -0
  10. data/.github/workflows/codeql.yml +65 -0
  11. data/.github/workflows/deploy.yml +54 -0
  12. data/.github/workflows/release.yml +51 -0
  13. data/.gitignore +16 -0
  14. data/.markdownlint.json +4 -0
  15. data/.overcommit.yml +7 -0
  16. data/.rspec +2 -0
  17. data/.rubocop.yml +129 -0
  18. data/.yardopts +1 -0
  19. data/CHANGELOG.md +0 -0
  20. data/Gemfile +7 -0
  21. data/LICENSE.txt +21 -0
  22. data/README.md +305 -0
  23. data/Rakefile +17 -0
  24. data/bin/console +15 -0
  25. data/bin/setup +7 -0
  26. data/lib/onyxcord/allowed_mentions.rb +43 -0
  27. data/lib/onyxcord/api/application.rb +316 -0
  28. data/lib/onyxcord/api/channel.rb +700 -0
  29. data/lib/onyxcord/api/interaction.rb +67 -0
  30. data/lib/onyxcord/api/invite.rb +44 -0
  31. data/lib/onyxcord/api/server.rb +775 -0
  32. data/lib/onyxcord/api/user.rb +158 -0
  33. data/lib/onyxcord/api/webhook.rb +163 -0
  34. data/lib/onyxcord/api.rb +335 -0
  35. data/lib/onyxcord/await.rb +51 -0
  36. data/lib/onyxcord/bot.rb +1971 -0
  37. data/lib/onyxcord/cache.rb +326 -0
  38. data/lib/onyxcord/colour_rgb.rb +43 -0
  39. data/lib/onyxcord/commands/command_bot.rb +511 -0
  40. data/lib/onyxcord/commands/container.rb +112 -0
  41. data/lib/onyxcord/commands/events.rb +11 -0
  42. data/lib/onyxcord/commands/parser.rb +327 -0
  43. data/lib/onyxcord/commands/rate_limiter.rb +144 -0
  44. data/lib/onyxcord/configuration.rb +125 -0
  45. data/lib/onyxcord/container.rb +988 -0
  46. data/lib/onyxcord/data/activity.rb +271 -0
  47. data/lib/onyxcord/data/application.rb +341 -0
  48. data/lib/onyxcord/data/attachment.rb +91 -0
  49. data/lib/onyxcord/data/audit_logs.rb +438 -0
  50. data/lib/onyxcord/data/avatar_decoration.rb +26 -0
  51. data/lib/onyxcord/data/call.rb +22 -0
  52. data/lib/onyxcord/data/channel.rb +1355 -0
  53. data/lib/onyxcord/data/channel_tag.rb +69 -0
  54. data/lib/onyxcord/data/collectibles.rb +47 -0
  55. data/lib/onyxcord/data/component.rb +583 -0
  56. data/lib/onyxcord/data/embed.rb +258 -0
  57. data/lib/onyxcord/data/emoji.rb +123 -0
  58. data/lib/onyxcord/data/install_params.rb +24 -0
  59. data/lib/onyxcord/data/integration.rb +144 -0
  60. data/lib/onyxcord/data/interaction.rb +1141 -0
  61. data/lib/onyxcord/data/invite.rb +137 -0
  62. data/lib/onyxcord/data/member.rb +528 -0
  63. data/lib/onyxcord/data/message.rb +612 -0
  64. data/lib/onyxcord/data/message_activity.rb +41 -0
  65. data/lib/onyxcord/data/overwrite.rb +109 -0
  66. data/lib/onyxcord/data/poll.rb +365 -0
  67. data/lib/onyxcord/data/primary_server.rb +60 -0
  68. data/lib/onyxcord/data/profile.rb +79 -0
  69. data/lib/onyxcord/data/reaction.rb +64 -0
  70. data/lib/onyxcord/data/recipient.rb +34 -0
  71. data/lib/onyxcord/data/role.rb +449 -0
  72. data/lib/onyxcord/data/role_connection_data.rb +69 -0
  73. data/lib/onyxcord/data/role_subscription.rb +41 -0
  74. data/lib/onyxcord/data/scheduled_event.rb +513 -0
  75. data/lib/onyxcord/data/server.rb +1614 -0
  76. data/lib/onyxcord/data/server_preview.rb +68 -0
  77. data/lib/onyxcord/data/snapshot.rb +112 -0
  78. data/lib/onyxcord/data/team.rb +98 -0
  79. data/lib/onyxcord/data/timestamp.rb +69 -0
  80. data/lib/onyxcord/data/user.rb +324 -0
  81. data/lib/onyxcord/data/voice_region.rb +46 -0
  82. data/lib/onyxcord/data/voice_state.rb +41 -0
  83. data/lib/onyxcord/data/webhook.rb +238 -0
  84. data/lib/onyxcord/data.rb +57 -0
  85. data/lib/onyxcord/errors.rb +246 -0
  86. data/lib/onyxcord/event_executor.rb +80 -0
  87. data/lib/onyxcord/events/await.rb +48 -0
  88. data/lib/onyxcord/events/bans.rb +60 -0
  89. data/lib/onyxcord/events/channels.rb +225 -0
  90. data/lib/onyxcord/events/generic.rb +129 -0
  91. data/lib/onyxcord/events/guilds.rb +269 -0
  92. data/lib/onyxcord/events/integrations.rb +100 -0
  93. data/lib/onyxcord/events/interactions.rb +624 -0
  94. data/lib/onyxcord/events/invites.rb +127 -0
  95. data/lib/onyxcord/events/lifetime.rb +31 -0
  96. data/lib/onyxcord/events/members.rb +110 -0
  97. data/lib/onyxcord/events/message.rb +399 -0
  98. data/lib/onyxcord/events/polls.rb +118 -0
  99. data/lib/onyxcord/events/presence.rb +131 -0
  100. data/lib/onyxcord/events/raw.rb +74 -0
  101. data/lib/onyxcord/events/reactions.rb +218 -0
  102. data/lib/onyxcord/events/roles.rb +87 -0
  103. data/lib/onyxcord/events/scheduled_events.rb +171 -0
  104. data/lib/onyxcord/events/threads.rb +100 -0
  105. data/lib/onyxcord/events/typing.rb +73 -0
  106. data/lib/onyxcord/events/voice_server_update.rb +48 -0
  107. data/lib/onyxcord/events/voice_state_update.rb +106 -0
  108. data/lib/onyxcord/events/webhooks.rb +65 -0
  109. data/lib/onyxcord/gateway.rb +890 -0
  110. data/lib/onyxcord/id_object.rb +39 -0
  111. data/lib/onyxcord/light/data.rb +62 -0
  112. data/lib/onyxcord/light/integrations.rb +73 -0
  113. data/lib/onyxcord/light/light_bot.rb +58 -0
  114. data/lib/onyxcord/light.rb +8 -0
  115. data/lib/onyxcord/logger.rb +120 -0
  116. data/lib/onyxcord/message_components.rb +70 -0
  117. data/lib/onyxcord/paginator.rb +60 -0
  118. data/lib/onyxcord/permissions.rb +255 -0
  119. data/lib/onyxcord/rate_limiter/gateway.rb +42 -0
  120. data/lib/onyxcord/rate_limiter/rest.rb +89 -0
  121. data/lib/onyxcord/version.rb +7 -0
  122. data/lib/onyxcord/voice/encoder.rb +115 -0
  123. data/lib/onyxcord/voice/network.rb +380 -0
  124. data/lib/onyxcord/voice/opcodes.rb +29 -0
  125. data/lib/onyxcord/voice/sodium.rb +157 -0
  126. data/lib/onyxcord/voice/timer.rb +19 -0
  127. data/lib/onyxcord/voice/voice_bot.rb +386 -0
  128. data/lib/onyxcord/webhooks.rb +14 -0
  129. data/lib/onyxcord/websocket.rb +62 -0
  130. data/lib/onyxcord.rb +180 -0
  131. data/onyxcord-webhooks.gemspec +30 -0
  132. data/onyxcord.gemspec +50 -0
  133. metadata +421 -0
@@ -0,0 +1,890 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This file uses code from Websocket::Client::Simple, licensed under the following license:
4
+ #
5
+ # Copyright (c) 2013-2014 Sho Hashimoto
6
+ #
7
+ # MIT License
8
+ #
9
+ # Permission is hereby granted, free of charge, to any person obtaining
10
+ # a copy of this software and associated documentation files (the
11
+ # "Software"), to deal in the Software without restriction, including
12
+ # without limitation the rights to use, copy, modify, merge, publish,
13
+ # distribute, sublicense, and/or sell copies of the Software, and to
14
+ # permit persons to whom the Software is furnished to do so, subject to
15
+ # the following conditions:
16
+ #
17
+ # The above copyright notice and this permission notice shall be
18
+ # included in all copies or substantial portions of the Software.
19
+ #
20
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27
+
28
+ require 'onyxcord/rate_limiter/gateway'
29
+
30
+ module OnyxCord
31
+ # Gateway packet opcodes
32
+ module Opcodes
33
+ # **Received** when Discord dispatches an event to the gateway (like MESSAGE_CREATE, PRESENCE_UPDATE or whatever).
34
+ # The vast majority of received packets will have this opcode.
35
+ DISPATCH = 0
36
+
37
+ # **Two-way**: The client has to send a packet with this opcode every ~40 seconds (actual interval specified in
38
+ # READY or RESUMED) and the current sequence number, otherwise it will be disconnected from the gateway. In certain
39
+ # cases Discord may also send one, specifically if two clients are connected at once.
40
+ HEARTBEAT = 1
41
+
42
+ # **Sent**: This is one of the two possible ways to initiate a session after connecting to the gateway. It
43
+ # should contain the authentication token along with other stuff the server has to know right from the start, such
44
+ # as large_threshold and, for older gateway versions, the desired version.
45
+ IDENTIFY = 2
46
+
47
+ # **Sent**: Packets with this opcode are used to change the user's status and played game. (Sending this is never
48
+ # necessary for a gateway client to behave correctly)
49
+ PRESENCE = 3
50
+
51
+ # **Sent**: Packets with this opcode are used to change a user's voice state (mute/deaf/unmute/undeaf/etc.). It is
52
+ # also used to connect to a voice server in the first place. (Sending this is never necessary for a gateway client
53
+ # to behave correctly)
54
+ VOICE_STATE = 4
55
+
56
+ # **Sent**: This opcode is used to ping a voice server, whatever that means. The functionality of this opcode isn't
57
+ # known well but non-user clients should never send it.
58
+ VOICE_PING = 5
59
+
60
+ # **Sent**: This is the other of two possible ways to initiate a gateway session (other than {IDENTIFY}). Rather
61
+ # than starting an entirely new session, it resumes an existing session by replaying all events from a given
62
+ # sequence number. It should be used to recover from a connection error or anything like that when the session is
63
+ # still valid - sending this with an invalid session will cause an error to occur.
64
+ RESUME = 6
65
+
66
+ # **Received**: Discord sends this opcode to indicate that the client should reconnect to a different gateway
67
+ # server because the old one is currently being decommissioned. Counterintuitively, this opcode also invalidates the
68
+ # session - the client has to create an entirely new session with the new gateway instead of resuming the old one.
69
+ RECONNECT = 7
70
+
71
+ # **Sent**: This opcode identifies packets used to retrieve a list of members from a particular server. There is
72
+ # also a REST endpoint available for this, but it is inconvenient to use because the client has to implement
73
+ # pagination itself, whereas sending this opcode lets Discord handle the pagination and the client can just add
74
+ # members when it receives them. (Sending this is never necessary for a gateway client to behave correctly)
75
+ REQUEST_MEMBERS = 8
76
+
77
+ # **Received**: Sent by Discord when the session becomes invalid for any reason. This may include improperly
78
+ # resuming existing sessions, attempting to start sessions with invalid data, or something else entirely. The client
79
+ # should handle this by simply starting a new session.
80
+ INVALIDATE_SESSION = 9
81
+
82
+ # **Received**: Sent immediately for any opened connection; tells the client to start heartbeating early on, so the
83
+ # server can safely search for a session server to handle the connection without the connection being terminated.
84
+ # As a side-effect, large bots are less likely to disconnect because of very large READY parse times.
85
+ HELLO = 10
86
+
87
+ # **Received**: Returned after a heartbeat was sent to the server. This allows clients to identify and deal with
88
+ # zombie connections that don't dispatch any events anymore.
89
+ HEARTBEAT_ACK = 11
90
+ end
91
+
92
+ # This class stores the data of an active gateway session. Note that this is different from a websocket connection -
93
+ # there may be multiple sessions per connection or one session may persist over multiple connections.
94
+ class Session
95
+ # @return [String] Used to uniquely identify this session. Mostly used when resuming connections.
96
+ attr_reader :session_id
97
+
98
+ # @return [Integer] Incrementing integer used to determine the most recent event reccived from Discord.
99
+ attr_accessor :sequence
100
+
101
+ # @return [String] Gateway URL used to reconnect to the gateway node that Discord wants this session to use.
102
+ attr_reader :resume_gateway_url
103
+
104
+ # @!visibility private
105
+ def initialize(session_id, resume_gateway_url)
106
+ @session_id = session_id
107
+ @sequence = 0
108
+ @suspended = false
109
+ @invalid = false
110
+ @resume_gateway_url = resume_gateway_url
111
+ end
112
+
113
+ # Flags this session as suspended, so we know not to try and send heartbeats, etc. to the gateway until we've reconnected
114
+ def suspend
115
+ @suspended = true
116
+ end
117
+
118
+ def suspended?
119
+ @suspended
120
+ end
121
+
122
+ # Flags this session as no longer being suspended, so we can resume
123
+ def resume
124
+ @suspended = false
125
+ end
126
+
127
+ # Flags this session as being invalid
128
+ def invalidate
129
+ @invalid = true
130
+ @resume_gateway_url = nil
131
+ end
132
+
133
+ def invalid?
134
+ @invalid
135
+ end
136
+
137
+ def should_resume?
138
+ suspended? && !invalid?
139
+ end
140
+ end
141
+
142
+ # Client for the Discord gateway protocol
143
+ class Gateway
144
+ # How many members there need to be in a server for it to count as "large"
145
+ LARGE_THRESHOLD = 100
146
+
147
+ # The version of the gateway that's supposed to be used.
148
+ GATEWAY_VERSION = 9
149
+
150
+ # Close codes that are unrecoverable, after which we should not try to reconnect.
151
+ # - 4003: Not authenticated. How did this happen?
152
+ # - 4004: Authentication failed. Token was wrong, nothing we can do.
153
+ # - 4011: Sharding required. Currently requires developer intervention.
154
+ # - 4014: Use of disabled privileged intents.
155
+ FATAL_CLOSE_CODES = [4003, 4004, 4011, 4014].freeze
156
+
157
+ # Heartbeat ACKs are Discord's way of verifying on the client side whether the connection is still alive. If this is
158
+ # set to true (default value) the gateway client will use that functionality to detect zombie connections and
159
+ # reconnect in such a case; however it may lead to instability if there's some problem with the ACKs. If this occurs
160
+ # it can simply be set to false.
161
+ # @return [true, false] whether or not this gateway should check for heartbeat ACKs.
162
+ attr_accessor :check_heartbeat_acks
163
+
164
+ # @return [Integer] the intent parameter sent to the gateway server.
165
+ attr_reader :intents
166
+
167
+ def initialize(bot, token, shard_key = nil, compress_mode = :stream, intents = ALL_INTENTS)
168
+ @token = token
169
+ @bot = bot
170
+
171
+ @shard_key = shard_key
172
+
173
+ # Whether the connection to the gateway has succeeded yet
174
+ @ws_success = false
175
+
176
+ @check_heartbeat_acks = true
177
+
178
+ @compress_mode = compress_mode
179
+ @intents = intents
180
+ @send_limiter = OnyxCord::RateLimiter::Gateway.new
181
+ end
182
+
183
+ # Connect to the gateway server in a separate thread
184
+ def run_async
185
+ @ws_thread = Thread.new do
186
+ Thread.current[:onyxcord_name] = 'websocket'
187
+ connect_loop
188
+ LOGGER.warn('The WS loop exited! Not sure if this is a good thing')
189
+ end
190
+
191
+ LOGGER.debug('WS thread created! Now waiting for confirmation that everything worked')
192
+ loop do
193
+ sleep(0.5)
194
+
195
+ if @ws_success
196
+ LOGGER.debug('Confirmation received! Exiting run.')
197
+ break
198
+ end
199
+
200
+ if @should_reconnect == false
201
+ LOGGER.debug('Reconnection flag was unset. Exiting run.')
202
+ break
203
+ end
204
+ end
205
+ end
206
+
207
+ # Prevents all further execution until the websocket thread stops (e.g. through a closed connection).
208
+ def sync
209
+ @ws_thread.join
210
+ end
211
+
212
+ # Whether the WebSocket connection to the gateway is currently open
213
+ def open?
214
+ @handshake&.finished? && !@closed
215
+ end
216
+
217
+ # Stops the bot gracefully, disconnecting the websocket without immediately killing the thread. This means that
218
+ # Discord is immediately aware of the closed connection and makes the bot appear offline instantly.
219
+ #
220
+ # If this method doesn't work or you're looking for something more drastic, use {#kill} instead.
221
+ def stop
222
+ @should_reconnect = false
223
+ close
224
+
225
+ # Return nil so command bots don't send a message
226
+ nil
227
+ end
228
+
229
+ # Kills the websocket thread, stopping all connections to Discord.
230
+ def kill
231
+ @ws_thread.kill
232
+ end
233
+
234
+ # Notifies the {#run_async} method that everything is ready and the caller can now continue (i.e. with syncing,
235
+ # or with doing processing and then syncing)
236
+ def notify_ready
237
+ @ws_success = true
238
+ end
239
+
240
+ # Injects a reconnect event (op 7) into the event processor, causing Discord to reconnect to the given gateway URL.
241
+ # If the URL is set to nil, it will reconnect and get an entirely new gateway URL. This method has not much use
242
+ # outside of testing and implementing highly custom reconnect logic.
243
+ # @param url [String, nil] the URL to connect to or nil if one should be obtained from Discord.
244
+ def inject_reconnect(url = nil)
245
+ # When no URL is specified, the data should be nil, as is the case with Discord-sent packets.
246
+ data = url ? { url: url } : nil
247
+
248
+ handle_message({
249
+ op: Opcodes::RECONNECT,
250
+ d: data
251
+ }.to_json)
252
+ end
253
+
254
+ # Injects a resume packet (op 6) into the gateway. If this is done with a running connection, it will cause an
255
+ # error. It has no use outside of testing stuff that I know of, but if you want to use it anyway for some reason,
256
+ # here it is.
257
+ # @param seq [Integer, nil] The sequence ID to inject, or nil if the currently tracked one should be used.
258
+ def inject_resume(seq)
259
+ send_resume(raw_token, @session_id, seq || @sequence)
260
+ end
261
+
262
+ # Injects a terminal gateway error into the handler. Useful for testing the reconnect logic.
263
+ # @param e [Exception] The exception object to inject.
264
+ def inject_error(e)
265
+ handle_internal_close(e)
266
+ end
267
+
268
+ # Sends a heartbeat with the last received packet's seq (to acknowledge that we have received it and all packets
269
+ # before it), or if none have been received yet, with 0.
270
+ # @see #send_heartbeat
271
+ def heartbeat
272
+ if check_heartbeat_acks
273
+ unless @last_heartbeat_acked
274
+ # We're in a bad situation - apparently the last heartbeat wasn't ACK'd, which means the connection is likely
275
+ # a zombie. Reconnect
276
+ LOGGER.warn('Last heartbeat was not acked, so this is a zombie connection! Reconnecting')
277
+
278
+ # We can't send anything on zombie connections
279
+ @pipe_broken = true
280
+ reconnect
281
+ return
282
+ end
283
+
284
+ @last_heartbeat_acked = false
285
+ end
286
+
287
+ send_heartbeat(@session ? @session.sequence : 0)
288
+ end
289
+
290
+ # Sends a heartbeat packet (op 1). This tells Discord that the current connection is still active and that the last
291
+ # packets until the given sequence have been processed (in case of a resume).
292
+ # @param sequence [Integer] The sequence number for which to send a heartbeat.
293
+ def send_heartbeat(sequence)
294
+ send_packet(Opcodes::HEARTBEAT, sequence)
295
+ end
296
+
297
+ # Identifies to Discord with the default parameters.
298
+ # @see #send_identify
299
+ def identify
300
+ compress = @compress_mode == :large
301
+ send_identify(@token, {
302
+ os: RUBY_PLATFORM,
303
+ browser: 'onyxcord',
304
+ device: 'onyxcord'
305
+ }, compress, LARGE_THRESHOLD, @shard_key, @intents)
306
+ end
307
+
308
+ # Sends an identify packet (op 2). This starts a new session on the current connection and tells Discord who we are.
309
+ # This can only be done once a connection.
310
+ # @param token [String] The token with which to authorise the session. If it belongs to a bot account, it must be
311
+ # prefixed with "Bot ".
312
+ # @param properties [Hash<Symbol => String>] A list of properties for Discord to use in analytics. The following
313
+ # keys are recognised:
314
+ #
315
+ # - "os" (recommended value: the operating system the bot is running on)
316
+ # - "browser" (recommended value: library name)
317
+ # - "device" (recommended value: library name)
318
+ # - "referrer" (recommended value: empty)
319
+ # - "referring_domain" (recommended value: empty)
320
+ #
321
+ # @param compress [true, false] Whether certain large packets should be compressed using zlib.
322
+ # @param large_threshold [Integer] The member threshold after which a server counts as large and will have to have
323
+ # its member list chunked.
324
+ # @param shard_key [Array(Integer, Integer), nil] The shard key to use for sharding, represented as
325
+ # [shard_id, num_shards], or nil if the bot should not be sharded.
326
+ def send_identify(token, properties, compress, large_threshold, shard_key = nil, intents = ALL_INTENTS)
327
+ data = {
328
+ # Don't send a v anymore as it's entirely determined by the URL now
329
+ token: token,
330
+ properties: properties,
331
+ compress: compress,
332
+ large_threshold: large_threshold,
333
+ intents: intents
334
+ }
335
+
336
+ # Don't include the shard key at all if it is nil as Discord checks for its mere existence
337
+ data[:shard] = shard_key if shard_key
338
+
339
+ send_packet(Opcodes::IDENTIFY, data)
340
+ end
341
+
342
+ # Sends a status update packet (op 3). This sets the bot user's status (online/idle/...) and game playing/streaming.
343
+ # @param status [String] The status that should be set (`online`, `idle`, `dnd`, `invisible`).
344
+ # @param since [Integer] The Unix timestamp in milliseconds when the status was set. Should only be provided when
345
+ # `afk` is true.
346
+ # @param game [Hash<Symbol => Object>, nil] `nil` if no game should be played, or a hash of `:game => "name"` if a
347
+ # game should be played. The hash can also contain additional attributes for streaming statuses.
348
+ # @param afk [true, false] Whether the status was set due to inactivity on the user's part.
349
+ def send_status_update(status, since, game, afk)
350
+ data = {
351
+ status: status,
352
+ since: since,
353
+ game: game,
354
+ afk: afk
355
+ }
356
+
357
+ send_packet(Opcodes::PRESENCE, data)
358
+ end
359
+
360
+ # Sends a voice state update packet (op 4). This packet can connect a user to a voice channel, update self mute/deaf
361
+ # status in an existing voice connection, move the user to a new voice channel on the same server or disconnect an
362
+ # existing voice connection.
363
+ # @param server_id [Integer] The ID of the server on which this action should occur.
364
+ # @param channel_id [Integer, nil] The channel ID to connect/move to, or `nil` to disconnect.
365
+ # @param self_mute [true, false] Whether the user should itself be muted to everyone else.
366
+ # @param self_deaf [true, false] Whether the user should be deaf towards other users.
367
+ def send_voice_state_update(server_id, channel_id, self_mute, self_deaf)
368
+ data = {
369
+ guild_id: server_id,
370
+ channel_id: channel_id,
371
+ self_mute: self_mute,
372
+ self_deaf: self_deaf
373
+ }
374
+
375
+ send_packet(Opcodes::VOICE_STATE, data)
376
+ end
377
+
378
+ # Resumes the session from the last recorded point.
379
+ # @see #send_resume
380
+ def resume
381
+ send_resume(@token, @session.session_id, @session.sequence)
382
+ end
383
+
384
+ # Reconnects the gateway connection in a controlled manner.
385
+ # @param attempt_resume [true, false] Whether a resume should be attempted after the reconnection.
386
+ def reconnect(attempt_resume = true)
387
+ @session.suspend if @session && attempt_resume
388
+
389
+ @instant_reconnect = true
390
+ @should_reconnect = true
391
+
392
+ close(4000)
393
+ end
394
+
395
+ # Sends a resume packet (op 6). This replays all events from a previous point specified by its packet sequence. This
396
+ # will not work if the packet to resume from has already been acknowledged using a heartbeat, or if the session ID
397
+ # belongs to a now invalid session.
398
+ #
399
+ # If this packet is sent at the beginning of a connection, it will act similarly to an {#identify} in that it
400
+ # creates a session on the current connection. Unlike identify however, this packet can also be sent in an existing
401
+ # session and will just replay some of the events.
402
+ # @param token [String] The token that was used to identify the session to resume.
403
+ # @param session_id [String] The session ID of the session to resume.
404
+ # @param seq [Integer] The packet sequence of the packet after which the events should be replayed.
405
+ def send_resume(token, session_id, seq)
406
+ data = {
407
+ token: token,
408
+ session_id: session_id,
409
+ seq: seq
410
+ }
411
+
412
+ send_packet(Opcodes::RESUME, data)
413
+ end
414
+
415
+ # Sends a request members packet (op 8). This will order Discord to gradually sent all requested members as dispatch
416
+ # events with type `GUILD_MEMBERS_CHUNK`. It is necessary to use this method in order to get all members of a large
417
+ # server (see `large_threshold` in {#send_identify}), however it can also be used for other purposes.
418
+ # @param server_id [Integer] The ID of the server whose members to query.
419
+ # @param query [String] If this string is not empty, only members whose username starts with this string will be
420
+ # returned.
421
+ # @param limit [Integer] How many members to send at maximum, or `0` to send all members.
422
+ def send_request_members(server_id, query, limit)
423
+ data = {
424
+ guild_id: server_id,
425
+ query: query,
426
+ limit: limit
427
+ }
428
+
429
+ send_packet(Opcodes::REQUEST_MEMBERS, data)
430
+ end
431
+
432
+ # Sends a custom packet over the connection. This can be useful to implement future yet unimplemented functionality
433
+ # or for testing. You probably shouldn't use this unless you know what you're doing.
434
+ # @param opcode [Integer] The opcode the packet should be sent as. Can be one of {Opcodes} or a custom value if
435
+ # necessary.
436
+ # @param packet [Object] Some arbitrary JSON-serializable data that should be sent as the `d` field.
437
+ def send_packet(opcode, packet)
438
+ data = {
439
+ op: opcode,
440
+ d: packet
441
+ }
442
+
443
+ send(data.to_json)
444
+ end
445
+
446
+ # Sends custom raw data over the connection. Only useful for testing; even if you know what you're doing you
447
+ # probably want to use {#send_packet} instead.
448
+ # @param data [String] The data to send.
449
+ # @param type [Symbol] The type the WebSocket frame should have; either `:text`, `:binary`, `:ping`, `:pong`, or
450
+ # `:close`.
451
+ def send_raw(data, type = :text)
452
+ send(data, type)
453
+ end
454
+
455
+ private
456
+
457
+ def setup_heartbeats(interval)
458
+ # Make sure to reset ACK handling, so we don't keep reconnecting
459
+ @last_heartbeat_acked = true
460
+
461
+ # We don't want to have redundant heartbeat threads, so if one already exists, don't start a new one
462
+ return if @heartbeat_thread
463
+
464
+ @heartbeat_interval = interval
465
+ @heartbeat_thread = Thread.new do
466
+ Thread.current[:onyxcord_name] = 'heartbeat'
467
+ loop do
468
+ # Send a heartbeat if heartbeats are active and either no session exists yet, or an existing session is
469
+ # suspended (e.g. after op7)
470
+ if (@session && !@session.suspended?) || !@session
471
+ sleep @heartbeat_interval
472
+ # Check if we're connected here, since we could possibly be waiting for a reconnect to occur.
473
+ if @handshaked && !@closed
474
+ @bot.raise_heartbeat_event
475
+ heartbeat
476
+ else
477
+ LOGGER.debug('Tried to send a heartbeat without being connected! Ignoring, we should be fine.')
478
+ end
479
+ else
480
+ sleep 1
481
+ end
482
+ rescue StandardError => e
483
+ LOGGER.error('An error occurred while heartbeating!')
484
+ LOGGER.log_exception(e)
485
+ end
486
+ end
487
+ end
488
+
489
+ def connect_loop
490
+ # Initialize falloff so we wait for more time before reconnecting each time
491
+ @falloff = 1.0
492
+
493
+ @should_reconnect = true
494
+ loop do
495
+ connect
496
+
497
+ break unless @should_reconnect
498
+
499
+ if @instant_reconnect
500
+ LOGGER.info('Instant reconnection flag was set - reconnecting right away')
501
+ @instant_reconnect = false
502
+ else
503
+ wait_for_reconnect
504
+ end
505
+
506
+ # Restart the loop, i.e. reconnect
507
+ end
508
+ end
509
+
510
+ # Separate method to wait an ever-increasing amount of time before reconnecting after being disconnected in an
511
+ # unexpected way
512
+ def wait_for_reconnect
513
+ # We disconnected in an unexpected way! Wait before reconnecting so we don't spam Discord's servers.
514
+ LOGGER.debug("Attempting to reconnect in #{@falloff} seconds.")
515
+ sleep @falloff
516
+
517
+ # Calculate new falloff
518
+ @falloff *= 1.5
519
+ @falloff = 115 + (rand * 10) if @falloff > 120 # Cap the falloff at 120 seconds and then add some random jitter
520
+ end
521
+
522
+ # Create and connect a socket using a URI
523
+ def obtain_socket(uri)
524
+ socket = TCPSocket.new(uri.host, uri.port || socket_port(uri))
525
+
526
+ if secure_uri?(uri)
527
+ ctx = OpenSSL::SSL::SSLContext.new
528
+
529
+ if ENV['ONYXCORD_SSL_VERIFY_NONE']
530
+ ctx.ssl_version = 'SSLv23'
531
+ ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE # use VERIFY_PEER for verification
532
+
533
+ cert_store = OpenSSL::X509::Store.new
534
+ cert_store.set_default_paths
535
+ ctx.cert_store = cert_store
536
+ else
537
+ ctx.set_params ssl_version: :TLSv1_2 # rubocop:disable Naming/VariableNumber
538
+ end
539
+
540
+ socket = OpenSSL::SSL::SSLSocket.new(socket, ctx)
541
+ socket.connect
542
+ end
543
+
544
+ socket
545
+ end
546
+
547
+ # Whether the URI is secure (connection should be encrypted)
548
+ def secure_uri?(uri)
549
+ %w[https wss].include? uri.scheme
550
+ end
551
+
552
+ # The port we should connect to, if the URI doesn't have one set.
553
+ def socket_port(uri)
554
+ secure_uri?(uri) ? 443 : 80
555
+ end
556
+
557
+ def find_gateway
558
+ response = API.gateway(@token)
559
+ JSON.parse(response)['url']
560
+ end
561
+
562
+ def process_gateway
563
+ raw_url = @session&.resume_gateway_url || find_gateway
564
+
565
+ # Append a slash in case it's not there (I'm not sure how well WSCS handles it otherwise)
566
+ raw_url += '/' unless raw_url.end_with? '/'
567
+
568
+ query = if @compress_mode == :stream
569
+ "?encoding=json&v=#{GATEWAY_VERSION}&compress=zlib-stream"
570
+ else
571
+ "?encoding=json&v=#{GATEWAY_VERSION}"
572
+ end
573
+
574
+ raw_url + query
575
+ end
576
+
577
+ def connect
578
+ LOGGER.debug('Connecting')
579
+
580
+ # Get the URI we should connect to
581
+ url = process_gateway
582
+ LOGGER.debug("Gateway URL: #{url}")
583
+
584
+ # Parse it
585
+ gateway_uri = URI.parse(url)
586
+
587
+ # Zlib context for this gateway connection
588
+ @zlib_reader = Zlib::Inflate.new
589
+
590
+ # Connect to the obtained URI with a socket
591
+ @socket = obtain_socket(gateway_uri)
592
+ LOGGER.debug('Obtained socket')
593
+
594
+ # Initialise some properties
595
+ @handshake = ::WebSocket::Handshake::Client.new(url: url) # Represents the handshake between us and the server
596
+ @handshaked = false # Whether the handshake has finished yet
597
+ @pipe_broken = false # Whether we've received an EPIPE at any time
598
+ @closed = false # Whether the websocket is currently closed
599
+
600
+ # We're done! Delegate to the websocket loop
601
+ websocket_loop
602
+ rescue StandardError => e
603
+ LOGGER.error('An error occurred while connecting to the websocket!')
604
+ LOGGER.log_exception(e)
605
+ end
606
+
607
+ def websocket_loop
608
+ # Send the handshake data that we have so far
609
+ @socket.write(@handshake.to_s)
610
+
611
+ # Create a frame to handle received data
612
+ frame = ::WebSocket::Frame::Incoming::Client.new
613
+
614
+ until @closed
615
+ begin
616
+ unless @socket
617
+ LOGGER.warn('Socket is nil in websocket_loop! Reconnecting')
618
+ handle_internal_close('Socket is nil in websocket_loop')
619
+ next
620
+ end
621
+
622
+ # Get some data from the socket
623
+ begin
624
+ recv_data = @socket.readpartial(4096)
625
+ rescue EOFError
626
+ @pipe_broken = true
627
+ handle_internal_close('Socket EOF in websocket_loop')
628
+ next
629
+ end
630
+
631
+ # Check if we actually got data
632
+ unless recv_data
633
+ # If we didn't, wait
634
+ sleep 1
635
+ next
636
+ end
637
+
638
+ # Check whether the handshake has finished yet
639
+ if @handshaked
640
+ # If it hasn't, add the received data to the current frame
641
+ frame << recv_data
642
+
643
+ # Try to parse a message from the frame
644
+ msg = frame.next
645
+ while msg
646
+ # Check whether the message is a close frame, and if it is, handle accordingly
647
+ if msg.respond_to?(:code) && msg.code
648
+ handle_internal_close(msg)
649
+ break
650
+ end
651
+
652
+ # If there is one, handle it and try again
653
+ handle_message(msg.data)
654
+ msg = frame.next
655
+ end
656
+ else
657
+ # If the handshake hasn't finished, handle it
658
+ handle_handshake_data(recv_data)
659
+ end
660
+ rescue StandardError => e
661
+ handle_error(e)
662
+ end
663
+ end
664
+ end
665
+
666
+ def handle_handshake_data(recv_data)
667
+ @handshake << recv_data
668
+ return unless @handshake.finished?
669
+
670
+ @handshaked = true
671
+ handle_open
672
+ end
673
+
674
+ def handle_open; end
675
+
676
+ def handle_error(e)
677
+ LOGGER.error('An error occurred in the main websocket loop!')
678
+ LOGGER.log_exception(e)
679
+ end
680
+
681
+ ZLIB_SUFFIX = "\x00\x00\xFF\xFF".b.freeze
682
+ private_constant :ZLIB_SUFFIX
683
+
684
+ def handle_message(msg)
685
+ case @compress_mode
686
+ when :large
687
+ if msg.byteslice(0) == 'x'
688
+ # The message is compressed, inflate it
689
+ msg = Zlib::Inflate.inflate(msg)
690
+ end
691
+ when :stream
692
+ # Write deflated string to buffer
693
+ @zlib_reader << msg
694
+
695
+ # Check if message ends in `ZLIB_SUFFIX`
696
+ return if msg.bytesize < 4 || msg.byteslice(-4, 4) != ZLIB_SUFFIX
697
+
698
+ # Inflate the deflated buffer
699
+ msg = @zlib_reader.inflate('')
700
+ end
701
+
702
+ # Parse packet
703
+ packet = JSON.parse(msg)
704
+ op = packet['op'].to_i
705
+
706
+ LOGGER.in(packet)
707
+
708
+ # If the packet has a sequence defined (all dispatch packets have one), make sure to update that in the
709
+ # session so it will be acknowledged next heartbeat.
710
+ # Only do this, of course, if a session has been created already; for a READY dispatch (which has s=0 set but is
711
+ # the packet that starts the session in the first place) we need not do any handling since initialising the
712
+ # session will set it to 0 by default.
713
+ @session.sequence = packet['s'] if packet['s'] && @session
714
+
715
+ case op
716
+ when Opcodes::DISPATCH
717
+ handle_dispatch(packet)
718
+ when Opcodes::HELLO
719
+ handle_hello(packet)
720
+ when Opcodes::RECONNECT
721
+ handle_reconnect
722
+ when Opcodes::INVALIDATE_SESSION
723
+ handle_invalidate_session(packet)
724
+ when Opcodes::HEARTBEAT_ACK
725
+ handle_heartbeat_ack(packet)
726
+ when Opcodes::HEARTBEAT
727
+ handle_heartbeat(packet)
728
+ else
729
+ LOGGER.warn("Received invalid opcode #{op} - please report with this information: #{msg}")
730
+ end
731
+ end
732
+
733
+ # Op 0
734
+ def handle_dispatch(packet)
735
+ data = packet['d']
736
+ type = packet['t'].intern
737
+
738
+ case type
739
+ when :READY
740
+ LOGGER.info("Discord using gateway protocol version: #{data['v']}, requested: #{GATEWAY_VERSION}")
741
+
742
+ @session = Session.new(data['session_id'], data['resume_gateway_url'])
743
+ @session.sequence = 0
744
+ @bot.__send__(:notify_ready) if @intents && @intents.nobits?(INTENTS[:servers])
745
+ when :RESUMED
746
+ # The RESUMED event is received after a successful op 6 (resume). It does nothing except tell the bot the
747
+ # connection is initiated (like READY would). Starting with v5, it doesn't set a new heartbeat interval anymore
748
+ # since that is handled by op 10 (HELLO).
749
+ LOGGER.info 'Resumed'
750
+ return
751
+ end
752
+
753
+ @bot.dispatch(packet)
754
+ end
755
+
756
+ # Op 1
757
+ def handle_heartbeat(packet)
758
+ # If we receive a heartbeat, we have to resend one with the same sequence
759
+ send_heartbeat(packet['s'])
760
+ end
761
+
762
+ # Op 7
763
+ def handle_reconnect
764
+ LOGGER.debug('Received op 7, reconnecting and attempting resume')
765
+ reconnect
766
+ end
767
+
768
+ # Op 9
769
+ def handle_invalidate_session(packet)
770
+ LOGGER.debug('Received op 9, invalidating session and re-identifying.')
771
+
772
+ if @session
773
+ if packet['d'] == true
774
+ reconnect
775
+ else
776
+ @session.invalidate
777
+ end
778
+ else
779
+ LOGGER.warn('Received op 9 without a running session! Not invalidating, we *should* be fine though.')
780
+ end
781
+
782
+ identify
783
+ end
784
+
785
+ # Op 10
786
+ def handle_hello(packet)
787
+ LOGGER.debug('Hello!')
788
+
789
+ # The heartbeat interval is given in ms, so divide it by 1000 to get seconds
790
+ interval = packet['d']['heartbeat_interval'].to_f / 1000.0
791
+ setup_heartbeats(interval)
792
+
793
+ LOGGER.debug("Trace: #{packet['d']['_trace']}")
794
+ LOGGER.debug("Session: #{@session.inspect}")
795
+
796
+ if @session&.should_resume?
797
+ # Make sure we're sending heartbeats again
798
+ @session.resume
799
+
800
+ # Send the actual resume packet to get the missing events
801
+ resume
802
+ else
803
+ identify
804
+ end
805
+ end
806
+
807
+ # Op 11
808
+ def handle_heartbeat_ack(packet)
809
+ LOGGER.debug("Received heartbeat ack for packet: #{packet.inspect}")
810
+ @last_heartbeat_acked = true if @check_heartbeat_acks
811
+ end
812
+
813
+ # Called when the websocket has been disconnected in some way - say due to a pipe error while sending
814
+ def handle_internal_close(e)
815
+ close
816
+ handle_close(e)
817
+ end
818
+
819
+ def handle_close(e)
820
+ @bot.__send__(:raise_event, Events::DisconnectEvent.new(@bot))
821
+
822
+ if e.respond_to? :code
823
+ # It is a proper close frame we're dealing with, print reason and message to console
824
+ LOGGER.error('Websocket close frame received!')
825
+ LOGGER.error("Code: #{e.code}")
826
+ LOGGER.error("Message: #{e.data}")
827
+
828
+ if e.code == 4014
829
+ LOGGER.error(<<~ERROR)
830
+ You attempted to identify with privileged intents that your bot is not authorized to use
831
+ Please enable the privileged intents on the bot page of your application on the discord developer page.
832
+ Read more here https://discord.com/developers/docs/topics/gateway#privileged-intents
833
+ ERROR
834
+ end
835
+
836
+ @should_reconnect = false if FATAL_CLOSE_CODES.include?(e.code)
837
+ elsif e.is_a? Exception
838
+ # Log the exception
839
+ LOGGER.error('The websocket connection has closed due to an error!')
840
+ LOGGER.log_exception(e)
841
+ else
842
+ LOGGER.error("The websocket connection has closed: #{e&.inspect || '(no information)'}")
843
+ end
844
+ end
845
+
846
+ def send(data, type = :text, code = nil)
847
+ LOGGER.out(data)
848
+
849
+ unless @handshaked && !@closed
850
+ # If we're not handshaked or closed, it means there's no connection to send anything to
851
+ raise 'Tried to send something to the websocket while not being connected!'
852
+ end
853
+
854
+ @send_limiter.wait if %i[text binary].include?(type)
855
+
856
+ # Create the frame we're going to send
857
+ frame = ::WebSocket::Frame::Outgoing::Client.new(data: data, type: type, version: @handshake.version, code: code)
858
+
859
+ # Try to send it
860
+ begin
861
+ @socket.write frame.to_s
862
+ rescue StandardError => e
863
+ # There has been an error!
864
+ @pipe_broken = true
865
+ handle_internal_close(e)
866
+ end
867
+ end
868
+
869
+ def close(code = 1000)
870
+ # If we're already closed, there's no need to do anything - return
871
+ return if @closed
872
+
873
+ # Suspend the session so we don't send heartbeats
874
+ @session&.suspend
875
+
876
+ # Send a close frame (if we can)
877
+ send nil, :close, code unless @pipe_broken
878
+
879
+ # We're officially closed, notify the main loop.
880
+ @closed = true
881
+
882
+ # Close the socket if possible
883
+ @socket&.close
884
+ @socket = nil
885
+
886
+ # Make sure we do necessary things as soon as we're closed
887
+ handle_close(nil)
888
+ end
889
+ end
890
+ end