@zygout/eris 0.0.0-stage → 0.19.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 (88) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +80 -3
  3. package/esm.mjs +72 -0
  4. package/index.d.ts +4397 -0
  5. package/index.js +75 -0
  6. package/lib/Client.js +4683 -0
  7. package/lib/Constants.d.ts +988 -0
  8. package/lib/Constants.js +1161 -0
  9. package/lib/command/Command.js +552 -0
  10. package/lib/command/CommandClient.js +460 -0
  11. package/lib/errors/DiscordHTTPError.js +63 -0
  12. package/lib/errors/DiscordRESTError.js +77 -0
  13. package/lib/gateway/Shard.js +3029 -0
  14. package/lib/gateway/ShardManager.js +164 -0
  15. package/lib/rest/Endpoints.js +172 -0
  16. package/lib/rest/RequestHandler.js +459 -0
  17. package/lib/structures/ApplicationCommand.js +125 -0
  18. package/lib/structures/AutoModerationRule.js +143 -0
  19. package/lib/structures/AutocompleteInteraction.js +80 -0
  20. package/lib/structures/Base.js +81 -0
  21. package/lib/structures/CategoryChannel.js +77 -0
  22. package/lib/structures/Channel.js +98 -0
  23. package/lib/structures/CommandInteraction.js +473 -0
  24. package/lib/structures/ComponentInteraction.js +538 -0
  25. package/lib/structures/DMChannel.js +278 -0
  26. package/lib/structures/Entitlement.js +77 -0
  27. package/lib/structures/ExtendedUser.js +46 -0
  28. package/lib/structures/ForumChannel.js +24 -0
  29. package/lib/structures/GroupChannel.js +106 -0
  30. package/lib/structures/Guild.js +1677 -0
  31. package/lib/structures/GuildAuditLogEntry.js +190 -0
  32. package/lib/structures/GuildChannel.js +128 -0
  33. package/lib/structures/GuildIntegration.js +99 -0
  34. package/lib/structures/GuildPreview.js +97 -0
  35. package/lib/structures/GuildScheduledEvent.js +176 -0
  36. package/lib/structures/GuildTemplate.js +76 -0
  37. package/lib/structures/GuildTextableChannel.js +260 -0
  38. package/lib/structures/Interaction.js +133 -0
  39. package/lib/structures/Invite.js +143 -0
  40. package/lib/structures/Lobby.js +108 -0
  41. package/lib/structures/LobbyMember.js +59 -0
  42. package/lib/structures/MediaChannel.js +216 -0
  43. package/lib/structures/Member.js +371 -0
  44. package/lib/structures/Message.js +708 -0
  45. package/lib/structures/ModalSubmitInteraction.js +478 -0
  46. package/lib/structures/NewsChannel.js +34 -0
  47. package/lib/structures/NewsThreadChannel.js +12 -0
  48. package/lib/structures/Permission.js +80 -0
  49. package/lib/structures/PermissionOverwrite.js +32 -0
  50. package/lib/structures/PingInteraction.js +39 -0
  51. package/lib/structures/PrivateThreadChannel.js +25 -0
  52. package/lib/structures/PublicThreadChannel.js +26 -0
  53. package/lib/structures/Role.js +163 -0
  54. package/lib/structures/SKU.js +80 -0
  55. package/lib/structures/SoundboardSound.js +79 -0
  56. package/lib/structures/StageChannel.js +59 -0
  57. package/lib/structures/StageInstance.js +55 -0
  58. package/lib/structures/Subscription.js +69 -0
  59. package/lib/structures/TextChannel.js +202 -0
  60. package/lib/structures/ThreadChannel.js +143 -0
  61. package/lib/structures/ThreadMember.js +59 -0
  62. package/lib/structures/UnavailableGuild.js +26 -0
  63. package/lib/structures/UnknownInteraction.js +502 -0
  64. package/lib/structures/User.js +296 -0
  65. package/lib/structures/VoiceChannel.js +166 -0
  66. package/lib/structures/VoiceState.js +84 -0
  67. package/lib/util/BrowserWebSocket.js +76 -0
  68. package/lib/util/Bucket.js +89 -0
  69. package/lib/util/Collection.js +202 -0
  70. package/lib/util/MultipartData.js +70 -0
  71. package/lib/util/Opus.js +33 -0
  72. package/lib/util/SequentialBucket.js +83 -0
  73. package/lib/util/emitDeprecation.js +26 -0
  74. package/lib/voice/Piper.js +300 -0
  75. package/lib/voice/SharedStream.js +238 -0
  76. package/lib/voice/VoiceConnection.js +1440 -0
  77. package/lib/voice/VoiceConnectionManager.js +151 -0
  78. package/lib/voice/VoiceDataStream.js +22 -0
  79. package/lib/voice/streams/BaseTransformer.js +40 -0
  80. package/lib/voice/streams/DCAOpusTransformer.js +78 -0
  81. package/lib/voice/streams/FFmpegDuplex.js +192 -0
  82. package/lib/voice/streams/FFmpegOggTransformer.js +35 -0
  83. package/lib/voice/streams/FFmpegPCMTransformer.js +26 -0
  84. package/lib/voice/streams/OggOpusTransformer.js +108 -0
  85. package/lib/voice/streams/PCMOpusTransformer.js +61 -0
  86. package/lib/voice/streams/VolumeTransformer.js +50 -0
  87. package/lib/voice/streams/WebmOpusTransformer.js +258 -0
  88. package/package.json +82 -6
@@ -0,0 +1,3029 @@
1
+ "use strict";
2
+
3
+ const util = require("util");
4
+ const Base = require("../structures/Base");
5
+ const Bucket = require("../util/Bucket");
6
+ const Channel = require("../structures/Channel");
7
+ const ForumChannel = require("../structures/ForumChannel");
8
+ const GuildChannel = require("../structures/GuildChannel");
9
+ const Message = require("../structures/Message");
10
+ const DMChannel = require("../structures/DMChannel");
11
+ const ExtendedUser = require("../structures/ExtendedUser");
12
+ const User = require("../structures/User");
13
+ const Invite = require("../structures/Invite");
14
+ const Interaction = require("../structures/Interaction");
15
+ const Constants = require("../Constants");
16
+ const ThreadChannel = require("../structures/ThreadChannel");
17
+ const StageInstance = require("../structures/StageInstance");
18
+ const GuildScheduledEvent = require("../structures/GuildScheduledEvent");
19
+ const GuildAuditLogEntry = require("../structures/GuildAuditLogEntry");
20
+ const AutoModerationRule = require("../structures/AutoModerationRule");
21
+ const SoundboardSound = require("../structures/SoundboardSound");
22
+ const Entitlement = require("../structures/Entitlement");
23
+ const GuildIntegration = require("../structures/GuildIntegration");
24
+ const Subscription = require("../structures/Subscription");
25
+
26
+ const WebSocket = typeof window !== "undefined" ? require("../util/BrowserWebSocket") : require("ws");
27
+
28
+ let EventEmitter;
29
+ try {
30
+ EventEmitter = require("eventemitter3");
31
+ } catch {
32
+ EventEmitter = require("events").EventEmitter;
33
+ }
34
+ let Erlpack;
35
+ try {
36
+ Erlpack = require("erlpack");
37
+ } catch {} // eslint-disable-line no-empty
38
+ let ZlibSync;
39
+ try {
40
+ ZlibSync = require("zlib-sync");
41
+ } catch {
42
+ try {
43
+ ZlibSync = require("pako");
44
+ } catch {} // eslint-disable-line no-empty
45
+ }
46
+
47
+ /**
48
+ * Represents a shard
49
+ * @extends EventEmitter
50
+ * @prop {Number} id The ID of the shard
51
+ * @prop {Boolean} connecting Whether the shard is connecting
52
+ * @prop {Array<String>?} discordServerTrace Debug trace of Discord servers
53
+ * @prop {Number} lastHeartbeatReceived Last time Discord acknowledged a heartbeat, null if shard has not sent heartbeat yet
54
+ * @prop {Number} lastHeartbeatSent Last time shard sent a heartbeat, null if shard has not sent heartbeat yet
55
+ * @prop {Number} latency The current latency between the shard and Discord, in milliseconds
56
+ * @prop {Boolean} ready Whether the shard is ready
57
+ * @prop {String} status The status of the shard. "disconnected"/"connecting"/"handshaking"/"ready"/"identifying"/"resuming"
58
+ */
59
+ function getOldUserData(user) {
60
+ return {
61
+ avatar: user.avatar,
62
+ avatarDecorationData: user.avatarDecorationData,
63
+ collectibles: user.collectibles,
64
+ discriminator: user.discriminator,
65
+ globalName: user.globalName,
66
+ primaryGuild: user.primaryGuild,
67
+ username: user.username,
68
+ };
69
+ }
70
+
71
+ function hasUserChanged(user, data) {
72
+ if (user.username !== data.username || user.globalName !== data.global_name || user.discriminator !== data.discriminator || user.avatar !== data.avatar) {
73
+ return true;
74
+ }
75
+ if (data.avatar_decoration_data !== undefined && (user.avatarDecorationData ? user.avatarDecorationData.asset : null) !== (data.avatar_decoration_data ? data.avatar_decoration_data.asset : null)) {
76
+ return true;
77
+ }
78
+ if (data.collectibles !== undefined) {
79
+ const oldNameplate = user.collectibles && user.collectibles.nameplate ? user.collectibles.nameplate.sku_id : null;
80
+ const newNameplate = data.collectibles && data.collectibles.nameplate ? data.collectibles.nameplate.sku_id : null;
81
+ if (oldNameplate !== newNameplate) {
82
+ return true;
83
+ }
84
+ }
85
+ if (data.primary_guild !== undefined) {
86
+ const oldGuild = user.primaryGuild || {};
87
+ const newGuild = data.primary_guild || {};
88
+ if (oldGuild.identityGuildID !== newGuild.identity_guild_id || oldGuild.identityEnabled !== newGuild.identity_enabled || oldGuild.tag !== newGuild.tag || oldGuild.badge !== newGuild.badge) {
89
+ return true;
90
+ }
91
+ }
92
+ return false;
93
+ }
94
+
95
+ class Shard extends EventEmitter {
96
+ constructor(id, client) {
97
+ super();
98
+
99
+ this.id = id;
100
+ this.client = client;
101
+
102
+ this.onPacket = this.onPacket.bind(this);
103
+ this._onWSOpen = this._onWSOpen.bind(this);
104
+ this._onWSMessage = this._onWSMessage.bind(this);
105
+ this._onWSError = this._onWSError.bind(this);
106
+ this._onWSClose = this._onWSClose.bind(this);
107
+
108
+ this.hardReset();
109
+ }
110
+
111
+ checkReady() {
112
+ if (!this.ready) {
113
+ if (this.getAllUsersQueue.length > 0) {
114
+ this.requestGuildMembers(this.getAllUsersQueue);
115
+ this.getAllUsersQueue = [];
116
+ this.getAllUsersLength = 1;
117
+ return;
118
+ }
119
+ if (Object.keys(this.getAllUsersCount).length === 0) {
120
+ this.ready = true;
121
+ /**
122
+ * Fired when the shard turns ready
123
+ * @event Shard#ready
124
+ */
125
+ super.emit("ready");
126
+ }
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Tells the shard to connect
132
+ */
133
+ connect() {
134
+ if (this.ws && this.ws.readyState != WebSocket.CLOSED) {
135
+ this.emit("error", new Error("Existing connection detected"), this.id);
136
+ return;
137
+ }
138
+ ++this.connectAttempts;
139
+ this.connecting = true;
140
+ return this.initializeWS();
141
+ }
142
+
143
+ createGuild(_guild) {
144
+ this.client.guildShardMap[_guild.id] = this.id;
145
+ const guild = this.client.guilds.add(_guild, this.client, true);
146
+ if (this.client.options.getAllUsers && guild.members.size < guild.memberCount) {
147
+ this.getGuildMembers(guild.id, {
148
+ presences: this.client.options.intents && this.client.options.intents & Constants.Intents.guildPresences,
149
+ });
150
+ }
151
+ return guild;
152
+ }
153
+
154
+ /**
155
+ * Disconnects the shard
156
+ * @arg {Object?} [options] Shard disconnect options
157
+ * @arg {String | Boolean} [options.reconnect] false means destroy everything, true means you want to reconnect in the future, "auto" will autoreconnect
158
+ * @arg {Error} [error] The error that causes the disconnect
159
+ */
160
+ disconnect(options = {}, error) {
161
+ if (!this.ws) {
162
+ return;
163
+ }
164
+
165
+ if (this.heartbeatInterval) {
166
+ clearInterval(this.heartbeatInterval);
167
+ this.heartbeatInterval = null;
168
+ }
169
+
170
+ if (this.ws.readyState !== WebSocket.CLOSED) {
171
+ this.ws.removeListener("message", this._onWSMessage);
172
+ this.ws.removeListener("close", this._onWSClose);
173
+ try {
174
+ if (options.reconnect && this.sessionID) {
175
+ if (this.ws.readyState === WebSocket.OPEN) {
176
+ this.ws.close(4901, "Eris: reconnect");
177
+ } else {
178
+ this.emit("debug", `Terminating websocket (state: ${this.ws.readyState})`, this.id);
179
+ this.ws.terminate();
180
+ }
181
+ } else {
182
+ this.ws.close(1000, "Eris: normal");
183
+ }
184
+ } catch (err) {
185
+ this.emit("error", err, this.id);
186
+ }
187
+ }
188
+ this.ws = null;
189
+ this.reset();
190
+
191
+ if (error) {
192
+ this.emit("error", error, this.id);
193
+ }
194
+
195
+ /**
196
+ * Fired when the shard disconnects
197
+ * @event Shard#disconnect
198
+ * @prop {Error?} err The error, if any
199
+ */
200
+ super.emit("disconnect", error);
201
+
202
+ if (this.sessionID && this.connectAttempts >= this.client.options.maxResumeAttempts) {
203
+ this.emit("debug", `Automatically invalidating session due to excessive resume attempts | Attempt ${this.connectAttempts}`, this.id);
204
+ this.sessionID = null;
205
+ this.resumeURL = null;
206
+ }
207
+
208
+ if (options.reconnect === "auto" && this.client.options.autoreconnect) {
209
+ /**
210
+ * Fired when stuff happens and gives more info
211
+ * @event Client#debug
212
+ * @prop {String} message The debug message
213
+ * @prop {Number} id The ID of the shard
214
+ */
215
+ if (this.sessionID) {
216
+ this.emit("debug", `Immediately reconnecting for potential resume | Attempt ${this.connectAttempts}`, this.id);
217
+ this.client.shards.connect(this);
218
+ } else {
219
+ this.emit("debug", `Queueing reconnect in ${this.reconnectInterval}ms | Attempt ${this.connectAttempts}`, this.id);
220
+ setTimeout(() => {
221
+ this.client.shards.connect(this);
222
+ }, this.reconnectInterval);
223
+ this.reconnectInterval = Math.min(Math.round(this.reconnectInterval * (Math.random() * 2 + 1)), 30000);
224
+ }
225
+ } else if (!options.reconnect) {
226
+ this.hardReset();
227
+ }
228
+ }
229
+
230
+ /**
231
+ * Update the bot's AFK status.
232
+ * @arg {Boolean} afk Whether the bot user is AFK or not
233
+ */
234
+ editAFK(afk) {
235
+ this.presence.afk = !!afk;
236
+
237
+ this.sendStatusUpdate();
238
+ }
239
+
240
+ /**
241
+ * Updates the bot's status on all guilds the shard is in
242
+ * @arg {String} [status] Sets the bot's status, either "online", "idle", "dnd", or "invisible"
243
+ * @arg {Array | Object} [activities] Sets the bot's activities. A single activity object is also accepted for backwards compatibility
244
+ * @arg {String} [activities[].name] The name of the activity. Note: When setting a custom status, use `state` instead
245
+ * @arg {Number} activities[].type The type of the activity. 0 is playing, 1 is streaming (Twitch only), 2 is listening, 3 is watching, 4 is custom status, 5 is competing in
246
+ * @arg {String} [activities[].url] The URL of the activity
247
+ * @arg {String} [activities[].state] The state of the activity. This is the text to be displayed as the bots custom status
248
+ */
249
+ editStatus(status, activities) {
250
+ if (activities === undefined && typeof status === "object") {
251
+ activities = status;
252
+ status = undefined;
253
+ }
254
+ if (status) {
255
+ this.presence.status = status;
256
+ }
257
+ if (activities === null) {
258
+ activities = [];
259
+ } else if (activities && !Array.isArray(activities)) {
260
+ activities = [activities];
261
+ }
262
+ if (activities !== undefined) {
263
+ this.presence.activities = activities;
264
+ }
265
+
266
+ this.sendStatusUpdate();
267
+ }
268
+
269
+ emit(event, ...args) {
270
+ this.client.emit.call(this.client, event, ...args);
271
+ if (event !== "error" || this.listeners("error").length > 0) {
272
+ super.emit.call(this, event, ...args);
273
+ }
274
+ }
275
+
276
+ getGuildMembers(guildID, timeout) {
277
+ if (this.getAllUsersCount.hasOwnProperty(guildID)) {
278
+ throw new Error("Cannot request all members while an existing request is processing");
279
+ }
280
+ this.getAllUsersCount[guildID] = true;
281
+ // Using intents, request one guild at a time
282
+ if (this.client.options.intents) {
283
+ if (!(this.client.options.intents & Constants.Intents.guildMembers)) {
284
+ throw new Error("Cannot request all members without guildMembers intent");
285
+ }
286
+ this.requestGuildMembers([guildID], timeout);
287
+ } else {
288
+ if (this.getAllUsersLength + 3 + guildID.length > 4048) { // 4096 - "{\"op\":8,\"d\":{\"guild_id\":[],\"query\":\"\",\"limit\":0}}".length + 1 for lazy comma offset
289
+ this.requestGuildMembers(this.getAllUsersQueue);
290
+ this.getAllUsersQueue = [guildID];
291
+ this.getAllUsersLength = 1 + guildID.length + 3;
292
+ } else {
293
+ this.getAllUsersQueue.push(guildID);
294
+ this.getAllUsersLength += guildID.length + 3;
295
+ }
296
+ }
297
+ }
298
+
299
+ hardReset() {
300
+ this.reset();
301
+ this.seq = 0;
302
+ this.sessionID = null;
303
+ this.resumeURL = null;
304
+ this.reconnectInterval = 1000;
305
+ this.connectAttempts = 0;
306
+ this.ws = null;
307
+ this.heartbeatInterval = null;
308
+ this.guildCreateTimeout = null;
309
+ this.globalBucket = new Bucket(120, 60000, { reservedTokens: 5 });
310
+ this.presenceUpdateBucket = new Bucket(5, 20000);
311
+ this.presence = JSON.parse(JSON.stringify(this.client.presence)); // Fast copy
312
+ Object.defineProperty(this, "_token", {
313
+ configurable: true,
314
+ enumerable: false,
315
+ writable: true,
316
+ value: this.client._token,
317
+ });
318
+ }
319
+
320
+ heartbeat(normal) {
321
+ // Can only heartbeat after identify/resume succeeds, session will be killed otherwise, discord/discord-api-docs#1619
322
+ if (this.status === "resuming" || this.status === "identifying") {
323
+ return;
324
+ }
325
+ if (normal) {
326
+ if (!this.lastHeartbeatAck) {
327
+ this.emit("debug", "Heartbeat timeout; " + JSON.stringify({
328
+ lastReceived: this.lastHeartbeatReceived,
329
+ lastSent: this.lastHeartbeatSent,
330
+ interval: this.heartbeatInterval,
331
+ status: this.status,
332
+ timestamp: Date.now(),
333
+ }));
334
+ return this.disconnect({
335
+ reconnect: "auto",
336
+ }, new Error("Server didn't acknowledge previous heartbeat, possible lost connection"));
337
+ }
338
+ this.lastHeartbeatAck = false;
339
+ }
340
+ this.lastHeartbeatSent = Date.now();
341
+ this.sendWS(Constants.GatewayOPCodes.HEARTBEAT, this.seq, true);
342
+ }
343
+
344
+ identify() {
345
+ if (this.client.options.compress && !ZlibSync) {
346
+ /**
347
+ * Fired when the shard encounters an error
348
+ * @event Client#error
349
+ * @prop {Error} err The error
350
+ * @prop {Number} id The ID of the shard
351
+ */
352
+ this.emit("error", new Error("pako/zlib-sync not found, cannot decompress data"));
353
+ return;
354
+ }
355
+ this.status = "identifying";
356
+ const identify = {
357
+ token: this._token,
358
+ v: Constants.GATEWAY_VERSION,
359
+ compress: !!this.client.options.compress,
360
+ large_threshold: this.client.options.largeThreshold,
361
+ intents: this.client.options.intents,
362
+ properties: {
363
+ os: process.platform,
364
+ browser: "Eris",
365
+ device: "Eris",
366
+ },
367
+ };
368
+ if (this.client.options.maxShards > 1) {
369
+ identify.shard = [this.id, this.client.options.maxShards];
370
+ }
371
+ if (this.presence.status) {
372
+ identify.presence = this.presence;
373
+ }
374
+ this.sendWS(Constants.GatewayOPCodes.IDENTIFY, identify);
375
+ }
376
+
377
+ initializeWS() {
378
+ if (!this._token) {
379
+ return this.disconnect(null, new Error("Token not specified"));
380
+ }
381
+
382
+ this.status = "connecting";
383
+ if (this.client.options.compress) {
384
+ this.emit("debug", "Initializing zlib-sync-based compression");
385
+ this._zlibSync = new ZlibSync.Inflate({
386
+ chunkSize: 128 * 1024,
387
+ });
388
+ }
389
+ if (this.sessionID) {
390
+ if (!this.resumeURL) {
391
+ this.emit("warn", "Resume url is not currently present. Discord may disconnect you quicker.");
392
+ }
393
+ this.ws = new WebSocket(this.resumeURL || this.client.gatewayURL, this.client.options.ws);
394
+ } else {
395
+ this.ws = new WebSocket(this.client.gatewayURL, this.client.options.ws);
396
+ }
397
+ this.ws.on("open", this._onWSOpen);
398
+ this.ws.on("message", this._onWSMessage);
399
+ this.ws.on("error", this._onWSError);
400
+ this.ws.on("close", this._onWSClose);
401
+
402
+ this.connectTimeout = setTimeout(() => {
403
+ if (this.connecting) {
404
+ this.disconnect({
405
+ reconnect: "auto",
406
+ }, new Error("Connection timeout"));
407
+ }
408
+ }, this.client.options.connectionTimeout);
409
+ }
410
+
411
+ onPacket(packet) {
412
+ if (this.listeners("rawWS").length > 0 || this.client.listeners("rawWS").length) {
413
+ /**
414
+ * Fired when the shard receives a websocket packet
415
+ * @event Client#rawWS
416
+ * @prop {Object} packet The packet
417
+ * @prop {Number} id The ID of the shard
418
+ */
419
+ this.emit("rawWS", packet, this.id);
420
+ }
421
+
422
+ if (packet.s) {
423
+ if (packet.s > this.seq + 1 && this.ws && this.status !== "resuming") {
424
+ /**
425
+ * Fired to warn of something weird but non-breaking happening
426
+ * @event Client#warn
427
+ * @prop {String} message The warning message
428
+ * @prop {Number} id The ID of the shard
429
+ */
430
+ this.emit("warn", `Non-consecutive sequence (${this.seq} -> ${packet.s})`, this.id);
431
+ }
432
+ this.seq = packet.s;
433
+ }
434
+
435
+ switch (packet.op) {
436
+ case Constants.GatewayOPCodes.DISPATCH: {
437
+ if (!this.client.options.disableEvents[packet.t]) {
438
+ this.wsEvent(packet);
439
+ }
440
+ break;
441
+ }
442
+ case Constants.GatewayOPCodes.HEARTBEAT: {
443
+ this.heartbeat();
444
+ break;
445
+ }
446
+ case Constants.GatewayOPCodes.INVALID_SESSION: {
447
+ this.seq = 0;
448
+ this.sessionID = null;
449
+ this.resumeURL = null;
450
+ this.emit("warn", "Invalid session, reidentifying!", this.id);
451
+ this.identify();
452
+ break;
453
+ }
454
+ case Constants.GatewayOPCodes.RECONNECT: {
455
+ this.emit("debug", "Reconnecting due to server request", this.id);
456
+ this.disconnect({
457
+ reconnect: "auto",
458
+ });
459
+ break;
460
+ }
461
+ case Constants.GatewayOPCodes.HELLO: {
462
+ if (packet.d.heartbeat_interval > 0) {
463
+ if (this.heartbeatInterval) {
464
+ clearInterval(this.heartbeatInterval);
465
+ }
466
+ this.heartbeatInterval = setInterval(() => this.heartbeat(true), packet.d.heartbeat_interval);
467
+ }
468
+
469
+ this.discordServerTrace = packet.d._trace;
470
+ this.connecting = false;
471
+ if (this.connectTimeout) {
472
+ clearTimeout(this.connectTimeout);
473
+ }
474
+ this.connectTimeout = null;
475
+
476
+ if (this.sessionID) {
477
+ this.resume();
478
+ } else {
479
+ this.identify();
480
+ // Cannot heartbeat when resuming, discord/discord-api-docs#1619
481
+ this.heartbeat();
482
+ }
483
+ /**
484
+ * Fired when a shard receives an OP:10/HELLO packet
485
+ * @event Client#hello
486
+ * @prop {Array<String>} trace The Discord server trace of the gateway and session servers
487
+ * @prop {Number} id The ID of the shard
488
+ */
489
+ this.emit("hello", packet.d._trace, this.id);
490
+ break;
491
+ }
492
+ case Constants.GatewayOPCodes.HEARTBEAT_ACK: {
493
+ this.lastHeartbeatAck = true;
494
+ this.lastHeartbeatReceived = Date.now();
495
+ this.latency = this.lastHeartbeatReceived - this.lastHeartbeatSent;
496
+ break;
497
+ }
498
+ default: {
499
+ this.emit("unknown", packet, this.id);
500
+ break;
501
+ }
502
+ }
503
+ }
504
+
505
+ requestChannelInfo(guildID, options = {}) {
506
+ this.sendWS(Constants.GatewayOPCodes.REQUEST_CHANNEL_INFO, {
507
+ guild_id: guildID,
508
+ fields: options.fields || ["status", "voice_start_time"],
509
+ });
510
+ return new Promise((res) => {
511
+ if (!this.requestChannelInfoPromise[guildID]) {
512
+ this.requestChannelInfoPromise[guildID] = [];
513
+ }
514
+ const request = {
515
+ res: res,
516
+ timeout: setTimeout(() => {
517
+ const requests = this.requestChannelInfoPromise[guildID];
518
+ if (requests) {
519
+ requests.splice(requests.indexOf(request), 1);
520
+ if (!requests.length) {
521
+ delete this.requestChannelInfoPromise[guildID];
522
+ }
523
+ }
524
+ res([]);
525
+ }, options.timeout || this.client.options.requestTimeout),
526
+ };
527
+ this.requestChannelInfoPromise[guildID].push(request);
528
+ });
529
+ }
530
+
531
+ requestGuildMembers(guildID, options) {
532
+ const opts = {
533
+ guild_id: guildID,
534
+ limit: (options && options.limit) || 0,
535
+ user_ids: options && options.userIDs,
536
+ query: options && options.query,
537
+ nonce: Date.now().toString() + Math.random().toString(36),
538
+ presences: options && options.presences,
539
+ };
540
+ if (!opts.user_ids && !opts.query) {
541
+ opts.query = "";
542
+ }
543
+ if (!opts.query && !opts.user_ids && (this.client.options.intents && !(this.client.options.intents & Constants.Intents.guildMembers))) {
544
+ throw new Error("Cannot request all members without guildMembers intent");
545
+ }
546
+ if (opts.presences && (this.client.options.intents && !(this.client.options.intents & Constants.Intents.guildPresences))) {
547
+ throw new Error("Cannot request members presences without guildPresences intent");
548
+ }
549
+ if (opts.user_ids && opts.user_ids.length > 100) {
550
+ throw new Error("Cannot request more than 100 users by their ID");
551
+ }
552
+ this.sendWS(Constants.GatewayOPCodes.REQUEST_GUILD_MEMBERS, opts);
553
+ return new Promise((res) => this.requestMembersPromise[opts.nonce] = {
554
+ res: res,
555
+ received: 0,
556
+ members: [],
557
+ timeout: setTimeout(() => {
558
+ res(this.requestMembersPromise[opts.nonce].members);
559
+ delete this.requestMembersPromise[opts.nonce];
560
+ }, (options && options.timeout) || this.client.options.requestTimeout),
561
+ });
562
+ }
563
+
564
+ requestGuildSoundboardSounds(options) {
565
+ const opts = {
566
+ guild_ids: options.guildIDs,
567
+ };
568
+ const soundboardSounds = options.guildIDs.reduce((obj, key) => {
569
+ obj[key] = undefined;
570
+ return obj;
571
+ }, {});
572
+ const nonce = Date.now().toString() + Math.random().toString(36);
573
+ this.sendWS(Constants.GatewayOPCodes.REQUEST_SOUNDBOARD_SOUNDS, opts);
574
+ return new Promise((res) => this.requestSoundboardSoundsPromise[nonce] = {
575
+ res: res,
576
+ soundboardSounds: soundboardSounds,
577
+ timeout: setTimeout(() => {
578
+ res(this.requestSoundboardSoundsPromise[nonce].soundboardSounds);
579
+ delete this.requestSoundboardSoundsPromise[nonce];
580
+ }, (options && options.timeout) || this.client.options.requestTimeout),
581
+ });
582
+ }
583
+
584
+ reset() {
585
+ this.connecting = false;
586
+ this.ready = false;
587
+ this.preReady = false;
588
+ if (this.requestMembersPromise !== undefined) {
589
+ for (const guildID in this.requestMembersPromise) {
590
+ if (!this.requestMembersPromise.hasOwnProperty(guildID)) {
591
+ continue;
592
+ }
593
+ clearTimeout(this.requestMembersPromise[guildID].timeout);
594
+ this.requestMembersPromise[guildID].res(this.requestMembersPromise[guildID].received);
595
+ }
596
+ }
597
+ this.requestMembersPromise = {};
598
+ if (this.requestChannelInfoPromise !== undefined) {
599
+ for (const guildID in this.requestChannelInfoPromise) {
600
+ for (const request of this.requestChannelInfoPromise[guildID]) {
601
+ clearTimeout(request.timeout);
602
+ request.res([]);
603
+ }
604
+ }
605
+ }
606
+ this.requestChannelInfoPromise = {};
607
+ this.requestSoundboardSoundsPromise = {};
608
+ this.getAllUsersCount = {};
609
+ this.getAllUsersQueue = [];
610
+ this.getAllUsersLength = 1;
611
+ this.latency = Infinity;
612
+ this.lastHeartbeatAck = true;
613
+ this.lastHeartbeatReceived = null;
614
+ this.lastHeartbeatSent = null;
615
+ this.status = "disconnected";
616
+ if (this.connectTimeout) {
617
+ clearTimeout(this.connectTimeout);
618
+ }
619
+ this.connectTimeout = null;
620
+ }
621
+
622
+ restartGuildCreateTimeout() {
623
+ if (this.guildCreateTimeout) {
624
+ clearTimeout(this.guildCreateTimeout);
625
+ this.guildCreateTimeout = null;
626
+ }
627
+ if (!this.ready) {
628
+ if (this.client.unavailableGuilds.size === 0) {
629
+ return this.checkReady();
630
+ }
631
+ this.guildCreateTimeout = setTimeout(() => {
632
+ this.checkReady();
633
+ }, this.client.options.guildCreateTimeout);
634
+ }
635
+ }
636
+
637
+ resume() {
638
+ this.status = "resuming";
639
+ this.sendWS(Constants.GatewayOPCodes.RESUME, {
640
+ token: this._token,
641
+ session_id: this.sessionID,
642
+ seq: this.seq,
643
+ });
644
+ }
645
+
646
+ sendStatusUpdate() {
647
+ this.sendWS(Constants.GatewayOPCodes.PRESENCE_UPDATE, {
648
+ activities: this.presence.activities,
649
+ afk: !!this.presence.afk,
650
+ since: this.presence.status === "idle" ? Date.now() : null,
651
+ status: this.presence.status,
652
+ });
653
+ }
654
+
655
+ sendWS(op, _data, priority = false) {
656
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
657
+ let i = 0;
658
+ let waitFor = 1;
659
+ const func = () => {
660
+ if (++i >= waitFor && this.ws && this.ws.readyState === WebSocket.OPEN) {
661
+ const data = Erlpack ? Erlpack.pack({ op: op, d: _data }) : JSON.stringify({ op: op, d: _data });
662
+ this.ws.send(data);
663
+ if (_data.token) {
664
+ delete _data.token;
665
+ }
666
+ this.emit("debug", JSON.stringify({ op: op, d: _data }), this.id);
667
+ }
668
+ };
669
+ if (op === Constants.GatewayOPCodes.PRESENCE_UPDATE) {
670
+ ++waitFor;
671
+ this.presenceUpdateBucket.queue(func, priority);
672
+ }
673
+ this.globalBucket.queue(func, priority);
674
+ }
675
+ }
676
+
677
+ wsEvent(packet) {
678
+ switch (packet.t) {
679
+ case "AUTO_MODERATION_ACTION_EXECUTION": {
680
+ const guild = this.client.guilds.get(packet.d.guild_id);
681
+ if (!guild) {
682
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in AUTO_MODERATION_ACTION_EXECUTION`);
683
+ break;
684
+ }
685
+
686
+ /**
687
+ * Fired when an auto moderation action is executed.
688
+ * @event Client#autoModerationActionExecution
689
+ * @prop {Guild} guild The guild associated with the action
690
+ * @prop {Object} action The exection action
691
+ */
692
+ this.emit("autoModerationActionExecution", guild, {
693
+ action: packet.d.action,
694
+ alertSystemMessageID: packet.d.alert_system_message_id,
695
+ channelID: packet.d.channel_id,
696
+ content: packet.d.content,
697
+ guildID: packet.d.guild_id,
698
+ matchedContent: packet.d.matched_content,
699
+ matchedKeyword: packet.d.matched_keyword,
700
+ messageID: packet.d.message_id,
701
+ ruleID: packet.d.rule_id,
702
+ ruleTriggerType: packet.d.rule_trigger_type,
703
+ userID: packet.d.user_id,
704
+ });
705
+ break;
706
+ }
707
+
708
+ case "AUTO_MODERATION_RULE_CREATE": {
709
+ const guild = this.client.guilds.get(packet.d.guild_id);
710
+ if (!guild) {
711
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in AUTO_MODERATION_RULE_CREATE`);
712
+ break;
713
+ }
714
+
715
+ /**
716
+ * Fired when an auto moderation rule is created
717
+ * @event Client#autoModerationRuleCreate
718
+ * @prop {Guild} guild The guild associated with the rule
719
+ * @prop {AutoModerationRule} rule The created rule
720
+ */
721
+ this.emit("autoModerationRuleCreate", guild, guild.autoModerationRules.add(packet.d, this.client));
722
+ break;
723
+ }
724
+ case "AUTO_MODERATION_RULE_DELETE": {
725
+ const guild = this.client.guilds.get(packet.d.guild_id);
726
+ if (!guild) {
727
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in AUTO_MODERATION_RULE_DELETE`);
728
+ break;
729
+ }
730
+
731
+ /**
732
+ * Fired when an auto moderation rule is deleted
733
+ * @event Client#autoModerationRuleDelete
734
+ * @prop {Guild} guild The guild associated with the rule
735
+ * @prop {AutoModerationRule} rule The deleted rule
736
+ */
737
+ this.emit("autoModerationRuleDelete", guild, guild.autoModerationRules.remove(packet.d) || new AutoModerationRule(packet.d, this.client));
738
+ break;
739
+ }
740
+ case "AUTO_MODERATION_RULE_UPDATE": {
741
+ const guild = this.client.guilds.get(packet.d.guild_id);
742
+ if (!guild) {
743
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in AUTO_MODERATION_RULE_DELETE`);
744
+ break;
745
+ }
746
+
747
+ const rule = guild.autoModerationRules.get(packet.d.id);
748
+ let oldRule = null;
749
+
750
+ oldRule = {
751
+ actions: rule.actions,
752
+ enabled: rule.enabled,
753
+ eventType: rule.eventType,
754
+ exemptChannels: rule.exemptChannels,
755
+ exemptRoles: rule.exemptRoles,
756
+ name: rule.name,
757
+ triggerMetadata: rule.triggerMetadata,
758
+ };
759
+
760
+ /**
761
+ * Fired when an auto moderation rule is updated
762
+ * @event Client#autoModerationRuleUpdate
763
+ * @prop {Guild} guild The guild associated with the rule
764
+ * @prop {AutoModerationRule} rule The updated role
765
+ * @prop {Object?} oldRule The old rule. If the rule was uncached, this will be null
766
+ */
767
+ this.emit("autoModerationRuleUpdate", guild, guild.autoModerationRules.update(packet.d, this.client), oldRule);
768
+ break;
769
+ }
770
+ case "PRESENCE_UPDATE": {
771
+ if (packet.d.user.username !== undefined) {
772
+ let user = this.client.users.get(packet.d.user.id);
773
+ let oldUser = null;
774
+ if (user && hasUserChanged(user, packet.d.user)) {
775
+ oldUser = getOldUserData(user);
776
+ }
777
+ if (!user || oldUser) {
778
+ user = this.client.users.update(packet.d.user, this.client);
779
+ /**
780
+ * Fired when a user's avatar, avatar decoration, collectibles, discriminator, display name, primary guild or username changes
781
+ * @event Client#userUpdate
782
+ * @prop {User} user The updated user
783
+ * @prop {Object?} oldUser The old user data. If the user was uncached, this will be null
784
+ * @prop {String?} oldUser.avatar The hash of the user's avatar, or null if no avatar
785
+ * @prop {Object?} oldUser.avatarDecorationData The data of the user's avatar decoration, including the asset and sku ID, or null if no avatar decoration
786
+ * @prop {Object?} oldUser.collectibles The data for the user's collectibles, including their nameplate, or null if no collectibles. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/user#collectibles) for object structure
787
+ * @prop {String} oldUser.discriminator The discriminator of the user
788
+ * @prop {String?} oldUser.globalName The user's display name, if it is set. For bots, this is the application name
789
+ * @prop {Object?} oldUser.primaryGuild The user's primary guild (guild tag), or null if not set
790
+ * @prop {String} oldUser.username The username of the user
791
+ */
792
+ this.emit("userUpdate", user, oldUser);
793
+ }
794
+ }
795
+ const guild = this.client.guilds.get(packet.d.guild_id);
796
+ if (!guild) {
797
+ this.emit("debug", "Rogue presence update: " + JSON.stringify(packet), this.id);
798
+ break;
799
+ }
800
+ let member = guild.members.get(packet.d.id = packet.d.user.id);
801
+ let oldPresence = null;
802
+ if (member) {
803
+ oldPresence = {
804
+ activities: member.activities,
805
+ clientStatus: member.clientStatus,
806
+ status: member.status,
807
+ };
808
+ }
809
+ if ((!member && packet.d.user.username) || oldPresence) {
810
+ member = guild.members.update(packet.d, guild);
811
+ /**
812
+ * Fired when a guild member's status or game changes
813
+ * @event Client#presenceUpdate
814
+ * @prop {Member} other The updated member
815
+ * @prop {Object?} oldPresence The old presence data. If the user was offline when the bot started and the client option getAllUsers is not true, this will be null
816
+ * @prop {Array<Object>?} oldPresence.activities The member's current activities
817
+ * @prop {Object?} oldPresence.clientStatus The member's per-client status
818
+ * @prop {String} oldPresence.clientStatus.desktop The member's status on desktop. Either "online", "idle", "dnd", or "offline". Will be "offline" for bots
819
+ * @prop {String} oldPresence.clientStatus.mobile The member's status on mobile. Either "online", "idle", "dnd", or "offline". Will be "offline" for bots
820
+ * @prop {String} oldPresence.clientStatus.web The member's status on web. Either "online", "idle", "dnd", or "offline". Will be "online" for bots
821
+ * @prop {String} oldPresence.status The other user's old status. Either "online", "idle", or "offline"
822
+ */
823
+ this.emit("presenceUpdate", member, oldPresence);
824
+ }
825
+ break;
826
+ }
827
+ case "VOICE_STATE_UPDATE": { // (╯°□°)╯︵ ┻━┻
828
+ if (packet.d.guild_id && packet.d.user_id === this.client.user.id) {
829
+ const voiceConnection = this.client.voiceConnections.get(packet.d.guild_id);
830
+ if (voiceConnection) {
831
+ if (packet.d.channel_id === null) {
832
+ this.client.voiceConnections.leave(packet.d.guild_id);
833
+ } else if (voiceConnection.channelID !== packet.d.channel_id) {
834
+ voiceConnection.switchChannel(packet.d.channel_id, true);
835
+ }
836
+ }
837
+ }
838
+ if (packet.d.self_stream === undefined) {
839
+ packet.d.self_stream = false;
840
+ }
841
+ const guild = this.client.guilds.get(packet.d.guild_id);
842
+ if (!guild) {
843
+ break;
844
+ }
845
+ let member = guild.members.get(packet.d.id = packet.d.user_id);
846
+ if (!member) {
847
+ if (!packet.d.member) {
848
+ this.emit("voiceStateUpdate", {
849
+ id: packet.d.user_id,
850
+ voiceState: {
851
+ deaf: packet.d.deaf,
852
+ mute: packet.d.mute,
853
+ selfDeaf: packet.d.self_deaf,
854
+ selfMute: packet.d.self_mute,
855
+ selfStream: packet.d.self_stream,
856
+ selfVideo: packet.d.self_video,
857
+ },
858
+ }, null);
859
+ break;
860
+ }
861
+ // Updates the member cache with this member for future events.
862
+ packet.d.member.id = packet.d.user_id;
863
+ member = guild.members.add(packet.d.member, guild);
864
+
865
+ const channel = guild.channels.find((channel) => (channel.type === Constants.ChannelTypes.GUILD_VOICE || channel.type === Constants.ChannelTypes.GUILD_STAGE_VOICE) && channel.voiceMembers.get(packet.d.id));
866
+ if (channel) {
867
+ channel.voiceMembers.remove(packet.d);
868
+ this.emit("debug", "VOICE_STATE_UPDATE member null but in channel: " + packet.d.id, this.id);
869
+ }
870
+ }
871
+ const oldState = {
872
+ deaf: member.voiceState.deaf,
873
+ mute: member.voiceState.mute,
874
+ selfDeaf: member.voiceState.selfDeaf,
875
+ selfMute: member.voiceState.selfMute,
876
+ selfStream: member.voiceState.selfStream,
877
+ selfVideo: member.voiceState.selfVideo,
878
+ };
879
+ const oldChannelID = member.voiceState.channelID;
880
+ member.update(packet.d, this.client);
881
+ if (oldChannelID != packet.d.channel_id) {
882
+ let oldChannel, newChannel;
883
+ if (oldChannelID) {
884
+ oldChannel = guild.channels.get(oldChannelID);
885
+ if (oldChannel && oldChannel.type !== Constants.ChannelTypes.GUILD_VOICE && oldChannel.type !== Constants.ChannelTypes.GUILD_STAGE_VOICE) {
886
+ this.emit("warn", "Old channel not a recognized voice channel: " + oldChannelID, this.id);
887
+ oldChannel = null;
888
+ }
889
+ }
890
+ if (packet.d.channel_id && (newChannel = guild.channels.get(packet.d.channel_id)) && (newChannel.type === Constants.ChannelTypes.GUILD_VOICE || newChannel.type === Constants.ChannelTypes.GUILD_STAGE_VOICE)) { // Welcome to Discord, where one can "join" text channels
891
+ if (oldChannel) {
892
+ /**
893
+ * Fired when a guild member switches voice channels
894
+ * @event Client#voiceChannelSwitch
895
+ * @prop {Member} member The member
896
+ * @prop {VoiceChannel | StageChannel} newChannel The new voice channel
897
+ * @prop {VoiceChannel | StageChannel} oldChannel The old voice channel
898
+ */
899
+ oldChannel.voiceMembers.remove(member);
900
+ this.emit("voiceChannelSwitch", newChannel.voiceMembers.add(member, guild), newChannel, oldChannel);
901
+ } else {
902
+ /**
903
+ * Fired when a guild member joins a voice channel. This event is not fired when a member switches voice channels, see `voiceChannelSwitch`
904
+ * @event Client#voiceChannelJoin
905
+ * @prop {Member} member The member
906
+ * @prop {VoiceChannel | StageChannel} newChannel The voice channel
907
+ */
908
+ this.emit("voiceChannelJoin", newChannel.voiceMembers.add(member, guild), newChannel);
909
+ }
910
+ } else if (oldChannel) {
911
+ oldChannel.voiceMembers.remove(member);
912
+ /**
913
+ * Fired when a guild member leaves a voice channel. This event is not fired when a member switches voice channels, see `voiceChannelSwitch`
914
+ * @event Client#voiceChannelLeave
915
+ * @prop {Member?} member The member
916
+ * @prop {VoiceChannel | StageChannel} oldChannel The voice channel
917
+ */
918
+ this.emit("voiceChannelLeave", member, oldChannel);
919
+ }
920
+ }
921
+ if (oldState.mute !== member.voiceState.mute || oldState.deaf !== member.voiceState.deaf || oldState.selfMute !== member.voiceState.selfMute || oldState.selfDeaf !== member.voiceState.selfDeaf || oldState.selfStream !== member.voiceState.selfStream || oldState.selfVideo !== member.voiceState.selfVideo) {
922
+ /**
923
+ * Fired when a guild member's voice state changes
924
+ * @event Client#voiceStateUpdate
925
+ * @prop {Member | Object} member The member. If the member is not cached and Discord doesn't send a member payload, this will be an object with `id` and `voiceState` keys. No other property is guaranteed
926
+ * @prop {Object?} oldState The old voice state of the member. If the above caveat applies, this will be null
927
+ * @prop {Boolean} oldState.deaf The previous server deaf status
928
+ * @prop {Boolean} oldState.mute The previous server mute status
929
+ * @prop {Boolean} oldState.selfDeaf The previous self deaf status
930
+ * @prop {Boolean} oldState.selfMute The previous self mute status
931
+ * @prop {Boolean} oldState.selfStream The previous self stream status
932
+ * @prop {Boolean} oldState.selfVideo The previous self video status
933
+ */
934
+ this.emit("voiceStateUpdate", member, oldState);
935
+ }
936
+ break;
937
+ }
938
+ case "VOICE_CHANNEL_STATUS_UPDATE": {
939
+ const channel = this.client.getChannel(packet.d.id);
940
+ if (!channel) {
941
+ break;
942
+ }
943
+ const oldChannel = {
944
+ status: channel.status,
945
+ };
946
+ channel.update({
947
+ status: packet.d.status,
948
+ });
949
+ /**
950
+ * Fired when a voice channel status is updated
951
+ * @event Client#voiceChannelStatusUpdate
952
+ * @prop {VoiceChannel} channel The updated voice channel
953
+ * @prop {Object} oldChannel The old channel data
954
+ * @prop {String?} oldChannel.status The old voice channel status
955
+ */
956
+ this.emit("voiceChannelStatusUpdate", channel, oldChannel);
957
+ break;
958
+ }
959
+ case "VOICE_CHANNEL_START_TIME_UPDATE": {
960
+ const channel = this.client.getChannel(packet.d.id);
961
+ if (!channel) {
962
+ break;
963
+ }
964
+ const oldChannel = {
965
+ voiceStartTime: channel.voiceStartTime,
966
+ };
967
+ channel.update({
968
+ voice_start_time: packet.d.voice_start_time === undefined ? null : packet.d.voice_start_time,
969
+ });
970
+ /**
971
+ * Fired when the start time of the voice session of a voice channel is updated
972
+ * @event Client#voiceChannelStartTimeUpdate
973
+ * @prop {VoiceChannel} channel The updated voice channel
974
+ * @prop {Object} oldChannel The old channel data
975
+ * @prop {Number?} oldChannel.voiceStartTime Timestamp of when the previous voice session started
976
+ */
977
+ this.emit("voiceChannelStartTimeUpdate", channel, oldChannel);
978
+ break;
979
+ }
980
+ case "VOICE_CHANNEL_EFFECT_SEND": {
981
+ const channel = this.client.getChannel(packet.d.channel_id) || { id: packet.d.channel_id };
982
+ const guild = this.client.guilds.get(packet.d.guild_id) || { id: packet.d.guild_id };
983
+ const user = this.client.users.get(packet.d.user_id) || { id: packet.d.user_id };
984
+ /**
985
+ * Fired when a user sends a voice channel effect
986
+ * @event Client#voiceChannelEffectSend
987
+ * @prop {Object} effect The effect that was sent
988
+ * @prop {Number?} effect.animationID The animation ID
989
+ * @prop {Number?} effect.animationType The animation type
990
+ * @prop {VoiceChannel | StageChannel | Object} effect.channel The voice channel the effect was sent in. If the channel is not cached, this will be an object with an `id` key. No other property is guaranteed
991
+ * @prop {Object?} effect.emoji The emoji sent
992
+ * @prop {Guild | Object} effect.guild The guild the effect was sent in. If the guild is not cached, this will be an object with an `id` key. No other property is guaranteed
993
+ * @prop {(String | Number)?} effect.soundID The sound ID
994
+ * @prop {Number?} effect.soundVolume The volume of the sound (a number between 0 and 1)
995
+ * @prop {User | Object} effect.user The user that sent the effect. If the user is not cached, this will be an object with an `id` key. No other property is guaranteed
996
+ */
997
+ this.emit("voiceChannelEffectSend", {
998
+ channel: channel,
999
+ guild: guild,
1000
+ user: user,
1001
+ emoji: packet.d.emoji,
1002
+ animationType: packet.d.animation_type,
1003
+ animationID: packet.d.animation_id,
1004
+ soundID: packet.d.sound_id,
1005
+ soundVolume: packet.d.sound_volume,
1006
+ });
1007
+ break;
1008
+ }
1009
+ case "TYPING_START": {
1010
+ let member = null;
1011
+ const guild = this.client.guilds.get(packet.d.guild_id);
1012
+ if (guild) {
1013
+ packet.d.member.id = packet.d.user_id;
1014
+ member = guild.members.update(packet.d.member, guild);
1015
+ }
1016
+ if (this.client.listeners("typingStart").length > 0) {
1017
+ /**
1018
+ * Fired when a user begins typing
1019
+ * @event Client#typingStart
1020
+ * @prop {DMChannel | TextChannel | NewsChannel | Object} channel The text channel the user is typing in. If the channel is not cached, this will be an object with an `id` key. No other property is guaranteed
1021
+ * @prop {User | Object} user The user. If the user is not cached, this will be an object with an `id` key. No other property is guaranteed
1022
+ * @prop {Member?} member The guild member, if typing in a guild channel, or `null`, if typing in a DMChannel
1023
+ */
1024
+ this.emit("typingStart", this.client.getChannel(packet.d.channel_id) || { id: packet.d.channel_id }, this.client.users.get(packet.d.user_id) || { id: packet.d.user_id }, member);
1025
+ }
1026
+ break;
1027
+ }
1028
+ case "MESSAGE_CREATE": {
1029
+ const channel = this.client.getChannel(packet.d.channel_id);
1030
+ if (channel) { // MESSAGE_CREATE just when deleting o.o
1031
+ channel.lastMessageID = packet.d.id;
1032
+ if (channel instanceof ThreadChannel) {
1033
+ channel.messageCount++;
1034
+ channel.totalMessageSent++;
1035
+ }
1036
+ /**
1037
+ * Fired when a message is created
1038
+ * @event Client#messageCreate
1039
+ * @prop {Message} message The message.
1040
+ */
1041
+ this.emit("messageCreate", channel.messages.add(packet.d, this.client));
1042
+ } else {
1043
+ this.emit("messageCreate", new Message(packet.d, this.client));
1044
+ }
1045
+ break;
1046
+ }
1047
+ case "MESSAGE_UPDATE": {
1048
+ const channel = this.client.getChannel(packet.d.channel_id);
1049
+ if (!channel) {
1050
+ packet.d.channel = {
1051
+ id: packet.d.channel_id,
1052
+ };
1053
+ this.emit("messageUpdate", packet.d, null);
1054
+ break;
1055
+ }
1056
+ const message = channel.messages.get(packet.d.id);
1057
+ let oldMessage = null;
1058
+ if (message) {
1059
+ oldMessage = {
1060
+ attachments: message.attachments,
1061
+ channelMentions: message.channelMentions,
1062
+ content: message.content,
1063
+ editedTimestamp: message.editedTimestamp,
1064
+ embeds: message.embeds,
1065
+ flags: message.flags,
1066
+ mentionedBy: message.mentionedBy,
1067
+ mentions: message.mentions,
1068
+ pinned: message.pinned,
1069
+ poll: message.poll,
1070
+ roleMentions: message.roleMentions,
1071
+ tts: message.tts,
1072
+ };
1073
+ } else if (!packet.d.timestamp) {
1074
+ packet.d.channel = channel;
1075
+ this.emit("messageUpdate", packet.d, null);
1076
+ break;
1077
+ }
1078
+ /**
1079
+ * Fired when a message is updated
1080
+ * @event Client#messageUpdate
1081
+ * @prop {Message} message The updated message. If oldMessage is null, it is recommended to discard this event, since the message data will be very incomplete (only `id` and `channel` are guaranteed). If the channel isn't cached, `channel` will be an object with an `id` key.
1082
+ * @prop {Object?} oldMessage The old message data. If the message was cached, this will return the full old message. Otherwise, it will be null
1083
+ * @prop {Array<Object>} oldMessage.attachments Array of attachments
1084
+ * @prop {Array<String>} oldMessage.channelMentions Array of mentions channels' ids.
1085
+ * @prop {String} oldMessage.content Message content
1086
+ * @prop {Number} oldMessage.editedTimestamp Timestamp of latest message edit
1087
+ * @prop {Array<Object>} oldMessage.embeds Array of embeds
1088
+ * @prop {Number} oldMessage.flags Old message flags (see constants)
1089
+ * @prop {Object} oldMessage.mentionedBy Object of if different things mention the bot user
1090
+ * @prop {Array<User>} oldMessage.mentions Array of mentioned users' ids
1091
+ * @prop {Boolean} oldMessage.pinned Whether the message was pinned or not
1092
+ * @prop {Object} oldMessage.poll A poll object. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/poll#poll-object) for object structure
1093
+ * @prop {Array<String>} oldMessage.roleMentions Array of mentioned roles' ids.
1094
+ * @prop {Boolean} oldMessage.tts Whether to play the message using TTS or not
1095
+ */
1096
+ this.emit("messageUpdate", channel.messages.update(packet.d, this.client), oldMessage);
1097
+ break;
1098
+ }
1099
+ case "MESSAGE_DELETE": {
1100
+ const channel = this.client.getChannel(packet.d.channel_id);
1101
+ if (channel instanceof ThreadChannel) {
1102
+ channel.messageCount--;
1103
+ }
1104
+ /**
1105
+ * Fired when a cached message is deleted
1106
+ * @event Client#messageDelete
1107
+ * @prop {Message | Object} message The message object. If the message is not cached, this will be an object with `id` and `channel` keys. If the channel is not cached, channel will be an object with an `id` key. If the uncached message is from a guild, the message will also contain a `guildID` key, and the channel will contain a `guild` with an `id` key. No other property is guaranteed.
1108
+ */
1109
+ this.emit("messageDelete", (channel && channel.messages.remove(packet.d)) || {
1110
+ id: packet.d.id,
1111
+ channel: channel || {
1112
+ id: packet.d.channel_id,
1113
+ guild: packet.d.guild_id ? { id: packet.d.guild_id } : undefined,
1114
+ },
1115
+ guildID: packet.d.guild_id,
1116
+ });
1117
+ break;
1118
+ }
1119
+ case "MESSAGE_DELETE_BULK": {
1120
+ const channel = this.client.getChannel(packet.d.channel_id);
1121
+ if (channel instanceof ThreadChannel) {
1122
+ channel.messageCount -= packet.d.ids.length;
1123
+ }
1124
+ /**
1125
+ * Fired when a bulk delete occurs
1126
+ * @event Client#messageDeleteBulk
1127
+ * @prop {Array<Message> | Array<Object>} messages An array of (potentially partial) message objects. If a message is not cached, it will be an object with `id` and `channel` keys If the uncached messages are from a guild, the messages will also contain a `guildID` key, and the channel will contain a `guild` with an `id` key. No other property is guaranteed
1128
+ */
1129
+ this.emit("messageDeleteBulk", packet.d.ids.map((id) => ((channel && channel.messages.remove({ id })) || {
1130
+ id: id,
1131
+ channel: { id: packet.d.channel_id, guild: packet.d.guild_id ? { id: packet.d.guild_id } : undefined },
1132
+ guildID: packet.d.guild_id,
1133
+ })));
1134
+ break;
1135
+ }
1136
+ case "MESSAGE_REACTION_ADD": {
1137
+ const channel = this.client.getChannel(packet.d.channel_id);
1138
+ let message;
1139
+ let member;
1140
+ if (channel) {
1141
+ message = channel.messages.get(packet.d.message_id);
1142
+ if (channel.guild) {
1143
+ if (packet.d.member) {
1144
+ // Updates the member cache with this member for future events.
1145
+ packet.d.member.id = packet.d.user_id;
1146
+ member = channel.guild.members.update(packet.d.member, channel.guild);
1147
+ }
1148
+ }
1149
+ }
1150
+ if (message) {
1151
+ const reaction = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
1152
+ if (message.reactions[reaction]) {
1153
+ ++message.reactions[reaction].count;
1154
+ ++message.reactions[reaction].count_details[packet.d.burst ? "burst" : "normal"];
1155
+ if (packet.d.user_id === this.client.user.id) {
1156
+ message.reactions[reaction].me = true;
1157
+ if (packet.d.burst) {
1158
+ message.reactions[reaction].me_burst = true;
1159
+ }
1160
+ }
1161
+ message.reactions[reaction].burst_colors = packet.d.burst_colors;
1162
+ } else {
1163
+ message.reactions[reaction] = {
1164
+ burst_colors: packet.d.burst_colors,
1165
+ count: 1,
1166
+ count_details: {
1167
+ burst: +packet.d.burst,
1168
+ normal: +!packet.d.burst,
1169
+ },
1170
+ me: packet.d.user_id === this.client.user.id && !packet.d.burst,
1171
+ me_burst: packet.d.user_id === this.client.user.id && packet.d.burst,
1172
+ type: packet.d.type,
1173
+ };
1174
+ }
1175
+ } else {
1176
+ message = {
1177
+ id: packet.d.message_id,
1178
+ channel: channel || { id: packet.d.channel_id },
1179
+ };
1180
+
1181
+ if (packet.d.guild_id) {
1182
+ message.guildID = packet.d.guild_id;
1183
+ if (!message.channel.guild) {
1184
+ message.channel.guild = { id: packet.d.guild_id };
1185
+ }
1186
+ }
1187
+ }
1188
+ /**
1189
+ * Fired when someone adds a reaction to a message
1190
+ * @event Client#messageReactionAdd
1191
+ * @prop {Message | Object} message The message object. If the message is not cached, this will be an object with `id`, `channel`, and if inside a guild, `guildID` keys. If the channel is not cached, channel key will be an object with only an id. `guildID` will be present if the message was sent in a guild channel. No other property is guaranteed
1192
+ * @prop {Object} emoji The reaction emoji object
1193
+ * @prop {Boolean?} emoji.animated Whether the emoji is animated or not
1194
+ * @prop {String?} emoji.id The emoji ID (null for non-custom emojis)
1195
+ * @prop {String} emoji.name The emoji name
1196
+ * @prop {Member | Object} reactor The member, if the reaction is in a guild. If the reaction is not in a guild, this will be an object with an `id` key. No other property is guaranteed
1197
+ * @prop {Boolean} burst Whether the reaction is a super reaction
1198
+ */
1199
+ this.emit("messageReactionAdd", message, packet.d.emoji, member || { id: packet.d.user_id }, packet.d.burst);
1200
+ break;
1201
+ }
1202
+ case "MESSAGE_REACTION_REMOVE": {
1203
+ const channel = this.client.getChannel(packet.d.channel_id);
1204
+ let message;
1205
+ if (channel) {
1206
+ message = channel.messages.get(packet.d.message_id);
1207
+ }
1208
+ if (message) {
1209
+ const reaction = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
1210
+ const reactionObj = message.reactions[reaction];
1211
+ if (reactionObj) {
1212
+ --reactionObj.count;
1213
+ --reactionObj.count_details[packet.d.burst ? "burst" : "normal"];
1214
+ if (reactionObj.count === 0) {
1215
+ delete message.reactions[reaction];
1216
+ } else if (packet.d.user_id === this.client.user.id) {
1217
+ message.reactions[reaction].me = false;
1218
+ if (packet.d.burst) {
1219
+ message.reactions[reaction].me_burst = false;
1220
+ }
1221
+ }
1222
+ }
1223
+ } else {
1224
+ message = {
1225
+ id: packet.d.message_id,
1226
+ channel: channel || { id: packet.d.channel_id },
1227
+ };
1228
+
1229
+ if (packet.d.guild_id) {
1230
+ message.guildID = packet.d.guild_id;
1231
+ if (!message.channel.guild) {
1232
+ message.channel.guild = { id: packet.d.guild_id };
1233
+ }
1234
+ }
1235
+ }
1236
+ /**
1237
+ * Fired when someone removes a reaction from a message
1238
+ * @event Client#messageReactionRemove
1239
+ * @prop {Message | Object} message The message object. If the message is not cached, this will be an object with `id`, `channel`, and if inside a guild, `guildID` keys. If the channel is not cached, channel key will be an object with only an id. `guildID` will be present if the message was sent in a guild channel. No other property is guaranteed
1240
+ * @prop {Object} emoji The reaction emoji object
1241
+ * @prop {Boolean?} emoji.animated Whether the emoji is animated or not
1242
+ * @prop {String?} emoji.id The ID of the emoji (null for non-custom emojis)
1243
+ * @prop {String} emoji.name The emoji name
1244
+ * @prop {String} userID The ID of the user that removed the reaction
1245
+ * @prop {Boolean} burst Whether the reaction is a super reaction
1246
+ */
1247
+ this.emit("messageReactionRemove", message, packet.d.emoji, packet.d.user_id, packet.d.burst);
1248
+ break;
1249
+ }
1250
+ case "MESSAGE_REACTION_REMOVE_ALL": {
1251
+ const channel = this.client.getChannel(packet.d.channel_id);
1252
+ let message;
1253
+ if (channel) {
1254
+ message = channel.messages.get(packet.d.message_id);
1255
+ if (message) {
1256
+ message.reactions = {};
1257
+ }
1258
+ }
1259
+ if (!message) {
1260
+ message = {
1261
+ id: packet.d.message_id,
1262
+ channel: channel || { id: packet.d.channel_id },
1263
+ };
1264
+ if (packet.d.guild_id) {
1265
+ message.guildID = packet.d.guild_id;
1266
+ if (!message.channel.guild) {
1267
+ message.channel.guild = { id: packet.d.guild_id };
1268
+ }
1269
+ }
1270
+ }
1271
+ /**
1272
+ * Fired when all reactions are removed from a message
1273
+ * @event Client#messageReactionRemoveAll
1274
+ * @prop {Message | Object} message The message object. If the message is not cached, this will be an object with `id`, `channel`, and if inside a guild, `guildID` keys. If the channel is not cached, channel key will be an object with only an id. No other property is guaranteed
1275
+ */
1276
+ this.emit("messageReactionRemoveAll", message);
1277
+ break;
1278
+ }
1279
+ case "MESSAGE_REACTION_REMOVE_EMOJI": {
1280
+ const channel = this.client.getChannel(packet.d.channel_id);
1281
+ let message;
1282
+ if (channel) {
1283
+ message = channel.messages.get(packet.d.message_id);
1284
+ if (message) {
1285
+ const reaction = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
1286
+ delete message.reactions[reaction];
1287
+ }
1288
+ }
1289
+ if (!message) {
1290
+ message = {
1291
+ id: packet.d.message_id,
1292
+ channel: channel || { id: packet.d.channel_id },
1293
+ };
1294
+ if (packet.d.guild_id) {
1295
+ message.guildID = packet.d.guild_id;
1296
+ if (!message.channel.guild) {
1297
+ message.channel.guild = { id: packet.d.guild_id };
1298
+ }
1299
+ }
1300
+ }
1301
+ /**
1302
+ * Fired when someone removes all reactions from a message for a single emoji
1303
+ * @event Client#messageReactionRemoveEmoji
1304
+ * @prop {Message | Object} message The message object. If the message is not cached, this will be an object with `id` and `channel` keys. If the channel is not cached, channel key will be an object with only an id. No other property is guaranteed
1305
+ * @prop {Object} emoji The reaction emoji object
1306
+ * @prop {Boolean?} emoji.animated Whether the emoji is animated or not
1307
+ * @prop {String?} emoji.id The ID of the emoji (null for non-custom emojis)
1308
+ * @prop {String} emoji.name The emoji name
1309
+ */
1310
+ this.emit("messageReactionRemoveEmoji", message, packet.d.emoji);
1311
+ break;
1312
+ }
1313
+ case "MESSAGE_POLL_VOTE_ADD": {
1314
+ const user = this.client.users.get(packet.d.user_id);
1315
+ const channel = this.client.getChannel(packet.d.channel_id);
1316
+ let message;
1317
+ if (channel) {
1318
+ message = channel.messages.get(packet.d.message_id);
1319
+ }
1320
+ if (!message) {
1321
+ message = {
1322
+ id: packet.d.message_id,
1323
+ channel: channel || { id: packet.d.channel_id },
1324
+ };
1325
+ if (packet.d.guild_id) {
1326
+ message.guildID = packet.d.guild_id;
1327
+ if (!message.channel.guild) {
1328
+ message.channel.guild = { id: packet.d.guild_id };
1329
+ }
1330
+ }
1331
+ } else if (message.poll.results && message.poll.results.answer_counts) {
1332
+ const answer = message.poll.results.answer_counts.find((answer) => answer.id === packet.d.answer_id);
1333
+ if (answer) {
1334
+ answer.count++;
1335
+ if (packet.d.user_id === this.client.user.id) {
1336
+ answer.me_voted = true;
1337
+ }
1338
+ } else {
1339
+ message.poll.results.answer_counts.push({
1340
+ id: packet.d.answer_id,
1341
+ count: 1,
1342
+ me_voted: packet.d.user_id === this.client.user.id,
1343
+ });
1344
+ }
1345
+ }
1346
+ /**
1347
+ * Fired when a user votes on a poll. If the poll allows multiple selection, one event will be sent per answer
1348
+ * @event Client#messagePollVoteAdd
1349
+ * @prop {Message | Object} message The message object. If the message is not cached, this will be an object with `id` and `channel` keys. If the channel is not cached, channel key will be an object with an id and a `guild` key with only an id. No other property is guaranteed
1350
+ * @prop {User | Object} user The user who voted on the poll. If the user is not cached, this will be an object with only an `id` key
1351
+ * @prop {Number} answerID The ID of the answer
1352
+ */
1353
+ this.emit("messagePollVoteAdd", message, user || { id: packet.d.user_id }, packet.d.answer_id);
1354
+ break;
1355
+ }
1356
+ case "MESSAGE_POLL_VOTE_REMOVE": {
1357
+ const user = this.client.users.get(packet.d.user_id);
1358
+ const channel = this.client.getChannel(packet.d.channel_id);
1359
+ let message;
1360
+ if (channel) {
1361
+ message = channel.messages.get(packet.d.message_id);
1362
+ }
1363
+ if (!message) {
1364
+ message = {
1365
+ id: packet.d.message_id,
1366
+ channel: channel || { id: packet.d.channel_id },
1367
+ };
1368
+ if (packet.d.guild_id) {
1369
+ message.guildID = packet.d.guild_id;
1370
+ if (!message.channel.guild) {
1371
+ message.channel.guild = { id: packet.d.guild_id };
1372
+ }
1373
+ }
1374
+ } else if (message.poll.results && message.poll.results.answer_counts) {
1375
+ const answer = message.poll.results.answer_counts.find((answer) => answer.id === packet.d.answer_id);
1376
+ if (answer) {
1377
+ answer.count--;
1378
+ if (packet.d.user_id === this.client.user.id) {
1379
+ answer.me_voted = false;
1380
+ }
1381
+ }
1382
+ }
1383
+ /**
1384
+ * Fired when a user removes their vote on a poll. If the poll allows multiple selection, one event will be sent per answer
1385
+ * @event Client#messagePollVoteRemove
1386
+ * @prop {Message | Object} message The message object. If the message is not cached, this will be an object with `id` and `channel` keys. If the channel is not cached, channel key will be an object with an id and a `guild` key with only an id. No other property is guaranteed
1387
+ * @prop {User | Object} user The user who removed their vote from the poll. If the user is not cached, this will be an object with only an `id` key
1388
+ * @prop {Number} answerID The ID of the answer
1389
+ */
1390
+ this.emit("messagePollVoteRemove", message, user || { id: packet.d.user_id }, packet.d.answer_id);
1391
+ break;
1392
+ }
1393
+ case "GUILD_AUDIT_LOG_ENTRY_CREATE": {
1394
+ /**
1395
+ * Fired when a guild audit log entry is created
1396
+ * @event Client#guildAuditLogEntryCreate
1397
+ * @prop {GuildAuditLogEntry} guildAuditLogEntry The created guild audit log entry
1398
+ */
1399
+ this.emit("guildAuditLogEntryCreate", new GuildAuditLogEntry(packet.d, this.client));
1400
+ break;
1401
+ }
1402
+ case "GUILD_MEMBER_ADD": {
1403
+ const guild = this.client.guilds.get(packet.d.guild_id);
1404
+ if (!guild) { // Eventual Consistency™ (╯°□°)╯︵ ┻━┻
1405
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in GUILD_MEMBER_ADD`);
1406
+ break;
1407
+ }
1408
+ packet.d.id = packet.d.user.id;
1409
+ ++guild.memberCount;
1410
+ /**
1411
+ * Fired when a member joins a server
1412
+ * @event Client#guildMemberAdd
1413
+ * @prop {Guild} guild The guild
1414
+ * @prop {Member} member The member
1415
+ */
1416
+ this.emit("guildMemberAdd", guild, guild.members.add(packet.d, guild));
1417
+ break;
1418
+ }
1419
+ case "GUILD_MEMBER_UPDATE": {
1420
+ // Check for member update if guildPresences intent isn't set, to prevent emitting twice
1421
+ if (!(this.client.options.intents & Constants.Intents.guildPresences) && packet.d.user.username !== undefined) {
1422
+ let user = this.client.users.get(packet.d.user.id);
1423
+ let oldUser = null;
1424
+ if (user && hasUserChanged(user, packet.d.user)) {
1425
+ oldUser = getOldUserData(user);
1426
+ }
1427
+ if (!user || oldUser) {
1428
+ user = this.client.users.update(packet.d.user, this.client);
1429
+ this.emit("userUpdate", user, oldUser);
1430
+ }
1431
+ }
1432
+ const guild = this.client.guilds.get(packet.d.guild_id);
1433
+ if (!guild) {
1434
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in GUILD_MEMBER_UPDATE`);
1435
+ break;
1436
+ }
1437
+ let member = guild.members.get(packet.d.id = packet.d.user.id);
1438
+ let oldMember = null;
1439
+ if (member) {
1440
+ oldMember = {
1441
+ avatar: member.avatar,
1442
+ avatarDecorationData: member.avatarDecorationData,
1443
+ banner: member.banner,
1444
+ collectibles: member.collectibles,
1445
+ communicationDisabledUntil: member.communicationDisabledUntil,
1446
+ flags: member.flags,
1447
+ roles: member.roles,
1448
+ nick: member.nick,
1449
+ premiumSince: member.premiumSince,
1450
+ pending: member.pending,
1451
+ };
1452
+ }
1453
+ member = guild.members.update(packet.d, guild);
1454
+ /**
1455
+ * Fired when a member's guild avatar, roles or nickname are updated or they start boosting a server
1456
+ * @event Client#guildMemberUpdate
1457
+ * @prop {Guild} guild The guild
1458
+ * @prop {Member} member The updated member
1459
+ * @prop {Object?} oldMember The old member data, or null if the member wasn't cached
1460
+ * @prop {String?} oldMember.avatar The hash of the member's guild avatar, or null if no guild avatar
1461
+ * @prop {Object?} oldMember.avatarDecorationData The data of the member's avatar decoration
1462
+ * @prop {String?} oldMember.banner The hash of the member's guild banner, or of the user's banner if the member had no guild banner
1463
+ * @prop {Object?} oldMember.collectibles The data of the member's collectibles
1464
+ * @prop {Number?} oldMember.communicationDisabledUntil Timestamp of previous timeout expiry. If `null`, the member was not timed out
1465
+ * @prop {Number?} oldMember.flags The member's flags (see Constants). Defaults to 0
1466
+ * @prop {String?} oldMember.nick The server nickname of the member
1467
+ * @prop {Boolean?} oldMember.pending Whether the member has passed the guild's Membership Screening requirements
1468
+ * @prop {Number?} oldMember.premiumSince Timestamp of when the member boosted the guild
1469
+ * @prop {Array<String>} oldMember.roles An array of role IDs this member is a part of
1470
+ */
1471
+ this.emit("guildMemberUpdate", guild, member, oldMember);
1472
+ break;
1473
+ }
1474
+ case "GUILD_MEMBER_REMOVE": {
1475
+ if (packet.d.user.id === this.client.user.id) { // The bot is probably leaving
1476
+ break;
1477
+ }
1478
+ const guild = this.client.guilds.get(packet.d.guild_id);
1479
+ if (!guild) {
1480
+ break;
1481
+ }
1482
+ --guild.memberCount;
1483
+ packet.d.id = packet.d.user.id;
1484
+ /**
1485
+ * Fired when a member leaves a server
1486
+ * @event Client#guildMemberRemove
1487
+ * @prop {Guild} guild The guild
1488
+ * @prop {Member | Object} member The member. If the member is not cached, this will be an object with `id` and `user` key
1489
+ */
1490
+ this.emit("guildMemberRemove", guild, guild.members.remove(packet.d) || {
1491
+ id: packet.d.id,
1492
+ user: new User(packet.d.user, this.client),
1493
+ });
1494
+ break;
1495
+ }
1496
+ case "GUILD_CREATE": {
1497
+ if (!packet.d.unavailable) {
1498
+ const guild = this.createGuild(packet.d);
1499
+ if (this.ready) {
1500
+ if (this.client.unavailableGuilds.remove(packet.d)) {
1501
+ /**
1502
+ * Fired when a guild becomes available
1503
+ * @event Client#guildAvailable
1504
+ * @prop {Guild} guild The guild
1505
+ */
1506
+ this.emit("guildAvailable", guild);
1507
+ } else {
1508
+ /**
1509
+ * Fired when a guild is created. This happens when:
1510
+ * - the client creates a guild
1511
+ * - the client joins a guild
1512
+ * @event Client#guildCreate
1513
+ * @prop {Guild} guild The guild
1514
+ */
1515
+ this.emit("guildCreate", guild);
1516
+ }
1517
+ } else {
1518
+ this.client.unavailableGuilds.remove(packet.d);
1519
+ this.restartGuildCreateTimeout();
1520
+ }
1521
+ } else {
1522
+ this.client.guilds.remove(packet.d);
1523
+ /**
1524
+ * Fired when an unavailable guild is created
1525
+ * @event Client#unavailableGuildCreate
1526
+ * @prop {UnavailableGuild} guild The unavailable guild
1527
+ */
1528
+ this.emit("unavailableGuildCreate", this.client.unavailableGuilds.add(packet.d, this.client));
1529
+ }
1530
+ break;
1531
+ }
1532
+ case "GUILD_UPDATE": {
1533
+ const guild = this.client.guilds.get(packet.d.id);
1534
+ if (!guild) {
1535
+ this.emit("debug", `Guild ${packet.d.id} undefined in GUILD_UPDATE`);
1536
+ break;
1537
+ }
1538
+ const oldGuild = {
1539
+ afkChannelID: guild.afkChannelID,
1540
+ afkTimeout: guild.afkTimeout,
1541
+ autoRemoved: guild.autoRemoved,
1542
+ banner: guild.banner,
1543
+ defaultNotifications: guild.defaultNotifications,
1544
+ description: guild.description,
1545
+ discoverySplash: guild.discoverySplash,
1546
+ emojiCount: guild.emojiCount,
1547
+ emojis: guild.emojis,
1548
+ explicitContentFilter: guild.explicitContentFilter,
1549
+ features: guild.features,
1550
+ icon: guild.icon,
1551
+ incidentsData: guild.incidentsData,
1552
+ keywords: guild.keywords,
1553
+ large: guild.large,
1554
+ maxMembers: guild.maxMembers,
1555
+ maxVideoChannelUsers: guild.maxVideoChannelUsers,
1556
+ mfaLevel: guild.mfaLevel,
1557
+ name: guild.name,
1558
+ nsfw: guild.nsfw,
1559
+ nsfwLevel: guild.nsfwLevel,
1560
+ ownerID: guild.ownerID,
1561
+ preferredLocale: guild.preferredLocale,
1562
+ premiumProgressBarEnabled: guild.premiumProgressBarEnabled,
1563
+ premiumSubscriptionCount: guild.premiumSubscriptionCount,
1564
+ premiumTier: guild.premiumTier,
1565
+ primaryCategory: guild.primaryCategory,
1566
+ primaryCategoryID: guild.primaryCategoryID,
1567
+ publicUpdatesChannelID: guild.publicUpdatesChannelID,
1568
+ rulesChannelID: guild.rulesChannelID,
1569
+ splash: guild.splash,
1570
+ stickers: guild.stickers,
1571
+ systemChannelFlags: guild.systemChannelFlags,
1572
+ systemChannelID: guild.systemChannelID,
1573
+ vanityURL: guild.vanityURL,
1574
+ verificationLevel: guild.verificationLevel,
1575
+ welcomeScreen: guild.welcomeScreen && {
1576
+ description: guild.welcomeScreen.description,
1577
+ welcomeChannels: guild.welcomeScreen.welcomeChannels,
1578
+ },
1579
+ };
1580
+ /**
1581
+ * Fired when a guild is updated
1582
+ * @event Client#guildUpdate
1583
+ * @prop {Guild} guild The guild
1584
+ * @prop {Object} oldGuild The old guild data
1585
+ * @prop {String?} oldGuild.afkChannelID The ID of the AFK voice channel
1586
+ * @prop {Number} oldGuild.afkTimeout The AFK timeout in seconds
1587
+ * @prop {Boolean?} oldGuild.autoRemoved Whether the guild was automatically removed from Discovery
1588
+ * @prop {String?} oldGuild.banner The hash of the guild banner image, or null if no splash (VIP only)
1589
+ * @prop {Number} oldGuild.defaultNotifications The default notification settings for the guild. 0 is "All Messages", 1 is "Only @mentions"
1590
+ * @prop {String?} oldGuild.description The description for the guild (VIP only)
1591
+ * @prop {Number?} oldGuild.emojiCount The number of emojis in the guild
1592
+ * @prop {Array<Object>} oldGuild.emojis An array of guild emojis
1593
+ * @prop {Number} oldGuild.explicitContentFilter The explicit content filter level for the guild. 0 is off, 1 is on for people without roles, 2 is on for all
1594
+ * @prop {Array<String>} oldGuild.features An array of guild features
1595
+ * @prop {String?} oldGuild.icon The hash of the guild icon, or null if no icon
1596
+ * @prop {Object?} oldGuild.incidentsData The incidents data for the guild
1597
+ * @prop {Number?} oldGuild.incidentsData.dmsDisabledUntil When DMs will get enabled again
1598
+ * @prop {Number?} oldGuild.incidentsData.dmSpamDetectedAt When the DM spam was detected
1599
+ * @prop {Number?} oldGuild.incidentsData.invitesDisabledUntil When invites will get enabled again
1600
+ * @prop {Number?} oldGuild.incidentsData.raidDetectedAt When the raid was detected
1601
+ * @prop {Array<String>?} oldGuild.keywords The guild's discovery keywords
1602
+ * @prop {Boolean} oldGuild.large Whether the guild is "large" by "some Discord standard"
1603
+ * @prop {Number?} oldGuild.maxMembers The maximum number of members for this guild
1604
+ * @prop {Number?} oldGuild.maxVideoChannelUsers The max number of users allowed in a video channel
1605
+ * @prop {Number} oldGuild.mfaLevel The admin 2FA level for the guild. 0 is not required, 1 is required
1606
+ * @prop {String} oldGuild.name The name of the guild
1607
+ * @prop {Boolean} oldGuild.nsfw [DEPRECATED] Whether the guild is designated as NSFW by Discord
1608
+ * @prop {Number} oldGuild.nsfwLevel The guild NSFW level designated by Discord
1609
+ * @prop {String} oldGuild.ownerID The ID of the user that is the guild owner
1610
+ * @prop {String} oldGuild.preferredLocale Preferred "COMMUNITY" guild language used in server discovery and notices from Discord
1611
+ * @prop {Boolean} oldGuild.premiumProgressBarEnabled If the boost progress bar is enabled
1612
+ * @prop {Number?} oldGuild.premiumSubscriptionCount The total number of users currently boosting this guild
1613
+ * @prop {Number} oldGuild.premiumTier Nitro boost level of the guild
1614
+ * @prop {Object?} oldGuild.primaryCategory The guild's primary discovery category
1615
+ * @prop {Number?} oldGuild.primaryCategoryID The guild's primary discovery category ID
1616
+ * @prop {String?} oldGuild.publicUpdatesChannelID ID of the guild's updates channel if the guild has "COMMUNITY" features
1617
+ * @prop {String?} oldGuild.rulesChannelID The channel where "COMMUNITY" guilds display rules and/or guidelines
1618
+ * @prop {String?} oldGuild.splash The hash of the guild splash image, or null if no splash (VIP only)
1619
+ * @prop {Array<Object>?} stickers An array of guild sticker objects
1620
+ * @prop {Number} oldGuild.systemChannelFlags the flags for the system channel
1621
+ * @prop {String?} oldGuild.systemChannelID The ID of the default channel for system messages (built-in join messages and boost messages)
1622
+ * @prop {String?} oldGuild.vanityURL The vanity URL of the guild (VIP only)
1623
+ * @prop {Number} oldGuild.verificationLevel The guild verification level
1624
+ * @prop {Object?} oldGuild.welcomeScreen The welcome screen of a Community guild, shown to new members
1625
+ * @prop {Object} oldGuild.welcomeScreen.description The description in the welcome screen
1626
+ * @prop {Array<Object>} oldGuild.welcomeScreen.welcomeChannels The list of channels in the welcome screens. Each channels have the following properties: `channelID`, `description`, `emojiID`, `emojiName`. `emojiID` and `emojiName` properties can be null.
1627
+ */
1628
+ this.emit("guildUpdate", this.client.guilds.update(packet.d, this.client), oldGuild);
1629
+ break;
1630
+ }
1631
+ case "GUILD_DELETE": {
1632
+ const voiceConnection = this.client.voiceConnections.get(packet.d.id);
1633
+ if (voiceConnection) {
1634
+ if (voiceConnection.channelID) {
1635
+ this.client.leaveVoiceChannel(voiceConnection.channelID);
1636
+ } else {
1637
+ this.client.voiceConnections.leave(packet.d.id);
1638
+ }
1639
+ }
1640
+
1641
+ delete this.client.guildShardMap[packet.d.id];
1642
+ const guild = this.client.guilds.remove(packet.d);
1643
+ if (guild) { // Discord sends GUILD_DELETE for guilds that were previously unavailable in READY
1644
+ guild.channels.forEach((channel) => {
1645
+ delete this.client.channelGuildMap[channel.id];
1646
+ });
1647
+ }
1648
+ if (packet.d.unavailable) {
1649
+ /**
1650
+ * Fired when a guild becomes unavailable
1651
+ * @event Client#guildUnavailable
1652
+ * @prop {Guild} guild The guild
1653
+ */
1654
+ this.emit("guildUnavailable", this.client.unavailableGuilds.add(packet.d, this.client));
1655
+ } else {
1656
+ /**
1657
+ * Fired when a guild is deleted. This happens when:
1658
+ * - the client left the guild
1659
+ * - the client was kicked/banned from the guild
1660
+ * - the guild was literally deleted
1661
+ * @event Client#guildDelete
1662
+ * @prop {Guild | Object} guild The guild. If the guild was not cached, it will be an object with an `id` key. No other property is guaranteed
1663
+ */
1664
+ this.emit("guildDelete", guild || {
1665
+ id: packet.d.id,
1666
+ });
1667
+ }
1668
+ break;
1669
+ }
1670
+ case "GUILD_BAN_ADD": {
1671
+ /**
1672
+ * Fired when a user is banned from a guild
1673
+ * @event Client#guildBanAdd
1674
+ * @prop {Guild} guild The guild
1675
+ * @prop {User} user The banned user
1676
+ */
1677
+ this.emit("guildBanAdd", this.client.guilds.get(packet.d.guild_id), this.client.users.update(packet.d.user, this.client));
1678
+ break;
1679
+ }
1680
+ case "GUILD_BAN_REMOVE": {
1681
+ /**
1682
+ * Fired when a user is unbanned from a guild
1683
+ * @event Client#guildBanRemove
1684
+ * @prop {Guild} guild The guild
1685
+ * @prop {User} user The banned user
1686
+ */
1687
+ this.emit("guildBanRemove", this.client.guilds.get(packet.d.guild_id), this.client.users.update(packet.d.user, this.client));
1688
+ break;
1689
+ }
1690
+ case "GUILD_ROLE_CREATE": {
1691
+ /**
1692
+ * Fired when a guild role is created
1693
+ * @event Client#guildRoleCreate
1694
+ * @prop {Guild} guild The guild
1695
+ * @prop {Role} role The role
1696
+ */
1697
+ const guild = this.client.guilds.get(packet.d.guild_id);
1698
+ if (!guild) {
1699
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in GUILD_ROLE_CREATE`);
1700
+ break;
1701
+ }
1702
+ this.emit("guildRoleCreate", guild, guild.roles.add(packet.d.role, guild));
1703
+ break;
1704
+ }
1705
+ case "GUILD_ROLE_UPDATE": {
1706
+ const guild = this.client.guilds.get(packet.d.guild_id);
1707
+ if (!guild) {
1708
+ this.emit("debug", `Guild ${packet.d.guild_id} undefined in GUILD_ROLE_UPDATE`);
1709
+ break;
1710
+ }
1711
+ const role = guild.roles.add(packet.d.role, guild);
1712
+ if (!role) {
1713
+ this.emit("debug", `Role ${packet.d.role} in guild ${packet.d.guild_id} undefined in GUILD_ROLE_UPDATE`);
1714
+ break;
1715
+ }
1716
+ const oldRole = {
1717
+ color: role.color,
1718
+ colors: role.colors,
1719
+ flags: role.flags,
1720
+ hoist: role.hoist,
1721
+ icon: role.icon,
1722
+ managed: role.managed,
1723
+ mentionable: role.mentionable,
1724
+ name: role.name,
1725
+ permissions: role.permissions,
1726
+ position: role.position,
1727
+ tags: role.tags,
1728
+ unicodeEmoji: role.unicodeEmoji,
1729
+ };
1730
+ /**
1731
+ * Fired when a guild role is updated
1732
+ * @event Client#guildRoleUpdate
1733
+ * @prop {Guild} guild The guild
1734
+ * @prop {Role} role The updated role
1735
+ * @prop {Object} oldRole The old role data
1736
+ * @prop {Number} oldRole.color The hex color of the role in base 10
1737
+ * @prop {Object} oldRole.colors The role's colors
1738
+ * @prop {Number} oldRole.colors.primaryColor The primary color of the role
1739
+ * @prop {Number?} oldRole.colors.secondaryColor The secondary color of the role (for gradient roles)
1740
+ * @prop {Number?} oldRole.colors.tertiaryColor The tertiary color of the role (for holographic roles)
1741
+ * @prop {Number} oldRole.flags The flags of the role (see constants)
1742
+ * @prop {Boolean} oldRole.hoist Whether users with the role are hoisted in the user list or not
1743
+ * @prop {String?} oldRole.icon The hash of the role's icon, or null if no icon
1744
+ * @prop {Boolean} oldRole.managed Whether a guild integration manages the role or not
1745
+ * @prop {Boolean} oldRole.mentionable Whether the role is mentionable or not
1746
+ * @prop {String} oldRole.name The name of the role
1747
+ * @prop {Permission} oldRole.permissions The permissions number of the role
1748
+ * @prop {Number} oldRole.position The position of the role
1749
+ * @prop {Object?} oldRole.tags The tags of the role
1750
+ * @prop {String?} oldRole.unicodeEmoji Unicode emoji for the role
1751
+ */
1752
+ this.emit("guildRoleUpdate", guild, guild.roles.update(packet.d.role, guild), oldRole);
1753
+ break;
1754
+ }
1755
+ case "GUILD_ROLE_DELETE": {
1756
+ /**
1757
+ * Fired when a guild role is deleted
1758
+ * @event Client#guildRoleDelete
1759
+ * @prop {Guild} guild The guild
1760
+ * @prop {Role} role The role
1761
+ */
1762
+ const guild = this.client.guilds.get(packet.d.guild_id);
1763
+ if (!guild) {
1764
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in GUILD_ROLE_DELETE`);
1765
+ break;
1766
+ }
1767
+ if (!guild.roles.has(packet.d.role_id)) {
1768
+ this.emit("debug", `Missing role ${packet.d.role_id} in GUILD_ROLE_DELETE`);
1769
+ break;
1770
+ }
1771
+ this.emit("guildRoleDelete", guild, guild.roles.remove({ id: packet.d.role_id }));
1772
+ break;
1773
+ }
1774
+ case "INVITE_CREATE": {
1775
+ const guild = this.client.guilds.get(packet.d.guild_id);
1776
+ if (!guild) {
1777
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in INVITE_CREATE`);
1778
+ break;
1779
+ }
1780
+ const channel = this.client.getChannel(packet.d.channel_id);
1781
+ if (!channel) {
1782
+ this.emit("debug", `Missing channel ${packet.d.channel_id} in INVITE_CREATE`);
1783
+ break;
1784
+ }
1785
+ /**
1786
+ * Fired when a guild invite is created
1787
+ * @event Client#inviteCreate
1788
+ * @prop {Guild} guild The guild this invite was created in.
1789
+ * @prop {Invite} invite The invite that was created
1790
+ */
1791
+ this.emit("inviteCreate", guild, new Invite({
1792
+ ...packet.d,
1793
+ guild,
1794
+ channel,
1795
+ }, this.client));
1796
+ break;
1797
+ }
1798
+ case "INVITE_DELETE": {
1799
+ const guild = this.client.guilds.get(packet.d.guild_id);
1800
+ if (!guild) {
1801
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in INVITE_DELETE`);
1802
+ break;
1803
+ }
1804
+ const channel = this.client.getChannel(packet.d.channel_id);
1805
+ if (!channel) {
1806
+ this.emit("debug", `Missing channel ${packet.d.channel_id} in INVITE_DELETE`);
1807
+ break;
1808
+ }
1809
+ /**
1810
+ * Fired when a guild invite is deleted
1811
+ * @event Client#inviteDelete
1812
+ * @prop {Guild} guild The guild this invite was created in.
1813
+ * @prop {Invite} invite The invite that was deleted
1814
+ */
1815
+ this.emit("inviteDelete", guild, new Invite({
1816
+ ...packet.d,
1817
+ guild,
1818
+ channel,
1819
+ }, this.client));
1820
+ break;
1821
+ }
1822
+ case "CHANNEL_CREATE": {
1823
+ const channel = Channel.from(packet.d, this.client);
1824
+ if (packet.d.guild_id) {
1825
+ if (!channel.guild) {
1826
+ channel.guild = this.client.guilds.get(packet.d.guild_id);
1827
+ if (!channel.guild) {
1828
+ this.emit("debug", `Received CHANNEL_CREATE for channel in missing guild ${packet.d.guild_id}`);
1829
+ break;
1830
+ }
1831
+ }
1832
+ channel.guild.channels.add(channel, this.client);
1833
+ this.client.channelGuildMap[packet.d.id] = packet.d.guild_id;
1834
+ /**
1835
+ * Fired when a channel is created
1836
+ * @event Client#channelCreate
1837
+ * @prop {CategoryChannel | ForumChannel | GuildChannel | NewsChannel | TextChannel | VoiceChannel} channel The channel
1838
+ */
1839
+ this.emit("channelCreate", channel);
1840
+ } else {
1841
+ this.emit("warn", new Error("Unhandled CHANNEL_CREATE type: " + JSON.stringify(packet, null, 2)));
1842
+ break;
1843
+ }
1844
+ break;
1845
+ }
1846
+ case "CHANNEL_UPDATE": {
1847
+ let channel = this.client.getChannel(packet.d.id);
1848
+ if (!channel) {
1849
+ break;
1850
+ }
1851
+ let oldChannel;
1852
+ if (channel instanceof GuildChannel) {
1853
+ oldChannel = {
1854
+ availableTags: channel.availableTags,
1855
+ bitrate: channel.bitrate,
1856
+ defaultAutoArchiveDuration: channel.defaultAutoArchiveDuration,
1857
+ defaultForumLayout: channel.defaultForumLayout,
1858
+ defaultReactionEmoji: channel.defaultReactionEmoji,
1859
+ defaultSortOrder: channel.defaultSortOrder,
1860
+ defaultThreadRateLimitPerUser: channel.defaultThreadRateLimitPerUser,
1861
+ flags: channel.flags,
1862
+ name: channel.name,
1863
+ nsfw: channel.nsfw,
1864
+ parentID: channel.parentID,
1865
+ permissionOverwrites: channel.permissionOverwrites,
1866
+ position: channel.position,
1867
+ rateLimitPerUser: channel.rateLimitPerUser,
1868
+ rtcRegion: channel.rtcRegion,
1869
+ topic: channel.topic,
1870
+ type: channel.type,
1871
+ userLimit: channel.userLimit,
1872
+ videoQualityMode: channel.videoQualityMode,
1873
+ };
1874
+ } else {
1875
+ this.emit("warn", `Unexpected CHANNEL_UPDATE for channel ${packet.d.id} with type ${oldType}`);
1876
+ }
1877
+ const oldType = channel.type;
1878
+ if (oldType === packet.d.type) {
1879
+ channel.update(packet.d);
1880
+ } else {
1881
+ this.emit("debug", `Channel ${packet.d.id} changed from type ${oldType} to ${packet.d.type}`);
1882
+ const newChannel = Channel.from(packet.d, this.client);
1883
+ if (packet.d.guild_id) {
1884
+ const guild = this.client.guilds.get(packet.d.guild_id);
1885
+ if (!guild) {
1886
+ this.emit("debug", `Received CHANNEL_UPDATE for channel in missing guild ${packet.d.guild_id}`);
1887
+ break;
1888
+ }
1889
+ guild.channels.remove(channel);
1890
+ guild.channels.add(newChannel, this.client);
1891
+ } else if (channel instanceof DMChannel) {
1892
+ this.client.dmChannels.remove(channel);
1893
+ this.client.dmChannels.add(newChannel, this.client);
1894
+ } else {
1895
+ this.emit("warn", new Error("Unhandled CHANNEL_UPDATE type: " + JSON.stringify(packet, null, 2)));
1896
+ break;
1897
+ }
1898
+ channel = newChannel;
1899
+ }
1900
+
1901
+ /**
1902
+ * Fired when a channel is updated
1903
+ * @event Client#channelUpdate
1904
+ * @prop {CategoryChannel | DMChannel | ForumChannel | GuildChannel | TextChannel | VoiceChannel | NewsChannel} channel The updated channel
1905
+ * @prop {Object} oldChannel The old channel data
1906
+ * @prop {Array<Object>} oldChannel.availableTags The available tags that can be applied to threads in a forum/media channel. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/channel#forum-tag-object) for object structure (forum/media channels only, max 20)
1907
+ * @prop {Number} oldChannel.bitrate The bitrate of the channel (voice channels only)
1908
+ * @prop {Number} oldChannel.defaultAutoArchiveDuration The default duration of newly created threads in minutes to automatically archive the thread after inactivity (60, 1440, 4320, 10080) (text/news/forum/media channels only)
1909
+ * @prop {Number} oldChannel.defaultForumLayout The default forum layout type used to display posts in forum channels (forum channels only)
1910
+ * @prop {Object} oldChannel.defaultReactionEmoji The emoji to show in the add reaction button on a thread in a forum/media channel (forum/media channels only)
1911
+ * @prop {Number} oldChannel.defaultSortOrder The default sort order type used to order posts in forum/media channels (forum/media channels only)
1912
+ * @prop {Number} oldChannel.defaultThreadRateLimitPerUser The initial rateLimitPerUser to set on newly created threads in a channel (text/forum/media channels only)
1913
+ * @prop {Number?} oldChannel.flags The flags for the channel combined as a bitfield (thread/forum/media channels only)
1914
+ * @prop {String} oldChannel.name The name of the channel
1915
+ * @prop {Boolean} oldChannel.nsfw Whether the channel is NSFW or not (text channels only)
1916
+ * @prop {String?} oldChannel.parentID The ID of the category this channel belongs to (guild channels only)
1917
+ * @prop {Collection} oldChannel.permissionOverwrites Collection of PermissionOverwrites in this channel (guild channels only)
1918
+ * @prop {Number} oldChannel.position The position of the channel (guild channels only)
1919
+ * @prop {Number?} oldChannel.rateLimitPerUser The time in seconds a user has to wait before sending another message (0-21600) (text/voice/stage/forum/media channels only)
1920
+ * @prop {String?} oldChannel.rtcRegion The RTC region ID of the channel (automatic when `null`) (voice channels only)
1921
+ * @prop {String?} oldChannel.topic The topic of the channel (text channels only)
1922
+ * @prop {Number} oldChannel.type The type of the old channel (text/news channels only)
1923
+ * @prop {Number?} oldChannel.userLimit The max number of users that can join the channel (voice channels only)
1924
+ * @prop {Number?} oldChannel.videoQualityMode The camera video quality mode of the channel (voice channels only)
1925
+ */
1926
+ this.emit("channelUpdate", channel, oldChannel);
1927
+ break;
1928
+ }
1929
+ case "CHANNEL_DELETE": {
1930
+ if (packet.d.type === Constants.ChannelTypes.DM || packet.d.type === undefined) {
1931
+ if (this.id === 0) {
1932
+ const channel = this.client.dmChannels.remove(packet.d);
1933
+ if (channel) {
1934
+ delete this.client.dmChannelMap[channel.recipient.id];
1935
+ /**
1936
+ * Fired when a channel is deleted
1937
+ * @event Client#channelDelete
1938
+ * @prop {CategoryChannel | DMChannel | ForumChannel | NewsChannel | TextChannel | VoiceChannel} channel The channel
1939
+ */
1940
+ this.emit("channelDelete", channel);
1941
+ }
1942
+ }
1943
+ } else if (packet.d.guild_id) {
1944
+ delete this.client.channelGuildMap[packet.d.id];
1945
+ const guild = this.client.guilds.get(packet.d.guild_id);
1946
+ if (!guild) {
1947
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in CHANNEL_DELETE`);
1948
+ break;
1949
+ }
1950
+ const channel = guild.channels.remove(packet.d);
1951
+ if (!channel) {
1952
+ break;
1953
+ }
1954
+ if (channel.type === Constants.ChannelTypes.GUILD_VOICE || channel.type === Constants.ChannelTypes.GUILD_STAGE_VOICE) {
1955
+ channel.voiceMembers.forEach((member) => {
1956
+ channel.voiceMembers.remove(member);
1957
+ this.emit("voiceChannelLeave", member, channel);
1958
+ });
1959
+ }
1960
+ this.emit("channelDelete", channel);
1961
+ } else {
1962
+ this.emit("warn", new Error("Unhandled CHANNEL_DELETE type: " + JSON.stringify(packet, null, 2)));
1963
+ }
1964
+ break;
1965
+ }
1966
+ case "GUILD_MEMBERS_CHUNK": {
1967
+ const guild = this.client.guilds.get(packet.d.guild_id);
1968
+ if (!guild) {
1969
+ this.emit("debug", `Received GUILD_MEMBERS_CHUNK, but guild ${packet.d.guild_id} is ` + (this.client.unavailableGuilds.has(packet.d.guild_id) ? "unavailable" : "missing"), this.id);
1970
+ break;
1971
+ }
1972
+
1973
+ const members = packet.d.members.map((member) => {
1974
+ member.id = member.user.id;
1975
+ return guild.members.add(member, guild);
1976
+ });
1977
+
1978
+ if (packet.d.presences) {
1979
+ packet.d.presences.forEach((presence) => {
1980
+ const member = guild.members.get(presence.user.id);
1981
+ if (member) {
1982
+ member.update(presence);
1983
+ }
1984
+ });
1985
+ }
1986
+
1987
+ if (this.requestMembersPromise.hasOwnProperty(packet.d.nonce)) {
1988
+ this.requestMembersPromise[packet.d.nonce].members.push(...members);
1989
+ }
1990
+
1991
+ if (packet.d.chunk_index >= packet.d.chunk_count - 1) {
1992
+ if (this.requestMembersPromise.hasOwnProperty(packet.d.nonce)) {
1993
+ clearTimeout(this.requestMembersPromise[packet.d.nonce].timeout);
1994
+ this.requestMembersPromise[packet.d.nonce].res(this.requestMembersPromise[packet.d.nonce].members);
1995
+ delete this.requestMembersPromise[packet.d.nonce];
1996
+ }
1997
+ if (this.getAllUsersCount.hasOwnProperty(guild.id)) {
1998
+ delete this.getAllUsersCount[guild.id];
1999
+ this.checkReady();
2000
+ }
2001
+ }
2002
+
2003
+ /**
2004
+ * Fired when Discord sends member chunks
2005
+ * @event Client#guildMemberChunk
2006
+ * @prop {Guild} guild The guild the chunked members are in
2007
+ * @prop {Array<Member>} members The members in the chunk
2008
+ */
2009
+ this.emit("guildMemberChunk", guild, members);
2010
+
2011
+ this.lastHeartbeatAck = true;
2012
+
2013
+ break;
2014
+ }
2015
+ case "RESUMED":
2016
+ case "READY": {
2017
+ this.connectAttempts = 0;
2018
+ this.reconnectInterval = 1000;
2019
+
2020
+ this.connecting = false;
2021
+ if (this.connectTimeout) {
2022
+ clearTimeout(this.connectTimeout);
2023
+ }
2024
+ this.connectTimeout = null;
2025
+ this.status = "ready";
2026
+ this.presence.status = "online";
2027
+ this.client.shards._readyPacketCB(this.id);
2028
+
2029
+ if (packet.t === "RESUMED") {
2030
+ // Can only heartbeat after resume succeeds, discord/discord-api-docs#1619
2031
+ this.heartbeat();
2032
+
2033
+ this.preReady = true;
2034
+ this.ready = true;
2035
+
2036
+ /**
2037
+ * Fired when a shard finishes resuming
2038
+ * @event Shard#resume
2039
+ */
2040
+ super.emit("resume");
2041
+ break;
2042
+ } else {
2043
+ this.resumeURL = `${packet.d.resume_gateway_url}?v=${Constants.GATEWAY_VERSION}&encoding=${Erlpack ? "etf" : "json"}`;
2044
+
2045
+ if (this.client.options.compress) {
2046
+ this.resumeURL += "&compress=zlib-stream";
2047
+ }
2048
+ }
2049
+
2050
+ this.client.user = this.client.users.update(new ExtendedUser(packet.d.user, this.client), this.client);
2051
+ if (this.client.user.bot) {
2052
+ this.client.bot = true;
2053
+ if (!this.client._token.startsWith("Bot ")) {
2054
+ this.client._token = "Bot " + this.client._token;
2055
+ }
2056
+ } else {
2057
+ this.emit("warn", new Error("User accounts are against Discord Terms of Service and not supported"));
2058
+ }
2059
+
2060
+ if (packet.d._trace) {
2061
+ this.discordServerTrace = packet.d._trace;
2062
+ }
2063
+
2064
+ this.sessionID = packet.d.session_id;
2065
+
2066
+ packet.d.guilds.forEach((guild) => {
2067
+ if (guild.unavailable) {
2068
+ this.client.guilds.remove(guild);
2069
+ this.client.unavailableGuilds.add(guild, this.client, true);
2070
+ } else {
2071
+ this.client.unavailableGuilds.remove(this.createGuild(guild));
2072
+ }
2073
+ });
2074
+
2075
+ packet.d.private_channels.forEach((channel) => {
2076
+ if (channel.type === undefined || channel.type === Constants.ChannelTypes.DM) {
2077
+ this.client.dmChannelMap[channel.recipients[0].id] = channel.id;
2078
+ this.client.dmChannels.add(channel, this.client, true);
2079
+ } else {
2080
+ this.emit("warn", new Error("Unhandled READY private_channel type: " + JSON.stringify(channel, null, 2)));
2081
+ }
2082
+ });
2083
+
2084
+ this.client.application = packet.d.application;
2085
+
2086
+ this.preReady = true;
2087
+ /**
2088
+ * Fired when a shard finishes processing the ready packet
2089
+ * @event Client#shardPreReady
2090
+ * @prop {Number} id The ID of the shard
2091
+ */
2092
+ this.emit("shardPreReady", this.id);
2093
+
2094
+ if (this.client.unavailableGuilds.size > 0 && packet.d.guilds.length > 0) {
2095
+ this.restartGuildCreateTimeout();
2096
+ } else {
2097
+ this.checkReady();
2098
+ }
2099
+
2100
+ break;
2101
+ }
2102
+ case "VOICE_SERVER_UPDATE": {
2103
+ packet.d.session_id = this.sessionID;
2104
+ packet.d.user_id = this.client.user.id;
2105
+ packet.d.shard = this;
2106
+ this.client.voiceConnections.voiceServerUpdate(packet.d);
2107
+ break;
2108
+ }
2109
+ case "USER_UPDATE": {
2110
+ let user = this.client.users.get(packet.d.id);
2111
+ let oldUser = null;
2112
+ if (user) {
2113
+ oldUser = getOldUserData(user);
2114
+ }
2115
+ user = this.client.users.update(packet.d, this.client);
2116
+ this.emit("userUpdate", user, oldUser);
2117
+ break;
2118
+ }
2119
+ case "GUILD_EMOJIS_UPDATE": {
2120
+ const guild = this.client.guilds.get(packet.d.guild_id);
2121
+ let oldEmojis = null;
2122
+ let emojis = packet.d.emojis;
2123
+ if (guild) {
2124
+ oldEmojis = guild.emojis;
2125
+ guild.update(packet.d);
2126
+ emojis = guild.emojis;
2127
+ }
2128
+ /**
2129
+ * Fired when a guild's emojis are updated
2130
+ * @event Client#guildEmojisUpdate
2131
+ * @prop {Guild} guild The guild. If the guild is uncached, this is an object with an ID key. No other property is guaranteed
2132
+ * @prop {Array} emojis The updated emojis of the guild
2133
+ * @prop {Array?} oldEmojis The old emojis of the guild. If the guild is uncached, this will be null
2134
+ */
2135
+ this.emit("guildEmojisUpdate", guild || { id: packet.d.guild_id }, emojis, oldEmojis);
2136
+ break;
2137
+ }
2138
+ case "GUILD_STICKERS_UPDATE": {
2139
+ const guild = this.client.guilds.get(packet.d.guild_id);
2140
+ let oldStickers = null;
2141
+ let stickers = packet.d.stickers;
2142
+ if (guild) {
2143
+ oldStickers = guild.stickers;
2144
+ guild.update(packet.d);
2145
+ stickers = guild.stickers;
2146
+ }
2147
+ /**
2148
+ * Fired when a guild's stickers are updated
2149
+ * @event Client#guildStickersUpdate
2150
+ * @prop {Guild} guild The guild. If the guild is uncached, this is an object with an ID key. No other property is guaranteed
2151
+ * @prop {Array} stickers The updated stickers of the guild
2152
+ * @prop {Array?} oldStickers The old stickers of the guild. If the guild is uncached, this will be null
2153
+ */
2154
+ this.emit("guildStickersUpdate", guild || { id: packet.d.guild_id }, stickers, oldStickers);
2155
+ break;
2156
+ }
2157
+ case "CHANNEL_PINS_UPDATE": {
2158
+ const channel = this.client.getChannel(packet.d.channel_id);
2159
+ if (!channel) {
2160
+ this.emit("debug", `CHANNEL_PINS_UPDATE target channel ${packet.d.channel_id} not found`);
2161
+ break;
2162
+ }
2163
+ const oldTimestamp = channel.lastPinTimestamp;
2164
+ channel.lastPinTimestamp = Date.parse(packet.d.last_pin_timestamp);
2165
+ /**
2166
+ * Fired when a channel pin timestamp is updated
2167
+ * @event Client#channelPinUpdate
2168
+ * @prop {DMChannel | TextChannel | NewsChannel} channel The channel
2169
+ * @prop {Number} timestamp The new timestamp
2170
+ * @prop {Number} oldTimestamp The old timestamp
2171
+ */
2172
+ this.emit("channelPinUpdate", channel, channel.lastPinTimestamp, oldTimestamp);
2173
+ break;
2174
+ }
2175
+ case "WEBHOOKS_UPDATE": {
2176
+ /**
2177
+ * Fired when a channel's webhooks are updated
2178
+ * @event Client#webhooksUpdate
2179
+ * @prop {Object} data The update data
2180
+ * @prop {String} data.channelID The ID of the channel that webhooks were updated in
2181
+ * @prop {String} data.guildID The ID of the guild that webhooks were updated in
2182
+ */
2183
+ this.emit("webhooksUpdate", {
2184
+ channelID: packet.d.channel_id,
2185
+ guildID: packet.d.guild_id,
2186
+ });
2187
+ break;
2188
+ }
2189
+ case "THREAD_CREATE": {
2190
+ const channel = Channel.from(packet.d, this.client);
2191
+ if (!channel.guild) {
2192
+ channel.guild = this.client.guilds.get(packet.d.guild_id);
2193
+ if (!channel.guild) {
2194
+ this.emit("debug", `Received THREAD_CREATE for channel in missing guild ${packet.d.guild_id}`);
2195
+ break;
2196
+ }
2197
+ }
2198
+ channel.guild.threads.add(channel, this.client);
2199
+ this.client.threadGuildMap[packet.d.id] = packet.d.guild_id;
2200
+
2201
+ const parent = channel.guild.channels.get(channel.parentID);
2202
+
2203
+ if (parent instanceof ForumChannel) {
2204
+ parent.lastMessageID = channel.id;
2205
+ }
2206
+
2207
+ /**
2208
+ * Fired when a channel is created
2209
+ * @event Client#threadCreate
2210
+ * @prop {NewsThreadChannel | PrivateThreadChannel | PublicThreadChannel} channel The channel
2211
+ */
2212
+ this.emit("threadCreate", channel);
2213
+ break;
2214
+ }
2215
+ case "THREAD_UPDATE": {
2216
+ const channel = this.client.getChannel(packet.d.id);
2217
+ if (!channel) {
2218
+ const thread = Channel.from(packet.d, this.client);
2219
+ this.emit("threadUpdate", this.client.guilds.get(packet.d.guild_id).threads.add(thread, this.client), null);
2220
+ this.client.threadGuildMap[packet.d.id] = packet.d.guild_id;
2221
+ break;
2222
+ }
2223
+ if (!(channel instanceof ThreadChannel)) {
2224
+ this.emit("warn", `Unexpected THREAD_UPDATE for channel ${packet.d.id} with type ${channel.type}`);
2225
+ break;
2226
+ }
2227
+ const oldChannel = {
2228
+ appliedTags: channel.appliedTags,
2229
+ autoArchiveDuration: channel.autoArchiveDuration,
2230
+ flags: channel.flags,
2231
+ name: channel.name,
2232
+ rateLimitPerUser: channel.rateLimitPerUser,
2233
+ threadMetadata: channel.threadMetadata,
2234
+ };
2235
+ channel.update(packet.d);
2236
+
2237
+ /**
2238
+ * Fired when a thread channel is updated
2239
+ * @event Client#threadUpdate
2240
+ * @prop {NewsThreadChannel | PrivateThreadChannel | PublicThreadChannel} channel The updated channel
2241
+ * @prop {Object?} oldChannel The old thread channel. This will be null if the channel was uncached
2242
+ * @prop {Array<String>?} oldChannel.appliedTags The IDs of the set of tags that have been applied to a thread in a forum/media channel
2243
+ * @prop {Number} oldChannel.autoArchiveDuration The duration in minutes to automatically archive the thread after recent activity, either 60, 1440, 4320 or 10080
2244
+ * @prop {Number} oldChannel.flags The flags for the channel combined as a bitfield
2245
+ * @prop {String} oldChannel.name The name of the channel
2246
+ * @prop {Number} oldChannel.rateLimitPerUser The time in seconds a user has to wait before sending another message (0-21600)
2247
+ * @prop {Object} oldChannel.threadMetadata Metadata for the thread
2248
+ * @prop {Boolean} oldChannel.threadMetadata.archived Whether the thread is archived
2249
+ * @prop {Number} oldChannel.threadMetadata.archiveTimestamp Timestamp when the thread's archive status was last changed, used for calculating recent activity
2250
+ * @prop {Number} oldChannel.threadMetadata.autoArchiveDuration Duration in minutes to automatically archive the thread after recent activity, either 60, 1440, 4320 or 10080
2251
+ * @prop {Boolean?} oldChannel.threadMetadata.locked Whether the thread is locked
2252
+ */
2253
+ this.emit("threadUpdate", channel, oldChannel);
2254
+ break;
2255
+ }
2256
+ case "THREAD_DELETE": {
2257
+ delete this.client.threadGuildMap[packet.d.id];
2258
+ const guild = this.client.guilds.get(packet.d.guild_id);
2259
+ if (!guild) {
2260
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in THREAD_DELETE`);
2261
+ break;
2262
+ }
2263
+ const channel = guild.threads.remove(packet.d);
2264
+ if (!channel) {
2265
+ break;
2266
+ }
2267
+ /**
2268
+ * Fired when a thread channel is deleted
2269
+ * @event Client#threadDelete
2270
+ * @prop {NewsThreadChannel | PrivateThreadChannel | PublicThreadChannel} channel The channel
2271
+ */
2272
+ this.emit("threadDelete", channel);
2273
+ break;
2274
+ }
2275
+ case "THREAD_LIST_SYNC": {
2276
+ const guild = this.client.guilds.get(packet.d.guild_id);
2277
+ if (!guild) {
2278
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in THREAD_LIST_SYNC`);
2279
+ break;
2280
+ }
2281
+ const deletedThreads = (packet.d.channel_ids || guild.threads.map((c) => c.id)) // REVIEW Is this a good name?
2282
+ .filter((c) => !packet.d.threads.some((t) => t.id === c)).map((id) => guild.threads.remove({ id }) || { id });
2283
+ const activeThreads = packet.d.threads.map((t) => guild.threads.update(t, this.client));
2284
+ const joinedThreadsMember = packet.d.members.map((m) => guild.threads.get(m.id).members.update(m, this.client));
2285
+ /**
2286
+ * Fired when the current user gains access to a channel
2287
+ * @event Client#threadListSync
2288
+ * @prop {Guild} guild The guild where threads are being synced
2289
+ * @prop {Array<NewsThreadChannel | PrivateThreadChannel | PublicThreadChannel | Object>} deletedThreads An array of synced threads that the current user no longer has access to. If a thread channel is uncached, it will be an object with an `id` key. No other property is guaranteed
2290
+ * @prop {Array<NewsThreadChannel | PrivateThreadChannel | PublicThreadChannel>} activeThreads An array of synced active threads that the current user can access
2291
+ * @prop {Array<ThreadMember>} joinedThreadsMember An array of thread member objects where the current user has been added in a synced thread channel
2292
+ */
2293
+ this.emit("threadListSync", guild, deletedThreads, activeThreads, joinedThreadsMember);
2294
+ break;
2295
+ }
2296
+ case "THREAD_MEMBER_UPDATE": {
2297
+ const channel = this.client.getChannel(packet.d.id);
2298
+ if (!channel) {
2299
+ this.emit("debug", `Missing channel ${packet.d.id} in THREAD_MEMBER_UPDATE`);
2300
+ break;
2301
+ }
2302
+ let oldMember = null;
2303
+ // Thanks Discord
2304
+ packet.d.thread_id = packet.d.id;
2305
+ let member = channel.members.get((packet.d.id = packet.d.user_id));
2306
+ if (member) {
2307
+ oldMember = {
2308
+ flags: member.flags,
2309
+ };
2310
+ }
2311
+ member = channel.members.update(packet.d, this.client);
2312
+ /**
2313
+ * Fired when a thread member is updated
2314
+ * @event Client#threadMemberUpdate
2315
+ * @prop {NewsThreadChannel | PrivateThreadChannel | PublicThreadChannel} channel The channel
2316
+ * @prop {ThreadMember} member The updated thread member
2317
+ * @prop {Object} oldMember The old thread member data
2318
+ * @prop {Number} oldMember.flags User thread settings
2319
+ */
2320
+ this.emit("threadMemberUpdate", channel, member, oldMember);
2321
+ break;
2322
+ }
2323
+ case "THREAD_MEMBERS_UPDATE": {
2324
+ const channel = this.client.getChannel(packet.d.id);
2325
+ if (!channel) {
2326
+ this.emit("debug", `Missing channel ${packet.d.id} in THREAD_MEMBERS_UPDATE`);
2327
+ break;
2328
+ }
2329
+ channel.update(packet.d);
2330
+ let addedMembers;
2331
+ let removedMembers;
2332
+ if (packet.d.added_members) {
2333
+ addedMembers = packet.d.added_members.map((m) => {
2334
+ if (m.presence) {
2335
+ m.presence.id = m.presence.user.id;
2336
+ this.client.users.update(m.presence.user, this.client);
2337
+ }
2338
+
2339
+ m.thread_id = m.id;
2340
+ m.id = m.user_id;
2341
+ m.member.id = m.member.user.id;
2342
+ const guild = this.client.guilds.get(packet.d.guild_id);
2343
+ if (guild) {
2344
+ if (m.presence) {
2345
+ guild.members.update(m.presence, guild);
2346
+ }
2347
+ guild.members.update(m.member, guild);
2348
+ }
2349
+ return channel.members.update(m, this.client);
2350
+ });
2351
+ }
2352
+ if (packet.d.removed_member_ids) {
2353
+ removedMembers = packet.d.removed_member_ids.map((id) => channel.members.remove({ id }) || { id });
2354
+ }
2355
+ /**
2356
+ * Fired when anyone is added or removed from a thread. If the `guildMembers` intent is not specified, this will only apply for the current user
2357
+ * @event Client#threadMembersUpdate
2358
+ * @prop {NewsThreadChannel | PrivateThreadChannel | PublicThreadChannel} channel The thread channel
2359
+ * @prop {Array<ThreadMember>} addedMembers An array of members that were added to the thread channel
2360
+ * @prop {Array<ThreadMember | Object>} removedMembers An array of members that were removed from the thread channel. If a member is uncached, it will be an object with an `id` key. No other property is guaranteed
2361
+ */
2362
+ this.emit("threadMembersUpdate", channel, addedMembers || [], removedMembers || []);
2363
+ break;
2364
+ }
2365
+ case "STAGE_INSTANCE_CREATE": {
2366
+ const guild = this.client.guilds.get(packet.d.guild_id);
2367
+ if (!guild) {
2368
+ this.emit("debug", `Missing guild ${packet.d.guild_id} in STAGE_INSTANCE_CREATE`);
2369
+ break;
2370
+ }
2371
+ /**
2372
+ * Fired when a stage instance is created
2373
+ * @event Client#stageInstanceCreate
2374
+ * @prop {StageInstance} stageInstance The stage instance
2375
+ */
2376
+ this.emit("stageInstanceCreate", guild.stageInstances.add(packet.d, this.client));
2377
+ break;
2378
+ }
2379
+ case "STAGE_INSTANCE_UPDATE": {
2380
+ const guild = this.client.guilds.get(packet.d.guild_id);
2381
+ if (!guild) {
2382
+ this.emit("stageInstanceUpdate", packet.d, null);
2383
+ break;
2384
+ }
2385
+ const stageInstance = guild.stageInstances.get(packet.d.id);
2386
+ let oldStageInstance = null;
2387
+ if (stageInstance) {
2388
+ oldStageInstance = {
2389
+ discoverableDisabled: stageInstance.discoverableDisabled,
2390
+ privacyLevel: stageInstance.privacyLevel,
2391
+ topic: stageInstance.topic,
2392
+ };
2393
+ }
2394
+ /**
2395
+ * Fired when a stage instance is updated
2396
+ * @event Client#stageInstanceUpdate
2397
+ * @prop {StageInstance} stageInstance The stage instance
2398
+ * @prop {Object?} oldStageInstance The old stage instance. If the stage instance was cached, this will be an object with the properties below. Otherwise, it will be null
2399
+ * @prop {Boolean} oldStageInstance.discoverableDisabled Whether or not stage discovery was disabled
2400
+ * @prop {Number} oldStageInstance.privacyLevel The privacy level of the stage instance. 1 is public, 2 is guild only
2401
+ * @prop {String} oldStageInstance.topic The stage instance topic
2402
+ */
2403
+ this.emit("stageInstanceUpdate", guild.stageInstances.update(packet.d, this.client), oldStageInstance);
2404
+ break;
2405
+ }
2406
+ case "STAGE_INSTANCE_DELETE": {
2407
+ const guild = this.client.guilds.get(packet.d.guild_id);
2408
+ if (!guild) {
2409
+ this.emit("stageInstanceDelete", new StageInstance(packet.d, this.client));
2410
+ break;
2411
+ }
2412
+ /**
2413
+ * Fired when a stage instance is deleted
2414
+ * @event Client#stageInstanceDelete
2415
+ * @prop {StageInstance} stageInstance The deleted stage instance
2416
+ */
2417
+ this.emit("stageInstanceDelete", guild.stageInstances.remove(packet.d) || new StageInstance(packet.d, this.client));
2418
+ break;
2419
+ }
2420
+ case "GUILD_SCHEDULED_EVENT_CREATE": {
2421
+ const guild = this.client.guilds.get(packet.d.guild_id);
2422
+ if (!guild) {
2423
+ this.emit("guildScheduledEventCreate", new GuildScheduledEvent(packet.d, this.client));
2424
+ break;
2425
+ }
2426
+
2427
+ /**
2428
+ * Fired when a guild scheduled event is created
2429
+ * @event Client#guildScheduledEventCreate
2430
+ * @prop {GuildScheduledEvent} event The event
2431
+ */
2432
+ this.emit("guildScheduledEventCreate", guild.events.add(packet.d, this.client));
2433
+ break;
2434
+ }
2435
+ case "GUILD_SCHEDULED_EVENT_UPDATE": {
2436
+ const guild = this.client.guilds.get(packet.d.guild_id);
2437
+ if (!guild) {
2438
+ this.emit("guildScheduledEventUpdate", new GuildScheduledEvent(packet.d, this.client), null);
2439
+ break;
2440
+ }
2441
+
2442
+ const event = guild.events.get(packet.d.id);
2443
+ let oldEvent = null;
2444
+ if (event) {
2445
+ oldEvent = {
2446
+ channel: event.channel,
2447
+ description: event.description,
2448
+ entityID: event.entityID,
2449
+ entityMetadata: event.entityMetadata,
2450
+ entityType: event.entityType,
2451
+ image: event.image,
2452
+ name: event.name,
2453
+ privacyLevel: event.privacyLevel,
2454
+ scheduledEndTime: event.scheduledEndTime,
2455
+ scheduledStartTime: event.scheduledStartTime,
2456
+ status: event.status,
2457
+ };
2458
+ }
2459
+
2460
+ /**
2461
+ * Fired when a guild scheduled event is updated
2462
+ * @event Client#guildScheduledEventUpdate
2463
+ * @prop {GuildScheduledEvent} event The updated event
2464
+ * @prop {Object?} oldEvent The old guild event data, or null if the event wasn't cached.
2465
+ * @prop {(VoiceChannel | StageChannel | Object)?} oldEvent.channel The channel where the event is held
2466
+ * @prop {String?} oldEvent.description The description of the event
2467
+ * @prop {String?} oldEvent.entityID The Entity ID associated to the event
2468
+ * @prop {Object?} oldEvent.entityMetadata Metadata for the event
2469
+ * @prop {String?} oldEvent.entityMetadata.location Location of the event
2470
+ * @prop {Number} oldEvent.entityType The event entity type
2471
+ * @prop {String?} oldEvent.image The hash of the event's image
2472
+ * @prop {String} oldEvent.name The name of the event
2473
+ * @prop {Number} oldEvent.privacyLevel The privacy level of the event
2474
+ * @prop {Number?} oldEvent.scheduledEndTime The time the event will start
2475
+ * @prop {Number} oldEvent.scheduledStartTime The time the event will start
2476
+ * @prop {Number} oldEvent.status The status of the guild scheduled event
2477
+ */
2478
+ this.emit("guildScheduledEventUpdate", guild.events.update(packet.d, this.client), oldEvent);
2479
+ break;
2480
+ }
2481
+ case "GUILD_SCHEDULED_EVENT_DELETE": {
2482
+ const guild = this.client.guilds.get(packet.d.guild_id);
2483
+ if (!guild) {
2484
+ this.emit("guildScheduledEventDelete", new GuildScheduledEvent(packet.d, this.client));
2485
+ break;
2486
+ }
2487
+ /**
2488
+ * Fired when a guild scheduled event is deleted
2489
+ * @event Client#guildScheduledEventDelete
2490
+ * @prop {GuildScheduledEvent} event The event that was deleted.
2491
+ */
2492
+ this.emit("guildScheduledEventDelete", guild.events.remove(packet.d) || new GuildScheduledEvent(packet.d, this.client));
2493
+ break;
2494
+ }
2495
+ case "GUILD_SCHEDULED_EVENT_USER_ADD": {
2496
+ const user = this.client.users.get(packet.d.user_id) || { id: packet.d.user_id };
2497
+
2498
+ const guild = this.client.guilds.get(packet.d.guild_id);
2499
+ if (!guild) {
2500
+ this.emit("guildScheduledEventUserAdd", { id: packet.d.guild_scheduled_event_id, guild: { id: packet.d.guild_id } }, user);
2501
+ break;
2502
+ }
2503
+
2504
+ const event = guild.events.get(packet.d.guild_scheduled_event_id);
2505
+ if (event) {
2506
+ ++event.userCount;
2507
+ }
2508
+
2509
+ /**
2510
+ * Fired when an user has subscribed to a Guild Event.
2511
+ * @event Client#guildScheduledEventUserAdd
2512
+ * @prop {GuildScheduledEvent | Object} event The guild event that the user subscribed to. If the event is uncached, this will be an object with `id` and `guild` keys. No other property is guaranteed
2513
+ * @prop {User | Object} user The user that subscribed to the Guild Event. If the user is uncached, this will be an object with an `id` key. No other property is guaranteed
2514
+ */
2515
+ this.emit("guildScheduledEventUserAdd", event || { id: packet.d.guild_scheduled_event_id, guild: guild }, user);
2516
+ break;
2517
+ }
2518
+ case "GUILD_SCHEDULED_EVENT_USER_REMOVE": {
2519
+ const user = this.client.users.get(packet.d.user_id) || { id: packet.d.user_id };
2520
+
2521
+ const guild = this.client.guilds.get(packet.d.guild_id);
2522
+ if (!guild) {
2523
+ this.emit("guildScheduledEventUserRemove", { id: packet.d.guild_scheduled_event_id, guild: { id: packet.d.guild_id } }, user);
2524
+ break;
2525
+ }
2526
+
2527
+ const event = guild.events.get(packet.d.guild_scheduled_event_id);
2528
+ if (event) {
2529
+ --event.userCount;
2530
+ }
2531
+
2532
+ /**
2533
+ * Fired when an user has unsubscribed from a Guild Event.
2534
+ * @event Client#guildScheduledEventUserRemove
2535
+ * @prop {GuildScheduledEvent | string} event The guild event that the user unsubscribed to. This will be the guild event ID if the guild was uncached
2536
+ * @prop {User | string} user The user that unsubscribed to the Guild Event. This will be the user ID if the user was uncached
2537
+ */
2538
+ this.emit("guildScheduledEventUserRemove", event || { id: packet.d.guild_scheduled_event_id, guild: guild }, user);
2539
+ break;
2540
+ }
2541
+ case "INTERACTION_CREATE": {
2542
+ /**
2543
+ * Fired when an interaction is created
2544
+ * @event Client#interactionCreate
2545
+ * @prop {PingInteraction | CommandInteraction | ComponentInteraction | AutocompleteInteraction | ModalSubmitInteraction | UnknownInteraction} interaction The Interaction that was created
2546
+ */
2547
+ this.emit("interactionCreate", Interaction.from(packet.d, this.client));
2548
+ break;
2549
+ }
2550
+ case "APPLICATION_COMMAND_PERMISSIONS_UPDATE": {
2551
+ /**
2552
+ * Fired when an application command's permissions are updated
2553
+ * @event Client#applicationCommandPermissionsUpdate
2554
+ * @prop {Object} guildApplicationCommandPermissions The updated command permissions
2555
+ */
2556
+ this.emit("applicationCommandPermissionsUpdate", packet.d);
2557
+ break;
2558
+ }
2559
+ case "GUILD_INTEGRATIONS_UPDATE": {
2560
+ /**
2561
+ * Fired when a guild integration is updated
2562
+ * @event Client#guildIntegrationsUpdate
2563
+ * @prop {Guild} guild The guild where the integration was updated. If the guild isn't cached, this will be an object with an `id` key. No other properties are guaranteed
2564
+ */
2565
+ this.emit("guildIntegrationsUpdate", this.client.guilds.get(packet.d.guild_id) || { id: packet.d.guild_id });
2566
+ break;
2567
+ }
2568
+ case "GUILD_SOUNDBOARD_SOUND_CREATE": {
2569
+ packet.d.id = packet.d.sound_id;
2570
+ const guild = this.client.guilds.get(packet.d.guild_id);
2571
+ if (!guild) {
2572
+ this.emit("guildSoundboardSoundCreate", new SoundboardSound(packet.d, this.client));
2573
+ break;
2574
+ }
2575
+ /**
2576
+ * Fired when a guild soundboard sound is created
2577
+ * @event Client#guildSoundboardSoundCreate
2578
+ * @prop {SoundboardSound} sound The created soundboard sound
2579
+ */
2580
+ this.emit("guildSoundboardSoundCreate", guild.soundboardSounds.add(packet.d, this.client));
2581
+ break;
2582
+ }
2583
+ case "GUILD_SOUNDBOARD_SOUND_DELETE": {
2584
+ packet.d.id = packet.d.sound_id;
2585
+ const guild = this.client.guilds.get(packet.d.guild_id);
2586
+ /**
2587
+ * Fired when a guild soundboard sound is deleted
2588
+ * @event Client#guildSoundboardSoundDelete
2589
+ * @prop {SoundboardSound} sound The deleted soundboard sound. If the soundboard sound isn't cached, this will be an object with `id` and `guild` keys. If the guild isn't cached, it will be an object with an `id` key. No other properties are guaranteed
2590
+ */
2591
+ this.emit("guildSoundboardSoundDelete", (guild && guild.soundboardSounds.remove(packet.d)) || {
2592
+ id: packet.d.id,
2593
+ guild: guild || {
2594
+ id: packet.d.guild_id,
2595
+ },
2596
+ });
2597
+ break;
2598
+ }
2599
+ case "GUILD_SOUNDBOARD_SOUND_UPDATE": {
2600
+ packet.d.id = packet.d.sound_id;
2601
+ const guild = this.client.guilds.get(packet.d.guild_id);
2602
+ if (!guild) {
2603
+ this.emit("guildSoundboardSoundUpdate", new SoundboardSound(packet.d, this.client), null);
2604
+ break;
2605
+ }
2606
+
2607
+ const sound = guild.soundboardSounds.get(packet.d.id);
2608
+ let oldSound = null;
2609
+ if (sound) {
2610
+ oldSound = {
2611
+ name: sound.name,
2612
+ volume: sound.volume,
2613
+ emojiID: sound.emojiID,
2614
+ emojiName: sound.emojiName,
2615
+ available: sound.available,
2616
+ };
2617
+ }
2618
+
2619
+ /**
2620
+ * Fired when a guild soundboard sound is updated
2621
+ * @event Client#guildSoundboardSoundUpdate
2622
+ * @prop {SoundboardSound} sound The updated soundboard sound
2623
+ * @prop {Object} oldSound The old soundboard sound data, or null if not cached
2624
+ * @prop {Boolean} oldSound.available Whether the soundboard sound was available or not
2625
+ * @prop {String?} oldSound.emojiID The ID of the relating custom emoji
2626
+ * @prop {String?} oldSound.emojiName The name of the relating default emoji
2627
+ * @prop {String} oldSound.name The name of the soundboard sound
2628
+ * @prop {Number} oldSound.volume The volume of the soundboard sound, between 0 and 1
2629
+ */
2630
+ this.emit("guildSoundboardSoundUpdate", guild.soundboardSounds.update(packet.d, this.client), oldSound);
2631
+ break;
2632
+ }
2633
+ case "GUILD_SOUNDBOARD_SOUNDS_UPDATE": {
2634
+ packet.d.soundboard_sounds = packet.d.soundboard_sounds.map((sound) => {
2635
+ sound.id = sound.sound_id;
2636
+ return sound;
2637
+ });
2638
+ const guild = this.client.guilds.get(packet.d.guild_id);
2639
+ if (!guild) {
2640
+ this.emit("guildSoundboardSoundsUpdate", { id: packet.d.guild_id }, packet.d.soundboard_sounds.map((sound) => new SoundboardSound(sound, this.client)), null);
2641
+ break;
2642
+ }
2643
+
2644
+ const oldSounds = packet.d.soundboard_sounds.map((_sound) => {
2645
+ const sound = guild.soundboardSounds.get(_sound.id);
2646
+ if (!sound) {
2647
+ return null;
2648
+ }
2649
+ return {
2650
+ name: sound.name,
2651
+ volume: sound.volume,
2652
+ emojiID: sound.emojiID,
2653
+ emojiName: sound.emojiName,
2654
+ available: sound.available,
2655
+ };
2656
+ });
2657
+
2658
+ /**
2659
+ * Fired when multiple guild soundboard sounds are updated
2660
+ * @event Client#guildSoundboardSoundsUpdate
2661
+ * @prop {Guild} guild The guild. If the guild is uncached, this is an object with an ID key. No other property is guaranteed
2662
+ * @prop {Array<SoundboardSound>} sounds The updated soundboard sounds
2663
+ * @prop {Array<Object>} oldSounds The old soundboard sounds data, or null if not cached
2664
+ * @prop {Boolean} oldSounds[].available Whether the soundboard sound was available or not
2665
+ * @prop {String?} oldSounds[].emojiID The ID of the relating custom emoji
2666
+ * @prop {String?} oldSounds[].emojiName The name of the relating default emoji
2667
+ * @prop {String} oldSounds[].name The name of the soundboard sound
2668
+ * @prop {Number} oldSounds[].volume The volume of the soundboard sound, between 0 and 1
2669
+ */
2670
+ this.emit("guildSoundboardSoundsUpdate", guild, packet.d.soundboard_sounds.map((sound) => guild.soundboardSounds.update(sound, this.client)), oldSounds);
2671
+ break;
2672
+ }
2673
+ case "SOUNDBOARD_SOUNDS": {
2674
+ const guild = this.client.guilds.get(packet.d.guild_id);
2675
+ const sounds = packet.d.soundboard_sounds.map((sound) => {
2676
+ sound.id = sound.sound_id;
2677
+ const s = guild ? guild.soundboardSounds.update(sound, this.client) : new SoundboardSound(sound, this.client);
2678
+ return s;
2679
+ });
2680
+
2681
+ /**
2682
+ * Fired when Discord sends a guild's soundboard sounds. Sent in response to `fetchSoundboardSounds()`
2683
+ * @prop {Guild} guild The ID of the guild. If the guild is uncached, this will be an object with an `id` key. No other properties are guaranteed
2684
+ * @prop {Array<SoundboardSound>} sounds The guild's soundboard sounds
2685
+ */
2686
+ this.emit("soundboardSounds", guild || { id: packet.d.guild_id }, sounds);
2687
+ this.lastHeartbeatAck = true;
2688
+
2689
+ for (const nonce in this.requestSoundboardSoundsPromise) {
2690
+ if (packet.d.guild_id in this.requestSoundboardSoundsPromise[nonce].soundboardSounds) {
2691
+ this.requestSoundboardSoundsPromise[nonce].soundboardSounds[packet.d.guild_id] = sounds;
2692
+ if (Object.values(this.requestSoundboardSoundsPromise[nonce].soundboardSounds).every((v) => v !== undefined)) {
2693
+ clearTimeout(this.requestSoundboardSoundsPromise[nonce].timeout);
2694
+ this.requestSoundboardSoundsPromise[nonce].res(this.requestSoundboardSoundsPromise[nonce].soundboardSounds);
2695
+ delete this.requestSoundboardSoundsPromise[nonce];
2696
+ }
2697
+ }
2698
+ }
2699
+ break;
2700
+ }
2701
+ case "CHANNEL_INFO": {
2702
+ const guild = this.client.guilds.get(packet.d.guild_id);
2703
+ const channels = packet.d.channels.map((info) => {
2704
+ const channel = this.client.getChannel(info.id);
2705
+ const result = {
2706
+ id: info.id,
2707
+ };
2708
+ if (info.status !== undefined) {
2709
+ result.status = info.status;
2710
+ if (channel) {
2711
+ channel.status = info.status;
2712
+ }
2713
+ }
2714
+ if (info.voice_start_time !== undefined) {
2715
+ result.voiceStartTime = info.voice_start_time ? info.voice_start_time * 1000 : null;
2716
+ if (channel) {
2717
+ channel.voiceStartTime = result.voiceStartTime;
2718
+ }
2719
+ }
2720
+ return result;
2721
+ });
2722
+ /**
2723
+ * Fired when Discord sends the ephemeral data of the channels of a guild. Sent in response to `Guild#fetchChannelInfo()`
2724
+ * @event Client#channelInfo
2725
+ * @prop {Guild | Object} guild The guild. If the guild is not cached, this will be an object with an `id` key. No other property is guaranteed
2726
+ * @prop {Array<Object>} channels The ephemeral data of the channels, each containing the channel `id` and the requested fields (`status`, `voiceStartTime`)
2727
+ */
2728
+ this.emit("channelInfo", guild || { id: packet.d.guild_id }, channels);
2729
+ const requests = this.requestChannelInfoPromise[packet.d.guild_id];
2730
+ if (requests) {
2731
+ for (const request of requests) {
2732
+ clearTimeout(request.timeout);
2733
+ request.res(channels);
2734
+ }
2735
+ delete this.requestChannelInfoPromise[packet.d.guild_id];
2736
+ }
2737
+ break;
2738
+ }
2739
+ case "ENTITLEMENT_CREATE": {
2740
+ /**
2741
+ * Fired when an entitlement is created
2742
+ * @event Client#entitlementCreate
2743
+ * @prop {Entitlement} entitlement The created entitlement
2744
+ */
2745
+ this.emit("entitlementCreate", new Entitlement(packet.d, this.client));
2746
+ break;
2747
+ }
2748
+ case "ENTITLEMENT_UPDATE": {
2749
+ /**
2750
+ * Fired when an entitlement is updated or renewed
2751
+ * @event Client#entitlementUpdate
2752
+ * @prop {Entitlement} entitlement The updated entitlement
2753
+ */
2754
+ this.emit("entitlementUpdate", new Entitlement(packet.d, this.client));
2755
+ break;
2756
+ }
2757
+ case "ENTITLEMENT_DELETE": {
2758
+ /**
2759
+ * Fired when an entitlement is deleted
2760
+ * @event Client#entitlementDelete
2761
+ * @prop {Entitlement} entitlement The deleted entitlement
2762
+ */
2763
+ this.emit("entitlementDelete", new Entitlement(packet.d, this.client));
2764
+ break;
2765
+ }
2766
+ case "INTEGRATION_CREATE": {
2767
+ const guild = this.client.guilds.get(packet.d.guild_id) || { id: packet.d.guild_id };
2768
+ /**
2769
+ * Fired when an integration is created in a guild
2770
+ * @event Client#integrationCreate
2771
+ * @prop {Guild | Object} guild The guild. If the guild is not cached, this will be an object with an `id` key. No other property is guaranteed
2772
+ * @prop {GuildIntegration} integration The created integration
2773
+ */
2774
+ this.emit("integrationCreate", guild, new GuildIntegration(packet.d, guild));
2775
+ break;
2776
+ }
2777
+ case "INTEGRATION_UPDATE": {
2778
+ const guild = this.client.guilds.get(packet.d.guild_id) || { id: packet.d.guild_id };
2779
+ /**
2780
+ * Fired when an integration is updated in a guild
2781
+ * @event Client#integrationUpdate
2782
+ * @prop {Guild | Object} guild The guild. If the guild is not cached, this will be an object with an `id` key. No other property is guaranteed
2783
+ * @prop {GuildIntegration} integration The updated integration
2784
+ */
2785
+ this.emit("integrationUpdate", guild, new GuildIntegration(packet.d, guild));
2786
+ break;
2787
+ }
2788
+ case "INTEGRATION_DELETE": {
2789
+ /**
2790
+ * Fired when an integration is deleted from a guild
2791
+ * @event Client#integrationDelete
2792
+ * @prop {Guild | Object} guild The guild. If the guild is not cached, this will be an object with an `id` key. No other property is guaranteed
2793
+ * @prop {Object} integration The deleted integration
2794
+ * @prop {String?} integration.applicationID The ID of the bot/OAuth2 application of the integration
2795
+ * @prop {String} integration.id The ID of the integration
2796
+ */
2797
+ this.emit("integrationDelete", this.client.guilds.get(packet.d.guild_id) || { id: packet.d.guild_id }, {
2798
+ applicationID: packet.d.application_id,
2799
+ id: packet.d.id,
2800
+ });
2801
+ break;
2802
+ }
2803
+ case "RATE_LIMITED": {
2804
+ const meta = packet.d.meta || {};
2805
+ if (packet.d.opcode === Constants.GatewayOPCodes.REQUEST_GUILD_MEMBERS && meta.nonce && this.requestMembersPromise[meta.nonce]) {
2806
+ clearTimeout(this.requestMembersPromise[meta.nonce].timeout);
2807
+ this.requestMembersPromise[meta.nonce].res(this.requestMembersPromise[meta.nonce].members);
2808
+ delete this.requestMembersPromise[meta.nonce];
2809
+ }
2810
+ /**
2811
+ * Fired when the shard is rate limited for a gateway opcode (e.g. Request Guild Members)
2812
+ * @event Client#rateLimited
2813
+ * @prop {Object} rateLimit The rate limit data
2814
+ * @prop {Object} rateLimit.meta Metadata of the rate limited request (`guildID` and `nonce` for Request Guild Members)
2815
+ * @prop {Number} rateLimit.opcode The gateway opcode that was rate limited
2816
+ * @prop {Number} rateLimit.retryAfter The number of seconds to wait before sending another request
2817
+ * @prop {Number} id The ID of the shard
2818
+ */
2819
+ this.emit("rateLimited", {
2820
+ meta: {
2821
+ guildID: meta.guild_id,
2822
+ nonce: meta.nonce,
2823
+ },
2824
+ opcode: packet.d.opcode,
2825
+ retryAfter: packet.d.retry_after,
2826
+ }, this.id);
2827
+ break;
2828
+ }
2829
+ case "SUBSCRIPTION_CREATE": {
2830
+ /**
2831
+ * Fired when a subscription to a premium application SKU is created
2832
+ * @event Client#subscriptionCreate
2833
+ * @prop {Subscription} subscription The created subscription
2834
+ */
2835
+ this.emit("subscriptionCreate", new Subscription(packet.d, this.client));
2836
+ break;
2837
+ }
2838
+ case "SUBSCRIPTION_UPDATE": {
2839
+ /**
2840
+ * Fired when a subscription to a premium application SKU is updated
2841
+ * @event Client#subscriptionUpdate
2842
+ * @prop {Subscription} subscription The updated subscription
2843
+ */
2844
+ this.emit("subscriptionUpdate", new Subscription(packet.d, this.client));
2845
+ break;
2846
+ }
2847
+ case "SUBSCRIPTION_DELETE": {
2848
+ /**
2849
+ * Fired when a subscription to a premium application SKU is deleted
2850
+ * @event Client#subscriptionDelete
2851
+ * @prop {Subscription} subscription The deleted subscription
2852
+ */
2853
+ this.emit("subscriptionDelete", new Subscription(packet.d, this.client));
2854
+ break;
2855
+ }
2856
+ default: {
2857
+ /**
2858
+ * Fired when the shard encounters an unknown packet
2859
+ * @event Client#unknown
2860
+ * @prop {Object} packet The unknown packet
2861
+ * @prop {Number} id The ID of the shard
2862
+ */
2863
+ this.emit("unknown", packet, this.id);
2864
+ break;
2865
+ }
2866
+ }
2867
+ }
2868
+
2869
+ _onWSClose(code, reason) {
2870
+ reason = reason.toString();
2871
+ this.emit("debug", "WS disconnected: " + JSON.stringify({
2872
+ code: code,
2873
+ reason: reason,
2874
+ status: this.status,
2875
+ }));
2876
+ let err = !code || code === 1000 ? null : new Error(code + ": " + reason);
2877
+ let reconnect = "auto";
2878
+ if (code) {
2879
+ this.emit("debug", `${code === 1000 ? "Clean" : "Unclean"} WS close: ${code}: ${reason}`, this.id);
2880
+ if (code === 4001) {
2881
+ err = new Error("Gateway received invalid OP code");
2882
+ } else if (code === 4002) {
2883
+ err = new Error("Gateway received invalid message");
2884
+ } else if (code === 4003) {
2885
+ err = new Error("Not authenticated");
2886
+ this.sessionID = null;
2887
+ this.resumeURL = null;
2888
+ } else if (code === 4004) {
2889
+ err = new Error("Authentication failed");
2890
+ this.sessionID = null;
2891
+ this.resumeURL = null;
2892
+ reconnect = false;
2893
+ // The token itself stays out of the message, which often ends up in logs
2894
+ this.emit("error", new Error("Invalid token: Discord refused it when identifying (4004)"), this.id);
2895
+ } else if (code === 4005) {
2896
+ err = new Error("Already authenticated");
2897
+ } else if (code === 4006 || code === 4009) {
2898
+ err = new Error("Invalid session");
2899
+ this.sessionID = null;
2900
+ this.resumeURL = null;
2901
+ } else if (code === 4007) {
2902
+ err = new Error("Invalid sequence number: " + this.seq);
2903
+ this.seq = 0;
2904
+ } else if (code === 4008) {
2905
+ err = new Error("Gateway connection was ratelimited");
2906
+ } else if (code === 4010) {
2907
+ err = new Error("Invalid shard key");
2908
+ this.sessionID = null;
2909
+ this.resumeURL = null;
2910
+ reconnect = false;
2911
+ } else if (code === 4011) {
2912
+ err = new Error("Shard has too many guilds (>2500)");
2913
+ this.sessionID = null;
2914
+ this.resumeURL = null;
2915
+ reconnect = false;
2916
+ } else if (code === 4012) {
2917
+ err = new Error("Invalid API version");
2918
+ this.sessionID = null;
2919
+ this.resumeURL = null;
2920
+ reconnect = false;
2921
+ } else if (code === 4013) {
2922
+ err = new Error("Invalid intents specified");
2923
+ this.sessionID = null;
2924
+ this.resumeURL = null;
2925
+ reconnect = false;
2926
+ } else if (code === 4014) {
2927
+ err = new Error("Disallowed intents specified");
2928
+ this.sessionID = null;
2929
+ this.resumeURL = null;
2930
+ reconnect = false;
2931
+ } else if (code === 1006) {
2932
+ err = new Error("Connection reset by peer");
2933
+ } else if (code !== 1000 && reason) {
2934
+ err = new Error(code + ": " + reason);
2935
+ }
2936
+ if (err) {
2937
+ err.code = code;
2938
+ }
2939
+ } else {
2940
+ this.emit("debug", "WS close: unknown code: " + reason, this.id);
2941
+ }
2942
+ this.disconnect({
2943
+ reconnect,
2944
+ }, err);
2945
+ }
2946
+
2947
+ _onWSError(err) {
2948
+ this.emit("error", err, this.id);
2949
+ }
2950
+
2951
+ _onWSMessage(data) {
2952
+ try {
2953
+ if (data instanceof ArrayBuffer) {
2954
+ if (this.client.options.compress || Erlpack) {
2955
+ data = Buffer.from(data);
2956
+ }
2957
+ } else if (Array.isArray(data)) { // Fragmented messages
2958
+ data = Buffer.concat(data); // Copyfull concat is slow, but no alternative
2959
+ }
2960
+ if (this.client.options.compress) {
2961
+ if (data.length >= 4 && data.readUInt32BE(data.length - 4) === 0xFFFF) {
2962
+ this._zlibSync.push(data, ZlibSync.Z_SYNC_FLUSH);
2963
+ if (this._zlibSync.err) {
2964
+ this.emit("error", new Error(`zlib error ${this._zlibSync.err}: ${this._zlibSync.msg}`));
2965
+ return;
2966
+ }
2967
+
2968
+ data = Buffer.from(this._zlibSync.result);
2969
+ if (Erlpack) {
2970
+ return this.onPacket(Erlpack.unpack(data));
2971
+ } else {
2972
+ return this.onPacket(JSON.parse(data.toString()));
2973
+ }
2974
+ } else {
2975
+ this._zlibSync.push(data, false);
2976
+ }
2977
+ } else if (Erlpack) {
2978
+ return this.onPacket(Erlpack.unpack(data));
2979
+ } else {
2980
+ return this.onPacket(JSON.parse(data.toString()));
2981
+ }
2982
+ } catch (err) {
2983
+ this.emit("error", err, this.id);
2984
+ }
2985
+ }
2986
+
2987
+ _onWSOpen() {
2988
+ this.status = "handshaking";
2989
+ /**
2990
+ * Fired when the shard establishes a connection
2991
+ * @event Client#connect
2992
+ * @prop {Number} id The ID of the shard
2993
+ */
2994
+ this.emit("connect", this.id);
2995
+ this.lastHeartbeatAck = true;
2996
+ }
2997
+
2998
+ [util.inspect.custom]() {
2999
+ return Base.prototype[util.inspect.custom].call(this);
3000
+ }
3001
+
3002
+ toString() {
3003
+ return Base.prototype.toString.call(this);
3004
+ }
3005
+
3006
+ toJSON(props = []) {
3007
+ return Base.prototype.toJSON.call(this, [
3008
+ "connectAttempts",
3009
+ "connecting",
3010
+ "discordServerTrace",
3011
+ "getAllUsersCount",
3012
+ "getAllUsersLength",
3013
+ "getAllUsersQueue",
3014
+ "lastHeartbeatAck",
3015
+ "lastHeartbeatReceived",
3016
+ "lastHeartbeatSent",
3017
+ "latency",
3018
+ "preReady",
3019
+ "ready",
3020
+ "reconnectInterval",
3021
+ "seq",
3022
+ "sessionID",
3023
+ "status",
3024
+ ...props,
3025
+ ]);
3026
+ }
3027
+ }
3028
+
3029
+ module.exports = Shard;