forked from abalabahaha/eris
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Shard.js
1849 lines (1785 loc) · 82.6 KB
/
Shard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
const Bucket = require("../util/Bucket");
const Call = require("../structures/Call");
const Channel = require("../structures/Channel");
const GroupChannel = require("../structures/GroupChannel");
const GuildChannel = require("../structures/GuildChannel");
const PrivateChannel = require("../structures/PrivateChannel");
const Constants = require("../Constants");
const ExtendedUser = require("../structures/ExtendedUser");
const OPCodes = Constants.GatewayOPCodes;
const User = require("../structures/User");
let WebSocket = typeof window !== "undefined" ? window.WebSocket : require("ws");
let EventEmitter;
try {
EventEmitter = require("eventemitter3");
} catch(err) {
EventEmitter = require("events").EventEmitter;
}
let Erlpack;
try {
Erlpack = require("erlpack");
} catch(err) { // eslint-disable no-empty
}
let ZlibSync;
try {
ZlibSync = require("zlib-sync");
} catch(err) {
try {
ZlibSync = require("pako");
} catch(err) { // eslint-disable no-empty
}
}
try {
WebSocket = require("uws");
} catch(err) { // eslint-disable no-empty
}
/**
* Represents a shard
* @extends EventEmitter
* @prop {Number} id The ID of the shard
* @prop {Boolean} connecting Whether the shard is connecting
* @prop {Boolean} ready Whether the shard is ready
* @prop {Array<String>?} discordServerTrace Debug trace of Discord servers
* @prop {String} status The status of the shard. "disconnected"/"connecting"/"handshaking"/"ready"
* @prop {Number} lastHeartbeatReceived Last time Discord acknowledged a heartbeat, null if shard has not sent heartbeat yet
* @prop {Number} lastHeartbeatSent Last time shard sent a heartbeat, null if shard has not sent heartbeat yet
* @prop {Number} latency The current latency between the shard and Discord, in milliseconds
*/
class Shard extends EventEmitter {
constructor(id, client) {
super();
this.id = id;
this.client = client;
this.onWSMessage = this.onWSMessage.bind(this);
this.hardReset();
}
get latency() {
return this.lastHeartbeatSent && this.lastHeartbeatReceived ? this.lastHeartbeatReceived - this.lastHeartbeatSent : Infinity;
}
/**
* Tells the shard to connect
*/
connect() {
if(this.ws && this.ws.readyState != WebSocket.CLOSED) {
this.emit("error", new Error("Existing connection detected"), this.id);
return;
}
++this.connectAttempts;
this.connecting = true;
return this.initializeWS();
}
/**
* Disconnects the shard
* @arg {Object?} [options] Shard disconnect options
* @arg {String | Boolean} [options.reconnect] false means destroy everything, true means you want to reconnect in the future, "auto" will autoreconnect
*/
disconnect(options = {}, error) {
if(!this.ws) {
return;
}
if(this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
this.ws.onclose = undefined;
try {
if(options.reconnect && this.sessionID) {
this.ws.terminate();
} else {
this.ws.close(1000);
}
} catch(err) {
/**
* Fired when the shard encounters an error
* @event Client#error
* @prop {Error} err The error
* @prop {Number} id The ID of the shard
*/
this.emit("error", err, this.id);
}
/**
* Fired when the shard disconnects
* @event Shard#disconnect
* @prop {Error?} err The error, if any
*/
super.emit("disconnect", error || null);
this.ws = null;
this.reset();
if(options.reconnect === "auto" && this.client.options.autoreconnect) {
/**
* Fired when stuff happens and gives more info
* @event Client#debug
* @prop {String} message The debug message
* @prop {Number} id The ID of the shard
*/
if(this.sessionID) {
this.emit("debug", `Immediately reconnecting for potential resume | Attempt ${this.connectAttempts}`, this.id);
this.client.shards.connect(this);
} else {
this.emit("debug", `Queueing reconnect in ${this.reconnectInterval}ms | Attempt ${this.connectAttempts}`, this.id);
setTimeout(() => {
this.client.shards.connect(this);
}, this.reconnectInterval);
this.reconnectInterval = Math.min(Math.round(this.reconnectInterval * (Math.random() * 2 + 1)), 30000);
}
} else if(!options.reconnect) {
this.hardReset();
}
}
reset() {
this.connecting = false;
this.ready = false;
this.preReady = false;
this.getAllUsersCount = {};
this.getAllUsersQueue = [];
this.getAllUsersLength = 1;
this.guildSyncQueue = [];
this.guildSyncQueueLength = 1;
this.unsyncedGuilds = 0;
this.lastHeartbeatAck = true;
this.lastHeartbeatReceived = null;
this.lastHeartbeatSent = null;
this.status = "disconnected";
}
hardReset() {
this.reset();
this.seq = 0;
this.sessionID = null;
this.reconnectInterval = 1000;
this.connectAttempts = 0;
this.ws = null;
this.heartbeatInterval = null;
this.guildCreateTimeout = null;
this.globalBucket = new Bucket(120, 60000);
this.presenceUpdateBucket = new Bucket(5, 60000);
this.presence = JSON.parse(JSON.stringify(this.client.presence)); // Fast copy
}
resume() {
this.status = "resuming";
this.sendWS(OPCodes.RESUME, {
token: this.client.token,
session_id: this.sessionID,
seq: this.seq
}, true);
}
identify() {
if(this.client.options.compress && !ZlibSync) {
this.emit("error", new Error("pako/zlib-sync not found, cannot decompress data"));
return;
}
const identify = {
token: this.client.token,
v: Constants.GATEWAY_VERSION,
compress: !!this.client.options.compress,
large_threshold: this.client.options.largeThreshold,
guild_subscriptions: !!this.client.options.guildSubscriptions,
properties: {
"os": process.platform,
"browser": "Eris",
"device": "Eris"
}
};
if(this.client.options.maxShards > 1) {
identify.shard = [this.id, this.client.options.maxShards];
}
if(this.presence.status) {
identify.presence = this.presence;
}
this.sendWS(OPCodes.IDENTIFY, identify, true);
}
wsEvent(packet) {
switch(packet.t) { /* eslint-disable no-redeclare */ // (╯°□°)╯︵ ┻━┻
case "PRESENCE_UPDATE": {
if(packet.d.user.username !== undefined) {
let user = this.client.users.get(packet.d.user.id);
let oldUser = null;
if(user && (user.username !== packet.d.user.username || user.avatar !== packet.d.user.avatar || user.discriminator !== packet.d.user.discriminator)) {
oldUser = {
username: user.username,
discriminator: user.discriminator,
avatar: user.avatar
};
}
if(!user || oldUser) {
user = this.client.users.update(packet.d.user, this.client);
/**
* Fired when a user's username, avatar, or discriminator changes
* @event Client#userUpdate
* @prop {User} user The updated user
* @prop {Object?} oldUser The old user data
* @prop {String} oldUser.username The username of the user
* @prop {String} oldUser.discriminator The discriminator of the user
* @prop {String?} oldUser.avatar The hash of the user's avatar, or null if no avatar
*/
this.emit("userUpdate", user, oldUser);
}
}
if(!packet.d.guild_id) {
packet.d.id = packet.d.user.id;
const relationship = this.client.relationships.get(packet.d.id);
if(!relationship) { // Removing relationships
break;
}
const oldPresence = {
game: relationship.game,
status: relationship.status
};
/**
* Fired when a guild member or relationship's status or game changes
* @event Client#presenceUpdate
* @prop {Member | Relationship} other The updated member or relationship
* @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
* @prop {String} oldPresence.status The other user's old status. Either "online", "idle", or "offline"
* @prop {Object?} oldPresence.game The old game the other user was playing
* @prop {String} oldPresence.game.name The name of the active game
* @prop {Number} oldPresence.game.type The type of the active game (0 is default, 1 is Twitch, 2 is YouTube)
* @prop {String} oldPresence.game.url The url of the active game
*/
this.emit("presenceUpdate", this.client.relationships.update(packet.d), oldPresence);
break;
}
const guild = this.client.guilds.get(packet.d.guild_id);
if(!guild) {
this.emit("debug", "Rogue presence update: " + JSON.stringify(packet), this.id);
break;
}
let member = guild.members.get(packet.d.id = packet.d.user.id);
if(member && JSON.stringify(member.game) === JSON.stringify(packet.d.game) && member.status === packet.d.status) {
this.emit("debug", "Duplicate presence update: " + JSON.stringify(packet));
break;
}
let oldPresence = null;
if(member) {
oldPresence = {
game: member.game,
status: member.status,
clientStatus: member.clientStatus,
activities: member.activities
};
}
if((!member && packet.d.user.username) || oldPresence) {
member = guild.members.update(packet.d, guild);
this.emit("presenceUpdate", member, oldPresence);
}
break;
}
case "VOICE_STATE_UPDATE": { // (╯°□°)╯︵ ┻━┻
if(packet.d.guild_id === undefined) {
packet.d.id = packet.d.user_id;
if(packet.d.channel_id === null) {
let flag = false;
for(const groupChannel of this.client.groupChannels) {
const call = (groupChannel[1].call || groupChannel[1].lastCall);
if(call && call.voiceStates.remove(packet.d)) {
flag = true;
break;
}
}
if(!flag) {
for(const privateChannel of this.client.privateChannels) {
const call = (privateChannel[1].call || privateChannel[1].lastCall);
if(call && call.voiceStates.remove(packet.d)) {
flag = true;
break;
}
}
if(!flag) {
this.emit("debug", new Error("VOICE_STATE_UPDATE for user leaving call not found"));
break;
}
}
} else {
const channel = this.client.getChannel(packet.d.channel_id);
if(!channel.call && !channel.lastCall) {
this.emit("debug", new Error("VOICE_STATE_UPDATE for untracked call"));
break;
}
(channel.call || channel.lastCall).voiceStates.update(packet.d);
}
break;
}
const guild = this.client.guilds.get(packet.d.guild_id);
if(!guild) {
break;
}
if(guild.pendingVoiceStates) {
guild.pendingVoiceStates.push(packet.d);
break;
}
const member = guild.members.get(packet.d.id = packet.d.user_id);
if(!member) {
const channel = guild.channels.find((channel) => channel.type === 2 && channel.voiceMembers.get(packet.d.id));
if(channel) {
channel.voiceMembers.remove(packet.d);
this.emit("debug", "VOICE_STATE_UPDATE member null but in channel: " + packet.d.id, this.id);
break;
}
break;
}
const oldState = {
mute: member.voiceState.mute,
deaf: member.voiceState.deaf,
selfMute: member.voiceState.selfMute,
selfDeaf: member.voiceState.selfDeaf
};
const oldChannelID = member.voiceState.channelID;
member.update(packet.d, this.client);
if(member.user.id === this.client.user.id) {
const voiceConnection = this.client.voiceConnections.get(packet.d.guild_id);
if(voiceConnection && voiceConnection.channelID !== packet.d.channel_id) {
voiceConnection.switchChannel(packet.d.channel_id, true);
}
}
if(oldChannelID != packet.d.channel_id) {
let oldChannel, newChannel;
if(oldChannelID) {
oldChannel = guild.channels.get(oldChannelID);
}
if(packet.d.channel_id && (newChannel = guild.channels.get(packet.d.channel_id)) && newChannel.type === 2) { // Welcome to Discord, where one can "join" text channels
if(oldChannel) {
/**
* Fired when a guild member switches voice channels
* @event Client#voiceChannelSwitch
* @prop {Member} member The member
* @prop {CategoryChannel | TextChannel | VoiceChannel} newChannel The new voice channel
* @prop {CategoryChannel | TextChannel | VoiceChannel} oldChannel The old voice channel
*/
oldChannel.voiceMembers.remove(member);
this.emit("voiceChannelSwitch", newChannel.voiceMembers.add(member, guild), newChannel, oldChannel);
} else {
/**
* Fired when a guild member joins a voice channel. This event is not fired when a member switches voice channels, see `voiceChannelSwitch`
* @event Client#voiceChannelJoin
* @prop {Member} member The member
* @prop {CategoryChannel | TextChannel | VoiceChannel} newChannel The voice channel
*/
this.emit("voiceChannelJoin", newChannel.voiceMembers.add(member, guild), newChannel);
}
} else if(oldChannel) {
/**
* Fired when a guild member leaves a voice channel. This event is not fired when a member switches voice channels, see `voiceChannelSwitch`
* @event Client#voiceChannelLeave
* @prop {Member} member The member
* @prop {CategoryChannel | TextChannel | VoiceChannel} oldChannel The voice channel
*/
this.emit("voiceChannelLeave", oldChannel.voiceMembers.remove(member), oldChannel);
}
}
if(oldState.mute !== member.mute || oldState.deaf !== member.deaf || oldState.selfMute !== member.selfMute || oldState.selfDeaf !== member.selfDeaf) {
/**
* Fired when a guild member's voice state changes
* @event Client#voiceStateUpdate
* @prop {Member} member The member
* @prop {Object} oldState The old voice state
* @prop {Boolean} oldState.mute The previous server mute status
* @prop {Boolean} oldState.deaf The previous server deaf status
* @prop {Boolean} oldState.selfMute The previous self mute status
* @prop {Boolean} oldState.selfDeaf The previous self deaf status
*/
this.emit("voiceStateUpdate", member, oldState);
}
break;
}
case "TYPING_START": {
if(this.client.listeners("typingStart").length > 0) {
/**
* Fired when a user begins typing
* @event Client#typingStart
* @prop {PrivateChannel | TextChannel} channel The text channel the user is typing in
* @prop {User} user The user
*/
this.emit("typingStart", this.client.getChannel(packet.d.channel_id), this.client.users.get(packet.d.user_id));
}
break;
}
case "MESSAGE_CREATE": {
const channel = this.client.getChannel(packet.d.channel_id);
if(channel) { // MESSAGE_CREATE just when deleting o.o
channel.lastMessageID = packet.d.id;
/**
* Fired when a message is created
* @event Client#messageCreate
* @prop {Message} message The message
*/
this.emit("messageCreate", channel.messages.add(packet.d, this.client));
} else {
this.emit("debug", "MESSAGE_CREATE but channel not found (OK if deleted channel)", this.id);
}
break;
}
case "MESSAGE_UPDATE": {
const channel = this.client.getChannel(packet.d.channel_id);
if(!channel) {
break;
}
const message = channel.messages.get(packet.d.id);
let oldMessage = null;
if(message) {
oldMessage = {
attachments: message.attachments,
content: message.content,
embeds: message.embeds,
editedTimestamp: message.editedTimestamp,
mentionedBy: message.mentionedBy,
mentions: message.mentions,
roleMentions: message.roleMentions,
channelMentions: message.channelMentions,
tts: message.tts,
pinned: message.pinned
};
} else if(!packet.d.timestamp) {
packet.d.channel = channel;
this.emit("messageUpdate", packet.d, null);
break;
}
/**
* Fired when a message is updated
* @event Client#messageUpdate
* @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)
* @prop {Object?} oldMessage The old message data. If the message was cached, this will return the full old message. Otherwise, it will be null
* @prop {Object[]} oldMessage.attachments Array of attachments
* @prop {Object[]} oldMessage.embeds Array of embeds
* @prop {String} oldMessage.content Message content
* @prop {Number} oldMessage.editedTimestamp Timestamp of latest message edit
* @prop {Object} oldMessage.mentionedBy Object of if different things mention the bot user
* @prop {Boolean} oldMessage.pinned Whether the message was pinned or not
* @prop {Boolean} oldMessage.tts Whether to play the message using TTS or not
* @prop {String[]} oldMessage.mentions Array of mentioned users' ids
* @prop {String[]} oldMessage.roleMentions Array of mentioned roles' ids.
* @prop {String[]} oldMessage.channelMentions Array of mentions channels' ids.
*/
this.emit("messageUpdate", channel.messages.update(packet.d, this.client), oldMessage);
break;
}
case "MESSAGE_DELETE": {
const channel = this.client.getChannel(packet.d.channel_id);
if(!channel) {
break;
}
/**
* Fired when a cached message is deleted
* @event Client#messageDelete
* @prop {Message | Object} message The message object. If the message is not cached, this will be an object with `id` and `channel` keys. No other property is guaranteed
*/
this.emit("messageDelete", channel.messages.remove(packet.d) || {
id: packet.d.id,
channel: channel
});
break;
}
case "MESSAGE_DELETE_BULK": {
const channel = this.client.getChannel(packet.d.channel_id);
if(!channel) {
break;
}
/**
* Fired when a bulk delete occurs
* @event Client#messageDeleteBulk
* @prop {Message[] | 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. No other property is guaranteed
*/
this.emit("messageDeleteBulk", packet.d.ids.map((id) => (channel.messages.remove({
id
}) || {
id,
channel
})));
break;
}
case "MESSAGE_REACTION_ADD": {
const channel = this.client.getChannel(packet.d.channel_id);
if(!channel) {
break;
}
const message = channel.messages.get(packet.d.message_id);
if(message) {
const reaction = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
if(message.reactions[reaction]) {
++message.reactions[reaction].count;
if(packet.d.user_id === this.client.user.id) {
message.reactions[reaction].me = true;
}
} else {
message.reactions[reaction] = {
count: 1,
me: packet.d.user_id === this.client.user.id
};
}
}
/**
* Fired when someone adds a reaction to a message
* @event Client#messageReactionAdd
* @prop {Message | Object} message The message object. If the message is not cached, this will be an object with `id` and `channel` keys. No other property is guaranteed
* @prop {Object} emoji The reaction emoji object
* @prop {String?} emoji.id The emoji ID (null for non-custom emojis)
* @prop {String} emoji.name The emoji name
* @prop {String} userID The ID of the user that added the reaction
*/
this.emit("messageReactionAdd", message || {
id: packet.d.message_id,
channel: channel
}, packet.d.emoji, packet.d.user_id);
break;
}
case "MESSAGE_REACTION_REMOVE": {
const channel = this.client.getChannel(packet.d.channel_id);
if(!channel) {
break;
}
const message = channel.messages.get(packet.d.message_id);
if(message) {
const reaction = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
if(message.reactions[reaction]) {
--message.reactions[reaction].count;
if(packet.d.user_id === this.client.user.id) {
message.reactions[reaction].me = false;
}
}
}
/**
* Fired when someone removes a reaction from a message
* @event Client#messageReactionRemove
* @prop {Message | Object} message The message object. If the message is not cached, this will be an object with `id` and `channel` keys. No other property is guaranteed
* @prop {Object} emoji The reaction emoji object
* @prop {String?} emoji.id The ID of the emoji (null for non-custom emojis)
* @prop {String} emoji.name The emoji name
* @prop {String} userID The ID of the user that removed the reaction
*/
this.emit("messageReactionRemove", message || {
id: packet.d.message_id,
channel: channel
}, packet.d.emoji, packet.d.user_id);
break;
}
case "MESSAGE_REACTION_REMOVE_ALL": {
const channel = this.client.getChannel(packet.d.channel_id);
if(!channel) {
break;
}
/**
* Fired when someone removes a reaction from a message
* @event Client#messageReactionRemoveAll
* @prop {Message | Object} message The message object. If the message is not cached, this will be an object with `id` and `channel` keys. No other property is guaranteed
*/
this.emit("messageReactionRemoveAll", channel.messages.get(packet.d.message_id) || {
id: packet.d.message_id,
channel: channel
});
break;
}
case "GUILD_MEMBER_ADD": {
const guild = this.client.guilds.get(packet.d.guild_id);
if(!guild) { // Eventual Consistency™ (╯°□°)╯︵ ┻━┻
this.emit("debug", `Missing guild ${packet.d.guild_id} in GUILD_MEMBER_ADD`);
break;
}
packet.d.id = packet.d.user.id;
++guild.memberCount;
/**
* Fired when a member joins a server
* @event Client#guildMemberAdd
* @prop {Guild} guild The guild
* @prop {Member} member The member
*/
this.emit("guildMemberAdd", guild, guild.members.add(packet.d, guild));
break;
}
case "GUILD_MEMBER_UPDATE": {
const guild = this.client.guilds.get(packet.d.guild_id);
if(!guild) {
this.emit("debug", `Missing guild ${packet.d.guild_id} in GUILD_MEMBER_UPDATE`);
break;
}
let member = guild.members.get(packet.d.id = packet.d.user.id);
let oldMember = null;
if(member) {
oldMember = {
roles: member.roles,
nick: member.nick
};
}
member = guild.members.update(packet.d, guild);
/**
* Fired when a member's roles or nickname are updated
* @event Client#guildMemberUpdate
* @prop {Guild} guild The guild
* @prop {Member} member The updated member
* @prop {Object?} oldMember The old member data
* @prop {String[]} oldMember.roles An array of role IDs this member is a part of
* @prop {String?} oldMember.nick The server nickname of the member
*/
this.emit("guildMemberUpdate", guild, member, oldMember);
break;
}
case "GUILD_MEMBER_REMOVE": {
if(packet.d.user.id === this.client.user.id) { // The bot is probably leaving
break;
}
const guild = this.client.guilds.get(packet.d.guild_id);
if(!guild) {
break;
}
--guild.memberCount;
packet.d.id = packet.d.user.id;
/**
* Fired when a member leaves a server
* @event Client#guildMemberRemove
* @prop {Guild} guild The guild
* @prop {Member | Object} member The member. If the member is not cached, this will be an object with `id` and `user` key
*/
this.emit("guildMemberRemove", guild, guild.members.remove(packet.d) || {
id: packet.d.id,
user: new User(packet.d.user, this.client)
});
break;
}
case "GUILD_CREATE": {
if(!packet.d.unavailable) {
const guild = this.createGuild(packet.d);
if(this.ready) {
if(this.client.unavailableGuilds.remove(packet.d)) {
/**
* Fired when a guild becomes available
* @event Client#guildAvailable
* @prop {Guild} guild The guild
*/
this.emit("guildAvailable", guild);
} else {
/**
* Fired when a guild is created. This happens when:
* - the client creates a guild
* - the client joins a guild
*/
this.emit("guildCreate", guild);
}
} else {
this.client.unavailableGuilds.remove(packet.d);
this.restartGuildCreateTimeout();
}
} else {
this.client.guilds.remove(packet.d);
/**
* Fired when an unavailable guild is created
* @event Client#unavailableGuildCreate
* @prop {UnavailableGuild} guild The unavailable guild
*/
this.emit("unavailableGuildCreate", this.client.unavailableGuilds.add(packet.d, this.client));
}
break;
}
case "GUILD_UPDATE": {
const guild = this.client.guilds.get(packet.d.id);
if(!guild) {
this.emit("debug", `Guild ${packet.d.id} undefined in GUILD_UPDATE`);
break;
}
let oldGuild = null;
oldGuild = {
name: guild.name,
verificationLevel: guild.verificationLevel,
splash: guild.splash,
banner: guild.banner,
region: guild.region,
ownerID: guild.ownerID,
icon: guild.icon,
features: guild.features,
emojis: guild.emojis,
afkChannelID: guild.afkChannelID,
afkTimeout: guild.afkTimeout,
mfaLevel: guild.mfaLevel,
large: guild.large,
maxPresences: guild.maxPresences,
explicitContentFilter: guild.explicitContentFilter,
systemChannelID: guild.systemChannelID
};
/**
* Fired when a guild is updated
* @event Client#guildUpdate
* @prop {Guild} guild The guild
* @prop {Object} oldGuild The old guild data
* @prop {String} oldGuild.name The name of the guild
* @prop {Number} oldGuild.verificationLevel The guild verification level
* @prop {String} oldGuild.region The region of the guild
* @prop {String?} oldGuild.icon The hash of the guild icon, or null if no icon
* @prop {String} oldGuild.afkChannelID The ID of the AFK voice channel
* @prop {Number} oldGuild.afkTimeout The AFK timeout in seconds
* @prop {String} oldGuild.ownerID The ID of the user that is the guild owner
* @prop {String?} oldGuild.splash The hash of the guild splash image, or null if no splash (VIP only)
* @prop {String?} oldGuild.banner The hash of the guild banner image, or null if no splash (VIP only)
* @prop {Object[]} oldGuild.features An array of guild features
* @prop {Object[]} oldGuild.emojis An array of guild emojis
*/
this.emit("guildUpdate", this.client.guilds.update(packet.d, this.client), oldGuild);
break;
}
case "GUILD_DELETE": {
const voiceConnection = this.client.voiceConnections.get(packet.d.id);
if(voiceConnection) {
if(voiceConnection.channelID) {
this.client.leaveVoiceChannel(voiceConnection.channelID);
} else {
this.client.voiceConnections.leave(packet.d.id);
}
}
delete this.client.guildShardMap[packet.d.id];
const guild = this.client.guilds.remove(packet.d);
if(guild) { // Discord sends GUILD_DELETE for guilds that were previously unavailable in READY
guild.channels.forEach((channel) => {
delete this.client.channelGuildMap[channel.id];
});
}
if(packet.d.unavailable) {
/**
* Fired when a guild becomes unavailable
* @event Client#guildUnavailable
* @prop {Guild} guild The guild
*/
this.emit("guildUnavailable", this.client.unavailableGuilds.add(packet.d, this.client));
} else {
/**
* Fired when a guild is deleted. This happens when:
* - the client left the guild
* - the client was kicked/banned from the guild
* - the guild was literally deleted
* @event Client#guildDelete
* @prop {Guild} guild The guild
*/
this.emit("guildDelete", guild || {
id: packet.d.id
});
}
break;
}
case "GUILD_BAN_ADD": {
/**
* Fired when a user is banned from a guild
* @event Client#guildBanAdd
* @prop {Guild} guild The guild
* @prop {User} user The banned user
*/
this.emit("guildBanAdd", this.client.guilds.get(packet.d.guild_id), this.client.users.update(packet.d.user, this.client));
break;
}
case "GUILD_BAN_REMOVE": {
/**
* Fired when a user is unbanned from a guild
* @event Client#guildBanRemove
* @prop {Guild} guild The guild
* @prop {User} user The banned user
*/
this.emit("guildBanRemove", this.client.guilds.get(packet.d.guild_id), this.client.users.update(packet.d.user, this.client));
break;
}
case "GUILD_ROLE_CREATE": {
/**
* Fired when a guild role is created
* @event Client#guildRoleCreate
* @prop {Guild} guild The guild
* @prop {Role} role The role
*/
const guild = this.client.guilds.get(packet.d.guild_id);
if(!guild) {
this.emit("debug", `Missing guild ${packet.d.guild_id} in GUILD_ROLE_CREATE`);
break;
}
this.emit("guildRoleCreate", guild, guild.roles.add(packet.d.role, guild));
break;
}
case "GUILD_ROLE_UPDATE": {
const guild = this.client.guilds.get(packet.d.guild_id);
if(!guild) {
this.emit("debug", `Guild ${packet.d.guild_id} undefined in GUILD_ROLE_UPDATE`);
break;
}
const role = guild.roles.add(packet.d.role, guild);
if(!role) {
this.emit("debug", `Role ${packet.d.role} in guild ${packet.d.guild_id} undefined in GUILD_ROLE_UPDATE`);
break;
}
let oldRole = null;
if(role) {
oldRole = {
color: role.color,
hoist: role.hoist,
managed: role.managed,
name: role.name,
permissions: role.permissions,
position: role.position,
mentionable: role.mentionable
};
}
/**
* Fired when a guild role is updated
* @event Client#guildRoleUpdate
* @prop {Guild} guild The guild
* @prop {Role} role The updated role
* @prop {Object} oldRole The old role data
* @prop {String} oldRole.name The name of the role
* @prop {Boolean} oldRole.mentionable Whether the role is mentionable or not
* @prop {Boolean} oldRole.managed Whether a guild integration manages this role or not
* @prop {Boolean} oldRole.hoist Whether users with this role are hoisted in the user list or not
* @prop {Number} oldRole.color The hex color of the role in base 10
* @prop {Number} oldRole.position The position of the role
* @prop {Permission} oldRole.permissions The permissions number of the role
*/
this.emit("guildRoleUpdate", guild, guild.roles.update(packet.d.role, guild), oldRole);
break;
}
case "GUILD_ROLE_DELETE": {
/**
* Fired when a guild role is deleted
* @event Client#guildRoleDelete
* @prop {Guild} guild The guild
* @prop {Role} role The role
*/
const guild = this.client.guilds.get(packet.d.guild_id);
if(!guild) {
this.emit("debug", `Missing guild ${packet.d.guild_id} in GUILD_ROLE_DELETE`);
break;
}
this.emit("guildRoleDelete", guild, guild.roles.remove({id: packet.d.role_id}));
break;
}
case "CHANNEL_CREATE": {
const channel = Channel.from(packet.d, this.client);
if(packet.d.guild_id) {
if(!channel.guild) {
channel.guild = this.client.guilds.get(packet.d.guild_id);
if(!channel.guild) {
this.emit("debug", `Received CHANNEL_CREATE for channel in missing guild ${packet.d.guild_id}`);
break;
}
}
channel.guild.channels.add(channel, this.client);
this.client.channelGuildMap[packet.d.id] = packet.d.guild_id;
this.emit("channelCreate", channel);
} else if(channel instanceof PrivateChannel) {
if(channel instanceof GroupChannel) {
this.client.groupChannels.add(channel, this.client);
} else {
this.client.privateChannels.add(channel, this.client);
this.client.privateChannelMap[packet.d.recipients[0].id] = packet.d.id;
}
if(this.id === 0) {
this.emit("channelCreate", channel);
}
} else {
this.emit("warn", new Error("Unhandled CHANNEL_CREATE type: " + JSON.stringify(packet, null, 2)));
break;
}
break;
}
case "CHANNEL_UPDATE": {
let channel = this.client.getChannel(packet.d.id);
if(!channel) {
break;
}
let oldChannel;
if(channel instanceof GroupChannel) {
oldChannel = {
name: channel.name,
ownerID: channel.ownerID,
icon: channel.icon
};
} else if(channel instanceof GuildChannel) {
oldChannel = {
name: channel.name,
topic: channel.topic,
type: channel.type,
position: channel.position,
bitrate: channel.bitrate,
nsfw: channel.nsfw,
permissionOverwrites: channel.permissionOverwrites,
parentID: channel.parentID,
rateLimitPerUser: channel.rateLimitPerUser
};
} else {
this.emit("warn", `Unexpected CHANNEL_UPDATE for channel ${packet.d.id} with type ${oldType}`);
}
const oldType = channel.type;
if(oldType === packet.d.type) {
channel.update(packet.d);
} else {
this.emit("debug", `Channel ${packet.d.id} changed from type ${oldType} to ${packet.d.type}`);
const newChannel = Channel.from(packet.d);
if(packet.d.guild_id) {
const guild = this.client.guilds.get(packet.d.guild_id);
if(!guild) {
this.emit("debug", `Received CHANNEL_UPDATE for channel in missing guild ${packet.d.guild_id}`);
break;
}
guild.channels.remove(channel);
guild.channels.add(newChannel, this.client);
} else if(channel instanceof PrivateChannel) {
if(channel instanceof GroupChannel) {
this.client.groupChannels.remove(channel);
this.client.groupChannels.add(newChannel, this.client);
} else {
this.client.privateChannels.remove(channel);
this.client.privateChannels.add(newChannel, this.client);
}
} else {
this.emit("warn", new Error("Unhandled CHANNEL_UPDATE type: " + JSON.stringify(packet, null, 2)));
break;
}
channel = newChannel;
}
/**
* Fired when a channel is updated
* @event Client#channelUpdate
* @prop {PrivateChannel | TextChannel | VoiceChannel | CategoryChannel} channel The updated channel
* @prop {Object} oldChannel The old channel data
* @prop {String} oldChannel.name The name of the channel
* @prop {Number} oldChannel.position The position of the channel
* @prop {Boolean} oldChannel.nsfw Whether the channel is NSFW or not
* @prop {String?} oldChannel.topic The topic of the channel (text channels only)
* @prop {Number} oldChannel.type The type of the old channel
* @prop {Number?} oldChannel.bitrate The bitrate of the channel (voice channels only)
* @prop {Collection} oldChannel.permissionOverwrites Collection of PermissionOverwrites in this channel
*/
this.emit("channelUpdate", channel, oldChannel);
break;
}
case "CHANNEL_DELETE": {
if(packet.d.type === 1 || packet.d.type === undefined) {
if(this.id === 0) {
const channel = this.client.privateChannels.remove(packet.d);
if(channel) {
delete this.client.privateChannelMap[channel.recipient.id];
/**
* Fired when a channel is deleted
* @event Client#channelDelete
* @prop {PrivateChannel | TextChannel | VoiceChannel | CategoryChannel} channel The channel
*/
this.emit("channelDelete", channel);
}
}
} else if(packet.d.guild_id) {
delete this.client.channelGuildMap[packet.d.id];
const guild = this.client.guilds.get(packet.d.guild_id);
if(!guild) {
this.emit("debug", `Missing guild ${packet.d.guild_id} in CHANNEL_DELETE`);
break;
}
const channel = guild.channels.remove(packet.d);
if(!channel) {
break;
}
if(channel.type === 2) {
channel.voiceMembers.forEach((member) => {
this.emit("voiceChannelLeave", channel.voiceMembers.remove(member), channel);
});
}
this.emit("channelDelete", channel);
} else if(packet.d.type === 3) {
if(this.id === 0) {
this.emit("channelDelete", this.client.groupChannels.remove(packet.d));
}
} else {
this.emit("warn", new Error("Unhandled CHANNEL_DELETE type: " + JSON.stringify(packet, null, 2)));
}