/
Client.js
1979 lines (1855 loc) · 85.6 KB
/
Client.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 CategoryChannel = require("./structures/CategoryChannel");
const GuildChannel = require("./structures/GuildChannel");
const Collection = require("./util/Collection");
const Constants = require("./Constants");
const Endpoints = require("./rest/Endpoints");
const ExtendedUser = require("./structures/ExtendedUser");
const GroupChannel = require("./structures/GroupChannel");
const Guild = require("./structures/Guild");
const GuildAuditLogEntry = require("./structures/GuildAuditLogEntry");
const GuildIntegration = require("./structures/GuildIntegration");
const Invite = require("./structures/Invite");
const Member = require("./structures/Member");
const Message = require("./structures/Message");
const PrivateChannel = require("./structures/PrivateChannel");
const Relationship = require("./structures/Relationship");
const RequestHandler = require("./rest/RequestHandler");
const Role = require("./structures/Role");
const ShardManager = require("./gateway/ShardManager");
const UnavailableGuild = require("./structures/UnavailableGuild");
const User = require("./structures/User");
const VoiceConnectionManager = require("./voice/VoiceConnectionManager");
var EventEmitter;
try {
EventEmitter = require("eventemitter3");
} catch(err) {
EventEmitter = require("events").EventEmitter;
}
var Erlpack;
try {
Erlpack = require("erlpack");
} catch(err) { // eslint-disable no-empty
}
/**
* Represents the main Eris client
* @extends EventEmitter
* @prop {String} token The bot user token
* @prop {Boolean?} bot Whether the bot user belongs to an OAuth2 application
* @prop {Object} options Eris options
* @prop {Object} channelGuildMap Object mapping channel IDs to guild IDs
* @prop {Collection<Shard>} shards Collection of shards Eris is using
* @prop {Collection<Guild>} guilds Collection of guilds the bot is in
* @prop {Object} privateChannelMap Object mapping user IDs to private channel IDs
* @prop {Collection<PrivateChannel>} privateChannels Collection of private channels the bot is in
* @prop {Collection<GroupChannel>} groupChannels Collection of group channels the bot is in (user accounts only)
* @prop {VoiceConnectionManager} voiceConnections Extended collection of active VoiceConnections the bot has
* @prop {Object} retryAfters Object mapping endpoints to ratelimit expiry timestamps
* @prop {Object} guildShardMap Object mapping guild IDs to shard IDs
* @prop {Number} startTime Timestamp of bot ready event
* @prop {Collection<UnavailableGuild>} unavailableGuilds Collection of unavailable guilds the bot is in
* @prop {Number} uptime How long in milliseconds the bot has been up for
* @prop {ExtendedUser} user The bot user
* @prop {Collection<User>} users Collection of users the bot sees
* @prop {Collection<Relationship>} relationships Collection of relationships the bot user has (user accounts only)
* @prop {Object} userGuildSettings Object mapping guild IDs to individual guild settings for the bot user (user accounts only)
* @prop {Object} userSettings Object containing the user account settings (user accounts only)
* @prop {Object} notes Object mapping user IDs to user notes (user accounts only)
*/
class Client extends EventEmitter {
/**
* Create a Client
* @arg {String} token bot token
* @arg {Object} [options] Eris options (all options are optional)
* @arg {Boolean} [options.autoreconnect=true] Have Eris autoreconnect when connection is lost
* @arg {Boolean} [options.compress=true] Whether to request WebSocket data to be compressed or not
* @arg {Number} [options.connectionTimeout=30000] How long in milliseconds to wait for the connection to handshake with the server
* @arg {Object} [options.disableEvents] If disableEvents[eventName] is true, the WS event will not be processed. This can cause significant performance increase on large bots. [A full list of the WS event names can be found on the docs reference page](/Eris/docs/reference#ws-event-names)
* @arg {Boolean} [options.disableEveryone=true] When true, filter out @everyone/@here by default in createMessage/editMessage
* @arg {Number} [options.firstShardID=0] The ID of the first shard to run for this client
* @arg {Boolean} [options.getAllUsers=false] Get all the users in every guild. Ready time will be severely delayed
* @arg {Number} [options.guildCreateTimeout=2000] How long in milliseconds to wait for a GUILD_CREATE before "ready" is fired. Increase this value if you notice missing guilds
* @arg {Number} [options.largeThreshold=250] The maximum number of offline users per guild during initial guild data transmission
* @arg {Number} [options.lastShardID=options.maxShards - 1] The ID of the last shard to run for this client
* @arg {Number|String} [options.maxShards=1] The total number of shards you want to run. If "auto" Eris will use Discord's recommended shard count.
* @arg {Number} [options.messageLimit=100] The maximum size of a channel message cache
* @arg {Boolean} [options.opusOnly=false] Whether to suppress the node-opus not found error or not
* @arg {Boolean} [options.restMode=false] Whether to enable getting objects over REST. This should only be enabled if you are not connecting to the gateway. Bot tokens must be prefixed manually in REST mode
* @arg {Boolean} [options.seedVoiceConnections=false] Whether to populate bot.voiceConnections with existing connections the bot account has during startup. Note that this will disconnect connections from other bot sessions
* @arg {Number} [options.sequencerWait=200] How long to wait between sending potentially ratelimited requests. This number should be at least 3/4 your ping (in milliseconds)
* @arg {String} [options.defaultImageFormat="jpg"] The default format to provide user avatars, guild icons, and group icons in. Can be "jpg", "png", "gif", or "webp"
* @arg {Number} [options.defaultImageSize=128] The default size to return user avatars, guild icons, and group icons as. Can be 128, 256, 512, 1024, or 2048.
* @arg {Object} [options.ws] An object of WebSocket options to pass to the shard WebSocket constructors
*/
constructor(token, options) {
super();
this.options = {
autoreconnect: true,
compress: true,
connectionTimeout: 30000,
defaultImageFormat: "jpg",
defaultImageSize: 128,
disableEvents: {},
disableEveryone: true,
firstShardID: 0,
getAllUsers: false,
guildCreateTimeout: 2000,
largeThreshold: 250,
maxShards: 1,
messageLimit: 100,
opusOnly: false,
restMode: false,
seedVoiceConnections: false,
sequencerWait: 200,
ws: {}
};
if(typeof options === "object") {
for(var property of Object.keys(options)) {
this.options[property] = options[property];
}
}
if(this.options.lastShardID === undefined && this.options.maxShards !== "auto") {
this.options.lastShardID = this.options.maxShards - 1;
}
if(typeof window !== "undefined") {
try {
require("pako");
} catch(err) {
this.options.compress = false; // zlib does not like Blobs, Pako is not here
}
}
if(!~Constants.ImageFormats.indexOf(this.options.defaultImageFormat.toLowerCase())) {
this.options.defaultImageFormat = "jpg";
}
if(!~Constants.ImageSizes.indexOf(this.options.defaultImageSize)) {
this.options.defaultImageSize = 128;
}
this.token = token;
this.requestHandler = new RequestHandler(this);
this.ready = false;
this.bot = this.options.restMode && this.token ? this.token.startsWith("Bot ") : true;
this.startTime = 0;
this.lastConnect = 0;
this.channelGuildMap = {};
this.shards = new ShardManager(this);
this.groupChannels = new Collection(GroupChannel);
this.guilds = new Collection(Guild);
this.privateChannelMap = {};
this.privateChannels = new Collection(PrivateChannel);
this.retryAfters = {};
this.guildShardMap = {};
this.sharedStreams = {};
this.unavailableGuilds = new Collection(UnavailableGuild);
this.relationships = new Collection(Relationship);
this.users = new Collection(User);
this.presence = {
game: null,
status: "offline"
};
this.userGuildSettings = [];
this.userSettings = {};
this.notes = {};
this.voiceConnections = new VoiceConnectionManager();
}
get uptime() {
return this.startTime ? Date.now() - this.startTime : 0;
}
/**
* Tells all shards to connect.
* @returns {Promise} Resolves when all shards are initialized
*/
connect() {
const gatewayPromise = this.options.maxShards === "auto" ? this.getBotGateway() : this.getGateway();
return gatewayPromise.then((data) => {
if(!data.url || (this.options.maxShards === "auto" && !data.shards)) {
return Promise.reject(new Error("Invalid response from gateway REST call"));
}
if(data.url.includes("?")) {
data.url = data.url.substring(0, data.url.indexOf("?"));
}
if(!data.url.endsWith("/")) {
data.url += "/";
}
this.gatewayURL = data.url + "?v=" + Constants.GATEWAY_VERSION + "&encoding=" + (Erlpack ? "etf" : "json");
if (this.options.maxShards === "auto") {
if (!data.shards) {
return Promise.reject(new Error("Failed to autoshard due to lack of data from Discord."));
}
this.options.maxShards = data.shards;
if(this.options.lastShardID === undefined) {
this.options.lastShardID = data.shards - 1;
}
}
for(var i = this.options.firstShardID; i <= this.options.lastShardID; ++i) {
this.shards.spawn(i);
}
}).catch((err) => {
if(!this.options.autoreconnect) {
return Promise.reject(err);
}
this.emit("error", err);
return new Promise((res, rej) => {
setTimeout(() => this.connect().then(res).catch(rej), 2000);
});
});
}
/**
* Get the Discord gateway URL
* @returns {Promise<String>} Resolves with the gateway URL
*/
getGateway() {
return this.requestHandler.request("GET", Endpoints.GATEWAY);
}
/**
* Get the Discord gateway URL along with bot metadata
* @returns {Promise<Object>} Resolves with the gateway data
*/
getBotGateway() {
if(!this.token.startsWith("Bot ")) {
this.token = "Bot " + this.token;
}
return this.requestHandler.request("GET", Endpoints.GATEWAY_BOT, true);
}
/**
* Disconnects all shards
* @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) {
this.ready = false;
this.shards.forEach((shard) => {
shard.disconnect(options);
});
this.shards.connectQueue = [];
}
/**
* Join a voice channel. If joining a group call, the voice connection ID will be stored in voiceConnections as "call". Otherwise, it will be the guild ID
* @arg {String} channelID The ID of the voice channel
* @arg {Object} [options] VoiceConnection constructor options
* @arg {Object} [options.shared] Whether the VoiceConnection will be part of a SharedStream or not
* @arg {Object} [options.opusOnly] Skip opus encoder initialization. You should not enable this unless you know what you are doing
* @returns {Promise<VoiceConnection>} Resolves with a VoiceConnection
*/
joinVoiceChannel(channelID, options) {
var channel = this.getChannel(channelID);
if(!channel) {
return Promise.reject(new Error("Channel not found"));
}
if(channel.guild && !(channel.permissionsOf(this.user.id).allow & Constants.Permissions.voiceConnect)) {
return Promise.reject(new Error("Insufficient permission to connect to voice channel"));
}
this.shards.get(this.guildShardMap[this.channelGuildMap[channelID]] || 0).sendWS(Constants.GatewayOPCodes.VOICE_STATE_UPDATE, {
guild_id: this.channelGuildMap[channelID] || null,
channel_id: channelID || null,
self_mute: false,
self_deaf: false
});
options = options || {};
if(options.opusOnly === undefined) {
options.opusOnly = this.options.opusOnly;
}
return this.voiceConnections.join(this.channelGuildMap[channelID] || "call", channelID, options);
}
/**
* Leaves a voice channel
* @arg {String} channelID The ID of the voice channel
*/
leaveVoiceChannel(channelID) {
if(!channelID) {
return;
}
var channel = this.getChannel(channelID);
if(!channel) {
return;
}
this.shards.get(this.guildShardMap[this.channelGuildMap[channelID]] || 0).sendWS(Constants.GatewayOPCodes.VOICE_STATE_UPDATE, {
guild_id: this.channelGuildMap[channelID] || null,
channel_id: null,
self_mute: false,
self_deaf: false
});
this.voiceConnections.leave(this.channelGuildMap[channelID] || "call");
}
/**
* Update the bot's AFK status. Setting this to true will enable push notifications for userbots.
* @arg {Boolean} afk Whether the bot user is AFK or not
*/
editAFK(afk) {
this.presence.afk = !!afk;
this.shards.forEach((shard) => {
shard.editAFK(afk);
});
}
/**
* Update the bot's status on all guilds
* @arg {String} [status] Sets the bot's status, either "online", "idle", "dnd", or "invisible"
* @arg {Object} [game] Sets the bot's active game, null to clear
* @arg {String} game.name Sets the name of the bot's active game
* @arg {Number} [game.type] The type of game. 0 is default, 1 is streaming (Twitch only)
* @arg {String} [game.url] Sets the url of the shard's active game
*/
editStatus(status, game) {
if(game === undefined && typeof status === "object") {
game = status;
status = undefined;
}
if(status) {
this.presence.status = status;
}
if(game !== undefined) {
this.presence.game = game;
}
this.shards.forEach((shard) => {
shard.editStatus(status, game);
});
}
/**
* Get a Channel object from a channelID
* @arg {String} [channelID] The ID of the channel
* @returns {GuildChannel | GroupChannel | PrivateChannel}
*/
getChannel(channelID) {
if(!channelID) {
throw new Error(`Invalid channel ID: ${channelID}`);
}
return this.channelGuildMap[channelID] ? this.guilds.get(this.channelGuildMap[channelID]).channels.get(channelID) : this.privateChannels.get(channelID) || this.groupChannels.get(channelID);
}
/**
* Create a channel in a guild
* @arg {String} guildID The ID of the guild to create the channel in
* @arg {String} name The name of the channel
* @arg {String} [type=0] The type of the channel, either 0 or 2
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<GuildChannel>}
*/
createChannel(guildID, name, type, reason) {
var guild = this.guilds.get(guildID);
return this.requestHandler.request("POST", Endpoints.GUILD_CHANNELS(guildID), true, {
name,
type,
reason
}).then((channel) => new GuildChannel(channel, guild));
}
/**
* Edit a channel's properties
* @arg {String} channelID The ID of the channel
* @arg {Object} options The properties to edit
* @arg {String} [options.name] The name of the channel
* @arg {String} [options.icon] The icon of the channel as a base64 data URI (group channels only). Note: base64 strings alone are not base64 data URI strings
* @arg {String} [options.ownerID] The ID of the channel owner (group channels only)
* @arg {String} [options.topic] The topic of the channel (guild text channels only)
* @arg {Boolean} [options.nsfw] The nsfw status of the channel (guild channels only)
* @arg {Number} [options.bitrate] The bitrate of the channel (guild voice channels only)
* @arg {Number} [options.userLimit] The channel user limit (guild voice channels only)
* @arg {Number?} [options.parentID] The ID of the parent channel category for this channel (guild text/voice channels only)
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<GroupChannel | GuildChannel>}
*/
editChannel(channelID, options, reason) {
return this.requestHandler.request("PATCH", Endpoints.CHANNEL(channelID), true, {
name: options.name,
icon: options.icon,
owner_id: options.ownerID,
topic: options.topic,
nsfw: options.nsfw,
bitrate: options.bitrate,
user_limit: options.userLimit,
parent_id: options.parentID,
reason: reason
}).then((data) => {
if(!data.type || data.type === 2 || data.type === 4) { // undefined/0/2
var guild = this.channelGuildMap[channelID];
if(guild) {
guild = this.guilds.get(guild);
}
return new (data.type === 4 ? CategoryChannel : GuildChannel)(data, guild);
} else {
return new GroupChannel(data, this);
}
});
}
/**
* Edit a guild channel's position. Note that channel position numbers are lowest on top and highest at the bottom.
* @arg {String} channelID The ID of the channel
* @arg {Number} position The new position of the channel
* @returns {Promise}
*/
editChannelPosition(channelID, position) {
var channels = this.guilds.get(this.channelGuildMap[channelID]).channels;
var channel = channels.get(channelID);
if(!channel) {
return Promise.reject(new Error(`Channel ${channelID} not found`));
}
if(channel.position === position) {
return Promise.resolve();
}
var min = Math.min(position, channel.position);
var max = Math.max(position, channel.position);
channels = channels.filter((chan) => chan.type === channel.type && chan.parentID === channel.parentID && min <= chan.position && chan.position <= max && chan.id !== channelID).sort((a, b) => a.position - b.position);
if(position > channel.position) {
channels.push(channel);
} else {
channels.unshift(channel);
}
return this.requestHandler.request("PATCH", Endpoints.GUILD_CHANNELS(this.channelGuildMap[channelID]), true, channels.map((channel, index) => ({
id: channel.id,
position: index + min
})));
}
/**
* Delete a guild channel, or leave a private or group channel
* @arg {String} channelID The ID of the channel
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
deleteChannel(channelID, reason) {
return this.requestHandler.request("DELETE", Endpoints.CHANNEL(channelID), true, {
reason
});
}
/**
* Send typing status in a channel
* @arg {String} channelID The ID of the channel
* @returns {Promise}
*/
sendChannelTyping(channelID) {
return this.requestHandler.request("POST", Endpoints.CHANNEL_TYPING(channelID), true);
}
/**
* Create a channel permission overwrite
* @arg {String} channelID The ID of channel
* @arg {String} overwriteID The ID of the overwritten user or role (everyone role ID = guild ID)
* @arg {Number} allow The permissions number for allowed permissions
* @arg {Number} deny The permissions number for denied permissions
* @arg {String} type The object type of the overwrite, either "member" or "role"
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
editChannelPermission(channelID, overwriteID, allow, deny, type, reason) {
return this.requestHandler.request("PUT", Endpoints.CHANNEL_PERMISSION(channelID, overwriteID), true, {
allow,
deny,
type,
reason
});
}
/**
* Delete a channel permission overwrite
* @arg {String} channelID The ID of the channel
* @arg {String} overwriteID The ID of the overwritten user or role
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
deleteChannelPermission(channelID, overwriteID, reason) {
return this.requestHandler.request("DELETE", Endpoints.CHANNEL_PERMISSION(channelID, overwriteID), true, {
reason
});
}
/**
* Get all invites in a channel
* @arg {String} channelID The ID of the channel
* @returns {Promise<Invite[]>}
*/
getChannelInvites(channelID) {
return this.requestHandler.request("GET", Endpoints.CHANNEL_INVITES(channelID), true).then((invites) => invites.map((invite) => new Invite(invite, this)));
}
/**
* Create an invite for a channel
* @arg {String} channelID The ID of the channel
* @arg {Object} [options] Invite generation options
* @arg {Number} [options.maxAge] How long the invite should last in seconds
* @arg {Number} [options.maxUses] How many uses the invite should last for
* @arg {Boolean} [options.temporary] Whether the invite is temporary or not
* @arg {Boolean} [options.unique] Whether the invite is unique or not
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Invite>}
*/
createChannelInvite(channelID, options, reason) {
options = options || {};
return this.requestHandler.request("POST", Endpoints.CHANNEL_INVITES(channelID), true, {
max_age: options.maxAge,
max_uses: options.maxUses,
temporary: options.temporary,
unique: options.unique,
reason: reason
}).then(invite => new Invite(invite, this));
}
/**
* Get all the webhooks in a channel
* @arg {String} channelID The ID of the channel to get webhooks for
* @returns {Promise<Object[]>} Resolves with an array of webhook objects
*/
getChannelWebhooks(channelID) {
return this.requestHandler.request("GET", Endpoints.CHANNEL_WEBHOOKS(channelID), true);
}
/**
* Get a webhook
* @arg {String} webhookID The ID of the webhook
* @arg {String} [token] The token of the webhook, used instead of the Bot Authorization token
* @returns {Promise<Object>} Resolves with a webhook object
*/
getWebhook(webhookID, token) {
return this.requestHandler.request("GET", token ? Endpoints.WEBHOOK_TOKEN(webhookID, token) : Endpoints.WEBHOOK(webhookID), !token);
}
/**
* Create a channel webhook
* @arg {String} channelID The ID of the channel to create the webhook in
* @arg {Object} options Webhook options
* @arg {String} options.name The default name
* @arg {String} options.avatar The default avatar as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Object>} Resolves with a webhook object
*/
createChannelWebhook(channelID, options, reason) {
options.reason = reason;
return this.requestHandler.request("POST", Endpoints.CHANNEL_WEBHOOKS(channelID), true, options);
}
/**
* Edit a webhook
* @arg {String} webhookID The ID of the webhook
* @arg {Object} options Webhook options
* @arg {String} [options.name] The new default name
* @arg {String} [options.avatar] The new default avatar as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
* @arg {String} [token] The token of the webhook, used instead of the Bot Authorization token
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Object>} Resolves with a webhook object
*/
editWebhook(webhookID, options, token, reason) {
options.reason = reason;
return this.requestHandler.request("PATCH", token ? Endpoints.WEBHOOK_TOKEN(webhookID, token) : Endpoints.WEBHOOK(webhookID), !token, options);
}
/**
* Execute a webhook
* @arg {String} webhookID The ID of the webhook
* @arg {String} token The token of the webhook
* @arg {Object} options Webhook execution options
* @arg {String} [options.content=""] A content string
* @arg {Object | Object[]} [options.file] A file object (or an Array of them)
* @arg {Buffer} options.file.file A buffer containing file data
* @arg {String} options.file.name What to name the file
* @arg {Object[]} [options.embeds] An array of Discord embeds
* @arg {String} [options.username] A custom username, defaults to webhook default username if not specified
* @arg {String} [options.avatarURL] A URL for a custom avatar, defaults to webhook default avatar if not specified
* @arg {Boolean} [options.tts=false] Whether the message should be a TTS message or not
* @arg {Boolean} [options.wait=false] Whether to wait for the server to confirm the message create or not
* @arg {Boolean} [options.disableEveryone] Whether to filter @everyone/@here or not (overrides default)
* @returns {Promise}
*/
executeWebhook(webhookID, token, options) {
if(!options.content && !options.file && !options.embeds) {
return Promise.reject(new Error("No content, file, or embeds"));
}
if(options.content && (options.disableEveryone !== undefined ? options.disableEveryone : this.options.disableEveryone)) {
options.content = options.content.replace(/@everyone/g, "@\u200beveryone").replace(/@here/g, "@\u200bhere");
}
return this.requestHandler.request("POST", (token ? Endpoints.WEBHOOK_TOKEN(webhookID, token) : Endpoints.WEBHOOK(webhookID)) + (options.wait ? "?wait=true" : ""), !token, {
content: options.content,
embeds: options.embeds,
username: options.username,
avatar_url: options.avatarURL,
tts: options.tts
}, options.file);
}
/**
* Execute a slack-style webhook
* @arg {String} webhookID The ID of the webhook
* @arg {String} token The token of the webhook
* @arg {Object} options Slack webhook options
* @arg {Boolean} [options.wait=false] Whether to wait for the server to confirm the message create or not
* @returns {Promise}
*/
executeSlackWebhook(webhookID, token, options) {
var wait = !!options.wait;
options.wait = undefined;
return this.requestHandler.request("POST", (token ? Endpoints.WEBHOOK_TOKEN_SLACK(webhookID, token) : Endpoints.WEBHOOK_SLACK(webhookID)) + (wait ? "?wait=true" : ""), !token, options);
}
/**
* Delete a webhook
* @arg {String} webhookID The ID of the webhook
* @arg {String} [token] The token of the webhook, used instead of the Bot Authorization token
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
deleteWebhook(webhookID, token, reason) {
return this.requestHandler.request("DELETE", token ? Endpoints.WEBHOOK_TOKEN(webhookID, token) : Endpoints.WEBHOOK(webhookID), !token, {
reason
});
}
/**
* Get all the webhooks in a guild
* @arg {String} guildID The ID of the guild to get webhooks for
* @returns {Promise<Object[]>} Resolves with an array of webhook objects
*/
getGuildWebhooks(guildID) {
return this.requestHandler.request("GET", Endpoints.GUILD_WEBHOOKS(guildID), true);
}
/**
* Get the audit logs for a guild
* @arg {String} guildID The ID of the guild to get audit logs for
* @arg {Number} [limit=50] The maximum number of entries to return
* @arg {String} [before] Get entries before this entry ID
* @arg {Number} [actionType] Filter entries by action type
* @returns {Promise<Object>} Resolves with {users: Users[], entries: GuildAuditLogEntry[]}
*/
getGuildAuditLogs(guildID, limit, before, actionType) {
return this.requestHandler.request("GET", Endpoints.GUILD_AUDIT_LOGS(guildID), true, {
limit: limit || 50,
before: before,
action_type: actionType
}).then((data) => {
var guild = this.guilds.get(guildID);
return {
users: data.users.map((user) => this.users.add(user, this)),
entries: data.audit_log_entries.map((entry) => new GuildAuditLogEntry(entry, guild))
};
});
}
/**
* Create a guild emoji object (not for bot accounts)
* @arg {String} guildID The ID of the guild to create the emoji in
* @arg {Object} options Emoji options
* @arg {String} options.name The name of emoji
* @arg {String} options.image The base 64 encoded string
* @arg {Array} [options.roles] An array containing authorized role IDs
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Object>} A guild emoji object
*/
createGuildEmoji(guildID, options, reason) {
options.reason = reason;
return this.requestHandler.request("POST", Endpoints.GUILD_EMOJIS(guildID), true, options);
}
/**
* Edit a guild emoji object (not for bot accounts)
* @arg {String} guildID The ID of the guild to edit the emoji in
* @arg {String} emojiID The ID of the emoji you want to modify
* @arg {Object} options Emoji options
* @arg {String} [options.name] The name of emoji
* @arg {Array} [options.roles] An array containing authorized role IDs
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Object>} A guild emoji object
*/
editGuildEmoji(guildID, emojiID, options, reason) {
options.reason = reason;
return this.requestHandler.request("PATCH", Endpoints.GUILD_EMOJI(guildID, emojiID), true, options);
}
/**
* Delete a guild emoji object (not for bot accounts)
* @arg {String} guildID The ID of the guild to delete the emoji in
* @arg {String} emojiID The ID of the emoji
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
deleteGuildEmoji(guildID, emojiID, reason) {
return this.requestHandler.request("DELETE", Endpoints.GUILD_EMOJI(guildID, emojiID), true, {
reason
});
}
/**
* Create a guild role
* @arg {String} guildID The ID of the guild to create the role in
* @arg {Object} [options] The properties to set
* @arg {String} [options.name] The name of the role
* @arg {Number} [options.permissions] The role permissions number
* @arg {Number} [options.color] The hex color of the role, in number form (ex: 0x3d15b3 or 4040115)
* @arg {Boolean} [options.hoist] Whether to hoist the role in the user list or not
* @arg {Boolean} [options.mentionable] Whether the role is mentionable or not
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Role>}
*/
createRole(guildID, options, reason) {
options.reason = reason;
return this.requestHandler.request("POST", Endpoints.GUILD_ROLES(guildID), true, options).then((role) => new Role(role, this.guilds.get(guildID)));
}
/**
* Edit a guild role
* @arg {String} guildID The ID of the guild the role is in
* @arg {String} roleID The ID of the role
* @arg {Object} options The properties to edit
* @arg {String} [options.name] The name of the role
* @arg {Number} [options.permissions] The role permissions number
* @arg {Number} [options.color] The hex color of the role, in number form (ex: 0x3da5b3 or 4040115)
* @arg {Boolean} [options.hoist] Whether to hoist the role in the user list or not
* @arg {Boolean} [options.mentionable] Whether the role is mentionable or not
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Role>}
*/
editRole(guildID, roleID, options, reason) {
options.reason = reason;
return this.requestHandler.request("PATCH", Endpoints.GUILD_ROLE(guildID, roleID), true, options).then((role) => new Role(role, this.guilds.get(guildID)));
}
/**
* Edit a guild role's position. Note that role position numbers are highest on top and lowest at the bottom.
* @arg {String} guildID The ID of the guild the role is in
* @arg {String} roleID The ID of the role
* @arg {Number} position The new position of the role
* @returns {Promise}
*/
editRolePosition(guildID, roleID, position) {
if(guildID === roleID) {
return Promise.reject(new Error("Cannot move default role"));
}
var roles = this.guilds.get(guildID).roles;
var role = roles.get(roleID);
if(!role) {
return Promise.reject(new Error(`Role ${roleID} not found`));
}
if(role.position === position) {
return Promise.resolve();
}
var min = Math.min(position, role.position);
var max = Math.max(position, role.position);
roles = roles.filter((role) => min <= role.position && role.position <= max && role.id !== roleID).sort((a, b) => a.position - b.position);
if(position > role.position) {
roles.push(role);
} else {
roles.unshift(role);
}
return this.requestHandler.request("PATCH", Endpoints.GUILD_ROLES(guildID), true, roles.map((role, index) => ({
id: role.id,
position: index + min
})));
}
/**
* Delete a guild role
* @arg {String} guildID The ID of the guild to create the role in
* @arg {String} roleID The ID of the role
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
deleteRole(guildID, roleID, reason) {
return this.requestHandler.request("DELETE", Endpoints.GUILD_ROLE(guildID, roleID), true, {
reason
});
}
/**
* Get the prune count for a guild
* @arg {String} guildID The ID of the guild
* @arg {Number} days The number of days of inactivity to prune for
* @returns {Promise<Number>} Resolves with the number of users that would be pruned
*/
getPruneCount(guildID, days) {
return this.requestHandler.request("GET", Endpoints.GUILD_PRUNE(guildID), true, {
days
}).then((data) => data.pruned);
}
/**
* Begin pruning a guild
* @arg {String} guildID The ID of the guild
* @arg {Number} days The number of days of inactivity to prune for
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Number>} Resolves with the number of pruned users
*/
pruneMembers(guildID, days, reason) {
return this.requestHandler.request("POST", Endpoints.GUILD_PRUNE(guildID), true, {
days,
reason
}).then((data) => data.pruned);
}
/**
* Get a list of general/guild-specific voice reigons
* @arg {String} [guildID] The ID of the guild
* @returns {Promise<Object[]>} Resolves with an array of voice region objects
*/
getVoiceRegions(guildID) {
return guildID ? this.requestHandler.request("GET", Endpoints.GUILD_VOICE_REGIONS(guildID), true) : this.requestHandler.request("GET", Endpoints.VOICE_REGIONS, true); // TODO parse regions
}
/**
* Get info on an invite
* @arg {String} inviteID The ID of the invite
* @arg {Boolean} [withCounts] Whether to fetch additional invite info or not (approximate member counts, approximate presences, channel counts, etc.)
* @returns {Promise<Invite>}
*/
getInvite(inviteID, withCounts) {
return this.requestHandler.request("GET", Endpoints.INVITE(inviteID), true, {
with_counts: withCounts
}).then((invite) => new Invite(invite, this));
}
/**
* Accept an invite (not for bot accounts)
* @arg {String} inviteID The ID of the invite
* @returns {Promise<Invite>}
*/
acceptInvite(inviteID) {
return this.requestHandler.request("POST", Endpoints.INVITE(inviteID), true).then((invite) => new Invite(invite, this));
}
/**
* Delete an invite
* @arg {String} inviteID The ID of the invite
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
deleteInvite(inviteID, reason) {
return this.requestHandler.request("DELETE", Endpoints.INVITE(inviteID), true, {
reason
});
}
/**
* Get properties of the bot user
* @returns {Promise<ExtendedUser>}
*/
getSelf() {
return this.requestHandler.request("GET", Endpoints.USER("@me"), true).then((data) => new ExtendedUser(data, this));
}
/**
* Edit properties of the bot user
* @arg {Object} options The properties to edit
* @arg {String} [options.username] The new username
* @arg {String} [options.avatar] The new avatar as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
* @returns {Promise<ExtendedUser>}
*/
editSelf(options) {
return this.requestHandler.request("PATCH", Endpoints.USER("@me"), true, options).then((data) => new ExtendedUser(data, this));
}
/**
* Get a DM channel with a user, or create one if it does not exist
* @arg {String} userID The ID of the user
* @returns {Promise<PrivateChannel>}
*/
getDMChannel(userID) {
if(this.privateChannelMap[userID]) {
return Promise.resolve(this.privateChannels.get(this.privateChannelMap[userID]));
}
return this.requestHandler.request("POST", Endpoints.USER_CHANNELS("@me"), true, {
recipients: [userID],
type: 1
}).then((privateChannel) => new PrivateChannel(privateChannel, this));
}
/**
* Create a group channel with other users
* @arg {String[]} userIDs The IDs of the other users
* @returns {Promise<PrivateChannel>}
*/
createGroupChannel(userIDs) {
return this.requestHandler.request("POST", Endpoints.USER_CHANNELS("@me"), true, {
recipients: userIDs,
type: 3
}).then((privateChannel) => new GroupChannel(privateChannel, this));
}
/**
* Get a previous message in a channel
* @arg {String} channelID The ID of the channel
* @arg {String} messageID The ID of the message
* @returns {Promise<Message>}
*/
getMessage(channelID, messageID) {
return this.requestHandler.request("GET", Endpoints.CHANNEL_MESSAGE(channelID, messageID), true).then((message) => new Message(message, this));
}
/**
* Get previous messages in a channel
* @arg {String} channelID The ID of the channel
* @arg {Number} [limit=50] The max number of messages to get
* @arg {String} [before] Get messages before this message ID
* @arg {String} [after] Get messages after this message ID
* @arg {String} [around] Get messages around this message ID (does not work with limit > 100)
* @returns {Promise<Message[]>}
*/
getMessages(channelID, limit, before, after, around) {
if(limit && limit > 100) {
return new Promise((resolve, reject) => {
var logs = [];
var get = (_before, _after) => {
this.requestHandler.request("GET", Endpoints.CHANNEL_MESSAGES(channelID), true, {
limit: 100,
before: _before || undefined,
after: _after || undefined
}).then((messages) => {
if(limit <= messages.length) {
return resolve((_after ? messages.slice(messages.length - limit, messages.length).map((message) => new Message(message, this)).concat(logs) : logs.concat(messages.slice(0, limit).map((message) => new Message(message, this)))));
}
limit -= messages.length;
logs = (_after ? messages.map((message) => new Message(message, this)).concat(logs) : logs.concat(messages.map((message) => new Message(message, this))));
if(messages.length < 100) {
return resolve(logs);
}
this.emit("debug", `Getting ${limit} more messages during getMessages for ${channelID}: ${_before} ${_after}`, -1);
get((_before || !_after) && messages[messages.length - 1].id, _after && messages[0].id);
}).catch(reject);
};
get(before, after);
});
}
return this.requestHandler.request("GET", Endpoints.CHANNEL_MESSAGES(channelID), true, {
limit: limit || 50,
before,
after,
around
}).then((messages) => messages.map((message) => {
try {
return new Message(message, this);
} catch(err) {
this.emit("error", `Error creating message from channel messages\n${err.stack}\n${JSON.stringify(messages)}`);
return null;
}
}));
}
/**
* Get all the pins in a channel
* @arg {String} channelID The ID of the channel
* @returns {Promise<Message[]>}
*/
getPins(channelID) {
return this.requestHandler.request("GET", Endpoints.CHANNEL_PINS(channelID), true).then((messages) => messages.map((message) => new Message(message, this)));
}
/**
* Create a message in a channel
* Note: If you want to DM someone, the user ID is **not** the DM channel ID. use Client.getDMChannel() to get the DM channel for a user
* @arg {String} channelID The ID of the channel
* @arg {String | Array | Object} content A string, array of strings, or object. If an object is passed:
* @arg {String} content.content A content string
* @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure
* @arg {Boolean} [content.tts] Set the message TTS flag
* @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default)
* @arg {Object | Object[]} [file] A file object (or an Array of them)
* @arg {Buffer} file.file A buffer containing file data
* @arg {String} file.name What to name the file
* @returns {Promise<Message>}
*/
createMessage(channelID, content, file) {
if(content !== undefined) {
if(typeof content !== "object" || content === null) {
content = {
content: "" + content
};
} else if(content.content !== undefined && typeof content.content !== "string") {
content.content = "" + content.content;
} else if(content.content === undefined && !content.embed && !file) {
return Promise.reject(new Error("No content, file, or embed"));
}
if(content.content && (content.disableEveryone !== undefined ? content.disableEveryone : this.options.disableEveryone)) {
content.content = content.content.replace(/@everyone/g, "@\u200beveryone").replace(/@here/g, "@\u200bhere");
}
} else if(!file) {
return Promise.reject(new Error("No content, file, or embed"));
}
return this.requestHandler.request("POST", Endpoints.CHANNEL_MESSAGES(channelID), true, content, file).then((message) => new Message(message, this));
}
/**
* Edit a message
* @arg {String} channelID The ID of the channel
* @arg {String} messageID The ID of the message
* @arg {String | Array | Object} content A string, array of strings, or object. If an object is passed:
* @arg {String} content.content A content string
* @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default)
* @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure
* @returns {Promise<Message>}
*/
editMessage(channelID, messageID, content) {
if(content !== undefined) {
if(typeof content !== "object" || content === null) {