forked from abalabahaha/eris
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Client.js
3781 lines (3565 loc) · 199 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 ApplicationCommand = require("./structures/ApplicationCommand");
const Base = require("./structures/Base");
const Channel = require("./structures/Channel");
const Collection = require("./util/Collection");
const Constants = require("./Constants");
const emitDeprecation = require("./util/emitDeprecation");
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 GuildScheduledEvent = require("./structures/GuildScheduledEvent");
const Invite = require("./structures/Invite");
const Member = require("./structures/Member");
const Message = require("./structures/Message");
const Permission = require("./structures/Permission");
const DMChannel = require("./structures/DMChannel");
const RequestHandler = require("./rest/RequestHandler");
const Role = require("./structures/Role");
const ShardManager = require("./gateway/ShardManager");
const ThreadMember = require("./structures/ThreadMember");
const UnavailableGuild = require("./structures/UnavailableGuild");
const User = require("./structures/User");
const VoiceConnectionManager = require("./voice/VoiceConnectionManager");
const StageInstance = require("./structures/StageInstance");
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 {Object} dmChannelMap Object mapping user IDs to private channel IDs
* @prop {Collection<DMChannel>} dmChannels Collection of private channels the bot is in
* @prop {String} gatewayURL The URL for the discord gateway
* @prop {Collection<Guild>} guilds Collection of guilds the bot is in
* @prop {Object} guildShardMap Object mapping guild IDs to shard IDs
* @prop {Object} options Eris options
* @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 {Object} threadGuildMap Object mapping thread channel IDs to guild IDs
* @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<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
* @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} [options.allowedMentions.repliedUser] Whether or not to mention the author of the message being replied to
* @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.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|Number>} [options.intents] A list of [intent names](/Eris/docs/reference), pre-shifted intent numbers to add, or a 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. By default, all non-privileged intents are enabled
* @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 {Number | String} [options.shardConcurrency="auto"] The number of shards that can start simultaneously. If "auto" Eris will use Discord's recommended shard concurrency
* @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,
intents: Constants.Intents.allNonPrivileged,
largeThreshold: 250,
maxReconnectAttempts: Infinity,
maxResumeAttempts: 10,
maxShards: 1,
messageLimit: 100,
opusOnly: false,
requestTimeout: 15000,
rest: {},
restMode: false,
seedVoiceConnections: false,
shardConcurrency: "auto",
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(typeof intent === "number") {
bitmask |= intent;
} else 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;
const shardManagerOptions = {};
if(typeof this.options.shardConcurrency === "number") {
shardManagerOptions.concurrency = this.options.shardConcurrency;
}
this.shards = new ShardManager(this, shardManagerOptions);
this.ready = false;
this.bot = this._token.startsWith("Bot ");
this.startTime = 0;
this.lastConnect = 0;
this.channelGuildMap = {};
this.threadGuildMap = {};
this.guilds = new Collection(Guild);
this.dmChannelMap = {};
this.dmChannels = new Collection(DMChannel);
this.guildShardMap = {};
this.unavailableGuilds = new Collection(UnavailableGuild);
this.users = new Collection(User);
this.presence = {
activities: null,
afk: false,
since: null,
status: "offline"
};
this.voiceConnections = new VoiceConnectionManager();
this.connect = this.connect.bind(this);
this.lastReconnectDelay = 0;
this.reconnectAttempts = 0;
}
get privateChannelMap() {
emitDeprecation("PRIVATE_CHANNEL");
return this.dmChannelMap;
}
get privateChannels() {
emitDeprecation("PRIVATE_CHANNEL");
return this.dmChannels;
}
get uptime() {
return this.startTime ? Date.now() - this.startTime : 0;
}
/**
* Add a user to a group channel
* @arg {String} groupID The ID of the target group
* @arg {String} userID The ID of the user to add
* @arg {Object} options The options for adding the user
* @arg {String} options.accessToken The access token of the user to add. Requires having been authorized with the `gdm.join` scope
* @arg {String} [options.nick] The nickname to give the user
* @returns {Promise}
*/
addGroupRecipient(groupID, userID, options) {
options.access_token = options.accessToken;
return this.requestHandler.request("PUT", Endpoints.CHANNEL_RECIPIENT(groupID, userID), true, options);
}
/**
* 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 member to a guild
* @arg {String} guildID The ID of the guild
* @arg {String} userID The ID of the user
* @arg {String} accessToken The access token of the user
* @arg {Object} [options] Options for adding the member
* @arg {Boolean} [options.deaf] Whether the member should be deafened
* @arg {Boolean} [options.mute] Whether the member should be muted
* @arg {String} [options.nick] The nickname of the member
* @arg {Array<String>} [options.roles] Array of role IDs to add to the member
* @returns {Promise}
*/
addGuildMember(guildID, userID, accessToken, options = {}) {
return this.requestHandler.request("PUT", Endpoints.GUILD_MEMBER(guildID, userID), true, {
access_token: accessToken,
nick: options.nick,
roles: options.roles,
mute: options.mute,
deaf: options.deaf
});
}
/**
* 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)
* @returns {Promise}
*/
addMessageReaction(channelID, messageID, reaction) {
if(reaction === decodeURI(reaction)) {
reaction = encodeURIComponent(reaction);
}
return this.requestHandler.request("PUT", Endpoints.CHANNEL_MESSAGE_REACTION_USER(channelID, messageID, reaction, "@me"), true);
}
/**
* Ban a user from a guild
* @arg {String} guildID The ID of the guild
* @arg {String} userID The ID of the user
* @arg {Number} [options.deleteMessageDays=0] [DEPRECATED] Number of days to delete messages for, between 0-7 inclusive
* @arg {Number} [options.deleteMessageSeconds=0] Number of seconds to delete messages for, between 0 and 604800 inclusive
* @arg {String} [options.reason] The reason to be displayed in audit logs
* @arg {String} [reason] [DEPRECATED] The reason to be displayed in audit logs
* @returns {Promise}
*/
banGuildMember(guildID, userID, options, reason) {
if(!options || typeof options !== "object") {
options = {
deleteMessageDays: options
};
}
if(reason !== undefined) {
options.reason = reason;
}
if(options.deleteMessageDays && !isNaN(options.deleteMessageDays) && !Object.hasOwnProperty.call(options, "deleteMessageSeconds")) {
options.deleteMessageSeconds = options.deleteMessageDays * 24 * 60 * 60;
emitDeprecation("DELETE_MESSAGE_DAYS");
this.emit("warn", "[DEPRECATED] banGuildMember() was called with the deleteMessageDays argument");
}
return this.requestHandler.request("PUT", Endpoints.GUILD_BAN(guildID, userID), true, {
delete_message_seconds: options.deleteMessageSeconds || 0,
reason: options.reason
});
}
/**
* Bulk create/edit global application commands
* @arg {Array<Object>} commands An array of command objects
* @arg {BigInt | Number | String | Permission?} commands[].defaultMemberPermissions The default permissions the user must have to use the command
* @arg {Boolean} [commands[].defaultPermission=true] [DEPRECATED] Whether the command is enabled by default when the application is added to a guild. Replaced by `defaultMemberPermissions`
* @arg {String} [commands[].description] The command description, required for `CHAT_INPUT` commands
* @arg {Object?} [commands[].descriptionLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command description
* @arg {Boolean?} [commands[].dmPermission=true] Whether the command is available in DMs with the app
* @arg {String} [commands[].id] The command ID, if known
* @arg {String} commands[].name The command name
* @arg {Object?} [commands[].nameLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command name
* @arg {Boolean} [commands[].nsfw=false] Whether the command is age-restricted
* @arg {Array<Object>} [commands[].options] The application command [options](https://discord.dev/interactions/application-commands#application-command-object-application-command-option-structure)
* @arg {Number} [commands[].type=1] The command type, either `1` for `CHAT_INPUT`, `2` for `USER` or `3` for `MESSAGE`
* @returns {Promise<Array<ApplicationCommand>>} Resolves with the overwritten application commands
*/
bulkEditCommands(commands) {
for(const command of commands) {
if(command.name !== undefined) {
if(command.type === 1 || command.type === undefined) {
command.name = command.name.toLowerCase();
if(!command.name.match(/^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$/u)) {
throw new Error("Slash Command names must match the regular expression \"^[-_\\p{L}\\p{N}\\p{sc=Deva}\\p{sc=Thai}]{1,32}$\"");
}
}
}
if(command.defaultPermission !== undefined) {
emitDeprecation("DEFAULT_PERMISSION");
this.emit("warn", "[DEPRECATED] bulkEditCommands() was called with a `defaultPermission` parameter. This has been replaced with `defaultMemberPermissions`");
command.default_permission = command.defaultPermission;
}
if(command.defaultMemberPermissions !== undefined) {
command.default_member_permissions = command.defaultMemberPermissions === null ? null : String(command.defaultMemberPermissions.allow || command.defaultMemberPermissions);
}
command.dm_permission = command.dmPermission;
}
return this.requestHandler.request("PUT", Endpoints.COMMANDS(this.application.id), true, commands).then((commands) => commands.map((command) => new ApplicationCommand(command, this)));
}
/**
* Bulk create/edit guild application commands
* @arg {String} guildID The ID of the guild
* @arg {Array<Object>} commands An array of command objects
* @arg {BigInt | Number | String | Permission?} commands[].defaultMemberPermissions The default permissions the user must have to use the command
* @arg {Boolean} [commands[].defaultPermission=true] [DEPRECATED] Whether the command is enabled by default when the application is added to a guild. Replaced by `defaultMemberPermissions`
* @arg {String} [commands[].description] The command description, required for `CHAT_INPUT` commands
* @arg {Object?} [commands[].descriptionLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command description
* @arg {String} [commands[].id] The command ID, if known
* @arg {String} commands[].name The command name
* @arg {Object?} [commands[].nameLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command name
* @arg {Boolean} [commands[].nsfw=false] Whether the command is age-restricted
* @arg {Array<Object>} [commands[].options] The application command [options](https://discord.dev/interactions/application-commands#application-command-object-application-command-option-structure)
* @arg {Number} [commands[].type=1] The command type, either `1` for `CHAT_INPUT`, `2` for `USER` or `3` for `MESSAGE`
* @returns {Promise<Array<ApplicationCommand>>} Resolves with the overwritten application commands
*/
bulkEditGuildCommands(guildID, commands) {
for(const command of commands) {
if(command.name !== undefined) {
if(command.type === 1 || command.type === undefined) {
command.name = command.name.toLowerCase();
if(!command.name.match(/^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$/u)) {
throw new Error("Slash Command names must match the regular expression \"^[-_\\p{L}\\p{N}\\p{sc=Deva}\\p{sc=Thai}]{1,32}$\"");
}
}
}
if(command.defaultMemberPermissions !== undefined) {
command.default_member_permissions = command.defaultMemberPermissions === null ? null : String(command.defaultMemberPermissions.allow || command.defaultMemberPermissions);
}
if(command.defaultPermission !== undefined) {
emitDeprecation("DEFAULT_PERMISSION");
this.emit("warn", "[DEPRECATED] bulkEditGuildCommands() was called with a `defaultPermission` parameter. This has been replaced with `defaultMemberPermissions`");
command.default_permission = command.defaultPermission;
}
}
return this.requestHandler.request("PUT", Endpoints.GUILD_COMMANDS(this.application.id, guildID), true, commands).then((commands) => commands.map((command) => new ApplicationCommand(command, this)));
}
/**
* 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);
}
/**
* Tells all shards to connect. This will call `getBotGateway()`, which is ratelimited.
* @returns {Promise} Resolves when all shards are initialized
*/
async connect() {
if(typeof this._token !== "string") {
throw new Error(`Invalid token "${this._token}"`);
}
try {
const data = await (this.options.maxShards === "auto" || (this.options.shardConcurrency === "auto" && this.bot) ? 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;
}
}
if(this.options.shardConcurrency === "auto" && data.session_start_limit && typeof data.session_start_limit.max_concurrency === "number") {
this.shards.setConcurrency(data.session_start_limit.max_concurrency);
}
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 an auto moderation rule
* @arg {String} guildID the ID of the guild to create the rule in
* @arg {Object} options The rule to create
* @arg {Array<Object>} options.actions The [actions](https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-action-object) done when the rule is violated
* @arg {Boolean} [options.enabled=false] If the rule is enabled, false by default
* @arg {Number} options.eventType The [event type](https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-event-types) for the rule
* @arg {Array<String>} [options.exemptChannels] Any channels where this rule does not apply
* @arg {Array<String>} [options.exemptRoles] Any roles to which this rule does not apply
* @arg {String} options.name The name of the rule
* @arg {Object} [options.triggerMetadata] The [trigger metadata](https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata) for the rule
* @arg {Number} options.triggerType The [trigger type](https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-types) of the rule
* @arg {String} [options.reason] The reason to be displayed in audit logs
* @returns {Promise<Object>}
*/
createAutoModerationRule(guildID, options) {
return this.requestHandler.request("POST", Endpoints.AUTO_MODERATION_RULES(guildID), true, {
actions: options.actions,
enabled: options.enabled,
event_type: options.eventType,
exempt_channels: options.exemptChannels,
exempt_roles: options.exemptRoles,
name: options.name,
trigger_metadata: options.triggerMetadata,
trigger_type: options.triggerType
});
}
/**
* 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 {Number} [type=0] The type of the channel, either 0 (text), 2 (voice), 4 (category), 5 (news), 13 (stage), or 15 (forum)
* @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 {Array<Object>} [options.availableTags] The available tags that can be applied to threads in a forum/media channel. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/channel#forum-tag-object) for object structure (forum/media channels only, max 20)
* @arg {Number} [options.bitrate] The bitrate of the channel (voice channels only)
* @arg {Number} [options.defaultAutoArchiveDuration] The default duration of newly created threads in minutes to automatically archive the thread after inactivity (60, 1440, 4320, 10080) (text/news/forum/media channels only)
* @arg {Number} [options.defaultForumLayout] The default forum layout type used to display posts in forum channels (forum channels only)
* @arg {Object} [options.defaultReactionEmoji] The emoji to show in the add reaction button on a thread in a forum/media channel (forum/media channels only)
* @arg {Number} [options.defaultSortOrder] The default sort order type used to order posts in forum/media channels (forum/media channels only)
* @arg {Number} [options.defaultThreadRateLimitPerUser] The initial rateLimitPerUser to set on newly created threads in a channel (text/forum/media 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<Object>} [options.permissionOverwrites] An array containing permission overwrite objects
* @arg {Number} [options.position] The sorting position of the channel
* @arg {Number} [options.rateLimitPerUser] The time in seconds a user has to wait before sending another message (0-21600) (does not affect bots or users with manageMessages/manageChannel permissions) (text/voice/stage/forum/media 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 | ForumChannel | TextChannel | VoiceChannel>}
*/
createChannel(guildID, name, type, reason, options = {}) {
if(typeof options === "string") { // This used to be parentID, back-compat
emitDeprecation("CREATE_CHANNEL_OPTIONS");
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
emitDeprecation("CREATE_CHANNEL_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,
available_tags: options.availableTags,
bitrate: options.bitrate,
default_auto_archive_duration: options.defaultAutoArchiveDuration,
default_forum_layout: options.defaultForumLayout,
default_reaction_emoji: options.defaultReactionEmoji,
default_sort_order: options.defaultSortOrder,
default_thread_rate_limit_per_user: options.defaultThreadRateLimitPerUser,
nsfw: options.nsfw,
parent_id: options.parentID,
permission_overwrites: options.permissionOverwrites,
position: options.position,
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 {String} [options.targetApplicationID] The target application id
* @arg {Number} [options.targetType] The type of the target application
* @arg {String} [options.targetUserID] The ID of the user whose stream should be displayed for the invite (`options.targetType` must be `1`)
* @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,
target_application_id: options.targetApplicationID,
target_type: options.targetType,
target_user_id: options.targetUserID,
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.avatar] The default avatar as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
* @arg {String} options.name The default name
* @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);
}
/**
* Create a global application command
* @arg {Object} command A command object
* @arg {BigInt | Number | String | Permission?} command.defaultMemberPermissions The default permissions the user must have to use the command
* @arg {Boolean} [command.defaultPermission=true] [DEPRECATED] Whether the command is enabled by default when the application is added to a guild. Replaced by `defaultMemberPermissions`
* @arg {String} [command.description] The command description, required for `CHAT_INPUT` commands
* @arg {Object?} [command.descriptionLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command description
* @arg {Boolean?} [command.dmPermission=true] Whether the command is available in DMs with the app
* @arg {String} command.name The command name
* @arg {Object?} [command.nameLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command name
* @arg {Boolean} [command.nsfw=false] Whether the command is age-restricted
* @arg {Array<Object>} [command.options] The application command [options](https://discord.dev/interactions/application-commands#application-command-object-application-command-option-structure)
* @arg {Number} [command.type=1] The command type, either `1` for `CHAT_INPUT`, `2` for `USER` or `3` for `MESSAGE`
* @returns {Promise<ApplicationCommand>} Resolves with the created application command
*/
createCommand(command) {
if(command.name !== undefined) {
if(command.type === 1 || command.type === undefined) {
command.name = command.name.toLowerCase();
if(!command.name.match(/^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$/u)) {
throw new Error("Slash Command names must match the regular expression \"^[-_\\p{L}\\p{N}\\p{sc=Deva}\\p{sc=Thai}]{1,32}$\"");
}
}
}
if(command.defaultMemberPermissions !== undefined) {
command.default_member_permissions = command.defaultMemberPermissions === null ? null : String(command.defaultMemberPermissions.allow || command.defaultMemberPermissions);
}
if(command.defaultPermission !== undefined) {
emitDeprecation("DEFAULT_PERMISSION");
this.emit("warn", "[DEPRECATED] createCommand() was called with a `defaultPermission` parameter. This has been replaced with `defaultMemberPermissions`");
command.default_permission = command.defaultPermission;
}
command.dm_permission = command.dmPermission;
return this.requestHandler.request("POST", Endpoints.COMMANDS(this.application.id), true, command).then((command) => new ApplicationCommand(command, this));
}
/**
* Create a group channel with other users
* @arg {Object} options The options for the group channel
* @arg {Array<String>} options.acessTokens The OAuth2 access tokens of the users to add to the group. Requires them to have been authorized with the `gdm.join` scope
* @arg {Object} [options.nicks] An object with user IDs as keys for nicknames to give the users
* @returns {Promise<GroupChannel>}
*/
createGroupChannel(options) {
return this.requestHandler.request("POST", Endpoints.USER_CHANNELS("@me"), true, {
access_tokens: options.accessTokens,
nicks: options.nicks
}).then((groupChannel) => new GroupChannel(groupChannel, 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 {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,
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 application command
* @arg {String} guildID The ID of the guild
* @arg {Object} command A command object
* @arg {BigInt | Number | String | Permission?} command.defaultMemberPermissions The default permissions the user must have to use the command
* @arg {Boolean} [command.defaultPermission=true] [DEPRECATED] Whether the command is enabled by default when the application is added to a guild. Replaced by `defaultMemberPermissions`
* @arg {String} [command.description] The command description, required for `CHAT_INPUT` commands
* @arg {Object?} [command.descriptionLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command description
* @arg {String} command.name The command name
* @arg {Object?} [command.nameLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command name
* @arg {Boolean} [command.nsfw=false] Whether the command is age-restricted
* @arg {Array<Object>} [command.options] The application command [options](https://discord.dev/interactions/application-commands#application-command-object-application-command-option-structure)
* @arg {Number} [command.type=1] The command type, either `1` for `CHAT_INPUT`, `2` for `USER` or `3` for `MESSAGE`
* @returns {Promise<ApplicationCommand>} Resolves with the created application command
*/
createGuildCommand(guildID, command) {
if(command.name !== undefined) {
if(command.type === 1 || command.type === undefined) {
command.name = command.name.toLowerCase();
if(!command.name.match(/^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$/u)) {
throw new Error("Slash Command names must match the regular expression \"^[-_\\p{L}\\p{N}\\p{sc=Deva}\\p{sc=Thai}]{1,32}$\"");
}
}
}
if(command.defaultMemberPermissions !== undefined) {
command.default_member_permissions = command.defaultMemberPermissions === null ? null : String(command.defaultMemberPermissions.allow || command.defaultMemberPermissions);
}
if(command.defaultPermission !== undefined) {
emitDeprecation("DEFAULT_PERMISSION");
this.emit("warn", "[DEPRECATED] createGuildCommand() was called with a `defaultPermission` parameter. This has been replaced with `defaultMemberPermissions`");
command.default_permission = command.defaultPermission;
}
return this.requestHandler.request("POST", Endpoints.GUILD_COMMANDS(this.application.id, guildID), true, command).then((command) => new ApplicationCommand(command, 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 guild scheduled event
* @arg {String} guildID The guild ID where the event will be created
* @arg {Object} event The event to be created
* @arg {String} [event.channelID] The channel ID of the event. This is optional if `entityType` is `3` (external)
* @arg {String} [event.description] The description of the event
* @arg {Object} [event.entityMetadata] The entity metadata for the scheduled event. This is required if `entityType` is `3` (external)
* @arg {String} [event.entityMetadata.location] Location of the event
* @arg {Number} event.entityType The [entity type](https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-entity-types) of the scheduled event
* @arg {String} [event.image] Base 64 encoded image for the scheduled event
* @arg {String} event.name The name of the event
* @arg {String} event.privacyLevel The privacy level of the event
* @arg {Date} [event.scheduledEndTime] The time when the event is scheduled to end. This is required if `entityType` is `3` (external)
* @arg {Date} event.scheduledStartTime The time the event will start
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<GuildScheduledEvent>}
*/
createGuildScheduledEvent(guildID, event, reason) {
return this.requestHandler.request("POST", Endpoints.GUILD_SCHEDULED_EVENTS(guildID), true, {
channel_id: event.channelID,
description: event.description,
entity_metadata: event.entityMetadata,
entity_type: event.entityType,
image: event.image,
name: event.name,
privacy_level: event.privacyLevel,
scheduled_end_time: event.scheduledEndTime,
scheduled_start_time: event.scheduledStartTime,
reason: reason
}).then((data) => new GuildScheduledEvent(data, this));
}
/**
* Create a guild sticker
* @arg {Object} options Sticker options
* @arg {String} [options.description] The description of the sticker
* @arg {Object} options.file A file object
* @arg {Buffer} options.file.file A buffer containing file data
* @arg {String} options.file.name What to name the file
* @arg {String} options.name The name of the sticker
* @arg {String} options.tags The Discord name of a unicode emoji representing the sticker's expression
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Object>} A sticker object
*/
createGuildSticker(guildID, options, reason) {
return this.requestHandler.request("POST", Endpoints.GUILD_STICKERS(guildID), true, {
description: options.description || "",
name: options.name,
tags: options.tags,
reason: reason
}, options.file);
}
/**
* 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));
}
/**
* Respond to the interaction with a message
* Note: Use webhooks if you have already responded with an interaction response.
* @arg {String} interactionID The interaction ID.
* @arg {String} interactionToken The interaction Token.
* @arg {Object} options The options object.
* @arg {Object} [options.data] The data to send with the response. For response types 4 and 7, see [here](https://discord.dev/interactions/receiving-and-responding#interaction-response-object-messages). For response type 8, see [here](https://discord.dev/interactions/receiving-and-responding#interaction-response-object-autocomplete). For response type 9, see [here](https://discord.dev/interactions/receiving-and-responding#interaction-response-object-modal)
* @arg {Number} options.type The response type to send. See [the official Discord API documentation entry](https://discord.dev/interactions/receiving-and-responding#interaction-response-object-interaction-callback-type) for valid types
* @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}
*/
createInteractionResponse(interactionID, interactionToken, options, file) {
if(options.data && options.data.embed) {
if(!options.data.embeds) {
options.data.embeds = [];
}
options.data.embeds.push(options.data.embed);
}
if(options.data && options.data.allowedMentions) {
options.data.allowed_mentions = this._formatAllowedMentions(options.data.allowedMentions);
}
if(file) {
options = {payload_json: options};
}
return this.requestHandler.request("POST", Endpoints.INTERACTION_RESPOND(interactionID, interactionToken), true, options, file, "/interactions/:id/:token/callback");
}
/**
* 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} [content.allowedMentions.repliedUser] Whether or not to mention the author of the message being replied to
* @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 {Array<Object>} [content.attachments] An array of attachment objects with the filename and description
* @arg {String} [content.attachments[].description] The description of the file
* @arg {String} [content.attachments[].filename] The name of the file
* @arg {Number} content.attachments[].id The index of the file
* @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
* @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 {String | Number} [content.nonce] A nonce value which will also appear in the messageCreate event
* @arg {Object} [content.poll] A poll object. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/poll#poll-object) for object structure
* @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) {
if(!content.embeds) {
content.embeds = [];
}
content.embeds.push(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) {
emitDeprecation("MESSAGE_REFERENCE");
this.emit("warn", "[DEPRECATED] content.messageReferenceID is deprecated. Use content.messageReference instead");
content.message_reference = {message_id: content.messageReferenceID};
}
if(file) {
content = {payload_json: content};
}
}
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 {String} [options.icon] The role icon as a base64 data URI
* @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} [options.unicodeEmoji] The role's unicode emoji
* @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,
icon: options.icon,
mentionable: options.mentionable,
unicode_emoji: options.unicodeEmoji,
reason: reason
}).then((role) => {
const guild = this.guilds.get(guildID);
if(guild) {
return guild.roles.add(role, guild);