-
Notifications
You must be signed in to change notification settings - Fork 417
/
Client.js
2850 lines (2683 loc) · 136 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 Base = require("./structures/Base");
const Channel = require("./structures/Channel");
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 GuildPreview = require("./structures/GuildPreview");
const GuildTemplate = require("./structures/GuildTemplate");
const Invite = require("./structures/Invite");
const Member = require("./structures/Member");
const Message = require("./structures/Message");
const Permission = require("./structures/Permission");
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");
let EventEmitter;
try {
EventEmitter = require("eventemitter3");
} catch(err) {
EventEmitter = require("events");
}
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
}
}
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
/**
* Represents the main Eris client
* @extends EventEmitter
* @prop {Object?} application Object containing the bot application's ID and its public flags
* @prop {Boolean} bot Whether the bot user belongs to an OAuth2 application
* @prop {Object} channelGuildMap Object mapping channel IDs to guild IDs
* @prop {String} gatewayURL The URL for the discord gateway
* @prop {Collection<GroupChannel>} groupChannels Collection of group channels the bot is in (user accounts only)
* @prop {Collection<Guild>} guilds Collection of guilds the bot is in
* @prop {Object} guildShardMap Object mapping guild IDs to shard IDs
* @prop {Object} notes Object mapping user IDs to user notes (user accounts only)
* @prop {Object} options Eris options
* @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<Relationship>} relationships Collection of relationships the bot user has (user accounts only)
* @prop {RequestHandler} requestHandler The request handler the client will use
* @prop {Collection<Shard>} shards Collection of shards Eris is using
* @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 {Object} userGuildSettings Object mapping guild IDs to individual guild settings for the bot user (user accounts only)
* @prop {Collection<User>} users Collection of users the bot sees
* @prop {Object} userSettings Object containing the user account settings (user accounts only)
* @prop {Collection<VoiceConnection>} voiceConnections Extended collection of active VoiceConnections the bot has
*/
class Client extends EventEmitter {
/**
* Create a Client
* @arg {String} token The auth token to use. Bot tokens should be prefixed with `Bot` (e.g. `Bot MTExIHlvdSAgdHJpZWQgMTEx.O5rKAA.dQw4w9WgXcQ_wpV-gGA4PSk_bm8`). Prefix-less bot tokens are [DEPRECATED]
* @arg {Object} options Eris client options (only `intents` is required)
* @arg {Object} [options.agent] [DEPRECATED] A HTTPS Agent used to proxy requests. This option has been moved under `options.rest`
* @arg {Object} [options.allowedMentions] A list of mentions to allow by default in createMessage/editMessage
* @arg {Boolean} [options.allowedMentions.everyone] Whether or not to allow @everyone/@here.
* @arg {Boolean | Array<String>} [options.allowedMentions.roles] Whether or not to allow all role mentions, or an array of specific role mentions to allow.
* @arg {Boolean | Array<String>} [options.allowedMentions.users] Whether or not to allow all user mentions, or an array of specific user mentions to allow.
* @arg {Boolean} [options.allowedMentions.repliedUser] Whether or not to mention the author of the message being replied to
* @arg {Boolean} [options.autoreconnect=true] Have Eris autoreconnect when connection is lost
* @arg {Boolean} [options.compress=false] 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 {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, banners, splashes, and group icons. Can be any power of two between 16 and 2048. If the height and width are different, the width will be the value specified, and the height relative to that
* @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 {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 | Array<String>} options.intents A list of intents, or raw bitmask value describing the intents to subscribe to. Some intents, like `guildPresences` and `guildMembers`, must be enabled on your application's page to be used.
* @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} [options.latencyThreshold=30000] [DEPRECATED] The average request latency at which Eris will start emitting latency errors. This option has been moved under `options.rest`
* @arg {Number} [options.maxReconnectAttempts=Infinity] The maximum amount of times that the client is allowed to try to reconnect to Discord.
* @arg {Number} [options.maxResumeAttempts=10] The maximum amount of times a shard can attempt to resume a session before considering that session invalid.
* @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 Opus encoder not found error or not
* @arg {Number} [options.ratelimiterOffset=0] [DEPRECATED] A number of milliseconds to offset the ratelimit timing calculations by. This option has been moved under `options.rest`
* @arg {Function} [options.reconnectDelay] A function which returns how long the bot should wait until reconnecting to Discord.
* @arg {Number} [options.requestTimeout=15000] A number of milliseconds before requests are considered timed out. This option will stop affecting REST in a future release; that behavior is [DEPRECATED] and replaced by `options.rest.requestTimeout`
* @arg {Object} [options.rest] Options for the REST request handler
* @arg {Object} [options.rest.agent] A HTTPS Agent used to proxy requests
* @arg {String} [options.rest.baseURL] The base URL to use for API requests. Defaults to `/api/v${REST_VERSION}`
* @arg {Boolean} [options.rest.decodeReasons=true] [DEPRECATED] Whether reasons should be decoded with `decodeURIComponent()` when making REST requests. This is true by default to mirror pre-0.15.0 behavior (where reasons were expected to be URI-encoded), and should be set to false once your bot code stops. Reasons will no longer be decoded in the future
* @arg {Boolean} [options.rest.disableLatencyCompensation=false] Whether to disable the built-in latency compensator or not
* @arg {String} [options.rest.domain="discord.com"] The domain to use for API requests
* @arg {Number} [options.rest.latencyThreshold=30000] The average request latency at which Eris will start emitting latency errors
* @arg {Number} [options.rest.ratelimiterOffset=0] A number of milliseconds to offset the ratelimit timing calculations by
* @arg {Number} [options.rest.requestTimeout=15000] A number of milliseconds before REST requests are considered timed out
* @arg {Boolean} [options.restMode=false] Whether to enable getting objects over REST. Even with this option enabled, it is recommended that you check the cache first before using REST
* @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 {Object} [options.ws] An object of WebSocket options to pass to the shard WebSocket constructors
*/
constructor(token, options) {
super();
this.options = Object.assign({
allowedMentions: {
users: true,
roles: true
},
autoreconnect: true,
compress: false,
connectionTimeout: 30000,
defaultImageFormat: "jpg",
defaultImageSize: 128,
disableEvents: {},
firstShardID: 0,
getAllUsers: false,
guildCreateTimeout: 2000,
largeThreshold: 250,
maxReconnectAttempts: Infinity,
maxResumeAttempts: 10,
maxShards: 1,
messageLimit: 100,
opusOnly: false,
requestTimeout: 15000,
rest: {},
restMode: false,
seedVoiceConnections: false,
ws: {},
reconnectDelay: (lastDelay, attempts) => Math.pow(attempts + 1, 0.7) * 20000
}, options);
this.options.allowedMentions = this._formatAllowedMentions(this.options.allowedMentions);
if(this.options.lastShardID === undefined && this.options.maxShards !== "auto") {
this.options.lastShardID = this.options.maxShards - 1;
}
if(typeof window !== "undefined" || !ZlibSync) {
this.options.compress = false; // zlib does not like Blobs, Pako is not here
}
if(!Constants.ImageFormats.includes(this.options.defaultImageFormat.toLowerCase())) {
throw new TypeError(`Invalid default image format: ${this.options.defaultImageFormat}`);
}
const defaultImageSize = this.options.defaultImageSize;
if(defaultImageSize < Constants.ImageSizeBoundaries.MINIMUM || defaultImageSize > Constants.ImageSizeBoundaries.MAXIMUM || (defaultImageSize & (defaultImageSize - 1))) {
throw new TypeError(`Invalid default image size: ${defaultImageSize}`);
}
// Set HTTP Agent on Websockets if not already set
if(this.options.agent && !(this.options.ws && this.options.ws.agent)) {
this.options.ws = this.options.ws || {};
this.options.ws.agent = this.options.agent;
}
if(this.options.hasOwnProperty("intents")) {
// Resolve intents option to the proper integer
if(Array.isArray(this.options.intents)) {
let bitmask = 0;
for(const intent of this.options.intents) {
if(Constants.Intents[intent]) {
bitmask |= Constants.Intents[intent];
} else {
this.emit("warn", `Unknown intent: ${intent}`);
}
}
this.options.intents = bitmask;
}
// Ensure requesting all guild members isn't destined to fail
if(this.options.getAllUsers && !(this.options.intents & Constants.Intents.guildMembers)) {
throw new Error("Cannot request all members without guildMembers intent");
}
}
Object.defineProperty(this, "_token", {
configurable: true,
enumerable: false,
writable: true,
value: token
});
this.requestHandler = new RequestHandler(this, this.options.rest);
delete this.options.rest;
this.ready = false;
this.bot = this._token.startsWith("Bot ");
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.guildShardMap = {};
this.unavailableGuilds = new Collection(UnavailableGuild);
this.relationships = new Collection(Relationship);
this.users = new Collection(User);
this.presence = {
activities: null,
afk: false,
since: null,
status: "offline"
};
this.userGuildSettings = [];
this.userSettings = {};
this.notes = {};
this.voiceConnections = new VoiceConnectionManager();
this.connect = this.connect.bind(this);
this.lastReconnectDelay = 0;
this.reconnectAttempts = 0;
}
get uptime() {
return this.startTime ? Date.now() - this.startTime : 0;
}
/**
* [USER ACCOUNT] Accept an invite
* @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));
}
/**
* [USER ACCOUNT] Add a user to a group
* @arg {String} groupID The ID of the target group
* @arg {String} userID The ID of the target user
* @returns {Promise}
*/
addGroupRecipient(groupID, userID) {
return this.requestHandler.request("PUT", Endpoints.CHANNEL_RECIPIENT(groupID, userID), true);
}
/**
* Add a guild discovery subcategory
* @arg {String} guildID The ID of the guild
* @arg {String} categoryID The ID of the discovery category
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Object>}
*/
addGuildDiscoverySubcategory(guildID, categoryID, reason) {
return this.requestHandler.request("POST", Endpoints.GUILD_DISCOVERY_CATEGORY(guildID, categoryID), true, {reason});
}
/**
* Add a role to a guild member
* @arg {String} guildID The ID of the guild
* @arg {String} memberID The ID of the member
* @arg {String} roleID The ID of the role
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
addGuildMemberRole(guildID, memberID, roleID, reason) {
return this.requestHandler.request("PUT", Endpoints.GUILD_MEMBER_ROLE(guildID, memberID, roleID), true, {
reason
});
}
/**
* Add a reaction to a message
* @arg {String} channelID The ID of the channel
* @arg {String} messageID The ID of the message
* @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
* @arg {String} [userID="@me"] The ID of the user to react as. Passing this parameter is deprecated and will not be supported in future versions.
* @returns {Promise}
*/
addMessageReaction(channelID, messageID, reaction, userID) {
if(userID !== undefined) {
this.emit("warn", "[DEPRECATED] addMessageReaction() was called without an \"@me\" `userID` argument");
}
if(reaction === decodeURI(reaction)) {
reaction = encodeURIComponent(reaction);
}
return this.requestHandler.request("PUT", Endpoints.CHANNEL_MESSAGE_REACTION_USER(channelID, messageID, reaction, userID || "@me"), true);
}
/**
* [USER ACCOUNT] Create a relationship with a user
* @arg {String} userID The ID of the target user
* @arg {Boolean} [block=false] If true, block the user. Otherwise, add the user as a friend
* @returns {Promise}
*/
addRelationship(userID, block) {
return this.requestHandler.request("PUT", Endpoints.USER_RELATIONSHIP("@me", userID), true, {
type: block ? 2 : undefined
});
}
/**
* [USER ACCOUNT] Purchase a premium subscription (Nitro) for the current user
* You must get a Stripe card token from the Stripe API for this to work
* @arg {String} token The Stripe credit card token
* @arg {String} plan The plan to purchase, either "premium_month" or "premium_year"
* @returns {Promise}
*/
addSelfPremiumSubscription(token, plan) {
return this.requestHandler.request("PUT", Endpoints.USER_BILLING_PREMIUM_SUBSCRIPTION("@me"), true, {
token: token,
payment_gateway: "stripe",
plan: plan
});
}
/**
* Ban a user from a guild
* @arg {String} guildID The ID of the guild
* @arg {String} userID The ID of the user
* @arg {Number} [deleteMessageDays=0] Number of days to delete messages for, between 0-7 inclusive
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
banGuildMember(guildID, userID, deleteMessageDays, reason) {
if(!isNaN(deleteMessageDays) && (deleteMessageDays < 0 || deleteMessageDays > 7)) {
return Promise.reject(new Error(`Invalid deleteMessageDays value (${deleteMessageDays}), should be a number between 0-7 inclusive`));
}
return this.requestHandler.request("PUT", Endpoints.GUILD_BAN(guildID, userID), true, {
delete_message_days: deleteMessageDays || 0,
reason: reason
});
}
/**
* Closes a voice connection with a guild ID
* @arg {String} guildID The ID of the guild
*/
closeVoiceConnection(guildID) {
this.shards.get(this.guildShardMap[guildID] || 0).sendWS(Constants.GatewayOPCodes.VOICE_STATE_UPDATE, {
guild_id: guildID || null,
channel_id: null,
self_mute: false,
self_deaf: false
});
this.voiceConnections.leave(guildID || "call");
}
/**
* Tells all shards to connect.
* @returns {Promise} Resolves when all shards are initialized
*/
async connect() {
try {
const data = await (this.options.maxShards === "auto" ? this.getBotGateway() : this.getGateway());
if(!data.url || (this.options.maxShards === "auto" && !data.shards)) {
throw 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.compress) {
this.gatewayURL += "&compress=zlib-stream";
}
if(this.options.maxShards === "auto") {
if(!data.shards) {
throw 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(let i = this.options.firstShardID; i <= this.options.lastShardID; ++i) {
this.shards.spawn(i);
}
} catch(err) {
if(!this.options.autoreconnect) {
throw err;
}
const reconnectDelay = this.options.reconnectDelay(this.lastReconnectDelay, this.reconnectAttempts);
await sleep(reconnectDelay);
this.lastReconnectDelay = reconnectDelay;
this.reconnectAttempts = this.reconnectAttempts + 1;
return this.connect();
}
}
/**
* 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 (text), 2 (voice), 4 (category), 5 (news), 6 (store), or 13 (stage)
* @arg {Object | String} [options] The properties the channel should have. If `options` is a string, it will be treated as `options.parentID` (see below). Passing a string is deprecated and will not be supported in future versions.
* @arg {Number} [options.bitrate] The bitrate of the channel (voice channels only)
* @arg {Boolean} [options.nsfw] The nsfw status of the channel
* @arg {String?} [options.parentID] The ID of the parent category channel for this channel
* @arg {Array} [options.permissionOverwrites] An array containing permission overwrite objects
* @arg {Number} [options.rateLimitPerUser] The time in seconds a user has to wait before sending another message (does not affect bots or users with manageMessages/manageChannel permissions) (text channels only)
* @arg {String} [options.reason] The reason to be displayed in audit logs
* @arg {String} [options.topic] The topic of the channel (text channels only)
* @arg {Number} [options.userLimit] The channel user limit (voice channels only)
* @returns {Promise<CategoryChannel | TextChannel | VoiceChannel>}
*/
createChannel(guildID, name, type, reason, options = {}) {
if(typeof options === "string") { // This used to be parentID, back-compat
this.emit("warn", "[DEPRECATED] createChannel() was called with a string `options` argument");
options = {
parentID: options
};
}
if(typeof reason === "string") { // Reason is deprecated, will be folded into options
this.emit("warn", "[DEPRECATED] createChannel() was called with a string `reason` argument");
options.reason = reason;
reason = undefined;
} else if(typeof reason === "object" && reason !== null) {
options = reason;
reason = undefined;
}
return this.requestHandler.request("POST", Endpoints.GUILD_CHANNELS(guildID), true, {
name: name,
type: type,
bitrate: options.bitrate,
nsfw: options.nsfw,
parent_id: options.parentID,
permission_overwrites: options.permissionOverwrites,
rate_limit_per_user: options.rateLimitPerUser,
reason: options.reason,
topic: options.topic,
user_limit: options.userLimit
}).then((channel) => Channel.from(channel, 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 grants temporary membership 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) {
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));
}
/**
* 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);
}
/**
* [USER ACCOUNT] Create a group channel with other users
* @arg {Array<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));
}
/**
* Create a guild
* @arg {String} name The name of the guild
* @arg {Object} options The properties of the guild
* @arg {String} [options.afkChannelID] The ID of the AFK voice channel
* @arg {Number} [options.afkTimeout] The AFK timeout in seconds
* @arg {Array<Object>} [options.channels] The new channels of the guild. IDs are placeholders which allow use of category channels.
* @arg {Number} [options.defaultNotifications] The default notification settings for the guild. 0 is "All Messages", 1 is "Only @mentions".
* @arg {Number} [options.explicitContentFilter] The level of the explicit content filter for messages/images in the guild. 0 disables message scanning, 1 enables scanning the messages of members without roles, 2 enables scanning for all messages.
* @arg {String} [options.icon] The guild icon as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
* @arg {String} [options.region] The region of the guild
* @arg {Array<Object>} [options.roles] The new roles of the guild, the first one is the @everyone role. IDs are placeholders which allow channel overwrites.
* @arg {String} [options.systemChannelID] The ID of the system channel
* @arg {Number} [options.verificationLevel] The guild verification level
* @returns {Promise<Guild>}
*/
createGuild(name, options) {
if(this.guilds.size > 9) {
throw new Error("This method can't be used when in 10 or more guilds.");
}
return this.requestHandler.request("POST", Endpoints.GUILDS, true, {
name: name,
region: options.region,
icon: options.icon,
verification_level: options.verificationLevel,
default_message_notifications: options.defaultNotifications,
explicit_content_filter: options.explicitContentFilter,
system_channel_id: options.systemChannelID,
afk_channel_id: options.afkChannelID,
afk_timeout: options.afkTimeout,
roles: options.roles,
channels: options.channels
}).then((guild) => new Guild(guild, this));
}
/**
* Create a guild emoji object
* @arg {String} guildID The ID of the guild to create the emoji in
* @arg {Object} options Emoji options
* @arg {String} options.image The base 64 encoded string
* @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
*/
createGuildEmoji(guildID, options, reason) {
options.reason = reason;
return this.requestHandler.request("POST", Endpoints.GUILD_EMOJIS(guildID), true, options);
}
/**
* Create a guild based on a template. This can only be used with bots in less than 10 guilds
* @arg {String} code The template code
* @arg {String} name The name of the guild
* @arg {String} [icon] The 128x128 icon as a base64 data URI
* @returns {Promise<Guild>}
*/
createGuildFromTemplate(code, name, icon) {
return this.requestHandler.request("POST", Endpoints.GUILD_TEMPLATE(code), true, {
name,
icon
}).then((guild) => new Guild(guild, this));
}
/**
* Create a template for a guild
* @arg {String} guildID The ID of the guild
* @arg {String} name The name of the template
* @arg {String} [description] The description for the template
* @returns {Promise<GuildTemplate>}
*/
createGuildTemplate(guildID, name, description) {
return this.requestHandler.request("POST", Endpoints.GUILD_TEMPLATES(guildID), true, {
name,
description
}).then((template) => new GuildTemplate(template, 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 | Object} content A string or object. If an object is passed:
* @arg {Object} [content.allowedMentions] A list of mentions to allow (overrides default)
* @arg {Boolean} [content.allowedMentions.everyone] Whether or not to allow @everyone/@here.
* @arg {Boolean | Array<String>} [content.allowedMentions.roles] Whether or not to allow all role mentions, or an array of specific role mentions to allow.
* @arg {Boolean | Array<String>} [content.allowedMentions.users] Whether or not to allow all user mentions, or an array of specific user mentions to allow.
* @arg {Boolean} [content.allowedMentions.repliedUser] Whether or not to mention the author of the message being replied to.
* @arg {Array<Object>} [content.components] An array of component objects
* @arg {String} [content.components[].custom_id] The ID of the component (type 2 style 0-4 and type 3 only)
* @arg {Boolean} [content.components[].disabled] Whether the component is disabled (type 2 and 3 only)
* @arg {Object} [content.components[].emoji] The emoji to be displayed in the component (type 2)
* @arg {String} [content.components[].label] The label to be displayed in the component (type 2)
* @arg {Number} [content.components[].max_values] The maximum number of items that can be chosen (1-25, default 1)
* @arg {Number} [content.components[].min_values] The minimum number of items that must be chosen (0-25, default 1)
* @arg {Array<Object>} [content.components[].options] The options for this component (type 3 only)
* @arg {Boolean} [content.components[].options[].default] Whether this option should be the default value selected
* @arg {String} [content.components[].options[].description] The description for this option
* @arg {Object} [content.components[].options[].emoji] The emoji to be displayed in this option
* @arg {String} content.components[].options[].label The label for this option
* @arg {Number | String} content.components[].options[].value The value for this option
* @arg {String} [content.components[].placeholder] The placeholder text for the component when no option is selected (type 3 only)
* @arg {Number} [content.components[].style] The style of the component (type 2 only) - If 0-4, `custom_id` is required; if 5, `url` is required
* @arg {Number} content.components[].type The type of component - If 1, it is a collection and a `components` array (nested) is required; if 2, it is a button; if 3, it is a select menu
* @arg {String} [content.components[].url] The URL that the component should open for users (type 2 style 5 only)
* @arg {String} content.content A content string
* @arg {Object} [content.embed] [DEPRECATED] An embed object. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/channel#embed-object) for object structure. Use `embeds` instead
* @arg {Array<Object>} [content.embeds] An array of embed objects. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/channel#embed-object) for object structure
* @arg {Object} [content.messageReference] The message reference, used when replying to messages
* @arg {String} [content.messageReference.channelID] The channel ID of the referenced message
* @arg {Boolean} [content.messageReference.failIfNotExists=true] Whether to throw an error if the message reference doesn't exist. If false, and the referenced message doesn't exist, the message is created without a referenced message
* @arg {String} [content.messageReference.guildID] The guild ID of the referenced message
* @arg {String} content.messageReference.messageID The message ID of the referenced message. This cannot reference a system message
* @arg {String} [content.messageReferenceID] [DEPRECATED] The ID of the message should be replied to. Use `messageReference` instead
* @arg {Array<String>} [content.stickerIDs] An array of IDs corresponding to stickers to send
* @arg {Boolean} [content.tts] Set the message TTS flag
* @arg {Object | Array<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.embed && !content.embeds) {
this.emit("warn", "[DEPRECATED] content.embed is deprecated. Use content.embeds instead");
content.embeds = [content.embed];
}
content.allowed_mentions = this._formatAllowedMentions(content.allowedMentions);
content.sticker_ids = content.stickerIDs;
if(content.messageReference) {
content.message_reference = content.messageReference;
if(content.messageReference.messageID !== undefined) {
content.message_reference.message_id = content.messageReference.messageID;
content.messageReference.messageID = undefined;
}
if(content.messageReference.channelID !== undefined) {
content.message_reference.channel_id = content.messageReference.channelID;
content.messageReference.channelID = undefined;
}
if(content.messageReference.guildID !== undefined) {
content.message_reference.guild_id = content.messageReference.guildID;
content.messageReference.guildID = undefined;
}
if(content.messageReference.failIfNotExists !== undefined) {
content.message_reference.fail_if_not_exists = content.messageReference.failIfNotExists;
content.messageReference.failIfNotExists = undefined;
}
} else if(content.messageReferenceID) {
this.emit("warn", "[DEPRECATED] content.messageReferenceID is deprecated. Use content.messageReference instead");
content.message_reference = {message_id: content.messageReferenceID};
}
}
return this.requestHandler.request("POST", Endpoints.CHANNEL_MESSAGES(channelID), true, content, file).then((message) => new Message(message, this));
}
/**
* Create a guild role
* @arg {String} guildID The ID of the guild to create the role in
* @arg {Object | Role} [options] An object or Role containing the properties to set
* @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} [options.name] The name of the role
* @arg {BigInt | Number | String | Permission} [options.permissions] The role permissions
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Role>}
*/
createRole(guildID, options, reason) {
if(options.permissions !== undefined) {
options.permissions = options.permissions instanceof Permission ? String(options.permissions.allow) : String(options.permissions);
}
return this.requestHandler.request("POST", Endpoints.GUILD_ROLES(guildID), true, {
name: options.name,
permissions: options.permissions,
color: options.color,
hoist: options.hoist,
mentionable: options.mentionable,
reason: reason
}).then((role) => {
const guild = this.guilds.get(guildID);
if(guild) {
return guild.roles.add(role, guild);
} else {
return new Role(role);
}
});
}
/**
* Crosspost (publish) a message to subscribed channels
* @arg {String} channelID The ID of the NewsChannel
* @arg {String} messageID The ID of the message
* @returns {Promise<Message>}
*/
crosspostMessage(channelID, messageID) {
return this.requestHandler.request("POST", Endpoints.CHANNEL_CROSSPOST(channelID, messageID), true).then((message) => new Message(message, this));
}
/**
* 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
});
}
/**
* 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
});
}
/**
* Delete a guild (bot user must be owner)
* @arg {String} guildID The ID of the guild
* @returns {Promise}
*/
deleteGuild(guildID) {
return this.requestHandler.request("DELETE", Endpoints.GUILD(guildID), true);
}
/**
* Delete a guild discovery subcategory
* @arg {String} guildID The ID of the guild
* @arg {String} categoryID The ID of the discovery category
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
deleteGuildDiscoverySubcategory(guildID, categoryID, reason) {
return this.requestHandler.request("DELETE", Endpoints.GUILD_DISCOVERY_CATEGORY(guildID, categoryID), true, {reason});
}
/**
* Delete a guild emoji object
* @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
});
}
/**
* Delete a guild integration
* @arg {String} guildID The ID of the guild
* @arg {String} integrationID The ID of the integration
* @returns {Promise}
*/
deleteGuildIntegration(guildID, integrationID) {
return this.requestHandler.request("DELETE", Endpoints.GUILD_INTEGRATION(guildID, integrationID), true);
}
/**
* Delete a guild template
* @arg {String} guildID The ID of the guild
* @arg {String} code The template code
* @returns {Promise<GuildTemplate>}
*/
deleteGuildTemplate(guildID, code) {
return this.requestHandler.request("DELETE", Endpoints.GUILD_TEMPLATE_GUILD(guildID, code), true).then((template) => new GuildTemplate(template, 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
});
}
/**
* Delete a message
* @arg {String} channelID The ID of the channel
* @arg {String} messageID The ID of the message
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
deleteMessage(channelID, messageID, reason) {
return this.requestHandler.request("DELETE", Endpoints.CHANNEL_MESSAGE(channelID, messageID), true, {
reason
});
}
/**
* Bulk delete messages (bot accounts only)
* @arg {String} channelID The ID of the channel
* @arg {Array<String>} messageIDs Array of message IDs to delete
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
deleteMessages(channelID, messageIDs, reason) {
if(messageIDs.length === 0) {
return Promise.resolve();
}
if(messageIDs.length === 1) {
return this.deleteMessage(channelID, messageIDs[0]);
}
const oldestAllowedSnowflake = (Date.now() - 1421280000000) * 4194304;
const invalidMessage = messageIDs.find((messageID) => messageID < oldestAllowedSnowflake);
if(invalidMessage) {
return Promise.reject(new Error(`Message ${invalidMessage} is more than 2 weeks old.`));
}
if(messageIDs.length > 100) {
return this.requestHandler.request("POST", Endpoints.CHANNEL_BULK_DELETE(channelID), true, {
messages: messageIDs.splice(0, 100),
reason: reason
}).then(() => this.deleteMessages(channelID, messageIDs));
}
return this.requestHandler.request("POST", Endpoints.CHANNEL_BULK_DELETE(channelID), true, {
messages: messageIDs,
reason: reason
});
}
/**
* 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
});
}
/**
* [USER ACCOUNT] Delete a connection for the current user
* @arg {String} platform The connection platform (e.g. "twitch", "reddit")
* @arg {String} id The connection ID
* @returns {Promise}
*/
deleteSelfConnection(platform, id) {
return this.requestHandler.request("DELETE", Endpoints.USER_CONNECTION_PLATFORM("@me", platform, id), true);
}
/**
* [USER ACCOUNT] Cancel the premium subscription (Nitro) for the current user
* @returns {Promise}
*/
deleteSelfPremiumSubscription() {
return this.requestHandler.request("DELETE", Endpoints.USER_BILLING_PREMIUM_SUBSCRIPTION("@me"), true);
}
/**
* [USER ACCOUNT] Delete the current user's note for another user
* @returns {Promise}
*/
deleteUserNote(userID) {
return this.requestHandler.request("DELETE", Endpoints.USER_NOTE("@me", userID), true);
}
/**
* 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
});
}
/**
* Delete a webhook message
* @arg {String} webhookID
* @arg {String} token
* @arg {String} messageID
* @returns {Promise}
*/
deleteWebhookMessage(webhookID, token, messageID) {
return this.requestHandler.request("DELETE", Endpoints.WEBHOOK_MESSAGE(webhookID, token, messageID), false);
}
/**
* [USER ACCOUNT] Disable TOTP authentication for the current user
* @arg {String} code The timed auth code for the current user
* @returns {Promise<Object>} An object containing the user's new authorization token
*/
disableSelfMFATOTP(code) {
return this.requestHandler.request("POST", Endpoints.USER_MFA_TOTP_DISABLE("@me"), true, {
code
}).then((data) => {
if(data.token) {
this._token = data.token;
}
});
}
/**
* 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 = [];
}
/**
* 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);
});
}
/**
* Edit a channel's properties
* @arg {String} channelID The ID of the channel
* @arg {Object} options The properties to edit
* @arg {Number} [options.bitrate] The bitrate of the channel (guild voice channels only)
* @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.name] The name of the channel
* @arg {Boolean} [options.nsfw] The nsfw status of the channel (guild channels only)
* @arg {String} [options.ownerID] The ID of the channel owner (group channels only)
* @arg {String?} [options.parentID] The ID of the parent channel category for this channel (guild text/voice channels only)
* @arg {Number} [options.rateLimitPerUser] The time in seconds a user has to wait before sending another message (does not affect bots or users with manageMessages/manageChannel permissions) (guild text channels only)
* @arg {String?} [options.rtcRegion] The RTC region ID of the channel (automatic if `null`) (guild voice channels only)
* @arg {String} [options.topic] The topic of the channel (guild text channels only)
* @arg {Number} [options.userLimit] The channel user limit (guild voice channels only)
* @arg {Number} [options.videoQualityMode] The camera video quality mode of the channel (guild voice channels only). `1` is auto, `2` is 720p
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<CategoryChannel | GroupChannel | TextChannel | VoiceChannel | NewsChannel>}
*/
editChannel(channelID, options, reason) {
return this.requestHandler.request("PATCH", Endpoints.CHANNEL(channelID), true, {
bitrate: options.bitrate,
icon: options.icon,
name: options.name,
nsfw: options.nsfw,
owner_id: options.ownerID,
parent_id: options.parentID,
rate_limit_per_user: options.rateLimitPerUser,
rtc_region: options.rtcRegion,
topic: options.topic,
user_limit: options.userLimit,
voice_quality_mode: options.voiceQualityMode,
reason: reason
}).then((channel) => Channel.from(channel, this));
}
/**
* 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 {BigInt} allow The permissions number for allowed permissions
* @arg {BigInt} deny The permissions number for denied permissions
* @arg {Number} type The object type of the overwrite, either 1 for "member" or 0 for "role"
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
editChannelPermission(channelID, overwriteID, allow, deny, type, reason) {
if(typeof type === "string") { // backward compatibility
type = type === "member" ? 1 : 0;
}
return this.requestHandler.request("PUT", Endpoints.CHANNEL_PERMISSION(channelID, overwriteID), true, {
allow,
deny,
type,
reason
});
}
/**
* 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
* @arg {Object} [options] Additional options when editing position