@zygout/eris 0.0.0-stage → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +108 -2
  3. package/esm.mjs +72 -0
  4. package/index.d.ts +4407 -0
  5. package/index.js +75 -0
  6. package/lib/Client.js +4708 -0
  7. package/lib/Constants.d.ts +990 -0
  8. package/lib/Constants.js +1163 -0
  9. package/lib/command/Command.js +552 -0
  10. package/lib/command/CommandClient.js +460 -0
  11. package/lib/errors/DiscordHTTPError.js +63 -0
  12. package/lib/errors/DiscordRESTError.js +77 -0
  13. package/lib/gateway/Shard.js +3029 -0
  14. package/lib/gateway/ShardManager.js +164 -0
  15. package/lib/rest/Endpoints.js +172 -0
  16. package/lib/rest/RequestHandler.js +459 -0
  17. package/lib/structures/ApplicationCommand.js +125 -0
  18. package/lib/structures/AutoModerationRule.js +143 -0
  19. package/lib/structures/AutocompleteInteraction.js +80 -0
  20. package/lib/structures/Base.js +81 -0
  21. package/lib/structures/CategoryChannel.js +77 -0
  22. package/lib/structures/Channel.js +98 -0
  23. package/lib/structures/CommandInteraction.js +473 -0
  24. package/lib/structures/ComponentInteraction.js +538 -0
  25. package/lib/structures/DMChannel.js +278 -0
  26. package/lib/structures/Entitlement.js +77 -0
  27. package/lib/structures/ExtendedUser.js +46 -0
  28. package/lib/structures/ForumChannel.js +24 -0
  29. package/lib/structures/GroupChannel.js +106 -0
  30. package/lib/structures/Guild.js +1677 -0
  31. package/lib/structures/GuildAuditLogEntry.js +190 -0
  32. package/lib/structures/GuildChannel.js +128 -0
  33. package/lib/structures/GuildIntegration.js +99 -0
  34. package/lib/structures/GuildPreview.js +97 -0
  35. package/lib/structures/GuildScheduledEvent.js +176 -0
  36. package/lib/structures/GuildTemplate.js +76 -0
  37. package/lib/structures/GuildTextableChannel.js +260 -0
  38. package/lib/structures/Interaction.js +133 -0
  39. package/lib/structures/Invite.js +143 -0
  40. package/lib/structures/Lobby.js +108 -0
  41. package/lib/structures/LobbyMember.js +59 -0
  42. package/lib/structures/MediaChannel.js +216 -0
  43. package/lib/structures/Member.js +371 -0
  44. package/lib/structures/Message.js +708 -0
  45. package/lib/structures/ModalSubmitInteraction.js +478 -0
  46. package/lib/structures/NewsChannel.js +34 -0
  47. package/lib/structures/NewsThreadChannel.js +12 -0
  48. package/lib/structures/Permission.js +80 -0
  49. package/lib/structures/PermissionOverwrite.js +32 -0
  50. package/lib/structures/PingInteraction.js +39 -0
  51. package/lib/structures/PrivateThreadChannel.js +25 -0
  52. package/lib/structures/PublicThreadChannel.js +26 -0
  53. package/lib/structures/Role.js +163 -0
  54. package/lib/structures/SKU.js +80 -0
  55. package/lib/structures/SoundboardSound.js +79 -0
  56. package/lib/structures/StageChannel.js +59 -0
  57. package/lib/structures/StageInstance.js +55 -0
  58. package/lib/structures/Subscription.js +69 -0
  59. package/lib/structures/TextChannel.js +202 -0
  60. package/lib/structures/ThreadChannel.js +143 -0
  61. package/lib/structures/ThreadMember.js +59 -0
  62. package/lib/structures/UnavailableGuild.js +26 -0
  63. package/lib/structures/UnknownInteraction.js +502 -0
  64. package/lib/structures/User.js +296 -0
  65. package/lib/structures/VoiceChannel.js +166 -0
  66. package/lib/structures/VoiceState.js +84 -0
  67. package/lib/util/BrowserWebSocket.js +76 -0
  68. package/lib/util/Bucket.js +89 -0
  69. package/lib/util/Collection.js +202 -0
  70. package/lib/util/MultipartData.js +70 -0
  71. package/lib/util/Opus.js +33 -0
  72. package/lib/util/SequentialBucket.js +83 -0
  73. package/lib/util/emitDeprecation.js +26 -0
  74. package/lib/voice/Piper.js +300 -0
  75. package/lib/voice/SharedStream.js +238 -0
  76. package/lib/voice/VoiceConnection.js +1440 -0
  77. package/lib/voice/VoiceConnectionManager.js +151 -0
  78. package/lib/voice/VoiceDataStream.js +22 -0
  79. package/lib/voice/streams/BaseTransformer.js +40 -0
  80. package/lib/voice/streams/DCAOpusTransformer.js +78 -0
  81. package/lib/voice/streams/FFmpegDuplex.js +192 -0
  82. package/lib/voice/streams/FFmpegOggTransformer.js +35 -0
  83. package/lib/voice/streams/FFmpegPCMTransformer.js +26 -0
  84. package/lib/voice/streams/OggOpusTransformer.js +108 -0
  85. package/lib/voice/streams/PCMOpusTransformer.js +61 -0
  86. package/lib/voice/streams/VolumeTransformer.js +50 -0
  87. package/lib/voice/streams/WebmOpusTransformer.js +258 -0
  88. package/package.json +81 -4
package/lib/Client.js ADDED
@@ -0,0 +1,4708 @@
1
+ "use strict";
2
+
3
+ const ApplicationCommand = require("./structures/ApplicationCommand");
4
+ const AutoModerationRule = require("./structures/AutoModerationRule");
5
+ const Base = require("./structures/Base");
6
+ const Channel = require("./structures/Channel");
7
+ const Collection = require("./util/Collection");
8
+ const Constants = require("./Constants");
9
+ const emitDeprecation = require("./util/emitDeprecation");
10
+ const Endpoints = require("./rest/Endpoints");
11
+ const Entitlement = require("./structures/Entitlement");
12
+ const ExtendedUser = require("./structures/ExtendedUser");
13
+ const GroupChannel = require("./structures/GroupChannel");
14
+ const Guild = require("./structures/Guild");
15
+ const GuildAuditLogEntry = require("./structures/GuildAuditLogEntry");
16
+ const GuildIntegration = require("./structures/GuildIntegration");
17
+ const GuildPreview = require("./structures/GuildPreview");
18
+ const GuildTemplate = require("./structures/GuildTemplate");
19
+ const GuildScheduledEvent = require("./structures/GuildScheduledEvent");
20
+ const Invite = require("./structures/Invite");
21
+ const Lobby = require("./structures/Lobby");
22
+ const LobbyMember = require("./structures/LobbyMember");
23
+ const Member = require("./structures/Member");
24
+ const Message = require("./structures/Message");
25
+ const Permission = require("./structures/Permission");
26
+ const DMChannel = require("./structures/DMChannel");
27
+ const RequestHandler = require("./rest/RequestHandler");
28
+ const Role = require("./structures/Role");
29
+ const ShardManager = require("./gateway/ShardManager");
30
+ const SKU = require("./structures/SKU");
31
+ const SoundboardSound = require("./structures/SoundboardSound");
32
+ const StageInstance = require("./structures/StageInstance");
33
+ const Subscription = require("./structures/Subscription");
34
+ const ThreadMember = require("./structures/ThreadMember");
35
+ const UnavailableGuild = require("./structures/UnavailableGuild");
36
+ const User = require("./structures/User");
37
+ const VoiceConnectionManager = require("./voice/VoiceConnectionManager");
38
+ const VoiceState = require("./structures/VoiceState");
39
+
40
+ let EventEmitter;
41
+ try {
42
+ EventEmitter = require("eventemitter3");
43
+ } catch {
44
+ EventEmitter = require("events");
45
+ }
46
+ let Erlpack;
47
+ try {
48
+ Erlpack = require("erlpack");
49
+ } catch {} // eslint-disable-line no-empty
50
+ let ZlibSync;
51
+ try {
52
+ ZlibSync = require("zlib-sync");
53
+ } catch {
54
+ try {
55
+ ZlibSync = require("pako");
56
+ } catch {} // eslint-disable-line no-empty
57
+ }
58
+ const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
59
+
60
+ const COMMAND_OPTION_KEYS = {
61
+ channelTypes: "channel_types",
62
+ descriptionLocalizations: "description_localizations",
63
+ maxLength: "max_length",
64
+ maxValue: "max_value",
65
+ minLength: "min_length",
66
+ minValue: "min_value",
67
+ nameLocalizations: "name_localizations",
68
+ };
69
+ function formatCommandOption(option) {
70
+ const formatted = Object.assign({}, option);
71
+ for (const key in COMMAND_OPTION_KEYS) {
72
+ if (formatted[key] !== undefined) {
73
+ formatted[COMMAND_OPTION_KEYS[key]] = formatted[key];
74
+ delete formatted[key];
75
+ }
76
+ }
77
+ if (Array.isArray(formatted.choices)) {
78
+ formatted.choices = formatted.choices.map(formatCommandOption);
79
+ }
80
+ if (Array.isArray(formatted.options)) {
81
+ formatted.options = formatted.options.map(formatCommandOption);
82
+ }
83
+ return formatted;
84
+ }
85
+
86
+ /**
87
+ * Represents the main Eris client
88
+ * @extends EventEmitter
89
+ * @prop {Object?} application Object containing the bot application's ID and its public flags
90
+ * @prop {Boolean} bot Whether the bot user belongs to an OAuth2 application
91
+ * @prop {Object} channelGuildMap Object mapping channel IDs to guild IDs
92
+ * @prop {Object} dmChannelMap Object mapping user IDs to private channel IDs
93
+ * @prop {Collection<DMChannel>} dmChannels Collection of private channels the bot is in
94
+ * @prop {String} gatewayURL The URL for the discord gateway
95
+ * @prop {Collection<Guild>} guilds Collection of guilds the bot is in
96
+ * @prop {Object} guildShardMap Object mapping guild IDs to shard IDs
97
+ * @prop {Object} options Eris options
98
+ * @prop {RequestHandler} requestHandler The request handler the client will use
99
+ * @prop {Collection<Shard>} shards Collection of shards Eris is using
100
+ * @prop {Number} startTime Timestamp of bot ready event
101
+ * @prop {Object} threadGuildMap Object mapping thread channel IDs to guild IDs
102
+ * @prop {Collection<UnavailableGuild>} unavailableGuilds Collection of unavailable guilds the bot is in
103
+ * @prop {Number} uptime How long in milliseconds the bot has been up for
104
+ * @prop {ExtendedUser} user The bot user
105
+ * @prop {Collection<User>} users Collection of users the bot sees
106
+ * @prop {Collection<VoiceConnection>} voiceConnections Extended collection of active VoiceConnections the bot has
107
+ */
108
+ class Client extends EventEmitter {
109
+ /**
110
+ * Create a Client
111
+ * @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]
112
+ * @arg {Object} options Eris client options
113
+ * @arg {Object} [options.agent] [DEPRECATED] A HTTPS Agent used to proxy requests. This option has been moved under `options.rest`
114
+ * @arg {Object} [options.allowedMentions] A list of mentions to allow by default in createMessage/editMessage
115
+ * @arg {Boolean} [options.allowedMentions.everyone] Whether or not to allow @everyone/@here
116
+ * @arg {Boolean} [options.allowedMentions.repliedUser] Whether or not to mention the author of the message being replied to
117
+ * @arg {Boolean | Array<String>} [options.allowedMentions.roles] Whether or not to allow all role mentions, or an array of specific role mentions to allow
118
+ * @arg {Boolean | Array<String>} [options.allowedMentions.users] Whether or not to allow all user mentions, or an array of specific user mentions to allow
119
+ * @arg {Boolean} [options.autoreconnect=true] Have Eris autoreconnect when connection is lost
120
+ * @arg {Boolean} [options.compress=false] Whether to request WebSocket data to be compressed or not
121
+ * @arg {Number} [options.connectionTimeout=30000] How long in milliseconds to wait for the connection to handshake with the server
122
+ * @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"
123
+ * @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
124
+ * @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)
125
+ * @arg {Number} [options.firstShardID=0] The ID of the first shard to run for this client
126
+ * @arg {Boolean} [options.getAllUsers=false] Get all the users in every guild. Ready time will be severely delayed
127
+ * @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
128
+ * @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
129
+ * @arg {Number} [options.largeThreshold=250] The maximum number of offline users per guild during initial guild data transmission
130
+ * @arg {Number} [options.lastShardID=options.maxShards - 1] The ID of the last shard to run for this client
131
+ * @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`
132
+ * @arg {Number} [options.maxReconnectAttempts=Infinity] The maximum amount of times that the client is allowed to try to reconnect to Discord
133
+ * @arg {Number} [options.maxResumeAttempts=10] The maximum amount of times a shard can attempt to resume a session before considering that session invalid
134
+ * @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
135
+ * @arg {Number} [options.messageLimit=100] The maximum size of a channel message cache
136
+ * @arg {Boolean} [options.opusOnly=false] Whether to suppress the Opus encoder not found error or not
137
+ * @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`
138
+ * @arg {Function} [options.reconnectDelay] A function which returns how long the bot should wait until reconnecting to Discord
139
+ * @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`
140
+ * @arg {Object} [options.rest] Options for the REST request handler
141
+ * @arg {Object} [options.rest.agent] A HTTPS Agent used to proxy requests
142
+ * @arg {String} [options.rest.baseURL] The base URL to use for API requests. Defaults to `/api/v${REST_VERSION}`
143
+ * @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
144
+ * @arg {Boolean} [options.rest.disableLatencyCompensation=false] Whether to disable the built-in latency compensator or not
145
+ * @arg {String} [options.rest.domain="discord.com"] The domain to use for API requests
146
+ * @arg {Number} [options.rest.latencyThreshold=30000] The average request latency at which Eris will start emitting latency errors
147
+ * @arg {Number} [options.rest.ratelimiterOffset=0] A number of milliseconds to offset the ratelimit timing calculations by
148
+ * @arg {Number} [options.rest.requestTimeout=15000] A number of milliseconds before REST requests are considered timed out
149
+ * @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
150
+ * @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
151
+ * @arg {Number | String} [options.shardConcurrency="auto"] The number of shards that can start simultaneously. If "auto" Eris will use Discord's recommended shard concurrency
152
+ * @arg {Object} [options.ws] An object of WebSocket options to pass to the shard WebSocket constructors
153
+ */
154
+ constructor(token, options) {
155
+ super();
156
+
157
+ this.options = Object.assign({
158
+ allowedMentions: {
159
+ users: true,
160
+ roles: true,
161
+ },
162
+ autoreconnect: true,
163
+ compress: false,
164
+ connectionTimeout: 30000,
165
+ defaultImageFormat: "jpg",
166
+ defaultImageSize: 128,
167
+ disableEvents: {},
168
+ firstShardID: 0,
169
+ getAllUsers: false,
170
+ guildCreateTimeout: 2000,
171
+ intents: Constants.Intents.allNonPrivileged,
172
+ largeThreshold: 250,
173
+ maxReconnectAttempts: Infinity,
174
+ maxResumeAttempts: 10,
175
+ maxShards: 1,
176
+ messageLimit: 100,
177
+ opusOnly: false,
178
+ requestTimeout: 15000,
179
+ rest: {},
180
+ restMode: false,
181
+ seedVoiceConnections: false,
182
+ shardConcurrency: "auto",
183
+ ws: {},
184
+ reconnectDelay: (lastDelay, attempts) => Math.pow(attempts + 1, 0.7) * 20000,
185
+ }, options);
186
+ this.options.allowedMentions = this._formatAllowedMentions(this.options.allowedMentions);
187
+ if (this.options.lastShardID === undefined && this.options.maxShards !== "auto") {
188
+ this.options.lastShardID = this.options.maxShards - 1;
189
+ }
190
+ if (typeof window !== "undefined" || !ZlibSync) {
191
+ this.options.compress = false; // zlib does not like Blobs, Pako is not here
192
+ }
193
+ if (!Constants.ImageFormats.includes(this.options.defaultImageFormat.toLowerCase())) {
194
+ throw new TypeError(`Invalid default image format: ${this.options.defaultImageFormat}`);
195
+ }
196
+ const defaultImageSize = this.options.defaultImageSize;
197
+ if (defaultImageSize < Constants.ImageSizeBoundaries.MINIMUM || defaultImageSize > Constants.ImageSizeBoundaries.MAXIMUM || (defaultImageSize & (defaultImageSize - 1))) {
198
+ throw new TypeError(`Invalid default image size: ${defaultImageSize}`);
199
+ }
200
+ // Set HTTP Agent on Websockets if not already set
201
+ if (this.options.agent && !(this.options.ws && this.options.ws.agent)) {
202
+ this.options.ws = this.options.ws || {};
203
+ this.options.ws.agent = this.options.agent;
204
+ }
205
+
206
+ if (this.options.hasOwnProperty("intents")) {
207
+ // Resolve intents option to the proper integer
208
+ if (Array.isArray(this.options.intents)) {
209
+ let bitmask = 0;
210
+ for (const intent of this.options.intents) {
211
+ if (typeof intent === "number") {
212
+ bitmask |= intent;
213
+ } else if (Constants.Intents[intent]) {
214
+ bitmask |= Constants.Intents[intent];
215
+ } else {
216
+ this.emit("warn", `Unknown intent: ${intent}`);
217
+ }
218
+ }
219
+ this.options.intents = bitmask;
220
+ }
221
+
222
+ // Ensure requesting all guild members isn't destined to fail
223
+ if (this.options.getAllUsers && !(this.options.intents & Constants.Intents.guildMembers)) {
224
+ throw new Error("Cannot request all members without guildMembers intent");
225
+ }
226
+ }
227
+
228
+ Object.defineProperty(this, "_token", {
229
+ configurable: true,
230
+ enumerable: false,
231
+ writable: true,
232
+ value: token,
233
+ });
234
+
235
+ this.requestHandler = new RequestHandler(this, this.options.rest);
236
+ delete this.options.rest;
237
+
238
+ const shardManagerOptions = {};
239
+ if (typeof this.options.shardConcurrency === "number") {
240
+ shardManagerOptions.concurrency = this.options.shardConcurrency;
241
+ }
242
+ this.shards = new ShardManager(this, shardManagerOptions);
243
+
244
+ this.ready = false;
245
+ this.bot = this._token.startsWith("Bot ");
246
+ this.startTime = 0;
247
+ this.lastConnect = 0;
248
+ this.channelGuildMap = {};
249
+ this.threadGuildMap = {};
250
+ this.guilds = new Collection(Guild);
251
+ this.dmChannelMap = {};
252
+ this.dmChannels = new Collection(DMChannel);
253
+ this.guildShardMap = {};
254
+ this.unavailableGuilds = new Collection(UnavailableGuild);
255
+ this.users = new Collection(User);
256
+ this.presence = {
257
+ activities: null,
258
+ afk: false,
259
+ since: null,
260
+ status: "offline",
261
+ };
262
+ this.voiceConnections = new VoiceConnectionManager();
263
+
264
+ this.connect = this.connect.bind(this);
265
+ this.lastReconnectDelay = 0;
266
+ this.reconnectAttempts = 0;
267
+ }
268
+
269
+ get privateChannelMap() {
270
+ emitDeprecation("PRIVATE_CHANNEL");
271
+ return this.dmChannelMap;
272
+ }
273
+
274
+ get privateChannels() {
275
+ emitDeprecation("PRIVATE_CHANNEL");
276
+ return this.dmChannels;
277
+ }
278
+
279
+ get uptime() {
280
+ return this.startTime ? Date.now() - this.startTime : 0;
281
+ }
282
+
283
+ /**
284
+ * Add a user to a group channel
285
+ * @arg {String} groupID The ID of the target group
286
+ * @arg {String} userID The ID of the user to add
287
+ * @arg {Object} options The options for adding the user
288
+ * @arg {String} options.accessToken The access token of the user to add. Requires having been authorized with the `gdm.join` scope
289
+ * @arg {String} [options.nick] The nickname to give the user
290
+ * @returns {Promise}
291
+ */
292
+ addGroupRecipient(groupID, userID, options) {
293
+ options.access_token = options.accessToken;
294
+ return this.requestHandler.request("PUT", Endpoints.CHANNEL_RECIPIENT(groupID, userID), true, options);
295
+ }
296
+
297
+ /**
298
+ * Add a guild discovery subcategory
299
+ * @arg {String} guildID The ID of the guild
300
+ * @arg {String} categoryID The ID of the discovery category
301
+ * @arg {String} [reason] The reason to be displayed in audit logs
302
+ * @returns {Promise<Object>}
303
+ */
304
+ addGuildDiscoverySubcategory(guildID, categoryID, reason) {
305
+ return this.requestHandler.request("POST", Endpoints.GUILD_DISCOVERY_CATEGORY(guildID, categoryID), true, { reason });
306
+ }
307
+
308
+ /**
309
+ * Add a member to a guild
310
+ * @arg {String} guildID The ID of the guild
311
+ * @arg {String} userID The ID of the user
312
+ * @arg {String} accessToken The access token of the user
313
+ * @arg {Object} [options] Options for adding the member
314
+ * @arg {Boolean} [options.deaf] Whether the member should be deafened
315
+ * @arg {Boolean} [options.mute] Whether the member should be muted
316
+ * @arg {String} [options.nick] The nickname of the member
317
+ * @arg {Array<String>} [options.roles] Array of role IDs to add to the member
318
+ * @returns {Promise}
319
+ */
320
+ addGuildMember(guildID, userID, accessToken, options = {}) {
321
+ return this.requestHandler.request("PUT", Endpoints.GUILD_MEMBER(guildID, userID), true, {
322
+ access_token: accessToken,
323
+ nick: options.nick,
324
+ roles: options.roles,
325
+ mute: options.mute,
326
+ deaf: options.deaf,
327
+ });
328
+ }
329
+
330
+ /**
331
+ * Add a role to a guild member
332
+ * @arg {String} guildID The ID of the guild
333
+ * @arg {String} memberID The ID of the member
334
+ * @arg {String} roleID The ID of the role
335
+ * @arg {String} [reason] The reason to be displayed in audit logs
336
+ * @returns {Promise}
337
+ */
338
+ addGuildMemberRole(guildID, memberID, roleID, reason) {
339
+ return this.requestHandler.request("PUT", Endpoints.GUILD_MEMBER_ROLE(guildID, memberID, roleID), true, {
340
+ reason,
341
+ });
342
+ }
343
+
344
+ /**
345
+ * Add a target user to an invite. Only the target users of an invite can see and accept it
346
+ * @arg {String} inviteID The code of the invite
347
+ * @arg {String} userID The ID of the user to add
348
+ * @returns {Promise}
349
+ */
350
+ addInviteTargetUser(inviteID, userID) {
351
+ return this.requestHandler.request("PUT", Endpoints.INVITE_TARGET_USER(inviteID, userID), true);
352
+ }
353
+
354
+ /**
355
+ * Add a user to a lobby, or update them if they are already a member
356
+ * @arg {String} lobbyID The ID of the lobby
357
+ * @arg {String} userID The ID of the user
358
+ * @arg {Object} [options] The properties of the member
359
+ * @arg {String?} [options.additionalName] An additional display name for the member, such as an in-game character name (1-80 characters). Omit it to keep the current one, or set it to `null` to remove it
360
+ * @arg {Number} [options.flags] The lobby member flags of the member. See `Constants.LobbyMemberFlags`
361
+ * @arg {Object<String, String>?} [options.metadata] The metadata of the member, as key/value pairs (1000 characters in total at most)
362
+ * @returns {Promise<LobbyMember>}
363
+ */
364
+ addLobbyMember(lobbyID, userID, options = {}) {
365
+ return this.requestHandler.request("PUT", Endpoints.LOBBY_MEMBER(lobbyID, userID), true, this._formatLobbyMember(options)).then((member) => new LobbyMember(member, this, lobbyID));
366
+ }
367
+
368
+ /**
369
+ * Add a reaction to a message
370
+ * @arg {String} channelID The ID of the channel
371
+ * @arg {String} messageID The ID of the message
372
+ * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
373
+ * @returns {Promise}
374
+ */
375
+ addMessageReaction(channelID, messageID, reaction) {
376
+ if (reaction === decodeURI(reaction)) {
377
+ reaction = encodeURIComponent(reaction);
378
+ }
379
+ return this.requestHandler.request("PUT", Endpoints.CHANNEL_MESSAGE_REACTION_USER(channelID, messageID, reaction, "@me"), true);
380
+ }
381
+
382
+ /**
383
+ * Ban a user from a guild
384
+ * @arg {String} guildID The ID of the guild
385
+ * @arg {String} userID The ID of the user
386
+ * @arg {Number} [options.deleteMessageDays=0] [DEPRECATED] Number of days to delete messages for, between 0-7 inclusive
387
+ * @arg {Number} [options.deleteMessageSeconds=0] Number of seconds to delete messages for, between 0 and 604800 inclusive
388
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
389
+ * @arg {String} [reason] [DEPRECATED] The reason to be displayed in audit logs
390
+ * @returns {Promise}
391
+ */
392
+ banGuildMember(guildID, userID, options, reason) {
393
+ if (!options || typeof options !== "object") {
394
+ options = {
395
+ deleteMessageDays: options,
396
+ };
397
+ }
398
+ if (reason !== undefined) {
399
+ options.reason = reason;
400
+ }
401
+ if (options.deleteMessageDays && !isNaN(options.deleteMessageDays) && !Object.hasOwnProperty.call(options, "deleteMessageSeconds")) {
402
+ options.deleteMessageSeconds = options.deleteMessageDays * 24 * 60 * 60;
403
+ emitDeprecation("DELETE_MESSAGE_DAYS");
404
+ this.emit("warn", "[DEPRECATED] banGuildMember() was called with the deleteMessageDays argument");
405
+ }
406
+ return this.requestHandler.request("PUT", Endpoints.GUILD_BAN(guildID, userID), true, {
407
+ delete_message_seconds: options.deleteMessageSeconds || 0,
408
+ reason: options.reason,
409
+ });
410
+ }
411
+
412
+ /**
413
+ * Add multiple target users to an invite
414
+ * @arg {String} inviteID The code of the invite
415
+ * @arg {Array<String>} userIDs The IDs of the users to add (max 1000)
416
+ * @returns {Promise}
417
+ */
418
+ bulkAddInviteTargetUsers(inviteID, userIDs) {
419
+ return this.requestHandler.request("POST", Endpoints.INVITE_TARGET_USERS_BULK_ADD(inviteID), true, {
420
+ user_ids: userIDs,
421
+ });
422
+ }
423
+
424
+ /**
425
+ * Bulk ban users from a guild - Note: Requires both BAN_MEMBERS and MANAGE_GUILD permissions
426
+ * @arg {String} guildID The ID of the guild
427
+ * @arg {Object} options Options for banning the users
428
+ * @arg {Array<String>} options.userIDs Array of user IDs to ban
429
+ * @arg {Number} [options.deleteMessageSeconds=0] Number of seconds to delete messages for each user, between 0 and 604800 inclusive
430
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
431
+ * @returns {Promise<Object>} An object with 2 arrays - `banned_users` with the IDs of the successfully banned users, and `failed_users` with the IDs of any users who could not be banned or were already banned
432
+ */
433
+ bulkBanGuildMembers(guildID, options) {
434
+ return this.requestHandler.request("POST", Endpoints.GUILD_BULK_BAN(guildID), true, {
435
+ user_ids: options.userIDs,
436
+ delete_message_seconds: options.deleteMessageSeconds || 0,
437
+ reason: options.reason,
438
+ });
439
+ }
440
+
441
+ /**
442
+ * Bulk create/edit global application commands
443
+ * @arg {Array<Object>} commands An array of command objects
444
+ * @arg {Array<Number>} [commands[].contexts] The interaction contexts where the command can be used, `0` for guilds, `1` for the app's bot DM and `2` for group DMs and other DMs. See `Constants.InteractionContextTypes`
445
+ * @arg {BigInt | Number | String | Permission?} commands[].defaultMemberPermissions The default permissions the user must have to use the command
446
+ * @arg {Boolean} [commands[].defaultPermission=true] [DEPRECATED] Whether the command is enabled by default when the application is added to a guild. Replaced by `defaultMemberPermissions`
447
+ * @arg {String} [commands[].description] The command description, required for `CHAT_INPUT` commands
448
+ * @arg {Object?} [commands[].descriptionLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command description
449
+ * @arg {Boolean?} [commands[].dmPermission=true] [DEPRECATED] Whether the command is available in DMs with the app. Use `contexts` instead
450
+ * @arg {Number} [commands[].handler] How the interaction is handled, `1` for the app (`APP_HANDLER`) or `2` for Discord launching the Activity (`DISCORD_LAUNCH_ACTIVITY`). `PRIMARY_ENTRY_POINT` commands only. See `Constants.EntryPointCommandHandlerTypes`
451
+ * @arg {String} [commands[].id] The command ID, if known
452
+ * @arg {Array<Number>} [commands[].integrationTypes] The installation contexts where the command is available, `0` for guild installs and `1` for user installs. See `Constants.ApplicationIntegrationTypes`
453
+ * @arg {String} commands[].name The command name
454
+ * @arg {Object?} [commands[].nameLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command name
455
+ * @arg {Boolean} [commands[].nsfw=false] Whether the command is age-restricted
456
+ * @arg {Array<Object>} [commands[].options] The application command [options](https://discord.dev/interactions/application-commands#application-command-object-application-command-option-structure)
457
+ * @arg {Number} [commands[].type=1] The command type, either `1` for `CHAT_INPUT`, `2` for `USER`, `3` for `MESSAGE` or `4` for `PRIMARY_ENTRY_POINT`
458
+ * @returns {Promise<Array<ApplicationCommand>>} Resolves with the overwritten application commands
459
+ */
460
+ bulkEditCommands(commands) {
461
+ return this.requestHandler.request("PUT", Endpoints.COMMANDS(this.application.id), true, commands.map((command) => this._formatCommand(command, "bulkEditCommands"))).then((commands) => commands.map((command) => new ApplicationCommand(command, this)));
462
+ }
463
+
464
+ /**
465
+ * Bulk create/edit guild application commands
466
+ * @arg {String} guildID The ID of the guild
467
+ * @arg {Array<Object>} commands An array of command objects
468
+ * @arg {BigInt | Number | String | Permission?} commands[].defaultMemberPermissions The default permissions the user must have to use the command
469
+ * @arg {Boolean} [commands[].defaultPermission=true] [DEPRECATED] Whether the command is enabled by default when the application is added to a guild. Replaced by `defaultMemberPermissions`
470
+ * @arg {String} [commands[].description] The command description, required for `CHAT_INPUT` commands
471
+ * @arg {Object?} [commands[].descriptionLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command description
472
+ * @arg {String} [commands[].id] The command ID, if known
473
+ * @arg {String} commands[].name The command name
474
+ * @arg {Object?} [commands[].nameLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command name
475
+ * @arg {Boolean} [commands[].nsfw=false] Whether the command is age-restricted
476
+ * @arg {Array<Object>} [commands[].options] The application command [options](https://discord.dev/interactions/application-commands#application-command-object-application-command-option-structure)
477
+ * @arg {Number} [commands[].type=1] The command type, either `1` for `CHAT_INPUT`, `2` for `USER` or `3` for `MESSAGE`
478
+ * @returns {Promise<Array<ApplicationCommand>>} Resolves with the overwritten application commands
479
+ */
480
+ bulkEditGuildCommands(guildID, commands) {
481
+ return this.requestHandler.request("PUT", Endpoints.GUILD_COMMANDS(this.application.id, guildID), true, commands.map((command) => this._formatCommand(command, "bulkEditGuildCommands"))).then((commands) => commands.map((command) => new ApplicationCommand(command, this)));
482
+ }
483
+
484
+ /**
485
+ * Add, update or remove up to 25 members of a lobby. Members are added if they are not in the lobby yet, and updated otherwise
486
+ * @arg {String} lobbyID The ID of the lobby
487
+ * @arg {Array<Object>} members The members to add, update or remove (between 1 and 25)
488
+ * @arg {String?} [members[].additionalName] An additional display name for the member, such as an in-game character name (1-80 characters). Omit it to keep the current one, or set it to `null` to remove it
489
+ * @arg {Number} [members[].flags] The lobby member flags of the member. See `Constants.LobbyMemberFlags`
490
+ * @arg {Object<String, String>?} [members[].metadata] The metadata of the member, as key/value pairs (1000 characters in total at most)
491
+ * @arg {String} members[].id The ID of the user
492
+ * @arg {Boolean} [members[].removeMember] Whether to remove the user from the lobby instead
493
+ * @returns {Promise<Array<LobbyMember>>} The added and updated members. Users who cannot join the lobby are left out
494
+ */
495
+ bulkEditLobbyMembers(lobbyID, members) {
496
+ return this.requestHandler.request("POST", Endpoints.LOBBY_MEMBERS_BULK(lobbyID), true, members.map((member) => this._formatLobbyMember(member))).then((members) => members.map((member) => new LobbyMember(member, this, lobbyID)));
497
+ }
498
+
499
+ /**
500
+ * Remove multiple target users from an invite
501
+ * @arg {String} inviteID The code of the invite
502
+ * @arg {Array<String>} userIDs The IDs of the users to remove (max 1000)
503
+ * @returns {Promise}
504
+ */
505
+ bulkRemoveInviteTargetUsers(inviteID, userIDs) {
506
+ return this.requestHandler.request("POST", Endpoints.INVITE_TARGET_USERS_BULK_DELETE(inviteID), true, {
507
+ user_ids: userIDs,
508
+ });
509
+ }
510
+
511
+ /**
512
+ * Closes a voice connection with a guild ID
513
+ * @arg {String} guildID The ID of the guild
514
+ */
515
+ closeVoiceConnection(guildID) {
516
+ this.shards.get(this.guildShardMap[guildID] || 0).sendWS(Constants.GatewayOPCodes.VOICE_STATE_UPDATE, {
517
+ guild_id: guildID || null,
518
+ channel_id: null,
519
+ self_mute: false,
520
+ self_deaf: false,
521
+ });
522
+ this.voiceConnections.leave(guildID);
523
+ }
524
+
525
+ /**
526
+ * Tells all shards to connect. This will call `getBotGateway()`, which is ratelimited.
527
+ * With `autoreconnect`, a failed gateway request is retried, except when Discord refuses the token
528
+ * @returns {Promise} Resolves when all shards are initialized, rejects when the token is invalid
529
+ */
530
+ async connect() {
531
+ if (typeof this._token !== "string") {
532
+ throw new Error(`Invalid token "${this._token}"`);
533
+ }
534
+ try {
535
+ const data = await (this.options.maxShards === "auto" || (this.options.shardConcurrency === "auto" && this.bot) ? this.getBotGateway() : this.getGateway());
536
+ if (!data.url || (this.options.maxShards === "auto" && !data.shards)) {
537
+ throw new Error("Invalid response from gateway REST call");
538
+ }
539
+ if (data.url.includes("?")) {
540
+ data.url = data.url.substring(0, data.url.indexOf("?"));
541
+ }
542
+ if (!data.url.endsWith("/")) {
543
+ data.url += "/";
544
+ }
545
+ this.gatewayURL = `${data.url}?v=${Constants.GATEWAY_VERSION}&encoding=${Erlpack ? "etf" : "json"}`;
546
+
547
+ if (this.options.compress) {
548
+ this.gatewayURL += "&compress=zlib-stream";
549
+ }
550
+
551
+ if (this.options.maxShards === "auto") {
552
+ if (!data.shards) {
553
+ throw new Error("Failed to autoshard due to lack of data from Discord.");
554
+ }
555
+ this.options.maxShards = data.shards;
556
+ if (this.options.lastShardID === undefined) {
557
+ this.options.lastShardID = data.shards - 1;
558
+ }
559
+ }
560
+
561
+ if (this.options.shardConcurrency === "auto" && data.session_start_limit && typeof data.session_start_limit.max_concurrency === "number") {
562
+ this.shards.setConcurrency(data.session_start_limit.max_concurrency);
563
+ }
564
+
565
+ for (let i = this.options.firstShardID; i <= this.options.lastShardID; ++i) {
566
+ this.shards.spawn(i);
567
+ }
568
+ } catch (err) {
569
+ // A refused token stays refused, so retrying would never connect
570
+ if (!this.options.autoreconnect || (err.res && err.res.statusCode === 401)) {
571
+ throw err;
572
+ }
573
+ const reconnectDelay = this.options.reconnectDelay(this.lastReconnectDelay, this.reconnectAttempts);
574
+ this.emit("debug", `Failed to get the gateway, retrying in ${reconnectDelay}ms: ${err.message}`);
575
+ await sleep(reconnectDelay);
576
+ this.lastReconnectDelay = reconnectDelay;
577
+ this.reconnectAttempts = this.reconnectAttempts + 1;
578
+ return this.connect();
579
+ }
580
+ }
581
+
582
+ /**
583
+ * Mark an entitlement as consumed. Only available for one-time purchase consumable SKUs
584
+ * @arg {String} entitlementID The ID of the entitlement
585
+ * @returns {Promise}
586
+ */
587
+ consumeEntitlement(entitlementID) {
588
+ return this.requestHandler.request("POST", Endpoints.ENTITLEMENT_CONSUME(this.application.id, entitlementID), true);
589
+ }
590
+
591
+ /**
592
+ * Create an auto moderation rule
593
+ * @arg {String} guildID the ID of the guild to create the rule in
594
+ * @arg {Object} options The rule to create
595
+ * @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. Their `metadata` takes camelCase keys, such as `durationSeconds`
596
+ * @arg {Boolean} [options.enabled=false] If the rule is enabled, false by default
597
+ * @arg {Number} options.eventType The [event type](https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-event-types) for the rule
598
+ * @arg {Array<String>} [options.exemptChannels] Any channels where this rule does not apply
599
+ * @arg {Array<String>} [options.exemptRoles] Any roles to which this rule does not apply
600
+ * @arg {String} options.name The name of the rule
601
+ * @arg {Object} [options.triggerMetadata] The [trigger metadata](https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata) for the rule, with camelCase keys such as `keywordFilter`
602
+ * @arg {Number} options.triggerType The [trigger type](https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-types) of the rule
603
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
604
+ * @returns {Promise<AutoModerationRule>}
605
+ */
606
+ createAutoModerationRule(guildID, options) {
607
+ return this.requestHandler.request("POST", Endpoints.AUTO_MODERATION_RULES(guildID), true, this._formatAutoModerationRule(options)).then((rule) => new AutoModerationRule(rule, this));
608
+ }
609
+
610
+ /**
611
+ * Create a channel in a guild
612
+ * @arg {String} guildID The ID of the guild to create the channel in
613
+ * @arg {String} name The name of the channel
614
+ * @arg {Number} [type=0] The type of the channel, either 0 (text), 2 (voice), 4 (category), 5 (news), 13 (stage), or 15 (forum)
615
+ * @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.
616
+ * @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)
617
+ * @arg {Number} [options.bitrate] The bitrate of the channel (voice channels only)
618
+ * @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)
619
+ * @arg {Number} [options.defaultForumLayout] The default forum layout type used to display posts in forum channels (forum channels only)
620
+ * @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)
621
+ * @arg {Number} [options.defaultSortOrder] The default sort order type used to order posts in forum/media channels (forum/media channels only)
622
+ * @arg {Number} [options.defaultThreadRateLimitPerUser] The initial rateLimitPerUser to set on newly created threads in a channel (text/forum/media channels only)
623
+ * @arg {Boolean} [options.nsfw] The nsfw status of the channel
624
+ * @arg {String?} [options.parentID] The ID of the parent category channel for this channel
625
+ * @arg {Array<Object>} [options.permissionOverwrites] An array containing permission overwrite objects
626
+ * @arg {Number} [options.position] The sorting position of the channel
627
+ * @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)
628
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
629
+ * @arg {String} [options.topic] The topic of the channel (text channels only)
630
+ * @arg {Number} [options.userLimit] The channel user limit (voice channels only)
631
+ * @returns {Promise<CategoryChannel | ForumChannel | TextChannel | VoiceChannel>}
632
+ */
633
+ createChannel(guildID, name, type, reason, options = {}) {
634
+ if (typeof options === "string") { // This used to be parentID, back-compat
635
+ emitDeprecation("CREATE_CHANNEL_OPTIONS");
636
+ this.emit("warn", "[DEPRECATED] createChannel() was called with a string `options` argument");
637
+ options = {
638
+ parentID: options,
639
+ };
640
+ }
641
+ if (typeof reason === "string") { // Reason is deprecated, will be folded into options
642
+ emitDeprecation("CREATE_CHANNEL_OPTIONS");
643
+ this.emit("warn", "[DEPRECATED] createChannel() was called with a string `reason` argument");
644
+ options.reason = reason;
645
+ reason = undefined;
646
+ } else if (typeof reason === "object" && reason !== null) {
647
+ options = reason;
648
+ reason = undefined;
649
+ }
650
+ return this.requestHandler.request("POST", Endpoints.GUILD_CHANNELS(guildID), true, {
651
+ name: name,
652
+ type: type,
653
+ available_tags: options.availableTags,
654
+ bitrate: options.bitrate,
655
+ default_auto_archive_duration: options.defaultAutoArchiveDuration,
656
+ default_forum_layout: options.defaultForumLayout,
657
+ default_reaction_emoji: options.defaultReactionEmoji,
658
+ default_sort_order: options.defaultSortOrder,
659
+ default_thread_rate_limit_per_user: options.defaultThreadRateLimitPerUser,
660
+ nsfw: options.nsfw,
661
+ parent_id: options.parentID,
662
+ permission_overwrites: options.permissionOverwrites,
663
+ position: options.position,
664
+ rate_limit_per_user: options.rateLimitPerUser,
665
+ reason: options.reason,
666
+ topic: options.topic,
667
+ user_limit: options.userLimit,
668
+ }).then((channel) => Channel.from(channel, this));
669
+ }
670
+
671
+ /**
672
+ * Create an invite for a channel
673
+ * @arg {String} channelID The ID of the channel
674
+ * @arg {Object} [options] Invite generation options
675
+ * @arg {Number} [options.maxAge] How long the invite should last in seconds
676
+ * @arg {Number} [options.maxUses] How many uses the invite should last for
677
+ * @arg {Array<String>} [options.roleIDs] The IDs of the roles given to the users that accept the invite. Requires the `manageRoles` permission
678
+ * @arg {String} [options.targetApplicationID] The target application id
679
+ * @arg {Number} [options.targetType] The type of the target application
680
+ * @arg {String} [options.targetUserID] The ID of the user whose stream should be displayed for the invite (`options.targetType` must be `1`)
681
+ * @arg {Array<String>} [options.targetUserIDs] The IDs of the only users able to see and accept the invite (max 1000). Mutually exclusive with `options.targetUsersFile`
682
+ * @arg {Buffer} [options.targetUsersFile] A CSV file with a single column of user IDs of the only users able to see and accept the invite. Mutually exclusive with `options.targetUserIDs`
683
+ * @arg {Boolean} [options.temporary] Whether the invite grants temporary membership or not
684
+ * @arg {Boolean} [options.unique] Whether the invite is unique or not
685
+ * @arg {String} [reason] The reason to be displayed in audit logs
686
+ * @returns {Promise<Invite>}
687
+ */
688
+ createChannelInvite(channelID, options = {}, reason) {
689
+ const payload = {
690
+ max_age: options.maxAge,
691
+ max_uses: options.maxUses,
692
+ role_ids: options.roleIDs,
693
+ target_application_id: options.targetApplicationID,
694
+ target_type: options.targetType,
695
+ target_user_id: options.targetUserID,
696
+ target_user_ids: options.targetUserIDs,
697
+ temporary: options.temporary,
698
+ unique: options.unique,
699
+ };
700
+ if (options.targetUsersFile) {
701
+ return this.requestHandler.request("POST", Endpoints.CHANNEL_INVITES(channelID), true, {
702
+ payload_json: payload,
703
+ reason: reason,
704
+ }, this._formatTargetUsersFile(options.targetUsersFile)).then((invite) => new Invite(invite, this));
705
+ }
706
+ payload.reason = reason;
707
+ return this.requestHandler.request("POST", Endpoints.CHANNEL_INVITES(channelID), true, payload).then((invite) => new Invite(invite, this));
708
+ }
709
+
710
+ /**
711
+ * Create a channel webhook
712
+ * @arg {String} channelID The ID of the channel to create the webhook in
713
+ * @arg {Object} options Webhook options
714
+ * @arg {String?} [options.avatar] The default avatar as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
715
+ * @arg {String} options.name The default name
716
+ * @arg {String} [reason] The reason to be displayed in audit logs
717
+ * @returns {Promise<Object>} Resolves with a webhook object
718
+ */
719
+ createChannelWebhook(channelID, options, reason) {
720
+ options.reason = reason;
721
+ return this.requestHandler.request("POST", Endpoints.CHANNEL_WEBHOOKS(channelID), true, options);
722
+ }
723
+
724
+ /**
725
+ * Create a global application command
726
+ * @arg {Object} command A command object
727
+ * @arg {Array<Number>} [command.contexts] The interaction contexts where the command can be used, `0` for guilds, `1` for the app's bot DM and `2` for group DMs and other DMs. See `Constants.InteractionContextTypes`
728
+ * @arg {BigInt | Number | String | Permission?} command.defaultMemberPermissions The default permissions the user must have to use the command
729
+ * @arg {Boolean} [command.defaultPermission=true] [DEPRECATED] Whether the command is enabled by default when the application is added to a guild. Replaced by `defaultMemberPermissions`
730
+ * @arg {String} [command.description] The command description, required for `CHAT_INPUT` commands
731
+ * @arg {Object?} [command.descriptionLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command description
732
+ * @arg {Boolean?} [command.dmPermission=true] [DEPRECATED] Whether the command is available in DMs with the app. Use `contexts` instead
733
+ * @arg {Number} [command.handler] How the interaction is handled, `1` for the app (`APP_HANDLER`) or `2` for Discord launching the Activity (`DISCORD_LAUNCH_ACTIVITY`). `PRIMARY_ENTRY_POINT` commands only. See `Constants.EntryPointCommandHandlerTypes`
734
+ * @arg {Array<Number>} [command.integrationTypes] The installation contexts where the command is available, `0` for guild installs and `1` for user installs. See `Constants.ApplicationIntegrationTypes`
735
+ * @arg {String} command.name The command name
736
+ * @arg {Object?} [command.nameLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command name
737
+ * @arg {Boolean} [command.nsfw=false] Whether the command is age-restricted
738
+ * @arg {Array<Object>} [command.options] The application command [options](https://discord.dev/interactions/application-commands#application-command-object-application-command-option-structure)
739
+ * @arg {Number} [command.type=1] The command type, either `1` for `CHAT_INPUT`, `2` for `USER`, `3` for `MESSAGE` or `4` for `PRIMARY_ENTRY_POINT`
740
+ * @returns {Promise<ApplicationCommand>} Resolves with the created application command
741
+ */
742
+ createCommand(command) {
743
+ return this.requestHandler.request("POST", Endpoints.COMMANDS(this.application.id), true, this._formatCommand(command, "createCommand")).then((command) => new ApplicationCommand(command, this));
744
+ }
745
+
746
+ /**
747
+ * Create an emoji for this application
748
+ * @arg {Object} options Emoji options
749
+ * @arg {String} options.image The base 64 encoded string
750
+ * @arg {String} options.name The name of emoji
751
+ * @returns {Promise<Object>} An emoji object
752
+ */
753
+ createEmoji(options) {
754
+ return this.requestHandler.request("POST", Endpoints.APPLICATION_EMOJIS(this.application.id), true, options);
755
+ }
756
+
757
+ /**
758
+ * Create a group channel with other users
759
+ * @arg {Object} options The options for the group channel
760
+ * @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
761
+ * @arg {Object} [options.nicks] An object with user IDs as keys for nicknames to give the users
762
+ * @returns {Promise<GroupChannel>}
763
+ */
764
+ createGroupChannel(options) {
765
+ return this.requestHandler.request("POST", Endpoints.USER_CHANNELS("@me"), true, {
766
+ access_tokens: options.accessTokens,
767
+ nicks: options.nicks,
768
+ }).then((groupChannel) => new GroupChannel(groupChannel, this));
769
+ }
770
+
771
+ /**
772
+ * Create a guild application command
773
+ * @arg {String} guildID The ID of the guild
774
+ * @arg {Object} command A command object
775
+ * @arg {BigInt | Number | String | Permission?} command.defaultMemberPermissions The default permissions the user must have to use the command
776
+ * @arg {Boolean} [command.defaultPermission=true] [DEPRECATED] Whether the command is enabled by default when the application is added to a guild. Replaced by `defaultMemberPermissions`
777
+ * @arg {String} [command.description] The command description, required for `CHAT_INPUT` commands
778
+ * @arg {Object?} [command.descriptionLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command description
779
+ * @arg {String} command.name The command name
780
+ * @arg {Object?} [command.nameLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command name
781
+ * @arg {Boolean} [command.nsfw=false] Whether the command is age-restricted
782
+ * @arg {Array<Object>} [command.options] The application command [options](https://discord.dev/interactions/application-commands#application-command-object-application-command-option-structure)
783
+ * @arg {Number} [command.type=1] The command type, either `1` for `CHAT_INPUT`, `2` for `USER` or `3` for `MESSAGE`
784
+ * @returns {Promise<ApplicationCommand>} Resolves with the created application command
785
+ */
786
+ createGuildCommand(guildID, command) {
787
+ return this.requestHandler.request("POST", Endpoints.GUILD_COMMANDS(this.application.id, guildID), true, this._formatCommand(command, "createGuildCommand")).then((command) => new ApplicationCommand(command, this));
788
+ }
789
+
790
+ /**
791
+ * Create a guild emoji object
792
+ * @arg {String} guildID The ID of the guild to create the emoji in
793
+ * @arg {Object} options Emoji options
794
+ * @arg {String} options.image The base 64 encoded string
795
+ * @arg {String} options.name The name of emoji
796
+ * @arg {Array} [options.roles] An array containing authorized role IDs
797
+ * @arg {String} [reason] The reason to be displayed in audit logs
798
+ * @returns {Promise<Object>} A guild emoji object
799
+ */
800
+ createGuildEmoji(guildID, options, reason) {
801
+ options.reason = reason;
802
+ return this.requestHandler.request("POST", Endpoints.GUILD_EMOJIS(guildID), true, options);
803
+ }
804
+
805
+ /**
806
+ * Create a guild scheduled event
807
+ * @arg {String} guildID The guild ID where the event will be created
808
+ * @arg {Object} event The event to be created
809
+ * @arg {String} [event.channelID] The channel ID of the event. This is optional if `entityType` is `3` (external)
810
+ * @arg {String} [event.description] The description of the event
811
+ * @arg {Object} [event.entityMetadata] The entity metadata for the scheduled event. This is required if `entityType` is `3` (external)
812
+ * @arg {String} [event.entityMetadata.location] Location of the event
813
+ * @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
814
+ * @arg {String} [event.image] Base 64 encoded image for the scheduled event
815
+ * @arg {String} event.name The name of the event
816
+ * @arg {String} event.privacyLevel The privacy level of the event
817
+ * @arg {Object} [event.recurrenceRule] The [definitions](https://discord.dev/resources/guild-scheduled-event#guild-scheduled-event-recurrence-rule-object) for how often this event should recur. Properties can be camelCase (preferred) or snake_case
818
+ * @arg {Date} [event.scheduledEndTime] The time when the event is scheduled to end. This is required if `entityType` is `3` (external)
819
+ * @arg {Date} event.scheduledStartTime The time the event will start
820
+ * @arg {String} [reason] The reason to be displayed in audit logs
821
+ * @returns {Promise<GuildScheduledEvent>}
822
+ */
823
+ createGuildScheduledEvent(guildID, event, reason) {
824
+ return this.requestHandler.request("POST", Endpoints.GUILD_SCHEDULED_EVENTS(guildID), true, {
825
+ channel_id: event.channelID,
826
+ description: event.description,
827
+ entity_metadata: event.entityMetadata,
828
+ entity_type: event.entityType,
829
+ image: event.image,
830
+ name: event.name,
831
+ privacy_level: event.privacyLevel,
832
+ recurrence_rule: this._formatScheduledEventRecurrence(event.recurrenceRule),
833
+ scheduled_end_time: event.scheduledEndTime,
834
+ scheduled_start_time: event.scheduledStartTime,
835
+ reason: reason,
836
+ }).then((data) => new GuildScheduledEvent(data, this));
837
+ }
838
+
839
+ /**
840
+ * Create a guild soundboard sound
841
+ * @arg {String} guildID The guild ID where the sound will be created
842
+ * @arg {Object} sound The sound to be created
843
+ * @arg {String?} [sound.emojiID] The ID of the relating custom emoji (mutually exclusive with sound.emojiName)
844
+ * @arg {String?} [sound.emojiName] The name of the relating default emoji (mutually exclusive with sound.emojiID)
845
+ * @arg {String} sound.name The name of the soundboard sound (2-32 characters)
846
+ * @arg {String} sound.sound The base 64 encoded mp3/ogg sound data
847
+ * @arg {Number?} [sound.volume=1] The volume of the soundboard sound, between 0 and 1
848
+ * @arg {String} [reason] The reason to be displayed in audit logs
849
+ * @returns {Promise<SoundboardSound>}
850
+ */
851
+ createGuildSoundboardSound(guildID, sound, reason) {
852
+ sound.emoji_id = sound.emojiID;
853
+ sound.emoji_name = sound.emojiName;
854
+ sound.reason = reason;
855
+ return this.requestHandler.request("POST", Endpoints.SOUNDBOARD_SOUNDS_GUILD(guildID), true, sound).then((sound) => new SoundboardSound(sound, this));
856
+ }
857
+
858
+ /**
859
+ * Create a guild sticker
860
+ * @arg {Object} options Sticker options
861
+ * @arg {String} [options.description] The description of the sticker
862
+ * @arg {Object} options.file A file object
863
+ * @arg {Buffer} options.file.file A buffer containing file data
864
+ * @arg {String} options.file.name What to name the file
865
+ * @arg {String} options.name The name of the sticker
866
+ * @arg {String} options.tags The Discord name of a unicode emoji representing the sticker's expression
867
+ * @arg {String} [reason] The reason to be displayed in audit logs
868
+ * @returns {Promise<Object>} A sticker object
869
+ */
870
+ createGuildSticker(guildID, options, reason) {
871
+ return this.requestHandler.request("POST", Endpoints.GUILD_STICKERS(guildID), true, {
872
+ description: options.description || "",
873
+ name: options.name,
874
+ tags: options.tags,
875
+ reason: reason,
876
+ }, options.file);
877
+ }
878
+
879
+ /**
880
+ * Create a template for a guild
881
+ * @arg {String} guildID The ID of the guild
882
+ * @arg {String} name The name of the template
883
+ * @arg {String} [description] The description for the template
884
+ * @returns {Promise<GuildTemplate>}
885
+ */
886
+ createGuildTemplate(guildID, name, description) {
887
+ return this.requestHandler.request("POST", Endpoints.GUILD_TEMPLATES(guildID), true, {
888
+ name,
889
+ description,
890
+ }).then((template) => new GuildTemplate(template, this));
891
+ }
892
+
893
+ /**
894
+ * Respond to the interaction with a message
895
+ * Note: Use webhooks if you have already responded with an interaction response.
896
+ * @arg {String} interactionID The interaction ID.
897
+ * @arg {String} interactionToken The interaction Token.
898
+ * @arg {Object} options The options object.
899
+ * @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)
900
+ * @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
901
+ * @arg {Boolean} [options.withResponse=false] Whether to resolve with the interaction callback response
902
+ * @arg {Object | Array<Object>} [file] A file object (or an Array of them)
903
+ * @arg {Buffer} file.file A buffer containing file data
904
+ * @arg {String} file.name What to name the file
905
+ * @returns {Promise<Object?>} If `options.withResponse` is true, resolves with an object containing `interaction` (`activityInstanceID`, `id`, `responseMessageEphemeral`, `responseMessageID`, `responseMessageLoading`, `type`) and `resource` (`activityInstance`, `message`, `type`), if any
906
+ */
907
+ createInteractionResponse(interactionID, interactionToken, options, file) {
908
+ const withResponse = !!options.withResponse;
909
+ options = Object.assign({}, options);
910
+ delete options.withResponse;
911
+ if (options.data && options.data.embed) {
912
+ if (!options.data.embeds) {
913
+ options.data.embeds = [];
914
+ }
915
+ options.data.embeds.push(options.data.embed);
916
+ }
917
+ if (options.data && options.data.allowedMentions) {
918
+ options.data.allowed_mentions = this._formatAllowedMentions(options.data.allowedMentions);
919
+ }
920
+ if (file) {
921
+ options = { payload_json: options };
922
+ }
923
+ const url = Endpoints.INTERACTION_RESPOND(interactionID, interactionToken) + (withResponse ? "?with_response=true" : "");
924
+ return this.requestHandler.request("POST", url, true, options, file, "/interactions/:id/:token/callback").then((response) => {
925
+ if (!withResponse || !response) {
926
+ return;
927
+ }
928
+ return {
929
+ interaction: {
930
+ activityInstanceID: response.interaction.activity_instance_id,
931
+ id: response.interaction.id,
932
+ responseMessageEphemeral: response.interaction.response_message_ephemeral,
933
+ responseMessageID: response.interaction.response_message_id,
934
+ responseMessageLoading: response.interaction.response_message_loading,
935
+ type: response.interaction.type,
936
+ },
937
+ resource: response.resource && {
938
+ activityInstance: response.resource.activity_instance,
939
+ message: response.resource.message && new Message(response.resource.message, this),
940
+ type: response.resource.type,
941
+ },
942
+ };
943
+ });
944
+ }
945
+
946
+ /**
947
+ * Create a lobby. Social SDK clients cannot join or leave a lobby created this way
948
+ * @arg {Object} [options] The properties of the lobby
949
+ * @arg {Number} [options.idleTimeoutSeconds] How long to wait, in seconds, before shutting down the lobby once it becomes idle (between 5 and 604800)
950
+ * @arg {Array<Object>} [options.members] The users to add to the lobby (25 at most). A lobby can hold up to 1000 members: add the others with `addLobbyMember` or `bulkEditLobbyMembers`
951
+ * @arg {String?} [options.members[].additionalName] An additional display name for the member, such as an in-game character name (1-80 characters)
952
+ * @arg {Number} [options.members[].flags] The lobby member flags of the member. See `Constants.LobbyMemberFlags`
953
+ * @arg {Object<String, String>?} [options.members[].metadata] The metadata of the member, as key/value pairs (1000 characters in total at most)
954
+ * @arg {String} options.members[].id The ID of the user
955
+ * @arg {Object<String, String>?} [options.metadata] The metadata of the lobby, as key/value pairs (1000 characters in total at most)
956
+ * @returns {Promise<Lobby>}
957
+ */
958
+ createLobby(options = {}) {
959
+ return this.requestHandler.request("POST", Endpoints.LOBBIES, true, this._formatLobby(options)).then((lobby) => new Lobby(lobby, this));
960
+ }
961
+
962
+ /**
963
+ * Create a single-use invite to the channel linked to a lobby for one of its members. The invite expires after one hour
964
+ * @arg {String} lobbyID The ID of the lobby
965
+ * @arg {String} userID The ID of the member
966
+ * @returns {Promise<Object>} An object containing the invite `code`
967
+ */
968
+ createLobbyChannelInvite(lobbyID, userID) {
969
+ return this.requestHandler.request("POST", Endpoints.LOBBY_MEMBER_INVITES(lobbyID, userID), true);
970
+ }
971
+
972
+ /**
973
+ * Create a message in a channel
974
+ * 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
975
+ * @arg {String} channelID The ID of the channel
976
+ * @arg {String | Object} content A string or object. If an object is passed:
977
+ * @arg {Object} [content.allowedMentions] A list of mentions to allow (overrides default)
978
+ * @arg {Boolean} [content.allowedMentions.everyone] Whether or not to allow @everyone/@here
979
+ * @arg {Boolean} [content.allowedMentions.repliedUser] Whether or not to mention the author of the message being replied to
980
+ * @arg {Boolean | Array<String>} [content.allowedMentions.roles] Whether or not to allow all role mentions, or an array of specific role mentions to allow
981
+ * @arg {Boolean | Array<String>} [content.allowedMentions.users] Whether or not to allow all user mentions, or an array of specific user mentions to allow
982
+ * @arg {Array<Object>} [content.attachments] An array of attachment objects with the filename and description
983
+ * @arg {String} [content.attachments[].description] The description of the file
984
+ * @arg {String} [content.attachments[].filename] The name of the file
985
+ * @arg {Number} content.attachments[].id The index of the file
986
+ * @arg {Array<Object>} [content.components] An array of component objects
987
+ * @arg {String} [content.components[].custom_id] The ID of the component (type 2 style 1-4 and type 3,5,6,7,8 only)
988
+ * @arg {Boolean} [content.components[].disabled] Whether the component is disabled (type 2 and 3,5,6,7,8 only)
989
+ * @arg {Object} [content.components[].emoji] The emoji to be displayed in the component (type 2)
990
+ * @arg {String} [content.components[].label] The label to be displayed in the component (type 2)
991
+ * @arg {Array<Object>} [content.components[].default_values] default values for the component (type 5,6,7,8 only)
992
+ * @arg {String} [content.components[].default_values[].id] id of a user, role, or channel
993
+ * @arg {String} [content.components[].default_values[].type] type of value that id represents (user, role, or channel)
994
+ * @arg {Number} [content.components[].max_values] The maximum number of items that can be chosen (1-25, default 1)
995
+ * @arg {Number} [content.components[].min_values] The minimum number of items that must be chosen (0-25, default 1)
996
+ * @arg {Array<Object>} [content.components[].options] The options for this component (type 3 only)
997
+ * @arg {Boolean} [content.components[].options[].default] Whether this option should be the default value selected
998
+ * @arg {String} [content.components[].options[].description] The description for this option
999
+ * @arg {Object} [content.components[].options[].emoji] The emoji to be displayed in this option
1000
+ * @arg {String} content.components[].options[].label The label for this option
1001
+ * @arg {Number | String} content.components[].options[].value The value for this option
1002
+ * @arg {String} [content.components[].placeholder] The placeholder text for the component when no option is selected (type 3,5,6,7,8 only)
1003
+ * @arg {String} [content.components[].sku_id] The ID of the SKU to purchase (type 2 style 6 only)
1004
+ * @arg {Number} [content.components[].style] The style of the component (type 2 only) - If 1-4, `custom_id` is required; if 5, `url` is required; if 6, `sku_id` is required
1005
+ * @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 string select; if 4, it is a text input; if 5, it is a user select; if 6, it is a role select; if 7, it is a mentionable select; if 8, it is a channel select; if 9, it is a section; if 10, it is a text display; if 11, it is a thumbnail; if 12, it is a media gallery; if 13, it is a file; if 14, it is a separator; if 17, it is a container; if 18, it is a label (modals only); if 19, it is a file upload (modals only); if 21, it is a radio group (modals only); if 22, it is a checkbox group (modals only); if 23, it is a checkbox (modals only)
1006
+ * @arg {String} [content.components[].url] The URL that the component should open for users (type 2 style 5 only)
1007
+ * @arg {String} [content.content] A content string
1008
+ * @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
1009
+ * @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
1010
+ * @arg {Boolean} [content.enforceNonce] If true and `content.nonce` is present, if multiple messages are sent with the same nonce within a few minutes of each other, that message will be returned and no new message created
1011
+ * @arg {Object} [content.messageReference] The message reference, used when replying to or forwarding messages
1012
+ * @arg {String} [content.messageReference.channelID] The channel ID of the referenced message. Required when forwarding messages
1013
+ * @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
1014
+ * @arg {String} [content.messageReference.guildID] The guild ID of the referenced message
1015
+ * @arg {String} content.messageReference.messageID The message ID of the referenced message. This cannot reference a system message
1016
+ * @arg {String} [content.messageReference.type=0] The type of reference. Either `0` (REPLY) or `1` (FORWARDED). Will become required in the future
1017
+ * @arg {String} [content.messageReferenceID] [DEPRECATED] The ID of the message should be replied to. Use `messageReference` instead
1018
+ * @arg {String | Number} [content.nonce] A nonce value which will also appear in the messageCreate event
1019
+ * @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
1020
+ * @arg {Array<String>} [content.stickerIDs] An array of IDs corresponding to stickers to send
1021
+ * @arg {Boolean} [content.tts] Set the message TTS flag
1022
+ * @arg {Object | Array<Object>} [file] A file object (or an Array of them)
1023
+ * @arg {Buffer} file.file A buffer containing file data
1024
+ * @arg {String} file.name What to name the file
1025
+ * @returns {Promise<Message>}
1026
+ */
1027
+ createMessage(channelID, content, file) {
1028
+ if (content !== undefined) {
1029
+ if (typeof content !== "object" || content === null) {
1030
+ content = {
1031
+ content: "" + content,
1032
+ };
1033
+ } else if (content.content !== undefined && typeof content.content !== "string") {
1034
+ content.content = "" + content.content;
1035
+ } else if (content.embed) {
1036
+ if (!content.embeds) {
1037
+ content.embeds = [];
1038
+ }
1039
+ content.embeds.push(content.embed);
1040
+ }
1041
+ content.allowed_mentions = this._formatAllowedMentions(content.allowedMentions);
1042
+ content.enforce_nonce = content.enforceNonce;
1043
+ content.sticker_ids = content.stickerIDs;
1044
+ if (content.messageReference) {
1045
+ content.message_reference = content.messageReference;
1046
+ if (content.messageReference.messageID !== undefined) {
1047
+ content.message_reference.message_id = content.messageReference.messageID;
1048
+ content.messageReference.messageID = undefined;
1049
+ }
1050
+ if (content.messageReference.channelID !== undefined) {
1051
+ content.message_reference.channel_id = content.messageReference.channelID;
1052
+ content.messageReference.channelID = undefined;
1053
+ }
1054
+ if (content.messageReference.guildID !== undefined) {
1055
+ content.message_reference.guild_id = content.messageReference.guildID;
1056
+ content.messageReference.guildID = undefined;
1057
+ }
1058
+ if (content.messageReference.failIfNotExists !== undefined) {
1059
+ content.message_reference.fail_if_not_exists = content.messageReference.failIfNotExists;
1060
+ content.messageReference.failIfNotExists = undefined;
1061
+ }
1062
+ } else if (content.messageReferenceID) {
1063
+ emitDeprecation("MESSAGE_REFERENCE");
1064
+ this.emit("warn", "[DEPRECATED] content.messageReferenceID is deprecated. Use content.messageReference instead");
1065
+ content.message_reference = { message_id: content.messageReferenceID };
1066
+ }
1067
+ if (file) {
1068
+ content = { payload_json: content };
1069
+ }
1070
+ }
1071
+ return this.requestHandler.request("POST", Endpoints.CHANNEL_MESSAGES(channelID), true, content, file).then((message) => new Message(message, this));
1072
+ }
1073
+
1074
+ /**
1075
+ * Create a guild role
1076
+ * @arg {String} guildID The ID of the guild to create the role in
1077
+ * @arg {Object | Role} [options] An object or Role containing the properties to set
1078
+ * @arg {Number} [options.color] The hex color of the role, in number form (ex: 0x3d15b3 or 4040115)
1079
+ * @arg {Object} [options.colors] The role's colors
1080
+ * @arg {Number} [options.colors.primaryColor] The primary color of the role
1081
+ * @arg {Number?} [options.colors.secondaryColor] The secondary color of the role (for gradient roles)
1082
+ * @arg {Number?} [options.colors.tertiaryColor] The tertiary color of the role (for holographic roles)
1083
+ * @arg {Boolean} [options.hoist] Whether to hoist the role in the user list or not
1084
+ * @arg {String} [options.icon] The role icon as a base64 data URI
1085
+ * @arg {Boolean} [options.mentionable] Whether the role is mentionable or not
1086
+ * @arg {String} [options.name] The name of the role
1087
+ * @arg {BigInt | Number | String | Permission} [options.permissions] The role permissions
1088
+ * @arg {String} [options.unicodeEmoji] The role's unicode emoji
1089
+ * @arg {String} [reason] The reason to be displayed in audit logs
1090
+ * @returns {Promise<Role>}
1091
+ */
1092
+ createRole(guildID, options, reason) {
1093
+ if (options.permissions !== undefined) {
1094
+ options.permissions = options.permissions instanceof Permission ? String(options.permissions.allow) : String(options.permissions);
1095
+ }
1096
+ return this.requestHandler.request("POST", Endpoints.GUILD_ROLES(guildID), true, {
1097
+ name: options.name,
1098
+ permissions: options.permissions,
1099
+ color: options.color,
1100
+ colors: options.colors && {
1101
+ primary_color: options.colors.primaryColor,
1102
+ secondary_color: options.colors.secondaryColor,
1103
+ tertiary_color: options.colors.tertiaryColor,
1104
+ },
1105
+ hoist: options.hoist,
1106
+ icon: options.icon,
1107
+ mentionable: options.mentionable,
1108
+ unicode_emoji: options.unicodeEmoji,
1109
+ reason: reason,
1110
+ }).then((role) => {
1111
+ const guild = this.guilds.get(guildID);
1112
+ if (guild) {
1113
+ return guild.roles.add(role, guild);
1114
+ } else {
1115
+ return new Role(role);
1116
+ }
1117
+ });
1118
+ }
1119
+
1120
+ /**
1121
+ * Create a stage instance
1122
+ * @arg {String} channelID The ID of the stage channel to create the instance in
1123
+ * @arg {Object} options The stage instance options
1124
+ * @arg {Number} [options.privacyLevel] The privacy level of the stage instance. 1 is public, 2 is guild only
1125
+ * @arg {String} options.topic The stage instance topic
1126
+ * @returns {Promise<StageInstance>}
1127
+ */
1128
+ createStageInstance(channelID, options) {
1129
+ return this.requestHandler.request("POST", Endpoints.STAGE_INSTANCES, true, {
1130
+ channel_id: channelID,
1131
+ privacy_level: options.privacyLevel,
1132
+ topic: options.topic,
1133
+ }).then((instance) => new StageInstance(instance, this));
1134
+ }
1135
+
1136
+ /**
1137
+ * Create a test entitlement, granting a SKU to a guild or a user for free (useful for testing premium features)
1138
+ * @arg {Object} options The options for the test entitlement
1139
+ * @arg {String} options.ownerID The ID of the guild or user to grant the entitlement to
1140
+ * @arg {Number} options.ownerType The type of the owner. `1` for a guild subscription, `2` for a user subscription
1141
+ * @arg {String} options.skuID The ID of the SKU to grant the entitlement to
1142
+ * @returns {Promise<Entitlement>}
1143
+ */
1144
+ createTestEntitlement(options) {
1145
+ return this.requestHandler.request("POST", Endpoints.ENTITLEMENTS(this.application.id), true, {
1146
+ owner_id: options.ownerID,
1147
+ owner_type: options.ownerType,
1148
+ sku_id: options.skuID,
1149
+ }).then((entitlement) => new Entitlement(entitlement, this));
1150
+ }
1151
+
1152
+ /**
1153
+ * Create a thread in a channel
1154
+ * @arg {String} channelID The ID of the channel
1155
+ * @arg {Object} options The thread options
1156
+ * @arg {Array<String>} [options.appliedTags] The IDs of the set of tags that have been applied to a thread in a forum/media channel (threads created in forum/media channels only, max 5)
1157
+ * @arg {Number} [options.autoArchiveDuration] The duration in minutes to automatically archive the thread after recent activity, either 60, 1440, 4320 or 10080
1158
+ * @arg {Boolean} [options.invitable] Whether non-moderators can add other non-moderators to the thread (private threads only)
1159
+ * @arg {Object} [options.message] The message to create with the thread (only use when creating a thread inside of a thread-only channel). Note: When creating a forum/media channel thread, you must provide at least one of `content`, `embeds`, `stickerIDs`, `components`, or `files`
1160
+ * @arg {Object} [options.message.allowedMentions] A list of mentions to allow (overrides default)
1161
+ * @arg {Boolean} [options.message.allowedMentions.everyone] Whether or not to allow @everyone/@here
1162
+ * @arg {Boolean} [options.message.allowedMentions.repliedUser] Whether or not to mention the author of the message being replied to
1163
+ * @arg {Boolean | Array<String>} [options.message.allowedMentions.roles] Whether or not to allow all role mentions, or an array of specific role mentions to allow
1164
+ * @arg {Boolean | Array<String>} [options.message.allowedMentions.users] Whether or not to allow all user mentions, or an array of specific user mentions to allow
1165
+ * @arg {Array<Object>} [options.message.attachments] An array of attachment objects with the filename and description
1166
+ * @arg {String} [options.message.attachments[].description] The description of the file
1167
+ * @arg {String} [options.message.attachments[].filename] The name of the file
1168
+ * @arg {Number} options.message.attachments[].id The index of the file
1169
+ * @arg {Array<Object>} [options.message.components] An array of component objects
1170
+ * @arg {String} [options.message.components[].custom_id] The ID of the component (type 2 style 1-4 and type 3,5,6,7,8 only)
1171
+ * @arg {Boolean} [options.message.components[].disabled] Whether the component is disabled (type 2 and 3,5,6,7,8 only)
1172
+ * @arg {Object} [options.message.components[].emoji] The emoji to be displayed in the component (type 2)
1173
+ * @arg {String} [options.message.components[].label] The label to be displayed in the component (type 2)
1174
+ * @arg {Array<Object>} [options.components[].default_values] default values for the component (type 5,6,7,8 only)
1175
+ * @arg {String} [options.components[].default_values[].id] id of a user, role, or channel
1176
+ * @arg {String} [options.components[].default_values[].type] type of value that id represents (user, role, or channel)
1177
+ * @arg {Number} [options.message.components[].max_values] The maximum number of items that can be chosen (1-25, default 1)
1178
+ * @arg {Number} [options.message.components[].min_values] The minimum number of items that must be chosen (0-25, default 1)
1179
+ * @arg {Array<Object>} [options.message.components[].options] The options for this component (type 3 only)
1180
+ * @arg {Boolean} [options.message.components[].options[].default] Whether this option should be the default value selected
1181
+ * @arg {String} [options.message.components[].options[].description] The description for this option
1182
+ * @arg {Object} [options.message.components[].options[].emoji] The emoji to be displayed in this option
1183
+ * @arg {String} options.message.components[].options[].label The label for this option
1184
+ * @arg {Number | String} options.message.components[].options[].value The value for this option
1185
+ * @arg {String} [options.message.components[].placeholder] The placeholder text for the component when no option is selected (type 3,5,6,7,8 only)
1186
+ * @arg {String} [options.message.components[].sku_id] The ID of the SKU to purchase (type 2 style 6 only)
1187
+ * @arg {Number} [options.message.components[].style] The style of the component (type 2 only) - If 1-4, `custom_id` is required; if 5, `url` is required; if 6, `sku_id` is required
1188
+ * @arg {Number} options.message.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 string select; if 4, it is a text input; if 5, it is a user select; if 6, it is a role select; if 7, it is a mentionable select; if 8, it is a channel select; if 9, it is a section; if 10, it is a text display; if 11, it is a thumbnail; if 12, it is a media gallery; if 13, it is a file; if 14, it is a separator; if 17, it is a container; if 18, it is a label (modals only); if 19, it is a file upload (modals only); if 21, it is a radio group (modals only); if 22, it is a checkbox group (modals only); if 23, it is a checkbox (modals only)
1189
+ * @arg {String} [options.message.components[].url] The URL that the component should open for users (type 2 style 5 only)
1190
+ * @arg {String} [options.message.content] A string containing the message content
1191
+ * @arg {Array<Object>} [options.message.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
1192
+ * @arg {Array<String>} [options.message.stickerIDs] An array of IDs corresponding to stickers to send
1193
+ * @arg {String} options.name The thread channel name
1194
+ * @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)
1195
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
1196
+ * @arg {Number} [options.type] The channel type of the thread to create. Either `10` (announcement thread, announcement channels only), `11` (public thread) or `12` (private thread). Note: Not required when creating a thread inside of a forum/media channel, it will always be public
1197
+ * @arg {Object | Array<Object>} [file] A file object (or an Array of them). Only use when creating a thread inside of a forum/media channel
1198
+ * @arg {Buffer} file.file A buffer containing file data
1199
+ * @arg {String} file.name What to name the file
1200
+ * @returns {Promise<NewsThreadChannel | PublicThreadChannel | PrivateThreadChannel>}
1201
+ */
1202
+ createThread(channelID, options, file) {
1203
+ if (options.message) {
1204
+ options.message.allowed_mentions = this._formatAllowedMentions(options.message.allowedMentions);
1205
+ options.message.sticker_ids = options.message.stickerIDs;
1206
+ }
1207
+ let payload = {
1208
+ applied_tags: options.appliedTags,
1209
+ auto_archive_duration: options.autoArchiveDuration,
1210
+ invitable: options.invitable,
1211
+ message: options.message,
1212
+ name: options.name,
1213
+ rate_limit_per_user: options.rateLimitPerUser,
1214
+ reason: options.reason,
1215
+ type: options.type,
1216
+ };
1217
+ if (file) {
1218
+ payload = { payload_json: payload };
1219
+ }
1220
+ return this.requestHandler.request("POST", Endpoints.THREAD_WITHOUT_MESSAGE(channelID), true, payload, file).then((channel) => Channel.from(channel, this));
1221
+ }
1222
+
1223
+ /**
1224
+ * Create a thread with an existing message
1225
+ * @arg {String} channelID The ID of the channel
1226
+ * @arg {String} messageID The ID of the message to create the thread from
1227
+ * @arg {Object} options The thread options
1228
+ * @arg {Number} [options.autoArchiveDuration] Duration in minutes to automatically archive the thread after recent activity, either 60, 1440, 4320 or 10080
1229
+ * @arg {String} options.name The thread channel name
1230
+ * @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)
1231
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
1232
+ * @returns {Promise<NewsThreadChannel | PublicThreadChannel>}
1233
+ */
1234
+ createThreadWithMessage(channelID, messageID, options) {
1235
+ return this.requestHandler.request("POST", Endpoints.THREAD_WITH_MESSAGE(channelID, messageID), true, {
1236
+ auto_archive_duration: options.autoArchiveDuration,
1237
+ name: options.name,
1238
+ rate_limit_per_user: options.rateLimitPerUser,
1239
+ reason: options.reason,
1240
+ }).then((channel) => Channel.from(channel, this));
1241
+ }
1242
+
1243
+ /**
1244
+ * [DEPRECATED] Create a thread without an existing message. Use `createThread` instead
1245
+ * @arg {String} channelID The ID of the channel
1246
+ * @arg {Object} options The thread options
1247
+ * @arg {Number} [options.autoArchiveDuration] Duration in minutes to automatically archive the thread after recent activity, either 60, 1440, 4320 or 10080
1248
+ * @arg {Boolean} [options.invitable] Whether non-moderators can add other non-moderators to the thread (private threads only)
1249
+ * @arg {String} options.name The thread channel name
1250
+ * @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)
1251
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
1252
+ * @arg {Number} [options.type] The channel type of the thread to create. Either `10` (announcement thread, announcement channels only), `11` (public thread) or `12` (private thread)
1253
+ * @returns {Promise<NewsThreadChannel | PublicThreadChannel | PrivateThreadChannel>}
1254
+ */
1255
+ createThreadWithoutMessage(channelID, options) {
1256
+ emitDeprecation("CREATE_THREAD_WITHOUT_MESSAGE");
1257
+ this.emit("warn", "[DEPRECATED] createThreadWithoutMessage() is deprecated. Use createThread() instead.");
1258
+ return this.requestHandler.request("POST", Endpoints.THREAD_WITHOUT_MESSAGE(channelID), true, {
1259
+ auto_archive_duration: options.autoArchiveDuration,
1260
+ invitable: options.invitable,
1261
+ name: options.name,
1262
+ type: options.type,
1263
+ }).then((channel) => Channel.from(channel, this));
1264
+ }
1265
+
1266
+ /**
1267
+ * Crosspost (publish) a message to subscribed channels
1268
+ * @arg {String} channelID The ID of the NewsChannel
1269
+ * @arg {String} messageID The ID of the message
1270
+ * @returns {Promise<Message>}
1271
+ */
1272
+ crosspostMessage(channelID, messageID) {
1273
+ return this.requestHandler.request("POST", Endpoints.CHANNEL_CROSSPOST(channelID, messageID), true).then((message) => new Message(message, this));
1274
+ }
1275
+
1276
+ /**
1277
+ * Delete an application identity of a user, along with its profile data. Discord refuses to delete the last identity that links the user's account
1278
+ * @arg {String} userID The ID of the user
1279
+ * @arg {String} providerType The type of the external account provider
1280
+ * @arg {String} providerIssuedUserID The ID of the user in the external system
1281
+ * @arg {String} [providerID] The ID used by the provider to tell identities with the same type and user ID apart
1282
+ * @returns {Promise}
1283
+ */
1284
+ deleteApplicationIdentity(userID, providerType, providerIssuedUserID, providerID) {
1285
+ return this.requestHandler.request("POST", Endpoints.USER_APPLICATION_IDENTITY_DELETE(userID, this.application.id, encodeURIComponent(providerType), encodeURIComponent(providerIssuedUserID)), true, {
1286
+ provider_id: providerID,
1287
+ }, undefined, "/users/:id/application-identities/:id/:type/:id/delete");
1288
+ }
1289
+
1290
+ /**
1291
+ * Delete an auto moderation rule
1292
+ * @arg {String} guildID The guildID to delete the rule from
1293
+ * @arg {String} ruleID The ID of the rule to delete
1294
+ * @arg {String} [reason] The reason to be displayed in audit logs
1295
+ * @returns {Promise}
1296
+ */
1297
+ deleteAutoModerationRule(guildID, ruleID, reason) {
1298
+ return this.requestHandler.request("DELETE", Endpoints.AUTO_MODERATION_RULE(guildID, ruleID), true, {
1299
+ reason,
1300
+ });
1301
+ }
1302
+
1303
+ /**
1304
+ * Delete a guild channel, or leave a DM channel
1305
+ * @arg {String} channelID The ID of the channel
1306
+ * @arg {String} [reason] The reason to be displayed in audit logs
1307
+ * @returns {Promise<CateogryChannel | DMChannel | GroupChannel | NewsChannel | StageChannel | TextChannel | VoiceChannel>}
1308
+ */
1309
+ deleteChannel(channelID, reason) {
1310
+ return this.requestHandler.request("DELETE", Endpoints.CHANNEL(channelID), true, {
1311
+ reason,
1312
+ }).then((channel) => Channel.from(channel, this));
1313
+ }
1314
+
1315
+ /**
1316
+ * Delete a channel permission overwrite
1317
+ * @arg {String} channelID The ID of the channel
1318
+ * @arg {String} overwriteID The ID of the overwritten user or role
1319
+ * @arg {String} [reason] The reason to be displayed in audit logs
1320
+ * @returns {Promise}
1321
+ */
1322
+ deleteChannelPermission(channelID, overwriteID, reason) {
1323
+ return this.requestHandler.request("DELETE", Endpoints.CHANNEL_PERMISSION(channelID, overwriteID), true, {
1324
+ reason,
1325
+ });
1326
+ }
1327
+
1328
+ /**
1329
+ * Delete a global application command
1330
+ * @arg {String} commandID The command id
1331
+ * @returns {Promise}
1332
+ */
1333
+ deleteCommand(commandID) {
1334
+ if (!commandID) {
1335
+ throw new Error("You must provide an id of the command to delete.");
1336
+ }
1337
+ return this.requestHandler.request("DELETE", Endpoints.COMMAND(this.application.id, commandID), true);
1338
+ }
1339
+
1340
+ /**
1341
+ * Delete an emoji for this application
1342
+ * @arg {String} emojiID The id of the emoji
1343
+ * @returns {Promise}
1344
+ */
1345
+ deleteEmoji(emojiID) {
1346
+ return this.requestHandler.request("DELETE", Endpoints.APPLICATION_EMOJI(this.application.id, emojiID), true);
1347
+ }
1348
+
1349
+ /**
1350
+ * Delete a guild application command
1351
+ * @arg {String} guildID The guild ID
1352
+ * @arg {String} commandID The command id
1353
+ * @returns {Promise}
1354
+ */
1355
+ deleteGuildCommand(guildID, commandID) {
1356
+ if (!guildID) {
1357
+ throw new Error("You must provide an id of the guild which the command is in.");
1358
+ }
1359
+ if (!commandID) {
1360
+ throw new Error("You must provide an id of the command to delete.");
1361
+ }
1362
+ return this.requestHandler.request("DELETE", Endpoints.GUILD_COMMAND(this.application.id, guildID, commandID), true);
1363
+ }
1364
+
1365
+ /**
1366
+ * Delete a guild discovery subcategory
1367
+ * @arg {String} guildID The ID of the guild
1368
+ * @arg {String} categoryID The ID of the discovery category
1369
+ * @arg {String} [reason] The reason to be displayed in audit logs
1370
+ * @returns {Promise}
1371
+ */
1372
+ deleteGuildDiscoverySubcategory(guildID, categoryID, reason) {
1373
+ return this.requestHandler.request("DELETE", Endpoints.GUILD_DISCOVERY_CATEGORY(guildID, categoryID), true, { reason });
1374
+ }
1375
+
1376
+ /**
1377
+ * Delete a guild emoji object
1378
+ * @arg {String} guildID The ID of the guild to delete the emoji in
1379
+ * @arg {String} emojiID The ID of the emoji
1380
+ * @arg {String} [reason] The reason to be displayed in audit logs
1381
+ * @returns {Promise}
1382
+ */
1383
+ deleteGuildEmoji(guildID, emojiID, reason) {
1384
+ return this.requestHandler.request("DELETE", Endpoints.GUILD_EMOJI(guildID, emojiID), true, {
1385
+ reason,
1386
+ });
1387
+ }
1388
+
1389
+ /**
1390
+ * Delete a guild integration
1391
+ * @arg {String} guildID The ID of the guild
1392
+ * @arg {String} integrationID The ID of the integration
1393
+ * @returns {Promise}
1394
+ */
1395
+ deleteGuildIntegration(guildID, integrationID) {
1396
+ return this.requestHandler.request("DELETE", Endpoints.GUILD_INTEGRATION(guildID, integrationID), true);
1397
+ }
1398
+
1399
+ /**
1400
+ * Delete a guild scheduled event
1401
+ * @arg {String} guildID The ID of the guild
1402
+ * @arg {String} eventID The ID of the event
1403
+ * @returns {Promise}
1404
+ */
1405
+ deleteGuildScheduledEvent(guildID, eventID) {
1406
+ return this.requestHandler.request("DELETE", Endpoints.GUILD_SCHEDULED_EVENT(guildID, eventID), true);
1407
+ }
1408
+
1409
+ /**
1410
+ * Delete a guild soundboard sound
1411
+ * @arg {String} guildID The ID of the guild
1412
+ * @arg {String} soundID The ID of the soundboard sound
1413
+ * @arg {String} [reason] The reason to be displayed in audit logs
1414
+ * @returns {Promise}
1415
+ */
1416
+ deleteGuildSoundboardSound(guildID, soundID, reason) {
1417
+ return this.requestHandler.request("DELETE", Endpoints.SOUNDBOARD_SOUND_GUILD(guildID, soundID), true, { reason });
1418
+ }
1419
+
1420
+ /**
1421
+ * Delete a guild sticker
1422
+ * @arg {String} guildID The ID of the guild
1423
+ * @arg {String} stickerID The ID of the sticker
1424
+ * @arg {String} [reason] The reason to be displayed in audit logs
1425
+ * @returns {Promise}
1426
+ */
1427
+ deleteGuildSticker(guildID, stickerID, reason) {
1428
+ return this.requestHandler.request("DELETE", Endpoints.GUILD_STICKER(guildID, stickerID), true, {
1429
+ reason,
1430
+ });
1431
+ }
1432
+
1433
+ /**
1434
+ * Delete a guild template
1435
+ * @arg {String} guildID The ID of the guild
1436
+ * @arg {String} code The template code
1437
+ * @returns {Promise<GuildTemplate>}
1438
+ */
1439
+ deleteGuildTemplate(guildID, code) {
1440
+ return this.requestHandler.request("DELETE", Endpoints.GUILD_TEMPLATE_GUILD(guildID, code), true).then((template) => new GuildTemplate(template, this));
1441
+ }
1442
+
1443
+ /**
1444
+ * Delete an invite
1445
+ * @arg {String} inviteID The ID of the invite
1446
+ * @arg {String} [reason] The reason to be displayed in audit logs
1447
+ * @returns {Promise}
1448
+ */
1449
+ deleteInvite(inviteID, reason) {
1450
+ return this.requestHandler.request("DELETE", Endpoints.INVITE(inviteID), true, {
1451
+ reason,
1452
+ });
1453
+ }
1454
+
1455
+ /**
1456
+ * Delete a lobby. Deleting a lobby that no longer exists succeeds
1457
+ * @arg {String} lobbyID The ID of the lobby
1458
+ * @returns {Promise}
1459
+ */
1460
+ deleteLobby(lobbyID) {
1461
+ return this.requestHandler.request("DELETE", Endpoints.LOBBY(lobbyID), true);
1462
+ }
1463
+
1464
+ /**
1465
+ * Delete a message
1466
+ * @arg {String} channelID The ID of the channel
1467
+ * @arg {String} messageID The ID of the message
1468
+ * @arg {String} [reason] The reason to be displayed in audit logs
1469
+ * @returns {Promise}
1470
+ */
1471
+ deleteMessage(channelID, messageID, reason) {
1472
+ return this.requestHandler.request("DELETE", Endpoints.CHANNEL_MESSAGE(channelID, messageID), true, {
1473
+ reason,
1474
+ });
1475
+ }
1476
+
1477
+ /**
1478
+ * Bulk delete messages (bot accounts only)
1479
+ * @arg {String} channelID The ID of the channel
1480
+ * @arg {Array<String>} messageIDs Array of message IDs to delete
1481
+ * @arg {String} [reason] The reason to be displayed in audit logs
1482
+ * @returns {Promise}
1483
+ */
1484
+ deleteMessages(channelID, messageIDs, reason) {
1485
+ if (messageIDs.length === 0) {
1486
+ return Promise.resolve();
1487
+ }
1488
+ if (messageIDs.length === 1) {
1489
+ return this.deleteMessage(channelID, messageIDs[0], reason);
1490
+ }
1491
+
1492
+ const oldestAllowedSnowflake = (Date.now() - 1421280000000) * 4194304;
1493
+ const invalidMessage = messageIDs.find((messageID) => messageID < oldestAllowedSnowflake);
1494
+ if (invalidMessage) {
1495
+ return Promise.reject(new Error(`Message ${invalidMessage} is more than 2 weeks old.`));
1496
+ }
1497
+
1498
+ if (messageIDs.length > 100) {
1499
+ return this.requestHandler.request("POST", Endpoints.CHANNEL_BULK_DELETE(channelID), true, {
1500
+ messages: messageIDs.splice(0, 100),
1501
+ reason: reason,
1502
+ }).then(() => this.deleteMessages(channelID, messageIDs, reason));
1503
+ }
1504
+ return this.requestHandler.request("POST", Endpoints.CHANNEL_BULK_DELETE(channelID), true, {
1505
+ messages: messageIDs,
1506
+ reason: reason,
1507
+ });
1508
+ }
1509
+
1510
+ /**
1511
+ * Delete a guild role
1512
+ * @arg {String} guildID The ID of the guild to create the role in
1513
+ * @arg {String} roleID The ID of the role
1514
+ * @arg {String} [reason] The reason to be displayed in audit logs
1515
+ * @returns {Promise}
1516
+ */
1517
+ deleteRole(guildID, roleID, reason) {
1518
+ return this.requestHandler.request("DELETE", Endpoints.GUILD_ROLE(guildID, roleID), true, {
1519
+ reason,
1520
+ });
1521
+ }
1522
+
1523
+ /**
1524
+ * Delete a stage instance
1525
+ * @arg {String} channelID The stage channel associated with the instance
1526
+ * @returns {Promise}
1527
+ */
1528
+ deleteStageInstance(channelID) {
1529
+ return this.requestHandler.request("DELETE", Endpoints.STAGE_INSTANCE(channelID), true);
1530
+ }
1531
+
1532
+ /**
1533
+ * Delete a test entitlement
1534
+ * @arg {String} entitlementID The ID of the entitlement
1535
+ * @returns {Promise}
1536
+ */
1537
+ deleteTestEntitlement(entitlementID) {
1538
+ return this.requestHandler.request("DELETE", Endpoints.ENTITLEMENT(this.application.id, entitlementID), true);
1539
+ }
1540
+
1541
+ /**
1542
+ * Delete a webhook
1543
+ * @arg {String} webhookID The ID of the webhook
1544
+ * @arg {String} [token] The token of the webhook, used instead of the Bot Authorization token
1545
+ * @arg {String} [reason] The reason to be displayed in audit logs
1546
+ * @returns {Promise}
1547
+ */
1548
+ deleteWebhook(webhookID, token, reason) {
1549
+ return this.requestHandler.request("DELETE", token ? Endpoints.WEBHOOK_TOKEN(webhookID, token) : Endpoints.WEBHOOK(webhookID), !token, {
1550
+ reason,
1551
+ });
1552
+ }
1553
+
1554
+ /**
1555
+ * Delete a webhook message
1556
+ * @arg {String} webhookID
1557
+ * @arg {String} token
1558
+ * @arg {String} messageID
1559
+ * @returns {Promise}
1560
+ */
1561
+ deleteWebhookMessage(webhookID, token, messageID) {
1562
+ return this.requestHandler.request("DELETE", Endpoints.WEBHOOK_MESSAGE(webhookID, token, messageID), false);
1563
+ }
1564
+
1565
+ /**
1566
+ * Disconnects all shards
1567
+ * @arg {Object?} [options] Shard disconnect options
1568
+ * @arg {String | Boolean} [options.reconnect] false means destroy everything, true means you want to reconnect in the future, "auto" will autoreconnect
1569
+ */
1570
+ disconnect(options) {
1571
+ this.ready = false;
1572
+ this.shards.forEach((shard) => {
1573
+ shard.disconnect(options);
1574
+ });
1575
+ this.shards.connectQueue = [];
1576
+ }
1577
+
1578
+ /**
1579
+ * Update the bot's AFK status. Setting this to true will enable push notifications for userbots.
1580
+ * @arg {Boolean} afk Whether the bot user is AFK or not
1581
+ */
1582
+ editAFK(afk) {
1583
+ this.presence.afk = !!afk;
1584
+
1585
+ this.shards.forEach((shard) => {
1586
+ shard.editAFK(afk);
1587
+ });
1588
+ }
1589
+
1590
+ /**
1591
+ * Edit the game profile of a user, shown in the game stats widgets of their Discord profile. The user must have authorized the application with the `application_identities.write` scope
1592
+ * @arg {String} userID The ID of the user
1593
+ * @arg {String} providerIssuedUserID The ID of the user in your system. If the user has no application identity yet, the first edit creates one with this ID and the `NONE` provider type
1594
+ * @arg {Object} options The properties to edit
1595
+ * @arg {Object} [options.data] The profile data, with the `primary` stats and the `dynamic` fields. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/application-identity-profile#profile-data-object) for its structure (10 KB at most). It replaces all of the previous data
1596
+ * @arg {String} [options.username] The username of the user in your system
1597
+ * @returns {Promise<Object?>} The profile (an object containing the `username`, `metadata` and `data`) when it is created, nothing when it is updated
1598
+ */
1599
+ editApplicationIdentityProfile(userID, providerIssuedUserID, options) {
1600
+ return this.requestHandler.request("PATCH", Endpoints.APPLICATION_IDENTITY_PROFILE(this.application.id, userID, encodeURIComponent(providerIssuedUserID)), true, {
1601
+ data: options.data,
1602
+ username: options.username,
1603
+ }, undefined, "/applications/:id/users/:id/identities/:id/profile");
1604
+ }
1605
+
1606
+ /**
1607
+ * Edit an existing auto moderation rule
1608
+ * @arg {String} guildID the ID of the guild to edit the rule in
1609
+ * @arg {String} ruleID The ID of the rule to edit
1610
+ * @arg {Object} options The properties to edit
1611
+ * @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. Their `metadata` takes camelCase keys, such as `durationSeconds`
1612
+ * @arg {Boolean} [options.enabled=false] If the rule is enabled, false by default
1613
+ * @arg {Number} [options.eventType] The [event type](https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-event-types) for the rule
1614
+ * @arg {Array<String>} [options.exemptChannels] Any channels where this rule does not apply
1615
+ * @arg {Array<String>} [options.exemptRoles] Any roles to which this rule does not apply
1616
+ * @arg {String} [options.name] The name of the rule
1617
+ * @arg {Object} [options.triggerMetadata] The [trigger metadata](https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata) for the rule, with camelCase keys such as `keywordFilter`
1618
+ * @arg {Number} [options.triggerType] The [trigger type](https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-types) of the rule
1619
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
1620
+ * @returns {Promise<AutoModerationRule>}
1621
+ */
1622
+ editAutoModerationRule(guildID, ruleID, options) {
1623
+ return this.requestHandler.request("PATCH", Endpoints.AUTO_MODERATION_RULE(guildID, ruleID), true, this._formatAutoModerationRule(options)).then((rule) => new AutoModerationRule(rule, this));
1624
+ }
1625
+
1626
+ /**
1627
+ * Edit a channel's properties
1628
+ * @arg {String} channelID The ID of the channel
1629
+ * @arg {Object} options The properties to edit
1630
+ * @arg {Array<String>} [options.appliedTags] The IDs of the set of tags that have been applied to a thread in a forum/media channel (threads created in forum/media channels only, max 5)
1631
+ * @arg {Boolean} [options.archived] The archive status of the channel (thread channels only)
1632
+ * @arg {Number} [options.autoArchiveDuration] The duration in minutes to automatically archive the thread after recent activity, either 60, 1440, 4320 or 10080 (thread channels only)
1633
+ * @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)
1634
+ * @arg {Number} [options.bitrate] The bitrate of the channel (guild voice channels only)
1635
+ * @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)
1636
+ * @arg {Number} [options.defaultForumLayout] The default forum layout type used to display posts in forum channels (forum channels only)
1637
+ * @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)
1638
+ * @arg {Number} [options.defaultSortOrder] The default sort order type used to order posts in forum/media channels (forum/media channels only)
1639
+ * @arg {Number} [options.defaultThreadRateLimitPerUser] The initial rateLimitPerUser to set on newly created threads in a channel (text/forum/media channels only)
1640
+ * @arg {Number} [options.flags] The flags for the channel combined as a bitfield (thread/forum/media channels only). Note: `PINNED` can only be set for threads in forum/media channels, `REQUIRE_TAG` can only be set for forum/media channels, and `HIDE_MEDIA_DOWNLOAD_OPTIONS` can only be set for media channels
1641
+ * @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
1642
+ * @arg {Boolean} [options.invitable] Whether non-moderators can add other non-moderators to the channel (private thread channels only)
1643
+ * @arg {Boolean} [options.locked] The lock status of the channel (thread channels only)
1644
+ * @arg {String} [options.name] The name of the channel
1645
+ * @arg {Boolean} [options.nsfw] The nsfw status of the channel (guild channels only)
1646
+ * @arg {String?} [options.parentID] The ID of the parent channel category for this channel (guild text/voice channels only)
1647
+ * @arg {Array<Object>} [options.permissionOverwrites] An array containing permission overwrite objects
1648
+ * @arg {Number} [options.position] The sorting position of the channel (guild channels only)
1649
+ * @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)
1650
+ * @arg {String?} [options.rtcRegion] The RTC region ID of the channel (automatic if `null`) (guild voice channels only)
1651
+ * @arg {String} [options.topic] The topic of the channel (guild text channels only)
1652
+ * @arg {Number} [options.userLimit] The channel user limit (guild voice channels only)
1653
+ * @arg {Number} [options.videoQualityMode] The camera video quality mode of the channel (guild voice channels only). `1` is auto, `2` is 720p
1654
+ * @arg {String} [reason] The reason to be displayed in audit logs
1655
+ * @returns {Promise<CategoryChannel | ForumChannel | GroupChannel | NewsChannel | NewsThreadChannel | PrivateThreadChannel | PublicThreadChannel | TextChannel | VoiceChannel>}
1656
+ */
1657
+ editChannel(channelID, options, reason) {
1658
+ return this.requestHandler.request("PATCH", Endpoints.CHANNEL(channelID), true, {
1659
+ applied_tags: options.appliedTags,
1660
+ archived: options.archived,
1661
+ auto_archive_duration: options.autoArchiveDuration,
1662
+ available_tags: options.availableTags,
1663
+ bitrate: options.bitrate,
1664
+ default_auto_archive_duration: options.defaultAutoArchiveDuration,
1665
+ default_forum_layout: options.defaultForumLayout,
1666
+ default_reaction_emoji: options.defaultReactionEmoji,
1667
+ default_sort_order: options.defaultSortOrder,
1668
+ default_thread_rate_limit_per_user: options.defaultThreadRateLimitPerUser,
1669
+ flags: options.flags,
1670
+ icon: options.icon,
1671
+ invitable: options.invitable,
1672
+ locked: options.locked,
1673
+ name: options.name,
1674
+ nsfw: options.nsfw,
1675
+ parent_id: options.parentID,
1676
+ position: options.position,
1677
+ rate_limit_per_user: options.rateLimitPerUser,
1678
+ rtc_region: options.rtcRegion,
1679
+ topic: options.topic,
1680
+ user_limit: options.userLimit,
1681
+ video_quality_mode: options.videoQualityMode,
1682
+ permission_overwrites: options.permissionOverwrites,
1683
+ reason: reason,
1684
+ }).then((channel) => Channel.from(channel, this));
1685
+ }
1686
+
1687
+ /**
1688
+ * Create a channel permission overwrite
1689
+ * @arg {String} channelID The ID of channel
1690
+ * @arg {String} overwriteID The ID of the overwritten user or role (everyone role ID = guild ID)
1691
+ * @arg {BigInt} allow The permissions number for allowed permissions
1692
+ * @arg {BigInt} deny The permissions number for denied permissions
1693
+ * @arg {Number} type The object type of the overwrite, either 1 for "member" or 0 for "role"
1694
+ * @arg {String} [reason] The reason to be displayed in audit logs
1695
+ * @returns {Promise}
1696
+ */
1697
+ editChannelPermission(channelID, overwriteID, allow, deny, type, reason) {
1698
+ if (typeof type === "string") { // backward compatibility
1699
+ type = type === "member" ? 1 : 0;
1700
+ }
1701
+ return this.requestHandler.request("PUT", Endpoints.CHANNEL_PERMISSION(channelID, overwriteID), true, {
1702
+ allow,
1703
+ deny,
1704
+ type,
1705
+ reason,
1706
+ });
1707
+ }
1708
+
1709
+ /**
1710
+ * Edit a guild channel's position. Note that channel position numbers are grouped by type (category, text, voice), then sorted in ascending order (lowest number is on top).
1711
+ * @arg {String} channelID The ID of the channel
1712
+ * @arg {Number} position The new position of the channel
1713
+ * @arg {Object} [options] Additional options when editing position
1714
+ * @arg {Boolean} [options.lockPermissions] Whether to sync the channel's permissions with the new parent, if changing parents
1715
+ * @arg {String} [options.parentID] The new parent ID (category channel) for the channel that is moved
1716
+ * @returns {Promise}
1717
+ */
1718
+ editChannelPosition(channelID, position, options = {}) {
1719
+ let channels = this.guilds.get(this.channelGuildMap[channelID]).channels;
1720
+ const channel = channels.get(channelID);
1721
+ if (!channel) {
1722
+ return Promise.reject(new Error(`Channel ${channelID} not found`));
1723
+ }
1724
+ if (channel.position === position) {
1725
+ return Promise.resolve();
1726
+ }
1727
+ const min = Math.min(position, channel.position);
1728
+ const max = Math.max(position, channel.position);
1729
+ channels = channels.filter((chan) => {
1730
+ return chan.type === channel.type
1731
+ && min <= chan.position
1732
+ && chan.position <= max
1733
+ && chan.id !== channelID;
1734
+ }).sort((a, b) => a.position - b.position);
1735
+ if (position > channel.position) {
1736
+ channels.push(channel);
1737
+ } else {
1738
+ channels.unshift(channel);
1739
+ }
1740
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_CHANNELS(this.channelGuildMap[channelID]), true, channels.map((channel, index) => ({
1741
+ id: channel.id,
1742
+ position: index + min,
1743
+ lock_permissions: options.lockPermissions,
1744
+ parent_id: options.parentID,
1745
+ })));
1746
+ }
1747
+
1748
+ /**
1749
+ * Edit multiple guild channels' positions. Note that channel position numbers are grouped by type (category, text, voice), then sorted in ascending order (lowest number is on top).
1750
+ * @arg {String} guildID The ID of the guild
1751
+ * @arg {Array<Object>} channelPositions An array of [ChannelPosition](https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions)
1752
+ * @arg {String} channelPositions[].id The ID of the channel
1753
+ * @arg {Boolean} [channelPositions[].lockPermissions] Whether to sync the channel's permissions with the new parent, if changing parents
1754
+ * @arg {String} [channelPositions[].parentID] The new parent ID (category channel) for the channel that is moved. For each request, only one channel can change parents
1755
+ * @arg {Number} channelPositions[].position The new position of the channel
1756
+ * @returns {Promise}
1757
+ */
1758
+ editChannelPositions(guildID, channelPositions) {
1759
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_CHANNELS(guildID), true, channelPositions.map((channelPosition) => {
1760
+ return {
1761
+ id: channelPosition.id,
1762
+ position: channelPosition.position,
1763
+ lock_permissions: channelPosition.lockPermissions,
1764
+ parent_id: channelPosition.parentID,
1765
+ };
1766
+ }));
1767
+ }
1768
+
1769
+ /**
1770
+ * Edit a global application command
1771
+ * @arg {String} commandID The command ID
1772
+ * @arg {Object} command A command object
1773
+ * @arg {Array<Number>} [command.contexts] The interaction contexts where the command can be used, `0` for guilds, `1` for the app's bot DM and `2` for group DMs and other DMs. See `Constants.InteractionContextTypes`
1774
+ * @arg {BigInt | Number | String | Permission?} [command.defaultMemberPermissions] The default permissions the user must have to use the command
1775
+ * @arg {Boolean} [command.defaultPermission] [DEPRECATED] Whether the command is enabled by default when the application is added to a guild. Replaced by `defaultMemberPermissions`
1776
+ * @arg {String} [command.description] The command description, required for `CHAT_INPUT` commands
1777
+ * @arg {Object?} [command.descriptionLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command description
1778
+ * @arg {Boolean?} [command.dmPermission=true] [DEPRECATED] Whether the command is available in DMs with the app. Use `contexts` instead
1779
+ * @arg {Number} [command.handler] How the interaction is handled, `1` for the app (`APP_HANDLER`) or `2` for Discord launching the Activity (`DISCORD_LAUNCH_ACTIVITY`). `PRIMARY_ENTRY_POINT` commands only. See `Constants.EntryPointCommandHandlerTypes`
1780
+ * @arg {Array<Number>} [command.integrationTypes] The installation contexts where the command is available, `0` for guild installs and `1` for user installs. See `Constants.ApplicationIntegrationTypes`
1781
+ * @arg {String} [command.name] The command name
1782
+ * @arg {Object?} [command.nameLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command name
1783
+ * @arg {Boolean} [command.nsfw] Whether the command is age-restricted
1784
+ * @arg {Array<Object>} [command.options] The application command [options](https://discord.dev/interactions/application-commands#application-command-object-application-command-option-structure)
1785
+ * @returns {Promise<ApplicationCommand>} Resolves with the edited application command
1786
+ */
1787
+ editCommand(commandID, command) {
1788
+ if (!commandID) {
1789
+ throw new Error("You must provide an id of the command to edit.");
1790
+ }
1791
+ return this.requestHandler.request("PATCH", Endpoints.COMMAND(this.application.id, commandID), true, this._formatCommand(command, "editCommand")).then((command) => new ApplicationCommand(command, this));
1792
+ }
1793
+
1794
+ /**
1795
+ * Edits command permissions for a specific command in a guild.
1796
+ * Note: You can only add up to 10 permission overwrites for a command.
1797
+ * @arg {String} guildID The guild ID
1798
+ * @arg {String} commandID The command id
1799
+ * @arg {Array<Object>} permissions An array of [permissions objects](https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-application-command-permissions-structure)
1800
+ * @returns {Promise<Object>} Resolves with a [GuildApplicationCommandPermissions](https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-guild-application-command-permissions-structure) object.
1801
+ * @arg {String} [reason] The reason to be displayed in audit logs
1802
+ */
1803
+ editCommandPermissions(guildID, commandID, permissions, reason) {
1804
+ if (!guildID) {
1805
+ throw new Error("You must provide an id of the guild whose permissions you want to edit.");
1806
+ }
1807
+ if (!commandID) {
1808
+ throw new Error("You must provide an id of the command whose permissions you want to edit.");
1809
+ }
1810
+ return this.requestHandler.request("PUT", Endpoints.COMMAND_PERMISSIONS(this.application.id, guildID, commandID), true, { permissions, reason });
1811
+ }
1812
+
1813
+ /**
1814
+ * Edit the application associated with the bot user
1815
+ * @arg {Object} options The properties to edit
1816
+ * @arg {String?} [options.coverImage] The default rich presence invite cover image, as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
1817
+ * @arg {String} [options.customInstallURL] The default custom authorization URL for the application, if enabled
1818
+ * @arg {String} [options.description] The description of the application
1819
+ * @arg {Number} [options.eventWebhooksStatus] Whether webhook events are enabled for the application. `1` to disable, `2` to enable
1820
+ * @arg {Array<String>} [options.eventWebhooksTypes] The webhook event types to subscribe to
1821
+ * @arg {String} [options.eventWebhooksURL] The URL to receive webhook events
1822
+ * @arg {Number} [options.flags] The public flags of the application. Only limited intent flags (`GATEWAY_PRESENCE_LIMITED`, `GATEWAY_GUILD_MEMBERS_LIMITED`, and `GATEWAY_MESSAGE_CONTENT_LIMITED`) can be updated
1823
+ * @arg {String?} [options.icon] The icon of the application, as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
1824
+ * @arg {Object} [options.installParams] The settings for the default in-app authorization link, if enabled
1825
+ * @arg {String} options.installParams.permissions The permissions to request for the bot role
1826
+ * @arg {Array<String>} options.installParams.scopes The scopes to add the application to the server with
1827
+ * @arg {Object} [options.integrationTypesConfig] The default scopes and permissions for each supported installation context, keyed by application integration type (`0` for guild install, `1` for user install). See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/application#application-object-application-integration-type-configuration-object) for object structure
1828
+ * @arg {String} [options.interactionsEndpointURL] The interactions endpoint URL of the application
1829
+ * @arg {String} [options.roleConnectionsVerificationURL] The role connection verification URL of the application
1830
+ * @arg {Array<String>} [options.tags] Tags describing the content and functionality of the application (max of 5 tags, 20 characters per tag)
1831
+ * @returns {Promise<Object>} The updated application object. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/application#application-object) for object structure
1832
+ */
1833
+ editCurrentApplication(options) {
1834
+ return this.requestHandler.request("PATCH", Endpoints.APPLICATION("@me"), true, {
1835
+ cover_image: options.coverImage,
1836
+ custom_install_url: options.customInstallURL,
1837
+ description: options.description,
1838
+ event_webhooks_status: options.eventWebhooksStatus,
1839
+ event_webhooks_types: options.eventWebhooksTypes,
1840
+ event_webhooks_url: options.eventWebhooksURL,
1841
+ flags: options.flags,
1842
+ icon: options.icon,
1843
+ install_params: options.installParams,
1844
+ integration_types_config: options.integrationTypesConfig,
1845
+ interactions_endpoint_url: options.interactionsEndpointURL,
1846
+ role_connections_verification_url: options.roleConnectionsVerificationURL,
1847
+ tags: options.tags,
1848
+ });
1849
+ }
1850
+
1851
+ /**
1852
+ * Edit an existing emoji for this application
1853
+ * @arg {Object} options Emoji options
1854
+ * @arg {String} options.name The name of emoji
1855
+ * @returns {Promise<Object>} An emoji object
1856
+ */
1857
+ editEmoji(emojiID, options) {
1858
+ return this.requestHandler.request("PATCH", Endpoints.APPLICATION_EMOJI(this.application.id, emojiID), true, options);
1859
+ }
1860
+
1861
+ /**
1862
+ * Edit a guild
1863
+ * @arg {String} guildID The ID of the guild
1864
+ * @arg {Object} options The properties to edit
1865
+ * @arg {String?} [options.afkChannelID] The ID of the AFK voice channel
1866
+ * @arg {Number} [options.afkTimeout] The AFK timeout in seconds
1867
+ * @arg {String?} [options.banner] The guild banner image as a base64 data URI (VIP only). Note: base64 strings alone are not base64 data URI strings
1868
+ * @arg {Number?} [options.defaultNotifications] The default notification settings for the guild. 0 is "All Messages", 1 is "Only @mentions".
1869
+ * @arg {String?} [options.description] The description for the guild (VIP only)
1870
+ * @arg {String?} [options.discoverySplash] The guild discovery splash image as a base64 data URI (VIP only). Note: base64 strings alone are not base64 data URI strings
1871
+ * @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.
1872
+ * @arg {Array<String>} [options.features] The enabled features for the guild. Note that only certain features can be toggled with the API
1873
+ * @arg {String?} [options.icon] The guild icon as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
1874
+ * @arg {String} [options.name] The name of the guild
1875
+ * @arg {String?} [options.preferredLocale] Preferred "COMMUNITY" guild language used in server discovery and notices from Discord
1876
+ * @arg {String?} [options.publicUpdatesChannelID] The ID of the channel where admins and moderators of "COMMUNITY" guilds receive notices from Discord
1877
+ * @arg {String?} [options.rulesChannelID] The ID of the channel where "COMMUNITY" guilds display rules and/or guidelines
1878
+ * @arg {String?} [options.safetyAlertsChannelID] The ID of the channel where admins and moderators of Community guilds receive safety alerts from Discord
1879
+ * @arg {String?} [options.splash] The guild splash image as a base64 data URI (VIP only). Note: base64 strings alone are not base64 data URI strings
1880
+ * @arg {Number} [options.systemChannelFlags] The flags for the system channel
1881
+ * @arg {String?} [options.systemChannelID] The ID of the system channel
1882
+ * @arg {Number?} [options.verificationLevel] The guild verification level
1883
+ * @arg {String} [reason] The reason to be displayed in audit logs
1884
+ * @returns {Promise<Guild>}
1885
+ */
1886
+ editGuild(guildID, options, reason) {
1887
+ return this.requestHandler.request("PATCH", Endpoints.GUILD(guildID), true, {
1888
+ name: options.name,
1889
+ icon: options.icon,
1890
+ verification_level: options.verificationLevel,
1891
+ default_message_notifications: options.defaultNotifications,
1892
+ explicit_content_filter: options.explicitContentFilter,
1893
+ system_channel_id: options.systemChannelID,
1894
+ system_channel_flags: options.systemChannelFlags,
1895
+ rules_channel_id: options.rulesChannelID,
1896
+ public_updates_channel_id: options.publicUpdatesChannelID,
1897
+ preferred_locale: options.preferredLocale,
1898
+ afk_channel_id: options.afkChannelID,
1899
+ afk_timeout: options.afkTimeout,
1900
+ splash: options.splash,
1901
+ banner: options.banner,
1902
+ description: options.description,
1903
+ discovery_splash: options.discoverySplash,
1904
+ features: options.features,
1905
+ safety_alerts_channel_id: options.safetyAlertsChannelID,
1906
+ reason: reason,
1907
+ }).then((guild) => new Guild(guild, this));
1908
+ }
1909
+
1910
+ /**
1911
+ * Edit a guild application command
1912
+ * @arg {String} guildID The ID of the guild
1913
+ * @arg {String} commandID The ID of the command
1914
+ * @arg {Object} command A command object
1915
+ * @arg {BigInt | Number | String | Permission?} [command.defaultMemberPermissions] The default permissions the user must have to use the command
1916
+ * @arg {Boolean} [command.defaultPermission] [DEPRECATED] Whether the command is enabled by default when the application is added to a guild. Replaced by `defaultMemberPermissions`
1917
+ * @arg {String} [command.description] The command description, required for `CHAT_INPUT` commands
1918
+ * @arg {Object?} [command.descriptionLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command description
1919
+ * @arg {String} [command.name] The command name
1920
+ * @arg {Object?} [command.nameLocalizations] Localization directory with keys in [available locales](https://discord.dev/reference#locales) for the command name
1921
+ * @arg {Boolean} [command.nsfw] Whether the command is age-restricted
1922
+ * @arg {Array<Object>} [command.options] The application command [options](https://discord.dev/interactions/application-commands#application-command-object-application-command-option-structure)
1923
+ * @returns {Promise<ApplicationCommand>} Resolves with the edited application command
1924
+ */
1925
+ editGuildCommand(guildID, commandID, command) {
1926
+ if (!commandID) {
1927
+ throw new Error("You must provide an id of the command to edit.");
1928
+ }
1929
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_COMMAND(this.application.id, guildID, commandID), true, this._formatCommand(command, "editGuildCommand")).then((command) => new ApplicationCommand(command, this));
1930
+ }
1931
+
1932
+ /**
1933
+ * Edit a guild's discovery data
1934
+ * @arg {String} guildID The ID of the guild
1935
+ * @arg {Object} [options] The guild discovery data
1936
+ * @arg {Boolean} [options.emojiDiscoverabilityEnabled] Whether guild info should be shown when emoji info is loaded
1937
+ * @arg {Array<String>} [options.keywords] The discovery keywords (max 10)
1938
+ * @arg {String} [options.primaryCategoryID] The primary discovery category ID
1939
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
1940
+ * @returns {Promise<Object>} The updated guild's discovery object
1941
+ */
1942
+ editGuildDiscovery(guildID, options = {}) {
1943
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_DISCOVERY(guildID), true, {
1944
+ primary_category_id: options.primaryCategoryID,
1945
+ keywords: options.keywords,
1946
+ emoji_discoverability_enabled: options.emojiDiscoverabilityEnabled,
1947
+ reason: options.reason,
1948
+ });
1949
+ }
1950
+
1951
+ /**
1952
+ * Edit a guild emoji object
1953
+ * @arg {String} guildID The ID of the guild to edit the emoji in
1954
+ * @arg {String} emojiID The ID of the emoji you want to modify
1955
+ * @arg {Object} options Emoji options
1956
+ * @arg {String} [options.name] The name of emoji
1957
+ * @arg {Array} [options.roles] An array containing authorized role IDs
1958
+ * @arg {String} [reason] The reason to be displayed in audit logs
1959
+ * @returns {Promise<Object>} A guild emoji object
1960
+ */
1961
+ editGuildEmoji(guildID, emojiID, options, reason) {
1962
+ options.reason = reason;
1963
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_EMOJI(guildID, emojiID), true, options);
1964
+ }
1965
+
1966
+ /**
1967
+ * Edit a guild's incident actions
1968
+ * @arg {String} guildID The ID of the guild
1969
+ * @arg {Object} options The incident action properties to edit
1970
+ * @arg {Date?} [options.dmsDisabledUntil] When DMs will be enabled again (set as `null` to enable now)
1971
+ * @arg {Date?} [options.invitesDisabledUntil] When invites will be enabled again (set as `null` to enable now)
1972
+ * @returns {Promise<{dmsDisabledUntil: Date?, dmSpamDetectedAt: Date?, invitesDisabledUntil: Date?, raidDetectedAt: Date?}>} An object containing guild incident data
1973
+ */
1974
+ editGuildIncidentActions(guildID, options) {
1975
+ return this.requestHandler.request("PUT", Endpoints.GUILD_INCIDENT_ACTIONS(guildID), true, {
1976
+ dms_disabled_until: options.dmsDisabledUntil,
1977
+ invites_disabled_until: options.invitesDisabledUntil,
1978
+ }).then((actions) => {
1979
+ return {
1980
+ dmsDisabledUntil: actions.dms_disabled_until && Date.parse(actions.dms_disabled_until),
1981
+ dmSpamDetectedAt: actions.dm_spam_detected_at && Date.parse(actions.dm_spam_detected_at),
1982
+ invitesDisabledUntil: actions.invites_disabled_until && Date.parse(actions.invites_disabled_until),
1983
+ raidDetectedAt: actions.raid_detected_at && Date.parse(actions.raid_detected_at),
1984
+ };
1985
+ });
1986
+ }
1987
+
1988
+ /**
1989
+ * Edit a guild member
1990
+ * @arg {String} guildID The ID of the guild
1991
+ * @arg {String} memberID The ID of the member (you can use "@me" if you are editing the bot user)
1992
+ * @arg {Object} options The properties to edit
1993
+ * @arg {String?} [options.avatar] The new avatar for the bot user for this guild, as a base64 data URI. Only available when editing the current bot user. Note: base64 strings alone are not base64 data URI strings
1994
+ * @arg {String?} [options.banner] The new banner for the bot user for this guild, as a base64 data URI. Only available when editing the current bot user. Note: base64 strings alone are not base64 data URI strings
1995
+ * @arg {String?} [options.bio] The new bio for the bot user for this guild. Only available when editing the current bot user
1996
+ * @arg {String?} [options.channelID] The ID of the voice channel to move the member to (must be in voice). Set to `null` to disconnect the member
1997
+ * @arg {Date?} [options.communicationDisabledUntil] When the user's timeout should expire. Set to `null` to instantly remove timeout
1998
+ * @arg {Boolean} [options.deaf] Server deafen the member
1999
+ * @arg {Number} [options.flags] The user's flags - `OR` the `BYPASSES_VERIFICATION` flag (4) to make the member exempt from verification requirements, `NAND` the flag to make the member not exempt
2000
+ * @arg {Boolean} [options.mute] Server mute the member
2001
+ * @arg {String} [options.nick] Set the member's server nickname, "" to remove
2002
+ * @arg {Array<String>} [options.roles] The array of role IDs the member should have
2003
+ * @arg {String} [reason] The reason to be displayed in audit logs
2004
+ * @returns {Promise<Member>}
2005
+ */
2006
+ editGuildMember(guildID, memberID, options, reason) {
2007
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_MEMBER(guildID, memberID), true, {
2008
+ roles: options.roles && options.roles.filter((roleID, index) => options.roles.indexOf(roleID) === index),
2009
+ avatar: options.avatar,
2010
+ banner: options.banner,
2011
+ bio: options.bio,
2012
+ nick: options.nick,
2013
+ mute: options.mute,
2014
+ deaf: options.deaf,
2015
+ channel_id: options.channelID,
2016
+ communication_disabled_until: options.communicationDisabledUntil,
2017
+ flags: options.flags,
2018
+ reason: reason,
2019
+ }).then((member) => new Member(member, this.guilds.get(guildID), this));
2020
+ }
2021
+
2022
+ /**
2023
+ * Edit a guild's onboarding settings
2024
+ * @arg {String} guildID The ID of the guild
2025
+ * @arg {Object} options The properties to edit
2026
+ * @arg {Array<String>} options.defaultChannelIDs The ID of channels that members are opted into automatically
2027
+ * @arg {Boolean} options.enabled Whether onboarding should be enabled or not for the guild
2028
+ * @arg {Number} options.mode The onboarding mode, `0` for default, `1` for advanced
2029
+ * @arg {Array<Object>} options.prompts The [prompts](https://discord.dev/resources/guild#guild-onboarding-object-onboarding-prompt-structure) shown during the onboarding process
2030
+ * @arg {String} [reason] The reason to be displayed in audit logs
2031
+ * @returns {Promise<Object>} The guild's [onboarding settings](https://discord.dev/resources/guild#guild-onboarding-object)
2032
+ */
2033
+ editGuildOnboarding(guildID, options, reason) {
2034
+ options.default_channel_ids = options.defaultChannelIDs;
2035
+ options.reason = reason;
2036
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_ONBOARDING(guildID), true, options);
2037
+ }
2038
+
2039
+ /**
2040
+ * Edit a guild scheduled event
2041
+ * @arg {String} guildID The guild ID where the event will be edited
2042
+ * @arg {String} eventID The guild scheduled event ID to be edited
2043
+ * @arg {Object} event The new guild scheduled event object
2044
+ * @arg {String} [event.channelID] The channel ID of the event. If updating `entityType` to `3` (external), this **must** be set to `null`
2045
+ * @arg {String} [event.description] The description of the event
2046
+ * @arg {Object} [event.entityMetadata] The entity metadata for the scheduled event. This is required if updating `entityType` to `3` (external)
2047
+ * @arg {String} [event.entityMetadata.location] Location of the event. This is required if updating `entityType` to `3` (external)
2048
+ * @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
2049
+ * @arg {String} [event.image] Base 64 encoded image for the event
2050
+ * @arg {String} [event.name] The name of the event
2051
+ * @arg {String} [event.privacyLevel] The privacy level of the event
2052
+ * @arg {Object?} [event.recurrenceRule] The [definitions](https://discord.dev/resources/guild-scheduled-event#guild-scheduled-event-recurrence-rule-object) for how often this event should recur. Properties can be camelCase (preferred) or snake_case
2053
+ * @arg {Date} [event.scheduledEndTime] The time when the scheduled event is scheduled to end. This is required if updating `entityType` to `3` (external)
2054
+ * @arg {Date} [event.scheduledStartTime] The time the event will start
2055
+ * @arg {Number} [event.status] The [status](https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-status) of the scheduled event
2056
+ * @arg {String} [reason] The reason to be displayed in audit logs
2057
+ * @returns {Promise<GuildScheduledEvent>}
2058
+ */
2059
+ editGuildScheduledEvent(guildID, eventID, event, reason) {
2060
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_SCHEDULED_EVENT(guildID, eventID), true, {
2061
+ channel_id: event.channelID,
2062
+ description: event.description,
2063
+ entity_metadata: event.entityMetadata,
2064
+ entity_type: event.entityType,
2065
+ image: event.image,
2066
+ name: event.name,
2067
+ privacy_level: event.privacyLevel,
2068
+ recurrence_rule: this._formatScheduledEventRecurrence(event.recurrenceRule),
2069
+ scheduled_end_time: event.scheduledEndTime,
2070
+ scheduled_start_time: event.scheduledStartTime,
2071
+ status: event.status,
2072
+ reason: reason,
2073
+ }).then((data) => new GuildScheduledEvent(data, this));
2074
+ }
2075
+
2076
+ /**
2077
+ * Edit a guild soundboard sound
2078
+ * @arg {String} guildID The guild ID where the sound will be edited
2079
+ * @arg {String} soundID The ID of the soundboard sound
2080
+ * @arg {Object} options The properties to edit
2081
+ * @arg {String?} [options.emojiID] The ID of the relating custom emoji (mutually exclusive with options.emojiName)
2082
+ * @arg {String?} [options.emojiName] The name of the relating default emoji (mutually exclusive with options.emojiID)
2083
+ * @arg {String} [options.name] The name of the soundboard sound (2-32 characters)
2084
+ * @arg {Number?} [options.volume] The volume of the soundboard sound, between 0 and 1
2085
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
2086
+ * @returns {Promise<SoundboardSound>}
2087
+ */
2088
+ editGuildSoundboardSound(guildID, soundID, options) {
2089
+ options.emoji_id = options.emojiID;
2090
+ options.emoji_name = options.emojiName;
2091
+ return this.requestHandler.request("PATCH", Endpoints.SOUNDBOARD_SOUND_GUILD(guildID, soundID), true, options).then((sound) => new SoundboardSound(sound, this));
2092
+ }
2093
+
2094
+ /**
2095
+ * Edit a guild sticker
2096
+ * @arg {String} stickerID The ID of the sticker
2097
+ * @arg {Object} options The properties to edit
2098
+ * @arg {String} [options.description] The description of the sticker
2099
+ * @arg {String} [options.name] The name of the sticker
2100
+ * @arg {String} [options.tags] The Discord name of a unicode emoji representing the sticker's expression
2101
+ * @arg {String} [reason] The reason to be displayed in audit logs
2102
+ * @returns {Promise<Object>} A sticker object
2103
+ */
2104
+ editGuildSticker(guildID, stickerID, options, reason) {
2105
+ options.reason = reason;
2106
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_STICKER(guildID, stickerID), true, options);
2107
+ }
2108
+
2109
+ /**
2110
+ * Edit a guild template
2111
+ * @arg {String} guildID The ID of the guild
2112
+ * @arg {String} code The template code
2113
+ * @arg {Object} options The properties to edit
2114
+ * @arg {String?} [options.description] The description for the template. Set to `null` to remove the description
2115
+ * @arg {String} [options.name] The name of the template
2116
+ * @returns {Promise<GuildTemplate>}
2117
+ */
2118
+ editGuildTemplate(guildID, code, options) {
2119
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_TEMPLATE_GUILD(guildID, code), true, options).then((template) => new GuildTemplate(template, this));
2120
+ }
2121
+
2122
+ /**
2123
+ * Modify a guild's vanity code
2124
+ * @arg {String} guildID The ID of the guild
2125
+ * @arg {String?} code The new vanity code
2126
+ * @returns {Promise<Object>}
2127
+ */
2128
+ editGuildVanity(guildID, code) {
2129
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_VANITY_URL(guildID), true, {
2130
+ code,
2131
+ });
2132
+ }
2133
+
2134
+ /**
2135
+ * Update a user's voice state - See [caveats](https://discord.com/developers/docs/resources/guild#modify-user-voice-state-caveats)
2136
+ * @arg {String} guildID The ID of the guild
2137
+ * @arg {Object} options The properties to edit
2138
+ * @arg {String} options.channelID The ID of the channel the user is currently in
2139
+ * @arg {Date?} [options.requestToSpeakTimestamp] Sets the user's request to speak - this can only be used when the `userID` param is "@me"
2140
+ * @arg {Boolean} [options.suppress] Toggles the user's suppress state
2141
+ * @arg {String} [userID="@me"] The user ID of the user to update
2142
+ * @returns {Promise}
2143
+ */
2144
+ editGuildVoiceState(guildID, options, userID = "@me") {
2145
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_VOICE_STATE(guildID, userID), true, {
2146
+ channel_id: options.channelID,
2147
+ request_to_speak_timestamp: options.requestToSpeakTimestamp,
2148
+ suppress: options.suppress,
2149
+ });
2150
+ }
2151
+
2152
+ /**
2153
+ * Edit a guild welcome screen
2154
+ * @arg {String} guildID The ID of the guild
2155
+ * @arg {Object} [options] The properties to edit
2156
+ * @arg {String?} [options.description] The description in the welcome screen
2157
+ * @arg {Boolean} [options.enabled] Whether the welcome screen is enabled
2158
+ * @arg {Array<Object>} [options.welcomeChannels] The list of channels in the welcome screen as an array
2159
+ * @arg {String} options.welcomeChannels[].channelID The channel ID of the welcome channel
2160
+ * @arg {String} options.welcomeChannels[].description The description of the welcome channel
2161
+ * @arg {String?} options.welcomeChannels[].emojiID The emoji ID of the welcome channel
2162
+ * @arg {String?} options.welcomeChannels[].emojiName The emoji name of the welcome channel
2163
+ * @returns {Promise<Object>}
2164
+ */
2165
+ editGuildWelcomeScreen(guildID, options) {
2166
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_WELCOME_SCREEN(guildID), true, {
2167
+ description: options.description,
2168
+ enabled: options.enabled,
2169
+ welcome_channels: options.welcomeChannels.map((c) => {
2170
+ return {
2171
+ channel_id: c.channelID,
2172
+ description: c.description,
2173
+ emoji_id: c.emojiID,
2174
+ emoji_name: c.emojiName,
2175
+ };
2176
+ }),
2177
+ });
2178
+ }
2179
+
2180
+ /**
2181
+ * Modify a guild's widget
2182
+ * @arg {String} guildID The ID of the guild
2183
+ * @arg {Object} options The widget object to modify (https://discord.com/developers/docs/resources/guild#modify-guild-widget)
2184
+ * @arg {String?} [options.channelID] The channel ID for the guild widget
2185
+ * @arg {Boolean} [options.enabled] Whether the guild widget is enabled
2186
+ * @arg {String?} [options.reason] The reason to be displayed in audit logs
2187
+ * @returns {Promise<Object>} A guild widget object
2188
+ */
2189
+ editGuildWidget(guildID, options) {
2190
+ if (options.channelID !== undefined) {
2191
+ options.channel_id = options.channelID;
2192
+ }
2193
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_WIDGET_SETTINGS(guildID), true, options);
2194
+ }
2195
+
2196
+ /**
2197
+ * Replace the target users of an invite. The list is processed asynchronously, see `Client#getInviteTargetUsersJobStatus`
2198
+ * @arg {String} inviteID The code of the invite
2199
+ * @arg {Array<String> | Buffer} targetUsers An array of user IDs, or a buffer containing a CSV file with a single column of user IDs
2200
+ * @returns {Promise}
2201
+ */
2202
+ editInviteTargetUsers(inviteID, targetUsers) {
2203
+ return this.requestHandler.request("PUT", Endpoints.INVITE_TARGET_USERS(inviteID), true, undefined, this._formatTargetUsersFile(targetUsers));
2204
+ }
2205
+
2206
+ /**
2207
+ * Edit a lobby
2208
+ * @arg {String} lobbyID The ID of the lobby
2209
+ * @arg {Object} options The properties to edit
2210
+ * @arg {Number} [options.idleTimeoutSeconds] How long to wait, in seconds, before shutting down the lobby once it becomes idle (between 5 and 604800)
2211
+ * @arg {Array<Object>} [options.members] The users of the lobby, replacing the current ones (25 at most). A lobby can hold up to 1000 members: add the others with `addLobbyMember` or `bulkEditLobbyMembers`
2212
+ * @arg {String?} [options.members[].additionalName] An additional display name for the member, such as an in-game character name (1-80 characters). Omit it to keep the current one, or set it to `null` to remove it
2213
+ * @arg {Number} [options.members[].flags] The lobby member flags of the member. See `Constants.LobbyMemberFlags`
2214
+ * @arg {Object<String, String>?} [options.members[].metadata] The metadata of the member, as key/value pairs (1000 characters in total at most)
2215
+ * @arg {String} options.members[].id The ID of the user
2216
+ * @arg {Object<String, String>?} [options.metadata] The metadata of the lobby, as key/value pairs (1000 characters in total at most). It replaces the current metadata
2217
+ * @returns {Promise<Lobby>}
2218
+ */
2219
+ editLobby(lobbyID, options) {
2220
+ return this.requestHandler.request("PATCH", Endpoints.LOBBY(lobbyID), true, this._formatLobby(options)).then((lobby) => new Lobby(lobby, this));
2221
+ }
2222
+
2223
+ /**
2224
+ * Set the moderation metadata of a lobby message. Social SDK clients receive it as a message update
2225
+ * @arg {String} lobbyID The ID of the lobby
2226
+ * @arg {String} messageID The ID of the message
2227
+ * @arg {Object<String, String>} metadata The moderation metadata, as key/value pairs (up to 5 keys, keys of up to 1024 characters and values of up to 2000 characters)
2228
+ * @returns {Promise}
2229
+ */
2230
+ editLobbyMessageModerationMetadata(lobbyID, messageID, metadata) {
2231
+ return this.requestHandler.request("PUT", Endpoints.LOBBY_MESSAGE_MODERATION_METADATA(lobbyID, messageID), true, metadata, undefined, undefined, undefined, {
2232
+ rawBody: true,
2233
+ });
2234
+ }
2235
+
2236
+ /**
2237
+ * Edit a message
2238
+ * @arg {String} channelID The ID of the channel
2239
+ * @arg {String} messageID The ID of the message
2240
+ * @arg {String | Array | Object} content A string, array of strings, or object. If an object is passed:
2241
+ * @arg {Object} [content.allowedMentions] A list of mentions to allow (overrides default)
2242
+ * @arg {Boolean} [content.allowedMentions.everyone] Whether or not to allow @everyone/@here
2243
+ * @arg {Boolean | Array<String>} [content.allowedMentions.roles] Whether or not to allow all role mentions, or an array of specific role mentions to allow
2244
+ * @arg {Boolean | Array<String>} [content.allowedMentions.users] Whether or not to allow all user mentions, or an array of specific user mentions to allow
2245
+ * @arg {Array<Object>} [content.attachments] An array of attachment objects that will be appended to the message, including new files. Only the provided files will be appended
2246
+ * @arg {String} [content.attachments[].description] The description of the file
2247
+ * @arg {String} [content.attachments[].filename] The name of the file. This is not required if you are attaching a new file
2248
+ * @arg {Number | String} content.attachments[].id The ID of the file. If you are attaching a new file, this would be the index of the file
2249
+ * @arg {Array<Object>} [content.components] An array of component objects
2250
+ * @arg {String} [content.components[].custom_id] The ID of the component (type 2 style 1-4 and type 3,5,6,7,8 only)
2251
+ * @arg {Boolean} [content.components[].disabled] Whether the component is disabled (type 2 and 3,5,6,7,8 only)
2252
+ * @arg {Object} [content.components[].emoji] The emoji to be displayed in the component (type 2)
2253
+ * @arg {String} [content.components[].label] The label to be displayed in the component (type 2)
2254
+ * @arg {Array<Object>} [content.components[].default_values] default values for the component (type 5,6,7,8 only)
2255
+ * @arg {String} [content.components[].default_values[].id] id of a user, role, or channel
2256
+ * @arg {String} [content.components[].default_values[].type] type of value that id represents (user, role, or channel)
2257
+ * @arg {Number} [content.components[].max_values] The maximum number of items that can be chosen (1-25, default 1)
2258
+ * @arg {Number} [content.components[].min_values] The minimum number of items that must be chosen (0-25, default 1)
2259
+ * @arg {Array<Object>} [content.components[].options] The options for this component (type 3 only)
2260
+ * @arg {Boolean} [content.components[].options[].default] Whether this option should be the default value selected
2261
+ * @arg {String} [content.components[].options[].description] The description for this option
2262
+ * @arg {Object} [content.components[].options[].emoji] The emoji to be displayed in this option
2263
+ * @arg {String} content.components[].options[].label The label for this option
2264
+ * @arg {Number | String} content.components[].options[].value The value for this option
2265
+ * @arg {String} [content.components[].placeholder] The placeholder text for the component when no option is selected (type 3,5,6,7,8 only)
2266
+ * @arg {String} [content.components[].sku_id] The ID of the SKU to purchase (type 2 style 6 only)
2267
+ * @arg {Number} [content.components[].style] The style of the component (type 2 only) - If 1-4, `custom_id` is required; if 5, `url` is required; if 6, `sku_id` is required
2268
+ * @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 string select; if 4, it is a text input; if 5, it is a user select; if 6, it is a role select; if 7, it is a mentionable select; if 8, it is a channel select; if 9, it is a section; if 10, it is a text display; if 11, it is a thumbnail; if 12, it is a media gallery; if 13, it is a file; if 14, it is a separator; if 17, it is a container; if 18, it is a label (modals only); if 19, it is a file upload (modals only); if 21, it is a radio group (modals only); if 22, it is a checkbox group (modals only); if 23, it is a checkbox (modals only)
2269
+ * @arg {String} [content.components[].url] The URL that the component should open for users (type 2 style 5 only)
2270
+ * @arg {String} [content.content] A content string
2271
+ * @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
2272
+ * @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
2273
+ * @arg {Object | Array<Object>} [content.file] A file object (or an Array of them)
2274
+ * @arg {Buffer} content.file[].file A buffer containing file data
2275
+ * @arg {String} content.file[].name What to name the file
2276
+ * @arg {Number} [content.flags] A number representing the [flags](https://discord.dev/resources/channel#message-object-message-flags) to apply to the message (only SUPPRESS_EMBEDS and SUPPRESS_NOTIFICATIONS)
2277
+ * @returns {Promise<Message>}
2278
+ */
2279
+ editMessage(channelID, messageID, content) {
2280
+ if (content !== undefined) {
2281
+ if (typeof content !== "object" || content === null) {
2282
+ content = {
2283
+ content: "" + content,
2284
+ };
2285
+ } else if (content.content !== undefined && typeof content.content !== "string") {
2286
+ content.content = "" + content.content;
2287
+ } else if (content.embed) {
2288
+ if (!content.embeds) {
2289
+ content.embeds = [];
2290
+ }
2291
+ content.embeds.push(content.embed);
2292
+ }
2293
+ if (content.content !== undefined || content.embeds || content.allowedMentions) {
2294
+ content.allowed_mentions = this._formatAllowedMentions(content.allowedMentions);
2295
+ }
2296
+ }
2297
+ const file = content.file;
2298
+ delete content.file;
2299
+ return this.requestHandler.request("PATCH", Endpoints.CHANNEL_MESSAGE(channelID, messageID), true, file ? { payload_json: content } : content, file).then((message) => new Message(message, this));
2300
+ }
2301
+
2302
+ /**
2303
+ * [DEPRECATED] Edit the bot's nickname in a guild. Use `editGuildMember` instead
2304
+ * @arg {String} guildID The ID of the guild
2305
+ * @arg {String} nick The nickname
2306
+ * @arg {String} [reason] The reason to be displayed in audit logs
2307
+ * @returns {Promise}
2308
+ */
2309
+ editNickname(guildID, nick, reason) {
2310
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_MEMBER_NICK(guildID, "@me"), true, {
2311
+ nick,
2312
+ reason,
2313
+ });
2314
+ }
2315
+
2316
+ /**
2317
+ * Edit a guild role
2318
+ * @arg {String} guildID The ID of the guild the role is in
2319
+ * @arg {String} roleID The ID of the role
2320
+ * @arg {Object} options The properties to edit
2321
+ * @arg {Number} [options.color] The hex color of the role, in number form (ex: 0x3da5b3 or 4040115)
2322
+ * @arg {Object} [options.colors] The role's colors
2323
+ * @arg {Number} [options.colors.primaryColor] The primary color of the role
2324
+ * @arg {Number?} [options.colors.secondaryColor] The secondary color of the role (for gradient roles)
2325
+ * @arg {Number?} [options.colors.tertiaryColor] The tertiary color of the role (for holographic roles)
2326
+ * @arg {Boolean} [options.hoist] Whether to hoist the role in the user list or not
2327
+ * @arg {String} [options.icon] The role icon as a base64 data URI
2328
+ * @arg {Boolean} [options.mentionable] Whether the role is mentionable or not
2329
+ * @arg {String} [options.name] The name of the role
2330
+ * @arg {BigInt | Number | String | Permission} [options.permissions] The role permissions
2331
+ * @arg {String} [options.unicodeEmoji] The role's unicode emoji
2332
+ * @arg {String} [reason] The reason to be displayed in audit logs
2333
+ * @returns {Promise<Role>}
2334
+ */
2335
+ editRole(guildID, roleID, options, reason) {
2336
+ options.unicode_emoji = options.unicodeEmoji;
2337
+ options.reason = reason;
2338
+ if (options.permissions !== undefined) {
2339
+ options.permissions = options.permissions instanceof Permission ? String(options.permissions.allow) : String(options.permissions);
2340
+ }
2341
+ if (options.colors !== undefined) {
2342
+ options.colors = {
2343
+ primary_color: options.colors.primaryColor,
2344
+ secondary_color: options.colors.secondaryColor,
2345
+ tertiary_color: options.colors.tertiaryColor,
2346
+ };
2347
+ }
2348
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_ROLE(guildID, roleID), true, options).then((role) => new Role(role, this.guilds.get(guildID)));
2349
+ }
2350
+
2351
+ /**
2352
+ * Update the role connection metadata for the application
2353
+ * @arg {Array<Object>} data An array of role connection metadata objects. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/application-role-connection-metadata#application-role-connection-metadata-object) for object structure
2354
+ * @returns {Promise<Array<Object>>} An array of role connection metadata objects
2355
+ */
2356
+ editRoleConnectionMetadataRecords(data) {
2357
+ for (const connection of data) {
2358
+ if (connection.key !== undefined) {
2359
+ if (!/^[a-z0-9_]{1,50}$/.test(connection.key)) {
2360
+ throw new Error("Role connection keys can only contain lowercase characters (a-z), numbers (0-9) or underscores (_)");
2361
+ }
2362
+ }
2363
+ }
2364
+ return this.requestHandler.request("PUT", Endpoints.ROLE_CONNECTION_METADATA_RECORDS(this.application.id), true, data);
2365
+ }
2366
+
2367
+ /**
2368
+ * Edit a guild role's position. Note that role position numbers are highest on top and lowest at the bottom.
2369
+ * @arg {String} guildID The ID of the guild the role is in
2370
+ * @arg {String} roleID The ID of the role
2371
+ * @arg {Number} position The new position of the role
2372
+ * @returns {Promise}
2373
+ */
2374
+ editRolePosition(guildID, roleID, position) {
2375
+ if (guildID === roleID) {
2376
+ return Promise.reject(new Error("Cannot move default role"));
2377
+ }
2378
+ let roles = this.guilds.get(guildID).roles;
2379
+ const role = roles.get(roleID);
2380
+ if (!role) {
2381
+ return Promise.reject(new Error(`Role ${roleID} not found`));
2382
+ }
2383
+ if (role.position === position) {
2384
+ return Promise.resolve();
2385
+ }
2386
+ const min = Math.min(position, role.position);
2387
+ const max = Math.max(position, role.position);
2388
+ roles = roles.filter((role) => min <= role.position && role.position <= max && role.id !== roleID).sort((a, b) => a.position - b.position);
2389
+ if (position > role.position) {
2390
+ roles.push(role);
2391
+ } else {
2392
+ roles.unshift(role);
2393
+ }
2394
+ return this.requestHandler.request("PATCH", Endpoints.GUILD_ROLES(guildID), true, roles.map((role, index) => ({
2395
+ id: role.id,
2396
+ position: index + min,
2397
+ })));
2398
+ }
2399
+
2400
+ /**
2401
+ * Edit properties of the bot user
2402
+ * @arg {Object} options The properties to edit
2403
+ * @arg {String?} [options.avatar] The new avatar as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
2404
+ * @arg {String?} [options.banner] The new banner as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
2405
+ * @arg {String} [options.username] The new username
2406
+ * @returns {Promise<ExtendedUser>}
2407
+ */
2408
+ editSelf(options) {
2409
+ return this.requestHandler.request("PATCH", Endpoints.USER("@me"), true, options).then((data) => new ExtendedUser(data, this));
2410
+ }
2411
+
2412
+ /**
2413
+ * Update a stage instance
2414
+ * @arg {String} channelID The ID of the stage channel associated with the instance
2415
+ * @arg {Object} options The properties to edit
2416
+ * @arg {Number} [options.privacyLevel] The privacy level of the stage instance. 1 is public, 2 is guild only
2417
+ * @arg {String} [options.topic] The stage instance topic
2418
+ * @returns {Promise<StageInstance>}
2419
+ */
2420
+ editStageInstance(channelID, options) {
2421
+ return this.requestHandler.request("PATCH", Endpoints.STAGE_INSTANCE(channelID), true, options).then((instance) => new StageInstance(instance, this));
2422
+ }
2423
+
2424
+ /**
2425
+ * Update the bot's status on all guilds
2426
+ * @arg {String} [status] Sets the bot's status, either "online", "idle", "dnd", or "invisible"
2427
+ * @arg {Array | Object} [activities] Sets the bot's activities. A single activity object is also accepted for backwards compatibility
2428
+ * @arg {String} [activities[].name] The name of the activity. Note: When setting a custom status, use `state` instead
2429
+ * @arg {Number} activities[].type The type of the activity. 0 is playing, 1 is streaming (Twitch only), 2 is listening, 3 is watching, 4 is custom status, 5 is competing in
2430
+ * @arg {String} [activities[].url] The URL of the activity
2431
+ * @arg {String} [activities[].state] The state of the activity. This is the text to be displayed as the bots custom status
2432
+ */
2433
+ editStatus(status, activities) {
2434
+ if (activities === undefined && typeof status === "object") {
2435
+ activities = status;
2436
+ status = undefined;
2437
+ }
2438
+ if (status) {
2439
+ this.presence.status = status;
2440
+ }
2441
+ if (activities === null) {
2442
+ activities = [];
2443
+ } else if (activities && !Array.isArray(activities)) {
2444
+ activities = [activities];
2445
+ }
2446
+ if (activities !== undefined) {
2447
+ this.presence.activities = activities;
2448
+ }
2449
+
2450
+ this.shards.forEach((shard) => {
2451
+ shard.editStatus(status, activities);
2452
+ });
2453
+ }
2454
+
2455
+ /**
2456
+ * Edit a webhook
2457
+ * @arg {String} webhookID The ID of the webhook
2458
+ * @arg {Object} options Webhook options
2459
+ * @arg {String} [options.avatar] The new default avatar as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
2460
+ * @arg {String} [options.channelID] The new channel ID where webhooks should be sent to
2461
+ * @arg {String} [options.name] The new default name
2462
+ * @arg {String} [token] The token of the webhook, used instead of the Bot Authorization token
2463
+ * @arg {String} [reason] The reason to be displayed in audit logs
2464
+ * @returns {Promise<Object>} Resolves with a webhook object
2465
+ */
2466
+ editWebhook(webhookID, options, token, reason) {
2467
+ return this.requestHandler.request("PATCH", token ? Endpoints.WEBHOOK_TOKEN(webhookID, token) : Endpoints.WEBHOOK(webhookID), !token, {
2468
+ name: options.name,
2469
+ avatar: options.avatar,
2470
+ channel_id: options.channelID,
2471
+ reason: reason,
2472
+ });
2473
+ }
2474
+
2475
+ /**
2476
+ * Edit a webhook message
2477
+ * @arg {String} webhookID The ID of the webhook
2478
+ * @arg {String} token The token of the webhook
2479
+ * @arg {String} messageID The ID of the message
2480
+ * @arg {Object} options Webhook message edit options
2481
+ * @arg {Object} [options.allowedMentions] A list of mentions to allow (overrides default)
2482
+ * @arg {Boolean} [options.allowedMentions.everyone] Whether or not to allow @everyone/@here
2483
+ * @arg {Boolean} [options.allowedMentions.repliedUser] Whether or not to mention the author of the message being replied to
2484
+ * @arg {Boolean | Array<String>} [options.allowedMentions.roles] Whether or not to allow all role mentions, or an array of specific role mentions to allow
2485
+ * @arg {Boolean | Array<String>} [options.allowedMentions.users] Whether or not to allow all user mentions, or an array of specific user mentions to allow
2486
+ * @arg {Array<Object>} [options.attachments] An array of attachment objects that will be appended to the message, including new files. Only the provided files will be appended
2487
+ * @arg {String} [options.attachments[].description] The description of the file
2488
+ * @arg {String} [options.attachments[].filename] The name of the file. This is not required if you are attaching a new file
2489
+ * @arg {Number | String} options.attachments[].id The ID of the file. If you are attaching a new file, this would be the index of the file
2490
+ * @arg {Array<Object>} [options.components] An array of component objects
2491
+ * @arg {String} [options.components[].custom_id] The ID of the component (type 2 style 1-4 and type 3,5,6,7,8 only)
2492
+ * @arg {Boolean} [options.components[].disabled] Whether the component is disabled (type 2 and 3,5,6,7,8 only)
2493
+ * @arg {Object} [options.components[].emoji] The emoji to be displayed in the component (type 2)
2494
+ * @arg {String} [options.components[].label] The label to be displayed in the component (type 2)
2495
+ * @arg {Array<Object>} [options.components[].default_values] default values for the component (type 5,6,7,8 only)
2496
+ * @arg {String} [options.components[].default_values[].id] id of a user, role, or channel
2497
+ * @arg {String} [options.components[].default_values[].type] type of value that id represents (user, role, or channel)
2498
+ * @arg {Number} [options.components[].max_values] The maximum number of items that can be chosen (1-25, default 1)
2499
+ * @arg {Number} [options.components[].min_values] The minimum number of items that must be chosen (0-25, default 1)
2500
+ * @arg {Array<Object>} [options.components[].options] The options for this component (type 3 only)
2501
+ * @arg {Boolean} [options.components[].options[].default] Whether this option should be the default value selected
2502
+ * @arg {String} [options.components[].options[].description] The description for this option
2503
+ * @arg {Object} [options.components[].options[].emoji] The emoji to be displayed in this option
2504
+ * @arg {String} options.components[].options[].label The label for this option
2505
+ * @arg {Number | String} options.components[].options[].value The value for this option
2506
+ * @arg {String} [options.components[].placeholder] The placeholder text for the component when no option is selected (type 3,5,6,7,8 only)
2507
+ * @arg {String} [options.components[].sku_id] The ID of the SKU to purchase (type 2 style 6 only)
2508
+ * @arg {Number} [options.components[].style] The style of the component (type 2 only) - If 1-4, `custom_id` is required; if 5, `url` is required; if 6, `sku_id` is required
2509
+ * @arg {Number} options.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 string select; if 4, it is a text input; if 5, it is a user select; if 6, it is a role select; if 7, it is a mentionable select; if 8, it is a channel select; if 9, it is a section; if 10, it is a text display; if 11, it is a thumbnail; if 12, it is a media gallery; if 13, it is a file; if 14, it is a separator; if 17, it is a container; if 18, it is a label (modals only); if 19, it is a file upload (modals only); if 21, it is a radio group (modals only); if 22, it is a checkbox group (modals only); if 23, it is a checkbox (modals only)
2510
+ * @arg {String} [options.components[].url] The URL that the component should open for users (type 2 style 5 only)
2511
+ * @arg {String} [options.content] A content string
2512
+ * @arg {Object} [options.embed] [DEPRECATED] An embed object. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/channel#embed-object) for object structure
2513
+ * @arg {Array<Object>} [options.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
2514
+ * @arg {Object | Array<Object>} [options.file] A file object (or an Array of them)
2515
+ * @arg {Buffer} options.file[].file A buffer containing file data
2516
+ * @arg {String} options.file[].name What to name the file
2517
+ * @returns {Promise<Message>}
2518
+ */
2519
+ editWebhookMessage(webhookID, token, messageID, options) {
2520
+ if (options.allowedMentions) {
2521
+ options.allowed_mentions = this._formatAllowedMentions(options.allowedMentions);
2522
+ }
2523
+ const file = options.file;
2524
+ delete options.file;
2525
+
2526
+ if (options.embed) {
2527
+ if (!options.embeds) {
2528
+ options.embeds = [];
2529
+ }
2530
+ options.embeds.push(options.embed);
2531
+ }
2532
+
2533
+ return this.requestHandler.request("PATCH", Endpoints.WEBHOOK_MESSAGE(webhookID, token, messageID), false, file ? { payload_json: options } : options, file).then((response) => new Message(response, this));
2534
+ }
2535
+
2536
+ /**
2537
+ * Immediately end a poll. Note: You cannot end polls created by another user.
2538
+ * @arg {String} channelID The ID of the channel
2539
+ * @arg {String} messageID The ID of the message that the poll is in
2540
+ * @returns {Promise<Message>}
2541
+ */
2542
+ endPoll(channelID, messageID) {
2543
+ return this.requestHandler.request("POST", Endpoints.POLL_END(channelID, messageID), true).then((message) => new Message(message, this));
2544
+ }
2545
+
2546
+ /**
2547
+ * Execute a GitHub-style webhook, the way GitHub sends its events
2548
+ * @arg {String} webhookID The ID of the webhook
2549
+ * @arg {String} token The token of the webhook
2550
+ * @arg {String} event The GitHub event of the payload, sent as the `X-GitHub-Event` header (e.g. "push", "issues", "pull_request"). See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/webhook#execute-githubcompatible-webhook) for the supported events
2551
+ * @arg {Object} payload The GitHub event payload
2552
+ * @arg {Object} [options] Execution options
2553
+ * @arg {Boolean} [options.auth=false] Whether or not to authenticate with the bot token
2554
+ * @arg {String} [options.threadID] The ID of the thread channel in the webhook's channel to send the message to
2555
+ * @arg {Boolean} [options.wait] Whether to wait for the server to confirm the message create or not (Discord waits by default)
2556
+ * @returns {Promise}
2557
+ */
2558
+ executeGitHubWebhook(webhookID, token, event, payload, options = {}) {
2559
+ let qs = "";
2560
+ if (options.wait !== undefined) {
2561
+ qs += "&wait=" + !!options.wait;
2562
+ }
2563
+ if (options.threadID) {
2564
+ qs += "&thread_id=" + options.threadID;
2565
+ }
2566
+ return this.requestHandler.request("POST", Endpoints.WEBHOOK_TOKEN_GITHUB(webhookID, token) + (qs ? "?" + qs.substring(1) : ""), !!options.auth, payload, undefined, undefined, undefined, {
2567
+ headers: { "X-GitHub-Event": event },
2568
+ rawBody: true,
2569
+ });
2570
+ }
2571
+
2572
+ /**
2573
+ * Execute a slack-style webhook
2574
+ * @arg {String} webhookID The ID of the webhook
2575
+ * @arg {String} token The token of the webhook
2576
+ * @arg {Object} options Slack webhook options
2577
+ * @arg {Boolean} [options.auth=false] Whether or not to authenticate with the bot token.
2578
+ * @arg {String} [options.threadID] The ID of the thread channel in the webhook's channel to send the message to
2579
+ * @arg {Boolean} [options.wait=false] Whether to wait for the server to confirm the message create or not
2580
+ * @returns {Promise}
2581
+ */
2582
+ executeSlackWebhook(webhookID, token, options) {
2583
+ const wait = !!options.wait;
2584
+ options.wait = undefined;
2585
+ const auth = !!options.auth;
2586
+ options.auth = undefined;
2587
+ const threadID = options.threadID;
2588
+ options.threadID = undefined;
2589
+ let qs = "";
2590
+ if (wait) {
2591
+ qs += "&wait=true";
2592
+ }
2593
+ if (threadID) {
2594
+ qs += "&thread_id=" + threadID;
2595
+ }
2596
+ return this.requestHandler.request("POST", Endpoints.WEBHOOK_TOKEN_SLACK(webhookID, token) + (qs ? "?" + qs : ""), auth, options);
2597
+ }
2598
+
2599
+ /**
2600
+ * Execute a webhook
2601
+ * @arg {String} webhookID The ID of the webhook
2602
+ * @arg {String} token The token of the webhook
2603
+ * @arg {Object} options Webhook execution options
2604
+ * @arg {Object} [options.allowedMentions] A list of mentions to allow (overrides default)
2605
+ * @arg {Boolean} [options.allowedMentions.everyone] Whether or not to allow @everyone/@here
2606
+ * @arg {Boolean | Array<String>} [options.allowedMentions.roles] Whether or not to allow all role mentions, or an array of specific role mentions to allow
2607
+ * @arg {Boolean | Array<String>} [options.allowedMentions.users] Whether or not to allow all user mentions, or an array of specific user mentions to allow
2608
+ * @arg {Array<Object>} [options.attachments] An array of attachment objects that will be appended to the message, including new files. Only the provided files will be appended
2609
+ * @arg {String} [options.attachments[].description] The description of the file
2610
+ * @arg {String} [options.attachments[].filename] The name of the file. This is not required if you are attaching a new file
2611
+ * @arg {Number | String} options.attachments[].id The ID of the file. If you are attaching a new file, this would be the index of the file
2612
+ * @arg {Boolean} [options.auth=false] Whether or not to authenticate with the bot token.
2613
+ * @arg {String} [options.avatarURL] A URL for a custom avatar, defaults to webhook default avatar if not specified
2614
+ * @arg {Array<Object>} [options.components] An array of component objects
2615
+ * @arg {String} [options.components[].custom_id] The ID of the component (type 2 style 1-4 and type 3,5,6,7,8 only)
2616
+ * @arg {Boolean} [options.components[].disabled] Whether the component is disabled (type 2 and 3,5,6,7,8 only)
2617
+ * @arg {Object} [options.components[].emoji] The emoji to be displayed in the component (type 2)
2618
+ * @arg {String} [options.components[].label] The label to be displayed in the component (type 2)
2619
+ * @arg {Array<Object>} [options.components[].default_values] default values for the component (type 5,6,7,8 only)
2620
+ * @arg {String} [options.components[].default_values[].id] id of a user, role, or channel
2621
+ * @arg {String} [options.components[].default_values[].type] type of value that id represents (user, role, or channel)
2622
+ * @arg {Number} [options.components[].max_values] The maximum number of items that can be chosen (1-25, default 1)
2623
+ * @arg {Number} [options.components[].min_values] The minimum number of items that must be chosen (0-25, default 1)
2624
+ * @arg {Array<Object>} [options.components[].options] The options for this component (type 3 only)
2625
+ * @arg {Boolean} [options.components[].options[].default] Whether this option should be the default value selected
2626
+ * @arg {String} [options.components[].options[].description] The description for this option
2627
+ * @arg {Object} [options.components[].options[].emoji] The emoji to be displayed in this option
2628
+ * @arg {String} options.components[].options[].label The label for this option
2629
+ * @arg {Number | String} options.components[].options[].value The value for this option
2630
+ * @arg {String} [options.components[].placeholder] The placeholder text for the component when no option is selected (type 3,5,6,7,8 only)
2631
+ * @arg {String} [options.components[].sku_id] The ID of the SKU to purchase (type 2 style 6 only)
2632
+ * @arg {Number} [options.components[].style] The style of the component (type 2 only) - If 1-4, `custom_id` is required; if 5, `url` is required; if 6, `sku_id` is required
2633
+ * @arg {Number} options.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 string select; if 4, it is a text input; if 5, it is a user select; if 6, it is a role select; if 7, it is a mentionable select; if 8, it is a channel select; if 9, it is a section; if 10, it is a text display; if 11, it is a thumbnail; if 12, it is a media gallery; if 13, it is a file; if 14, it is a separator; if 17, it is a container; if 18, it is a label (modals only); if 19, it is a file upload (modals only); if 21, it is a radio group (modals only); if 22, it is a checkbox group (modals only); if 23, it is a checkbox (modals only)
2634
+ * @arg {String} [options.components[].url] The URL that the component should open for users (type 2 style 5 only)
2635
+ * @arg {String} [options.content] A content string
2636
+ * @arg {Object} [options.embed] An embed object. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/channel#embed-object) for object structure
2637
+ * @arg {Array<Object>} [options.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
2638
+ * @arg {Object | Array<Object>} [options.file] A file object (or an Array of them)
2639
+ * @arg {Buffer} options.file.file A buffer containing file data
2640
+ * @arg {String} options.file.name What to name the file
2641
+ * @arg {Number} [options.flags] Flags to execute the webhook with, 64 for ephemeral (Interaction webhooks only)
2642
+ * @arg {Object} [options.poll] A poll object. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/poll#poll-object) for object structure
2643
+ * @arg {String} [options.threadID] The ID of the thread channel in the webhook's channel to send the message to
2644
+ * @arg {Boolean} [options.tts=false] Whether the message should be a TTS message or not
2645
+ * @arg {String} [options.username] A custom username, defaults to webhook default username if not specified
2646
+ * @arg {Boolean} [options.wait=false] Whether to wait for the server to confirm the message create or not
2647
+ * @returns {Promise<Message?>}
2648
+ */
2649
+ executeWebhook(webhookID, token, options) {
2650
+ let qs = "";
2651
+ if (options.wait) {
2652
+ qs += "&wait=true";
2653
+ }
2654
+ if (options.threadID) {
2655
+ qs += "&thread_id=" + options.threadID;
2656
+ }
2657
+ if (options.allowedMentions) {
2658
+ options.allowed_mentions = this._formatAllowedMentions(options.allowedMentions);
2659
+ }
2660
+ const file = options.file;
2661
+ delete options.file;
2662
+
2663
+ if (options.embed) {
2664
+ if (!options.embeds) {
2665
+ options.embeds = [];
2666
+ }
2667
+ options.embeds.push(options.embed);
2668
+ }
2669
+ options.avatar_url = options.avatarURL;
2670
+ return this.requestHandler.request("POST", Endpoints.WEBHOOK_TOKEN(webhookID, token) + (qs ? "?" + qs : ""), !!options.auth, file ? { payload_json: options } : options, file).then((response) => options.wait ? new Message(response, this) : undefined);
2671
+ }
2672
+
2673
+ /**
2674
+ * Follow a NewsChannel in another channel. This creates a webhook in the target channel
2675
+ * @arg {String} channelID The ID of the NewsChannel
2676
+ * @arg {String} options.webhookChannelID The ID of the target channel
2677
+ * @arg {String} [reason] The reason to be displayed in audit logs
2678
+ * @returns {Object} An object containing the NewsChannel's ID and the new webhook's ID
2679
+ */
2680
+ followChannel(channelID, webhookChannelID, reason) {
2681
+ return this.requestHandler.request("POST", Endpoints.CHANNEL_FOLLOW(channelID), true, { webhook_channel_id: webhookChannelID, reason: reason });
2682
+ }
2683
+
2684
+ /**
2685
+ * Get all active threads in a guild
2686
+ * @arg {String} guildID The ID of the guild
2687
+ * @returns {Promise<Object>} An object containing an array of `threads` and an array of `members`
2688
+ */
2689
+ getActiveGuildThreads(guildID) {
2690
+ return this.requestHandler.request("GET", Endpoints.THREADS_GUILD_ACTIVE(guildID), true).then((response) => {
2691
+ return {
2692
+ members: response.members.map((member) => new ThreadMember(member, this)),
2693
+ threads: response.threads.map((thread) => Channel.from(thread, this)),
2694
+ };
2695
+ });
2696
+ }
2697
+
2698
+ /**
2699
+ * Get an activity instance of the application
2700
+ * @arg {String} instanceID The ID of the activity instance
2701
+ * @returns {Promise<Object>} An object containing the `applicationID`, `instanceID`, `launchID`, `location` (with its `id`, `kind`, `channelID` and `guildID`) and the IDs of the connected `users`
2702
+ */
2703
+ getApplicationActivityInstance(instanceID) {
2704
+ return this.requestHandler.request("GET", Endpoints.APPLICATION_ACTIVITY_INSTANCE(this.application.id, instanceID), true).then((instance) => ({
2705
+ applicationID: instance.application_id,
2706
+ instanceID: instance.instance_id,
2707
+ launchID: instance.launch_id,
2708
+ location: instance.location && {
2709
+ channelID: instance.location.channel_id,
2710
+ guildID: instance.location.guild_id,
2711
+ id: instance.location.id,
2712
+ kind: instance.location.kind,
2713
+ },
2714
+ users: instance.users,
2715
+ }));
2716
+ }
2717
+
2718
+ /**
2719
+ * Get the game profile of a user, shown in the game stats widgets of their Discord profile. The user must have authorized the application with the `application_identities.write` scope
2720
+ * @arg {String} userID The ID of the user
2721
+ * @arg {String} providerIssuedUserID The ID of the user in your system
2722
+ * @returns {Promise<Object>} An object containing the `username` of the user in your system, the application's own `metadata`, and the profile `data`. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/application-identity-profile#profile-data-object) for the structure of `data`
2723
+ */
2724
+ getApplicationIdentityProfile(userID, providerIssuedUserID) {
2725
+ return this.requestHandler.request("GET", Endpoints.APPLICATION_IDENTITY_PROFILE(this.application.id, userID, encodeURIComponent(providerIssuedUserID)), true, undefined, undefined, "/applications/:id/users/:id/identities/:id/profile");
2726
+ }
2727
+
2728
+ /**
2729
+ * Get all archived threads in a channel
2730
+ * @arg {String} channelID The ID of the channel
2731
+ * @arg {String} type The type of thread channel, either "public" or "private"
2732
+ * @arg {Object} [options] Additional options when requesting archived threads
2733
+ * @arg {Date} [options.before] List of threads to return before the timestamp
2734
+ * @arg {Number} [options.limit] Maximum number of threads to return
2735
+ * @returns {Promise<Object>} An object containing an array of `threads`, an array of `members` and whether the response `hasMore` threads that could be returned in a subsequent call
2736
+ */
2737
+ getArchivedThreads(channelID, type, options = {}) {
2738
+ return this.requestHandler.request("GET", Endpoints.THREADS_ARCHIVED(channelID, type), true, options).then((response) => {
2739
+ return {
2740
+ hasMore: response.has_more,
2741
+ members: response.members.map((member) => new ThreadMember(member, this)),
2742
+ threads: response.threads.map((thread) => Channel.from(thread, this)),
2743
+ };
2744
+ });
2745
+ }
2746
+
2747
+ /**
2748
+ * Get an existing auto moderation rule
2749
+ * @arg {String} guildID The ID of the guild to get the rule from
2750
+ * @arg {String} ruleID The ID of the rule to get
2751
+ * @returns {Promise<AutoModerationRule>}
2752
+ */
2753
+ getAutoModerationRule(guildID, ruleID) {
2754
+ return this.requestHandler.request("GET", Endpoints.AUTO_MODERATION_RULE(guildID, ruleID), true).then((rule) => new AutoModerationRule(rule, this));
2755
+ }
2756
+
2757
+ /**
2758
+ * Get a guild's auto moderation rules
2759
+ * @arg {String} guildID The ID of the guild to get the rules of
2760
+ * @returns {Promise<Array<AutoModerationRule>>}
2761
+ */
2762
+ getAutoModerationRules(guildID) {
2763
+ return this.requestHandler.request("GET", Endpoints.AUTO_MODERATION_RULES(guildID), true).then((rules) => rules.map((rule) => new AutoModerationRule(rule, this)));
2764
+ }
2765
+
2766
+ /**
2767
+ * Get general and bot-specific info on connecting to the Discord gateway (e.g. connection ratelimit)
2768
+ * @returns {Promise<Object>} Resolves with an object containing gateway connection info
2769
+ */
2770
+ getBotGateway() {
2771
+ if (!this._token.startsWith("Bot ")) {
2772
+ this._token = "Bot " + this._token;
2773
+ }
2774
+ return this.requestHandler.request("GET", Endpoints.GATEWAY_BOT, true);
2775
+ }
2776
+
2777
+ /**
2778
+ * Get a Channel object from a channel ID
2779
+ * @arg {String} channelID The ID of the channel
2780
+ * @returns {CategoryChannel | DMChannel | ForumChannel | NewsChannel | NewsThreadChannel | PrivateThreadChannel | PublicThreadChannel | TextChannel | VoiceChannel}
2781
+ */
2782
+ getChannel(channelID) {
2783
+ if (!channelID) {
2784
+ throw new Error(`Invalid channel ID: ${channelID}`);
2785
+ }
2786
+
2787
+ if (this.channelGuildMap[channelID] && this.guilds.get(this.channelGuildMap[channelID])) {
2788
+ return this.guilds.get(this.channelGuildMap[channelID]).channels.get(channelID);
2789
+ }
2790
+ if (this.threadGuildMap[channelID] && this.guilds.get(this.threadGuildMap[channelID])) {
2791
+ return this.guilds.get(this.threadGuildMap[channelID]).threads.get(channelID);
2792
+ }
2793
+ return this.dmChannels.get(channelID);
2794
+ }
2795
+
2796
+ /**
2797
+ * Get all invites in a channel
2798
+ * @arg {String} channelID The ID of the channel
2799
+ * @returns {Promise<Array<Invite>>}
2800
+ */
2801
+ getChannelInvites(channelID) {
2802
+ return this.requestHandler.request("GET", Endpoints.CHANNEL_INVITES(channelID), true).then((invites) => invites.map((invite) => new Invite(invite, this)));
2803
+ }
2804
+
2805
+ /**
2806
+ * Get the computed permissions of a member in a channel, including their roles and member-specific overwrites
2807
+ * @arg {String} channelID The ID of the channel
2808
+ * @arg {String} memberID The ID of the member
2809
+ * @arg {Boolean} [implicit=true] Whether to apply implicit permission masking for a missing `VIEW_CHANNEL` or voice/stage `CONNECT` permission
2810
+ * @returns {Promise<Permission>}
2811
+ */
2812
+ getChannelMemberPermissions(channelID, memberID, implicit) {
2813
+ return this.requestHandler.request("GET", Endpoints.CHANNEL_PERMISSIONS_MEMBER(channelID, memberID), true, {
2814
+ implicit,
2815
+ }).then((response) => new Permission(response.permissions));
2816
+ }
2817
+
2818
+ /**
2819
+ * Get the permissions granted by a role (together with `@everyone`) in a channel, applying their channel overwrites
2820
+ * @arg {String} channelID The ID of the channel
2821
+ * @arg {String} roleID The ID of the role
2822
+ * @arg {Boolean} [implicit=true] Whether to apply implicit permission masking for a missing `VIEW_CHANNEL` or voice/stage `CONNECT` permission
2823
+ * @returns {Promise<Permission>}
2824
+ */
2825
+ getChannelRolePermissions(channelID, roleID, implicit) {
2826
+ return this.requestHandler.request("GET", Endpoints.CHANNEL_PERMISSIONS_ROLE(channelID, roleID), true, {
2827
+ implicit,
2828
+ }).then((response) => new Permission(response.permissions));
2829
+ }
2830
+
2831
+ /**
2832
+ * Get all the webhooks in a channel
2833
+ * @arg {String} channelID The ID of the channel to get webhooks for
2834
+ * @returns {Promise<Array<Object>>} Resolves with an array of webhook objects
2835
+ */
2836
+ getChannelWebhooks(channelID) {
2837
+ return this.requestHandler.request("GET", Endpoints.CHANNEL_WEBHOOKS(channelID), true);
2838
+ }
2839
+
2840
+ /**
2841
+ * Get a global application command
2842
+ * @arg {String} commandID The command id
2843
+ * @returns {Promise<ApplicationCommand>}
2844
+ */
2845
+ getCommand(commandID) {
2846
+ if (!commandID) {
2847
+ throw new Error("You must provide an id of the command to get.");
2848
+ }
2849
+ return this.requestHandler.request("GET", Endpoints.COMMAND(this.application.id, commandID), true).then((command) => new ApplicationCommand(command, this));
2850
+ }
2851
+
2852
+ /**
2853
+ * Get the a guild's application command permissions
2854
+ * @arg {String} guildID The guild ID
2855
+ * @arg {String} commandID The command id
2856
+ * @returns {Promise<Object>} Resolves with a guild application command permissions object.
2857
+ */
2858
+ getCommandPermissions(guildID, commandID) {
2859
+ if (!guildID) {
2860
+ throw new Error("You must provide an id of the guild whose permissions you want to get.");
2861
+ }
2862
+ if (!commandID) {
2863
+ throw new Error("You must provide an id of the command whose permissions you want to get.");
2864
+ }
2865
+ return this.requestHandler.request("GET", Endpoints.COMMAND_PERMISSIONS(this.application.id, guildID, commandID), true);
2866
+ }
2867
+
2868
+ /**
2869
+ * Get the global application commands
2870
+ * @arg {Boolean} [withLocalizations] Whether to include the `nameLocalizations` and `descriptionLocalizations` of the commands
2871
+ * @returns {Promise<Array<ApplicationCommand>>}
2872
+ */
2873
+ getCommands(withLocalizations) {
2874
+ return this.requestHandler.request("GET", Endpoints.COMMANDS(this.application.id), true, {
2875
+ with_localizations: withLocalizations,
2876
+ }).then((commands) => commands.map((command) => new ApplicationCommand(command, this)));
2877
+ }
2878
+
2879
+ /**
2880
+ * Get the application associated with the bot user
2881
+ * @returns {Promise<Object>} The application object. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/application#application-object) for object structure
2882
+ */
2883
+ getCurrentApplication() {
2884
+ return this.requestHandler.request("GET", Endpoints.APPLICATION("@me"), true);
2885
+ }
2886
+
2887
+ /**
2888
+ * Get a list of discovery categories
2889
+ * @returns {Promise<Array<Object>>}
2890
+ */
2891
+ getDiscoveryCategories() {
2892
+ return this.requestHandler.request("GET", Endpoints.DISCOVERY_CATEGORIES, true);
2893
+ }
2894
+
2895
+ /**
2896
+ * Get a DM channel with a user, or create one if it does not exist
2897
+ * @arg {String} userID The ID of the user
2898
+ * @returns {Promise<DMChannel>}
2899
+ */
2900
+ getDMChannel(userID) {
2901
+ if (this.dmChannelMap[userID]) {
2902
+ return Promise.resolve(this.dmChannels.get(this.dmChannelMap[userID]));
2903
+ }
2904
+ return this.requestHandler.request("POST", Endpoints.USER_CHANNELS("@me"), true, {
2905
+ recipient_id: userID,
2906
+ }).then((dmChannel) => new DMChannel(dmChannel, this));
2907
+ }
2908
+
2909
+ /**
2910
+ * Get an emoji for this application
2911
+ * @arg {String} emojiID The ID of the emoji
2912
+ * @returns {Promise<Object>} Resolves with an emoji object
2913
+ */
2914
+ getEmoji(emojiID) {
2915
+ return this.requestHandler.request("GET", Endpoints.APPLICATION_EMOJI(this.application.id, emojiID), true).then((emoji) => {
2916
+ if (emoji.user) {
2917
+ emoji.user = this.users.update(emoji.user, this);
2918
+ }
2919
+
2920
+ return emoji;
2921
+ });
2922
+ }
2923
+
2924
+ /**
2925
+ * Get a guild from the guild's emoji ID
2926
+ * @arg {String} emojiID The ID of the emoji
2927
+ * @returns {Promise<Guild>}
2928
+ */
2929
+ getEmojiGuild(emojiID) {
2930
+ return this.requestHandler.request("GET", Endpoints.CUSTOM_EMOJI_GUILD(emojiID), true).then((result) => new Guild(result, this));
2931
+ }
2932
+
2933
+ /**
2934
+ * Get the emojis for this application
2935
+ * @returns {Promise<Object>} Resolves with an object that contains a property "items" which is an array of emoji objects
2936
+ */
2937
+ getEmojis() {
2938
+ return this.requestHandler.request("GET", Endpoints.APPLICATION_EMOJIS(this.application.id), true).then((data) => {
2939
+ data.items = data.items.map((emoji) => {
2940
+ if (emoji.user) {
2941
+ emoji.user = this.users.update(emoji.user, this);
2942
+ }
2943
+
2944
+ return emoji;
2945
+ });
2946
+
2947
+ return data;
2948
+ });
2949
+ }
2950
+
2951
+ /**
2952
+ * Get an entitlement of the application
2953
+ * @arg {String} entitlementID The ID of the entitlement
2954
+ * @returns {Promise<Entitlement>}
2955
+ */
2956
+ getEntitlement(entitlementID) {
2957
+ return this.requestHandler.request("GET", Endpoints.ENTITLEMENT(this.application.id, entitlementID), true).then((entitlement) => new Entitlement(entitlement, this));
2958
+ }
2959
+
2960
+ /**
2961
+ * Get the entitlements of the application
2962
+ * @arg {Object} [options] The options for the request
2963
+ * @arg {String} [options.after] Retrieve entitlements after this entitlement ID
2964
+ * @arg {String} [options.before] Retrieve entitlements before this entitlement ID
2965
+ * @arg {Boolean} [options.excludeDeleted=true] Whether deleted entitlements should be omitted
2966
+ * @arg {Boolean} [options.excludeEnded=false] Whether ended entitlements should be omitted
2967
+ * @arg {String} [options.guildID] The ID of the guild to look up entitlements for
2968
+ * @arg {Number} [options.limit=100] The number of entitlements to return (1-100)
2969
+ * @arg {Array<String>} [options.skuIDs] The IDs of the SKUs to check entitlements for
2970
+ * @arg {String} [options.userID] The ID of the user to look up entitlements for
2971
+ * @returns {Promise<Array<Entitlement>>}
2972
+ */
2973
+ getEntitlements(options = {}) {
2974
+ return this.requestHandler.request("GET", Endpoints.ENTITLEMENTS(this.application.id), true, {
2975
+ after: options.after,
2976
+ before: options.before,
2977
+ exclude_deleted: options.excludeDeleted,
2978
+ exclude_ended: options.excludeEnded,
2979
+ guild_id: options.guildID,
2980
+ limit: options.limit,
2981
+ sku_ids: options.skuIDs && options.skuIDs.join(","),
2982
+ user_id: options.userID,
2983
+ }).then((entitlements) => entitlements.map((entitlement) => new Entitlement(entitlement, this)));
2984
+ }
2985
+
2986
+ /**
2987
+ * Get the application identities linked to an external account, to find the Discord user behind it. The user must have authorized the application with the `application_identities.write` scope
2988
+ * @arg {String} providerType The type of the external account provider
2989
+ * @arg {String} providerIssuedUserID The ID of the user in the external system
2990
+ * @arg {String} [providerID] The ID used by the provider to tell identities with the same type and user ID apart
2991
+ * @returns {Promise<Array<Object>>} An array of objects containing the `userID`, `providerType`, `providerID` and `providerIssuedUserID` of each identity. Empty if no identity matches
2992
+ */
2993
+ getExternalApplicationIdentities(providerType, providerIssuedUserID, providerID) {
2994
+ return this.requestHandler.request("GET", Endpoints.APPLICATION_IDENTITIES(this.application.id, encodeURIComponent(providerType), encodeURIComponent(providerIssuedUserID)), true, {
2995
+ provider_id: providerID,
2996
+ }, undefined, "/applications/:id/application-identities/:type/:id").then((response) => response.identities.map((identity) => this._formatApplicationIdentity(identity)));
2997
+ }
2998
+
2999
+ /**
3000
+ * Get info on connecting to the Discord gateway
3001
+ * @returns {Promise<Object>} Resolves with an object containing gateway connection info
3002
+ */
3003
+ getGateway() {
3004
+ return this.requestHandler.request("GET", Endpoints.GATEWAY);
3005
+ }
3006
+
3007
+ /**
3008
+ * Get the audit log for a guild
3009
+ * @arg {String} guildID The ID of the guild to get audit logs for
3010
+ * @arg {Object} [options] Options for the request. If this is a number ([DEPRECATED] behavior), it is treated as `options.limit`
3011
+ * @arg {Number} [options.actionType] Filter entries by action type
3012
+ * @arg {String} [options.before] Get entries before this entry ID
3013
+ * @arg {Number} [options.limit=50] The maximum number of entries to return
3014
+ * @arg {String} [options.userID] Filter entries by the user that performed the action
3015
+ * @returns {Promise<{entries: Array<GuildAuditLogEntry>, integrations: Array<PartialIntegration>, threads: Array<NewsThreadChannel | PrivateThreadChannel | PublicThreadChannel>, users: Array<User>, webhooks: Array<Webhook>}>}
3016
+ */
3017
+ getGuildAuditLog(guildID, options = {}, before, actionType, userID) {
3018
+ if (!options || typeof options !== "object") {
3019
+ options = {
3020
+ limit: options,
3021
+ };
3022
+ }
3023
+ if (options.limit === undefined) { // Legacy behavior
3024
+ options.limit = 50;
3025
+ }
3026
+ if (actionType !== undefined) {
3027
+ options.actionType = actionType;
3028
+ }
3029
+ if (before !== undefined) {
3030
+ options.before = before;
3031
+ }
3032
+ if (userID !== undefined) {
3033
+ options.userID = userID;
3034
+ }
3035
+ if (options.actionType !== undefined) {
3036
+ options.action_type = options.actionType;
3037
+ }
3038
+ if (options.userID !== undefined) {
3039
+ options.user_id = options.userID;
3040
+ }
3041
+ return this.requestHandler.request("GET", Endpoints.GUILD_AUDIT_LOGS(guildID), true, options).then((data) => {
3042
+ const guild = this.guilds.get(guildID);
3043
+ const users = data.users.map((user) => this.users.add(user, this));
3044
+ const threads = data.threads.map((thread) => guild.threads.update(thread, this));
3045
+ return {
3046
+ entries: data.audit_log_entries.map((entry) => new GuildAuditLogEntry(entry, this)),
3047
+ integrations: data.integrations.map((integration) => new GuildIntegration(integration, guild)),
3048
+ threads: threads,
3049
+ users: users,
3050
+ webhooks: data.webhooks,
3051
+ };
3052
+ });
3053
+ }
3054
+
3055
+ /**
3056
+ * [DEPRECATED] Get the audit log for a guild. Use `getGuildAuditLog` instead
3057
+ * @arg {String} guildID The ID of the guild to get audit logs for
3058
+ * @arg {Object} [limit=50] The maximum number of entries to return
3059
+ * @arg {String} [before] Get entries before this entry ID
3060
+ * @arg {Number} [actionType] Filter entries by action type
3061
+ * @arg {String} [userID] Filter entries by the user that performed the action
3062
+ * @returns {Promise<{users: Array<User>, entries: Array<GuildAuditLogEntry>, integrations: Array<PartialIntegration>, webhooks: Array<Webhook>}>}
3063
+ */
3064
+ getGuildAuditLogs(guildID, limit, before, actionType, userID) {
3065
+ return this.getGuildAuditLog.call(this, guildID, limit, before, actionType, userID);
3066
+ }
3067
+
3068
+ /**
3069
+ * Get a ban from the ban list of a guild
3070
+ * @arg {String} guildID The ID of the guild
3071
+ * @arg {String} userID The ID of the banned user
3072
+ * @returns {Promise<Object>} Resolves with {reason: String, user: User}
3073
+ */
3074
+ getGuildBan(guildID, userID) {
3075
+ return this.requestHandler.request("GET", Endpoints.GUILD_BAN(guildID, userID), true).then((ban) => {
3076
+ ban.user = new User(ban.user, this);
3077
+ return ban;
3078
+ });
3079
+ }
3080
+
3081
+ /**
3082
+ * Get the ban list of a guild
3083
+ * @arg {String} guildID The ID of the guild
3084
+ * @arg {Object} [options] Options for the request
3085
+ * @arg {String} [options.after] Only get users after given user ID
3086
+ * @arg {String} [options.before] Only get users before given user ID
3087
+ * @arg {Number} [options.limit=1000] The maximum number of users to return
3088
+ * @returns {Promise<Array<Object>>} Resolves with an array of { reason: String, user: User }
3089
+ */
3090
+ async getGuildBans(guildID, options = {}) {
3091
+ const bans = await this.requestHandler.request("GET", Endpoints.GUILD_BANS(guildID), true, {
3092
+ after: options.after,
3093
+ before: options.before,
3094
+ limit: options.limit && Math.min(options.limit, 1000),
3095
+ });
3096
+
3097
+ for (const ban of bans) {
3098
+ ban.user = this.users.update(ban.user, this);
3099
+ }
3100
+
3101
+ if (options.limit && options.limit > 1000 && bans.length >= 1000) {
3102
+ const page = await this.getGuildBans(guildID, {
3103
+ after: options.before ? undefined : bans[bans.length - 1].user.id,
3104
+ before: options.before ? bans[0].user.id : undefined,
3105
+ limit: options.limit - bans.length,
3106
+ });
3107
+
3108
+ if (options.before) {
3109
+ bans.unshift(...page);
3110
+ } else {
3111
+ bans.push(...page);
3112
+ }
3113
+ }
3114
+
3115
+ return bans;
3116
+ }
3117
+
3118
+ /**
3119
+ * Get a guild application command
3120
+ * @arg {String} guildID The guild ID
3121
+ * @arg {String} commandID The command id
3122
+ * @returns {Promise<ApplicationCommand>}
3123
+ */
3124
+ getGuildCommand(guildID, commandID) {
3125
+ if (!commandID) {
3126
+ throw new Error("You must provide an id of the command to get.");
3127
+ }
3128
+ return this.requestHandler.request("GET", Endpoints.GUILD_COMMAND(this.application.id, guildID, commandID), true).then((command) => new ApplicationCommand(command, this));
3129
+ }
3130
+
3131
+ /**
3132
+ * Get the all of a guild's application command permissions
3133
+ * @arg {String} guildID The guild ID
3134
+ * @returns {Promise<Array<Object>>} Resolves with an array of guild application command permissions objects.
3135
+ */
3136
+ getGuildCommandPermissions(guildID) {
3137
+ if (!guildID) {
3138
+ throw new Error("You must provide an id of the guild whose permissions you want to get.");
3139
+ }
3140
+ return this.requestHandler.request("GET", Endpoints.GUILD_COMMAND_PERMISSIONS(this.application.id, guildID), true);
3141
+ }
3142
+
3143
+ /**
3144
+ * Get a guild's application commands
3145
+ * @arg {String} guildID The guild ID
3146
+ * @arg {Boolean} [withLocalizations] Whether to include the `nameLocalizations` and `descriptionLocalizations` of the commands
3147
+ * @returns {Promise<Array<ApplicationCommand>>}
3148
+ */
3149
+ getGuildCommands(guildID, withLocalizations) {
3150
+ return this.requestHandler.request("GET", Endpoints.GUILD_COMMANDS(this.application.id, guildID), true, {
3151
+ with_localizations: withLocalizations,
3152
+ }).then((commands) => commands.map((command) => new ApplicationCommand(command, this)));
3153
+ }
3154
+
3155
+ /**
3156
+ * Get a guild's discovery object
3157
+ * @arg {String} guildID The ID of the guild
3158
+ * @returns {Promise<Object>}
3159
+ */
3160
+ getGuildDiscovery(guildID) {
3161
+ return this.requestHandler.request("GET", Endpoints.GUILD_DISCOVERY(guildID), true);
3162
+ }
3163
+
3164
+ /**
3165
+ * Get a list of integrations for a guild
3166
+ * @arg {String} guildID The ID of the guild
3167
+ * @returns {Promise<Array<GuildIntegration>>}
3168
+ */
3169
+ getGuildIntegrations(guildID) {
3170
+ const guild = this.guilds.get(guildID);
3171
+ return this.requestHandler.request("GET", Endpoints.GUILD_INTEGRATIONS(guildID), true).then((integrations) => integrations.map((integration) => new GuildIntegration(integration, guild)));
3172
+ }
3173
+
3174
+ /**
3175
+ * Get all invites in a guild
3176
+ * @arg {String} guildID The ID of the guild
3177
+ * @returns {Promise<Array<Invite>>}
3178
+ */
3179
+ getGuildInvites(guildID) {
3180
+ return this.requestHandler.request("GET", Endpoints.GUILD_INVITES(guildID), true).then((invites) => invites.map((invite) => new Invite(invite, this)));
3181
+ }
3182
+
3183
+ /**
3184
+ * Get the computed guild-wide permissions of a member, combining their roles with `@everyone`
3185
+ * @arg {String} guildID The ID of the guild
3186
+ * @arg {String} memberID The ID of the member
3187
+ * @returns {Promise<Permission>}
3188
+ */
3189
+ getGuildMemberPermissions(guildID, memberID) {
3190
+ return this.requestHandler.request("GET", Endpoints.GUILD_PERMISSIONS_MEMBER(guildID, memberID), true).then((response) => new Permission(response.permissions));
3191
+ }
3192
+
3193
+ /**
3194
+ * Get a guild's onboarding settings
3195
+ * @arg {String} guildID The ID of the guild
3196
+ * @returns {Promise<Object>} The guild's [onboarding settings](https://discord.dev/resources/guild#guild-onboarding-object)
3197
+ */
3198
+ getGuildOnboarding(guildID) {
3199
+ return this.requestHandler.request("GET", Endpoints.GUILD_ONBOARDING(guildID), true);
3200
+ }
3201
+
3202
+ /**
3203
+ * Get a guild preview for a guild. Only available for community guilds.
3204
+ * @arg {String} guildID The ID of the guild
3205
+ * @returns {Promise<Object>}
3206
+ */
3207
+ getGuildPreview(guildID) {
3208
+ return this.requestHandler.request("GET", Endpoints.GUILD_PREVIEW(guildID), true).then((data) => new GuildPreview(data, this));
3209
+ }
3210
+
3211
+ /**
3212
+ * Get a guild's role member counts
3213
+ * @arg {String} guildID The ID of the guild
3214
+ * @returns {Promise<Object<String, Number>>} A map of role IDs to the number of members with the role. Does not include the @everyone role.
3215
+ */
3216
+ getGuildRoleMemberCounts(guildID) {
3217
+ return this.requestHandler.request("GET", Endpoints.GUILD_ROLE_MEMBER_COUNTS(guildID), true);
3218
+ }
3219
+
3220
+ /**
3221
+ * Get the combined guild-wide permissions of a role and `@everyone`
3222
+ * @arg {String} guildID The ID of the guild
3223
+ * @arg {String} roleID The ID of the role
3224
+ * @returns {Promise<Permission>}
3225
+ */
3226
+ getGuildRolePermissions(guildID, roleID) {
3227
+ return this.requestHandler.request("GET", Endpoints.GUILD_PERMISSIONS_ROLE(guildID, roleID), true).then((response) => new Permission(response.permissions));
3228
+ }
3229
+
3230
+ /**
3231
+ * Get a guild's scheduled events
3232
+ * @arg {String} guildID The ID of the guild
3233
+ * @arg {Object} [options] Options for the request
3234
+ * @arg {Boolean} [options.withUserCount] Whether to include the number of users subscribed to each event
3235
+ * @returns {Promise<Array<GuildScheduledEvent>>}
3236
+ */
3237
+ getGuildScheduledEvents(guildID, options = {}) {
3238
+ options.with_user_count = options.withUserCount;
3239
+ return this.requestHandler.request("GET", Endpoints.GUILD_SCHEDULED_EVENTS(guildID), true, options).then((data) => data.map((event) => new GuildScheduledEvent(event, this)));
3240
+ }
3241
+
3242
+ /**
3243
+ * Get a list of users subscribed to a guild scheduled event
3244
+ * @arg {String} guildID The ID of the guild
3245
+ * @arg {String} eventID The ID of the event
3246
+ * @arg {Object} [options] Options for the request
3247
+ * @arg {String} [options.after] Get users after this user ID. If `options.before` is provided, this will be ignored. Fetching users in between `before` and `after` is not supported
3248
+ * @arg {String} [options.before] Get users before this user ID
3249
+ * @arg {Number} [options.limit=100] The number of users to get (max 100). Pagination will only work if one of `options.after` or `options.after` is also provided
3250
+ * @arg {Boolean} [options.withMember] Include guild member data
3251
+ * @returns {Promise<Array<{guildScheduledEventID: String, member?: Member, user: User}>>}
3252
+ */
3253
+ getGuildScheduledEventUsers(guildID, eventID, options = {}) {
3254
+ const guild = this.guilds.get(guildID);
3255
+
3256
+ options.with_member = options.withMember;
3257
+ return this.requestHandler.request("GET", Endpoints.GUILD_SCHEDULED_EVENT_USERS(guildID, eventID), true, options).then((data) => data.map((eventUser) => {
3258
+ if (eventUser.member) {
3259
+ eventUser.member.id = eventUser.user.id;
3260
+ }
3261
+ return {
3262
+ guildScheduledEventID: eventUser.guild_scheduled_event_id,
3263
+ member: eventUser.member && guild ? guild.members.update(eventUser.member) : new Member(eventUser.member),
3264
+ user: this.users.update(eventUser.user),
3265
+ };
3266
+ }));
3267
+ }
3268
+
3269
+ /**
3270
+ * Get a guild soundboard sound. Not to be confused with getGuildSoundboardSounds, which gets all soundboard sounds in a guild
3271
+ * @arg {String} guildID The guild ID where the sound was created
3272
+ * @arg {String} soundID The ID of the soundboard sound
3273
+ * @returns {Promise<SoundboardSound>}
3274
+ */
3275
+ getGuildSoundboardSound(guildID, soundID) {
3276
+ return this.requestHandler.request("GET", Endpoints.SOUNDBOARD_SOUND_GUILD(guildID, soundID), true).then((sound) => new SoundboardSound(sound, this));
3277
+ }
3278
+
3279
+ /**
3280
+ * Get a guild's soundboard sounds. Not to be confused with getGuildSoundboardSound, which gets a specified soundboard sound
3281
+ * @arg {String} guildID The ID of the guild
3282
+ * @returns {Promise<Array<SoundboardSound>>}
3283
+ */
3284
+ getGuildSoundboardSounds(guildID) {
3285
+ return this.requestHandler.request("GET", Endpoints.SOUNDBOARD_SOUNDS_GUILD(guildID), true).then((sounds) => sounds.map((sound) => new SoundboardSound(sound, this)));
3286
+ }
3287
+
3288
+ /**
3289
+ * Get a guild template
3290
+ * @arg {String} code The template code
3291
+ * @returns {Promise<GuildTemplate>}
3292
+ */
3293
+ getGuildTemplate(code) {
3294
+ return this.requestHandler.request("GET", Endpoints.GUILD_TEMPLATE(code), true).then((template) => new GuildTemplate(template, this));
3295
+ }
3296
+
3297
+ /**
3298
+ * Get a guild's templates
3299
+ * @arg {String} guildID The ID of the guild
3300
+ * @returns {Promise<Array<GuildTemplate>>}
3301
+ */
3302
+ getGuildTemplates(guildID) {
3303
+ return this.requestHandler.request("GET", Endpoints.GUILD_TEMPLATES(guildID), true).then((templates) => templates.map((t) => new GuildTemplate(t, this)));
3304
+ }
3305
+
3306
+ /**
3307
+ * Returns the vanity url of the guild
3308
+ * @arg {String} guildID The ID of the guild
3309
+ * @returns {Promise}
3310
+ */
3311
+ getGuildVanity(guildID) {
3312
+ return this.requestHandler.request("GET", Endpoints.GUILD_VANITY_URL(guildID), true);
3313
+ }
3314
+
3315
+ /**
3316
+ * Get a guild user's voice state
3317
+ * @arg {String} guildID The ID of the guild
3318
+ * @arg {String} [userID="@me"] The ID of the user
3319
+ * @returns {Promise<VoiceState>}
3320
+ */
3321
+ getGuildVoiceState(guildID, userID = "@me") {
3322
+ return this.requestHandler.request("GET", Endpoints.GUILD_VOICE_STATE(guildID, userID), true).then((state) => new VoiceState(state));
3323
+ }
3324
+
3325
+ /**
3326
+ * Get all the webhooks in a guild
3327
+ * @arg {String} guildID The ID of the guild to get webhooks for
3328
+ * @returns {Promise<Array<Object>>} Resolves with an array of webhook objects
3329
+ */
3330
+ getGuildWebhooks(guildID) {
3331
+ return this.requestHandler.request("GET", Endpoints.GUILD_WEBHOOKS(guildID), true);
3332
+ }
3333
+
3334
+ /**
3335
+ * Get the welcome screen of a Community guild, shown to new members
3336
+ * @arg {String} guildID The ID of the guild to get the welcome screen for
3337
+ * @returns {Promise<Object>}
3338
+ */
3339
+ getGuildWelcomeScreen(guildID) {
3340
+ return this.requestHandler.request("GET", Endpoints.GUILD_WELCOME_SCREEN(guildID), true);
3341
+ }
3342
+
3343
+ /**
3344
+ * Get a guild's widget object
3345
+ * @arg {String} guildID The ID of the guild
3346
+ * @returns {Promise<Object>} A guild widget object
3347
+ */
3348
+ getGuildWidget(guildID) {
3349
+ return this.requestHandler.request("GET", Endpoints.GUILD_WIDGET(guildID), true);
3350
+ }
3351
+
3352
+ /**
3353
+ * Get a guild's widget image
3354
+ * @arg {String} guildID The ID of the guild
3355
+ * @arg {String} [style="shield"] The style of widget image. Either `shield`, `banner1`, `banner2`, `banner3`, or `banner4`.
3356
+ * @returns {String} The widget image link
3357
+ */
3358
+ getGuildWidgetImageURL(guildID, style) {
3359
+ return Endpoints.CLIENT_URL + Endpoints.BASE_URL + Endpoints.GUILD_WIDGET_IMAGE(guildID) + (style !== undefined ? `?style=${style}` : "");
3360
+ }
3361
+
3362
+ /**
3363
+ * Get a guild's widget settings object. Requires MANAGE_GUILD permission
3364
+ * @arg {String} guildID The ID of the guild
3365
+ * @returns {Promise<Object>} A guild widget setting object
3366
+ */
3367
+ getGuildWidgetSettings(guildID) {
3368
+ return this.requestHandler.request("GET", Endpoints.GUILD_WIDGET_SETTINGS(guildID), true);
3369
+ }
3370
+
3371
+ /**
3372
+ * Get info on an invite
3373
+ * @arg {String} inviteID The ID of the invite
3374
+ * @arg {Boolean} [withCounts] Whether to fetch additional invite info or not (approximate member counts, approximate presences, channel counts, etc.)
3375
+ * @arg {Boolean} [withExpiration] [DEPRECATED] Whether to fetch the expiration time or not. This is deprecated because Discord will now always return the expiration date
3376
+ * @arg {String} [guildScheduledEventID] The guild scheduled event to include with the invite
3377
+ * @returns {Promise<Invite>}
3378
+ */
3379
+ getInvite(inviteID, withCounts, _withExpiration, guildScheduledEventID) {
3380
+ if (typeof _withExpiration === "string") {
3381
+ guildScheduledEventID = _withExpiration;
3382
+ } else if (typeof _withExpiration === "boolean") {
3383
+ emitDeprecation("GET_INVITE_WITH_EXPIRATION");
3384
+ }
3385
+ return this.requestHandler.request("GET", Endpoints.INVITE(inviteID), true, {
3386
+ with_counts: withCounts,
3387
+ guild_scheduled_event_id: guildScheduledEventID,
3388
+ }).then((invite) => new Invite(invite, this));
3389
+ }
3390
+
3391
+ /**
3392
+ * Get the target users of an invite (the users allowed to see and accept it)
3393
+ * @arg {String} inviteID The code of the invite
3394
+ * @returns {Promise<Array<String>>} The IDs of the target users
3395
+ */
3396
+ getInviteTargetUsers(inviteID) {
3397
+ return this.requestHandler.request("GET", Endpoints.INVITE_TARGET_USERS(inviteID), true).then((csv) => {
3398
+ if (typeof csv !== "string") {
3399
+ return [];
3400
+ }
3401
+ return csv.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && line !== "user_id");
3402
+ });
3403
+ }
3404
+
3405
+ /**
3406
+ * Get the status of the job processing the target users of an invite
3407
+ * @arg {String} inviteID The code of the invite
3408
+ * @returns {Promise<Object>} An object containing the `status` of the job (see `Constants.InviteTargetUsersJobStatus`), `totalUsers`, `processedUsers`, `createdAt`, `completedAt` and `errorMessage`
3409
+ */
3410
+ getInviteTargetUsersJobStatus(inviteID) {
3411
+ return this.requestHandler.request("GET", Endpoints.INVITE_TARGET_USERS_JOB_STATUS(inviteID), true).then((job) => ({
3412
+ completedAt: job.completed_at ? Date.parse(job.completed_at) : null,
3413
+ createdAt: job.created_at ? Date.parse(job.created_at) : null,
3414
+ errorMessage: job.error_message,
3415
+ processedUsers: job.processed_users,
3416
+ status: job.status,
3417
+ totalUsers: job.total_users,
3418
+ }));
3419
+ }
3420
+
3421
+ /**
3422
+ * Get joined private archived threads in a channel
3423
+ * @arg {String} channelID The ID of the channel
3424
+ * @arg {Object} [options] Additional options when requesting archived threads
3425
+ * @arg {Date} [options.before] List of threads to return before the timestamp
3426
+ * @arg {Number} [options.limit] Maximum number of threads to return
3427
+ * @returns {Promise<Object>} An object containing an array of `threads`, an array of `members` and whether the response `hasMore` threads that could be returned in a subsequent call
3428
+ */
3429
+ getJoinedPrivateArchivedThreads(channelID, options = {}) {
3430
+ return this.requestHandler.request("GET", Endpoints.THREADS_ARCHIVED_JOINED(channelID), true, options).then((response) => {
3431
+ return {
3432
+ hasMore: response.has_more,
3433
+ members: response.members.map((member) => new ThreadMember(member, this)),
3434
+ threads: response.threads.map((thread) => Channel.from(thread, this)),
3435
+ };
3436
+ });
3437
+ }
3438
+
3439
+ /**
3440
+ * Get a lobby
3441
+ * @arg {String} lobbyID The ID of the lobby
3442
+ * @returns {Promise<Lobby>}
3443
+ */
3444
+ getLobby(lobbyID) {
3445
+ return this.requestHandler.request("GET", Endpoints.LOBBY(lobbyID), true).then((lobby) => new Lobby(lobby, this));
3446
+ }
3447
+
3448
+ /**
3449
+ * Get a previous message in a channel
3450
+ * @arg {String} channelID The ID of the channel
3451
+ * @arg {String} messageID The ID of the message
3452
+ * @returns {Promise<Message>}
3453
+ */
3454
+ getMessage(channelID, messageID) {
3455
+ return this.requestHandler.request("GET", Endpoints.CHANNEL_MESSAGE(channelID, messageID), true).then((message) => new Message(message, this));
3456
+ }
3457
+
3458
+ /**
3459
+ * Get a list of users who reacted with a specific reaction
3460
+ * @arg {String} channelID The ID of the channel
3461
+ * @arg {String} messageID The ID of the message
3462
+ * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
3463
+ * @arg {Object} [options] Options for the request. If this is a number ([DEPRECATED] behavior), it is treated as `options.limit`
3464
+ * @arg {String} [options.after] Get users after this user ID
3465
+ * @arg {Number} [options.limit=100] The maximum number of users to get
3466
+ * @arg {Number} [options.type=0] The type of reaction (`0` for normal, `1` for burst)
3467
+ * @arg {String} [before] [DEPRECATED] Get users before this user ID. Discord no longer supports this parameter
3468
+ * @arg {String} [after] [DEPRECATED] Get users after this user ID
3469
+ * @returns {Promise<Array<User>>}
3470
+ */
3471
+ getMessageReaction(channelID, messageID, reaction, options = {}, before, after) {
3472
+ if (reaction === decodeURI(reaction)) {
3473
+ reaction = encodeURIComponent(reaction);
3474
+ }
3475
+ if (!options || typeof options !== "object") {
3476
+ options = {
3477
+ limit: options,
3478
+ };
3479
+ }
3480
+ if (options.limit === undefined) { // Legacy behavior
3481
+ options.limit = 100;
3482
+ }
3483
+ if (before !== undefined) {
3484
+ options.before = before;
3485
+ }
3486
+ if (after !== undefined) {
3487
+ options.after = after;
3488
+ }
3489
+ if (options.before) {
3490
+ emitDeprecation("GET_REACTION_BEFORE");
3491
+ this.emit("warn", "[DEPRECATED] getMessageReaction() was called with a `before` parameter. Discord no longer supports this parameter");
3492
+ }
3493
+ return this.requestHandler.request("GET", Endpoints.CHANNEL_MESSAGE_REACTION(channelID, messageID, reaction), true, options).then((users) => users.map((user) => new User(user, this)));
3494
+ }
3495
+
3496
+ /**
3497
+ * Get previous messages in a channel
3498
+ * @arg {String} channelID The ID of the channel
3499
+ * @arg {Object} [options] Options for the request. If this is a number ([DEPRECATED] behavior), it is treated as `options.limit`
3500
+ * @arg {String} [options.after] Get messages after this message ID
3501
+ * @arg {String} [options.around] Get messages around this message ID (does not work with limit > 100)
3502
+ * @arg {String} [options.before] Get messages before this message ID
3503
+ * @arg {Number} [options.limit=50] The max number of messages to get
3504
+ * @arg {String} [before] [DEPRECATED] Get messages before this message ID
3505
+ * @arg {String} [after] [DEPRECATED] Get messages after this message ID
3506
+ * @arg {String} [around] [DEPRECATED] Get messages around this message ID (does not work with limit > 100)
3507
+ * @returns {Promise<Array<Message>>}
3508
+ */
3509
+ async getMessages(channelID, options = {}, before, after, around) {
3510
+ if (!options || typeof options !== "object") {
3511
+ options = {
3512
+ limit: options,
3513
+ };
3514
+ }
3515
+ if (options.limit === undefined) { // Legacy behavior
3516
+ options.limit = 50;
3517
+ }
3518
+ if (after !== undefined) {
3519
+ options.after = after;
3520
+ }
3521
+ if (around !== undefined) {
3522
+ options.around = around;
3523
+ }
3524
+ if (before !== undefined) {
3525
+ options.before = before;
3526
+ }
3527
+ let limit = options.limit;
3528
+ if (limit && limit > 100) {
3529
+ let logs = [];
3530
+ const get = async (_before, _after) => {
3531
+ const messages = await this.requestHandler.request("GET", Endpoints.CHANNEL_MESSAGES(channelID), true, {
3532
+ limit: 100,
3533
+ before: _before || undefined,
3534
+ after: _after || undefined,
3535
+ });
3536
+ if (limit <= messages.length) {
3537
+ return (_after ? messages.slice(messages.length - limit, messages.length).map((message) => new Message(message, this)).concat(logs) : logs.concat(messages.slice(0, limit).map((message) => new Message(message, this))));
3538
+ }
3539
+ limit -= messages.length;
3540
+ logs = (_after ? messages.map((message) => new Message(message, this)).concat(logs) : logs.concat(messages.map((message) => new Message(message, this))));
3541
+ if (messages.length < 100) {
3542
+ return logs;
3543
+ }
3544
+ this.emit("debug", `Getting ${limit} more messages during getMessages for ${channelID}: ${_before} ${_after}`, -1);
3545
+ return get((_before || !_after) && messages[messages.length - 1].id, _after && messages[0].id);
3546
+ };
3547
+ return get(options.before, options.after);
3548
+ }
3549
+ const messages = await this.requestHandler.request("GET", Endpoints.CHANNEL_MESSAGES(channelID), true, options);
3550
+ return messages.map((message) => {
3551
+ try {
3552
+ return new Message(message, this);
3553
+ } catch (err) {
3554
+ this.emit("error", `Error creating message from channel messages\n${err.stack}\n${JSON.stringify(messages)}`);
3555
+ return null;
3556
+ }
3557
+ });
3558
+ }
3559
+
3560
+ /**
3561
+ * [DEPRECATED] Get the list of available sticker packs. This function is deprecated, use `getStickerPacks()` instead.
3562
+ * @returns {Promise<{sticker_packs: Array<Object>}>} An object containing a `sticker_packs` value which contains an array of sticker packs
3563
+ */
3564
+ getNitroStickerPacks() {
3565
+ emitDeprecation("GET_NITRO_STICKER_PACKS");
3566
+ return this.getStickerPacks();
3567
+ }
3568
+
3569
+ /**
3570
+ * Get data on the bot's OAuth2 application
3571
+ * @returns {Promise<Object>} The bot's application data. Refer to [the official Discord API documentation entry](https://discord.com/developers/docs/topics/oauth2#get-current-application-information) for object structure
3572
+ */
3573
+ getOAuthApplication() {
3574
+ return this.requestHandler.request("GET", Endpoints.OAUTH2_APPLICATION, true);
3575
+ }
3576
+
3577
+ /**
3578
+ * Get pinned messages in a channel
3579
+ * @arg {String} channelID The ID of the channel
3580
+ * @arg {Object} [options] The options to use to get pinned messages
3581
+ * @arg {Date} [options.before] Get pinned messages before this date
3582
+ * @arg {Number} [options.limit=50] The max number of pinned messages to get (1-50, default 50)
3583
+ * @returns {Promise<{hasMore: Boolean, items: Array<{pinnedAt: Number, message: Message}>}>} An object containing `hasMore` (Boolean, `true` if there are more pins available), and `items` which is an array of objects containing `pinnedAt` (Date of when the message was pinned) and `message` (the pinned message)
3584
+ */
3585
+ getPins(channelID, options) {
3586
+ if (options === undefined) {
3587
+ emitDeprecation("GET_CHANNEL_PINS");
3588
+ }
3589
+ return this.requestHandler.request("GET", Endpoints.CHANNEL_PINS(channelID), true, options).then((pinned) => {
3590
+ if (options === undefined) {
3591
+ return pinned.items.map((pin) => new Message(pin.message, this));
3592
+ }
3593
+ return {
3594
+ hasMore: pinned.has_more,
3595
+ items: pinned.items.map((pin) => ({
3596
+ pinnedAt: Date.parse(pin.pinned_at),
3597
+ message: new Message(pin.message, this),
3598
+ })),
3599
+ };
3600
+ });
3601
+ }
3602
+
3603
+ /**
3604
+ * Get a list of users that voted for a specific poll answer
3605
+ * @arg {String} channelID The ID of the channel
3606
+ * @arg {String} messageID The ID of the message that the poll is in
3607
+ * @arg {Number} answerID The ID of the answer to get voters for
3608
+ * @arg {Object} [options] Options for the request
3609
+ * @arg {String} [options.after] Get users after this user ID
3610
+ * @arg {Number} [options.limit=25] The max number of users to get
3611
+ * @returns {Promise<Array<User>>} An array of users who voted for this answer
3612
+ */
3613
+ getPollAnswerVoters(channelID, messageID, answerID, options = {}) {
3614
+ return this.requestHandler.request("GET", Endpoints.POLL_ANSWER_VOTERS(channelID, messageID, answerID), true, {
3615
+ after: options.after,
3616
+ limit: options.limit,
3617
+ }).then((voters) => voters.users.map((user) => new User(user, this)));
3618
+ }
3619
+
3620
+ /**
3621
+ * Get the prune count for a guild
3622
+ * @arg {String} guildID The ID of the guild
3623
+ * @arg {Number} [options] The options to use to get number of prune members
3624
+ * @arg {Number} [options.days=7] The number of days of inactivity to prune for
3625
+ * @arg {Array<String>} [options.includeRoles] An array of role IDs that members must have to be considered for pruning
3626
+ * @returns {Promise<Number>} Resolves with the number of members that would be pruned
3627
+ */
3628
+ getPruneCount(guildID, options = {}) {
3629
+ return this.requestHandler.request("GET", Endpoints.GUILD_PRUNE(guildID), true, {
3630
+ days: options.days,
3631
+ include_roles: options.includeRoles,
3632
+ }).then((data) => data.pruned);
3633
+ }
3634
+
3635
+ /**
3636
+ * Get a channel's data via the REST API. REST mode is required to use this endpoint.
3637
+ * @arg {String} channelID The ID of the channel
3638
+ * @returns {Promise<CategoryChannel | DMChannel | ForumChannel | GroupChannel | NewsChannel | NewsThreadChannel | PrivateThreadChannel | PublicThreadChannel | StageChannel | TextChannel | VoiceChannel>}
3639
+ */
3640
+ getRESTChannel(channelID) {
3641
+ if (!this.options.restMode) {
3642
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3643
+ }
3644
+ return this.requestHandler.request("GET", Endpoints.CHANNEL(channelID), true)
3645
+ .then((channel) => Channel.from(channel, this));
3646
+ }
3647
+
3648
+ /**
3649
+ * Get a guild's data via the REST API. REST mode is required to use this endpoint.
3650
+ * @arg {String} guildID The ID of the guild
3651
+ * @arg {Boolean} [withCounts=false] Whether the guild object will have approximateMemberCount and approximatePresenceCount
3652
+ * @returns {Promise<Guild>}
3653
+ */
3654
+ getRESTGuild(guildID, withCounts = false) {
3655
+ if (!this.options.restMode) {
3656
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3657
+ }
3658
+ return this.requestHandler.request("GET", Endpoints.GUILD(guildID), true, {
3659
+ with_counts: withCounts,
3660
+ }).then((guild) => new Guild(guild, this));
3661
+ }
3662
+
3663
+ /**
3664
+ * Get a guild's channels via the REST API. REST mode is required to use this endpoint.
3665
+ * @arg {String} guildID The ID of the guild
3666
+ * @returns {Promise<Array<CategoryChannel | ForumChannel | NewsChannel | StageChannel | TextChannel | VoiceChannel>>}
3667
+ */
3668
+ getRESTGuildChannels(guildID) {
3669
+ if (!this.options.restMode) {
3670
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3671
+ }
3672
+ return this.requestHandler.request("GET", Endpoints.GUILD_CHANNELS(guildID), true)
3673
+ .then((channels) => channels.map((channel) => Channel.from(channel, this)));
3674
+ }
3675
+
3676
+ /**
3677
+ * Get a guild emoji via the REST API. REST mode is required to use this endpoint.
3678
+ * @arg {String} guildID The ID of the guild
3679
+ * @arg {String} emojiID The ID of the emoji
3680
+ * @returns {Promise<Object>} An emoji object
3681
+ */
3682
+ getRESTGuildEmoji(guildID, emojiID) {
3683
+ if (!this.options.restMode) {
3684
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3685
+ }
3686
+ return this.requestHandler.request("GET", Endpoints.GUILD_EMOJI(guildID, emojiID), true);
3687
+ }
3688
+
3689
+ /**
3690
+ * Get a guild's emojis via the REST API. REST mode is required to use this endpoint.
3691
+ * @arg {String} guildID The ID of the guild
3692
+ * @returns {Promise<Array<Object>>} An array of guild emoji objects
3693
+ */
3694
+ getRESTGuildEmojis(guildID) {
3695
+ if (!this.options.restMode) {
3696
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3697
+ }
3698
+ return this.requestHandler.request("GET", Endpoints.GUILD_EMOJIS(guildID), true);
3699
+ }
3700
+
3701
+ /**
3702
+ * Get a guild's members via the REST API. REST mode is required to use this endpoint.
3703
+ * @arg {String} guildID The ID of the guild
3704
+ * @arg {String} memberID The ID of the member
3705
+ * @returns {Promise<Member>}
3706
+ */
3707
+ getRESTGuildMember(guildID, memberID) {
3708
+ if (!this.options.restMode) {
3709
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3710
+ }
3711
+ return this.requestHandler.request("GET", Endpoints.GUILD_MEMBER(guildID, memberID), true).then((member) => new Member(member, this.guilds.get(guildID), this));
3712
+ }
3713
+
3714
+ /**
3715
+ * Get a guild's members via the REST API. REST mode is required to use this endpoint.
3716
+ * @arg {String} guildID The ID of the guild
3717
+ * @arg {Object} [options] Options for the request. If this is a number ([DEPRECATED] behavior), it is treated as `options.limit`
3718
+ * @arg {String} [options.after] The highest user ID of the previous page
3719
+ * @arg {Number} [options.limit=1] The max number of members to get (1 to 1000)
3720
+ * @arg {String} [after] [DEPRECATED] The highest user ID of the previous page
3721
+ * @returns {Promise<Array<Member>>}
3722
+ */
3723
+ getRESTGuildMembers(guildID, options = {}, after) {
3724
+ if (!this.options.restMode) {
3725
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3726
+ }
3727
+ if (!options || typeof options !== "object") {
3728
+ options = {
3729
+ limit: options,
3730
+ };
3731
+ }
3732
+ if (after !== undefined) {
3733
+ options.after = after;
3734
+ }
3735
+ return this.requestHandler.request("GET", Endpoints.GUILD_MEMBERS(guildID), true, options).then((members) => members.map((member) => new Member(member, this.guilds.get(guildID), this)));
3736
+ }
3737
+
3738
+ /**
3739
+ * Get a guild role via the REST API. REST mode is required to use this endpoint.
3740
+ * @arg {String} guildID The ID of the guild
3741
+ * @arg {String} roleID The ID of the role
3742
+ * @returns {Promise<Role>}
3743
+ */
3744
+ getRESTGuildRole(guildID, roleID) {
3745
+ if (!this.options.restMode) {
3746
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3747
+ }
3748
+ return this.requestHandler.request("GET", Endpoints.GUILD_ROLE(guildID, roleID), true).then((role) => new Role(role, { shard: { client: this } }));
3749
+ }
3750
+
3751
+ /**
3752
+ * Get a guild's roles via the REST API. REST mode is required to use this endpoint.
3753
+ * @arg {String} guildID The ID of the guild
3754
+ * @returns {Promise<Array<Role>>}
3755
+ */
3756
+ getRESTGuildRoles(guildID) {
3757
+ if (!this.options.restMode) {
3758
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3759
+ }
3760
+ return this.requestHandler.request("GET", Endpoints.GUILD_ROLES(guildID), true).then((roles) => roles.map((role) => new Role(role, null)));
3761
+ }
3762
+
3763
+ /**
3764
+ * Get a list of the user's guilds via the REST API. REST mode is required to use this endpoint.
3765
+ * @arg {Object} [options] Options for the request. If this is a number ([DEPRECATED] behavior), it is treated as `options.limit`
3766
+ * @arg {String} [options.after] The highest guild ID of the previous page
3767
+ * @arg {String} [options.before] The lowest guild ID of the next page
3768
+ * @arg {Number} [options.limit=100] The max number of guilds to get (1 to 200)
3769
+ * @arg {Boolean} [options.withCounts=false] Whether to include approximate member and presence counts
3770
+ * @arg {String} [before] [DEPRECATED] The lowest guild ID of the next page
3771
+ * @arg {String} [after] [DEPRECATED] The highest guild ID of the previous page
3772
+ * @returns {Promise<Array<Guild>>}
3773
+ */
3774
+ getRESTGuilds(options = {}, before, after) {
3775
+ // TODO type
3776
+ if (!this.options.restMode) {
3777
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3778
+ }
3779
+ if (!options || typeof options !== "object") {
3780
+ options = {
3781
+ limit: options,
3782
+ };
3783
+ }
3784
+ if (after !== undefined) {
3785
+ options.after = after;
3786
+ }
3787
+ if (before !== undefined) {
3788
+ options.before = before;
3789
+ }
3790
+ options.with_counts = options.withCounts;
3791
+ return this.requestHandler.request("GET", Endpoints.USER_GUILDS("@me"), true, options).then((guilds) => guilds.map((guild) => new Guild(guild, this)));
3792
+ }
3793
+
3794
+ /**
3795
+ * Get a guild scheduled event via the REST API. REST mode is required to use this endpoint.
3796
+ * @arg {String} guildID The ID of the guild
3797
+ * @arg {String} eventID The ID of the guild scheduled event
3798
+ * @arg {Object} [options] Options for the request
3799
+ * @arg {Boolean} [options.withUserCount] Whether to include the number of users subscribed to the event
3800
+ * @returns {Promise<GuildScheduledEvent>}
3801
+ */
3802
+ getRESTGuildScheduledEvent(guildID, eventID, options = {}) {
3803
+ if (!this.options.restMode) {
3804
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3805
+ }
3806
+
3807
+ options.with_user_count = options.withUserCount;
3808
+ return this.requestHandler.request("GET", Endpoints.GUILD_SCHEDULED_EVENT(guildID, eventID), true, options).then((data) => new GuildScheduledEvent(data, this));
3809
+ }
3810
+
3811
+ /**
3812
+ * Get a guild sticker via the REST API. REST mode is required to use this endpoint.
3813
+ * @arg {String} guildID The ID of the guild
3814
+ * @arg {String} stickerID The ID of the sticker
3815
+ * @returns {Promise<Object>} A sticker object
3816
+ */
3817
+ getRESTGuildSticker(guildID, stickerID) {
3818
+ if (!this.options.restMode) {
3819
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3820
+ }
3821
+ return this.requestHandler.request("GET", Endpoints.GUILD_STICKER(guildID, stickerID), true);
3822
+ }
3823
+
3824
+ /**
3825
+ * Get a guild's stickers via the REST API. REST mode is required to use this endpoint.
3826
+ * @arg {String} guildID The ID of the guild
3827
+ * @returns {Promise<Array<Object>>} An array of guild sticker objects
3828
+ */
3829
+ getRESTGuildStickers(guildID) {
3830
+ if (!this.options.restMode) {
3831
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3832
+ }
3833
+ return this.requestHandler.request("GET", Endpoints.GUILD_STICKERS(guildID), true);
3834
+ }
3835
+
3836
+ /**
3837
+ * Get a sticker via the REST API. REST mode is required to use this endpoint.
3838
+ * @arg {String} stickerID The ID of the sticker
3839
+ * @returns {Promise<Object>} A sticker object
3840
+ */
3841
+ getRESTSticker(stickerID) {
3842
+ if (!this.options.restMode) {
3843
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3844
+ }
3845
+ return this.requestHandler.request("GET", Endpoints.STICKER(stickerID), true);
3846
+ }
3847
+
3848
+ /**
3849
+ * Get a user's data via the REST API. REST mode is required to use this endpoint.
3850
+ * @arg {String} userID The ID of the user
3851
+ * @returns {Promise<User>}
3852
+ */
3853
+ getRESTUser(userID) {
3854
+ if (!this.options.restMode) {
3855
+ return Promise.reject(new Error("Eris REST mode is not enabled"));
3856
+ }
3857
+ return this.requestHandler.request("GET", Endpoints.USER(userID), true).then((user) => new User(user, this));
3858
+ }
3859
+
3860
+ /**
3861
+ * Get the role connection metadata for the application
3862
+ * @returns {Promise<Array<Object>>} An array of role connection metadata objects. See [the official Discord API documentation entry](https://discord.com/developers/docs/resources/application-role-connection-metadata#application-role-connection-metadata-object) for object structure
3863
+ */
3864
+ getRoleConnectionMetadataRecords() {
3865
+ return this.requestHandler.request("GET", Endpoints.ROLE_CONNECTION_METADATA_RECORDS(this.application.id), true);
3866
+ }
3867
+
3868
+ /**
3869
+ * Get properties of the bot user
3870
+ * @returns {Promise<ExtendedUser>}
3871
+ */
3872
+ getSelf() {
3873
+ return this.requestHandler.request("GET", Endpoints.USER("@me"), true).then((data) => new ExtendedUser(data, this));
3874
+ }
3875
+
3876
+ /**
3877
+ * Get the SKUs of the application
3878
+ * @returns {Promise<Array<SKU>>}
3879
+ */
3880
+ getSKUs() {
3881
+ return this.requestHandler.request("GET", Endpoints.APPLICATION_SKUS(this.application.id), true).then((skus) => skus.map((sku) => new SKU(sku, this)));
3882
+ }
3883
+
3884
+ /**
3885
+ * Get a subscription to a SKU
3886
+ * @arg {String} skuID The ID of the SKU
3887
+ * @arg {String} subscriptionID The ID of the subscription
3888
+ * @returns {Promise<Subscription>}
3889
+ */
3890
+ getSKUSubscription(skuID, subscriptionID) {
3891
+ return this.requestHandler.request("GET", Endpoints.SKU_SUBSCRIPTION(skuID, subscriptionID), true).then((subscription) => new Subscription(subscription, this));
3892
+ }
3893
+
3894
+ /**
3895
+ * Get the subscriptions to a SKU
3896
+ * @arg {String} skuID The ID of the SKU
3897
+ * @arg {Object} options The options for the request
3898
+ * @arg {String} [options.after] Retrieve subscriptions after this subscription ID
3899
+ * @arg {String} [options.before] Retrieve subscriptions before this subscription ID
3900
+ * @arg {Number} [options.limit=50] The number of subscriptions to return (1-100)
3901
+ * @arg {String} options.userID The ID of the user to look up subscriptions for
3902
+ * @returns {Promise<Array<Subscription>>}
3903
+ */
3904
+ getSKUSubscriptions(skuID, options = {}) {
3905
+ return this.requestHandler.request("GET", Endpoints.SKU_SUBSCRIPTIONS(skuID), true, {
3906
+ after: options.after,
3907
+ before: options.before,
3908
+ limit: options.limit,
3909
+ user_id: options.userID,
3910
+ }).then((subscriptions) => subscriptions.map((subscription) => new Subscription(subscription, this)));
3911
+ }
3912
+
3913
+ /**
3914
+ * Get the default soundboard sounds
3915
+ * @returns {Promise<Array<SoundboardSound>>}
3916
+ */
3917
+ getSoundboardSounds() {
3918
+ return this.requestHandler.request("GET", Endpoints.SOUNDBOARD_SOUNDS_DEFAULT, true).then((sounds) => sounds.map((sound) => new SoundboardSound(sound, this)));
3919
+ }
3920
+
3921
+ /**
3922
+ * Get the stage instance associated with a stage channel
3923
+ * @arg {String} channelID The stage channel ID
3924
+ * @returns {Promise<StageInstance>}
3925
+ */
3926
+ getStageInstance(channelID) {
3927
+ return this.requestHandler.request("GET", Endpoints.STAGE_INSTANCE(channelID), true).then((instance) => new StageInstance(instance, this));
3928
+ }
3929
+
3930
+ /**
3931
+ * Get a sticker pack
3932
+ * @arg {String} packID The ID of the pack
3933
+ * @returns {Promise<Object>} An object representing the [sticker pack](https://discord.dev/resources/sticker#sticker-pack-object)
3934
+ */
3935
+ getStickerPack(packID) {
3936
+ return this.requestHandler.request("GET", Endpoints.STICKER_PACK(packID), true);
3937
+ }
3938
+
3939
+ /**
3940
+ * Get the list of available sticker packs
3941
+ * @returns {Promise<{sticker_packs: Array<Object>}>} An object containing a `sticker_packs` value which contains an array of sticker packs
3942
+ */
3943
+ getStickerPacks() {
3944
+ return this.requestHandler.request("GET", Endpoints.STICKER_PACKS, true);
3945
+ }
3946
+
3947
+ /**
3948
+ * Get a member that is part of a thread channel
3949
+ * @arg {String} channelID The ID of the thread channel
3950
+ * @arg {String} userID The ID of the user
3951
+ * @arg {Boolean} [withMember] Whether to include the guild member object within the response
3952
+ * @returns {Promise<ThreadMember>}
3953
+ */
3954
+ getThreadMember(channelID, userID, withMember) {
3955
+ return this.requestHandler.request("GET", Endpoints.THREAD_MEMBER(channelID, userID), true, {
3956
+ with_member: withMember,
3957
+ }).then((threadMember) => new ThreadMember(threadMember, this));
3958
+ }
3959
+
3960
+ /**
3961
+ * Get a list of members that are part of a thread channel
3962
+ * @arg {String} channelID The ID of the thread channel
3963
+ * @arg {Object} [options] Options for the request
3964
+ * @arg {String} [options.after] Get members after this user ID
3965
+ * @arg {Number} [options.limit=100] The maximum number of thread members to fetch (1-100)
3966
+ * @arg {Boolean} [options.withMember] Whether to include the guild member object for each member of the thread
3967
+ * @returns {Promise<Array<ThreadMember>>}
3968
+ */
3969
+ getThreadMembers(channelID, options = {}) {
3970
+ return this.requestHandler.request("GET", Endpoints.THREAD_MEMBERS(channelID), true, {
3971
+ after: options.after,
3972
+ limit: options.limit,
3973
+ with_member: options.withMember,
3974
+ }).then((members) => members.map((member) => new ThreadMember(member, this)));
3975
+ }
3976
+
3977
+ /**
3978
+ * Get the application identities of a user, without their profile data. The user must have authorized the application with the `application_identities.write` scope
3979
+ * @arg {String} userID The ID of the user
3980
+ * @returns {Promise<Array<Object>>} An array of objects containing the `userID`, `providerType`, `providerID` and `providerIssuedUserID` of each identity
3981
+ */
3982
+ getUserApplicationIdentities(userID) {
3983
+ return this.requestHandler.request("GET", Endpoints.USER_APPLICATION_IDENTITIES(userID, this.application.id), true).then((response) => response.identities.map((identity) => this._formatApplicationIdentity(identity)));
3984
+ }
3985
+
3986
+ /**
3987
+ * Get a list of general/guild-specific voice regions
3988
+ * @arg {String} [guildID] The ID of the guild
3989
+ * @returns {Promise<Array<Object>>} Resolves with an array of voice region objects
3990
+ */
3991
+ getVoiceRegions(guildID) {
3992
+ return guildID ? this.requestHandler.request("GET", Endpoints.GUILD_VOICE_REGIONS(guildID), true) : this.requestHandler.request("GET", Endpoints.VOICE_REGIONS, true);
3993
+ }
3994
+
3995
+ /**
3996
+ * Get a webhook
3997
+ * @arg {String} webhookID The ID of the webhook
3998
+ * @arg {String} [token] The token of the webhook, used instead of the Bot Authorization token
3999
+ * @returns {Promise<Object>} Resolves with a webhook object
4000
+ */
4001
+ getWebhook(webhookID, token) {
4002
+ return this.requestHandler.request("GET", token ? Endpoints.WEBHOOK_TOKEN(webhookID, token) : Endpoints.WEBHOOK(webhookID), !token);
4003
+ }
4004
+
4005
+ /**
4006
+ * Get a webhook message
4007
+ * @arg {String} webhookID The ID of the webhook
4008
+ * @arg {String} token The token of the webhook
4009
+ * @arg {String} messageID The message ID of a message sent by this webhook
4010
+ * @returns {Promise<Message>} Resolves with a webhook message
4011
+ */
4012
+ getWebhookMessage(webhookID, token, messageID) {
4013
+ return this.requestHandler.request("GET", Endpoints.WEBHOOK_MESSAGE(webhookID, token, messageID)).then((message) => new Message(message, this));
4014
+ }
4015
+
4016
+ /**
4017
+ * Join a thread
4018
+ * @arg {String} channelID The ID of the thread channel
4019
+ * @arg {String} [userID="@me"] The user ID of the user joining
4020
+ * @returns {Promise}
4021
+ */
4022
+ joinThread(channelID, userID = "@me") {
4023
+ return this.requestHandler.request("PUT", Endpoints.THREAD_MEMBER(channelID, userID), true);
4024
+ }
4025
+
4026
+ /**
4027
+ * Join a voice channel
4028
+ * @arg {String} channelID The ID of the voice channel
4029
+ * @arg {Object} [options] VoiceConnection constructor options
4030
+ * @arg {Boolean} [options.daveEncryption=true] Whether to support end-to-end encryption (DAVE protocol), required by Discord for voice channels. Requires the `@snazzah/davey` package
4031
+ * @arg {Number} [options.decryptionFailureTolerance=36] The number of consecutive end-to-end decryption failures from a single user after which the DAVE session is recovered (0 to never recover). Recoveries are at least 10 seconds apart, and skipped while packets from other users still decrypt
4032
+ * @arg {Object} [options.opusOnly] Skip opus encoder initialization. You should not enable this unless you know what you are doing
4033
+ * @arg {Boolean} [options.selfDeaf] Whether the bot joins the channel deafened or not
4034
+ * @arg {Boolean} [options.selfMute] Whether the bot joins the channel muted or not
4035
+ * @arg {Object} [options.shared] Whether the VoiceConnection will be part of a SharedStream or not
4036
+ * @returns {Promise<VoiceConnection>} Resolves with a VoiceConnection
4037
+ */
4038
+ joinVoiceChannel(channelID, options = {}) {
4039
+ const channel = this.getChannel(channelID);
4040
+ if (!channel) {
4041
+ return Promise.reject(new Error("Channel not found"));
4042
+ }
4043
+ if (channel.guild && channel.guild.members.has(this.user.id) && !(channel.permissionsOf(this.user.id).allow & Constants.Permissions.voiceConnect)) {
4044
+ return Promise.reject(new Error("Insufficient permission to connect to voice channel"));
4045
+ }
4046
+ this.shards.get(this.guildShardMap[this.channelGuildMap[channelID]] || 0).sendWS(Constants.GatewayOPCodes.VOICE_STATE_UPDATE, {
4047
+ guild_id: this.channelGuildMap[channelID] || null,
4048
+ channel_id: channelID || null,
4049
+ self_mute: options.selfMute || false,
4050
+ self_deaf: options.selfDeaf || false,
4051
+ });
4052
+ if (options.opusOnly === undefined) {
4053
+ options.opusOnly = this.options.opusOnly;
4054
+ }
4055
+ return this.voiceConnections.join(this.channelGuildMap[channelID], channelID, options);
4056
+ }
4057
+
4058
+ /**
4059
+ * Kick a user from a guild
4060
+ * @arg {String} guildID The ID of the guild
4061
+ * @arg {String} userID The ID of the user
4062
+ * @arg {String} [reason] The reason to be displayed in audit logs
4063
+ * @returns {Promise}
4064
+ */
4065
+ kickGuildMember(guildID, userID, reason) {
4066
+ return this.requestHandler.request("DELETE", Endpoints.GUILD_MEMBER(guildID, userID), true, {
4067
+ reason,
4068
+ });
4069
+ }
4070
+
4071
+ /**
4072
+ * Leave a guild
4073
+ * @arg {String} guildID The ID of the guild
4074
+ * @returns {Promise}
4075
+ */
4076
+ leaveGuild(guildID) {
4077
+ return this.requestHandler.request("DELETE", Endpoints.USER_GUILD("@me", guildID), true);
4078
+ }
4079
+
4080
+ /**
4081
+ * Leave a thread
4082
+ * @arg {String} channelID The ID of the thread channel
4083
+ * @arg {String} [userID="@me"] The user ID of the user leaving
4084
+ * @returns {Promise}
4085
+ */
4086
+ leaveThread(channelID, userID = "@me") {
4087
+ return this.requestHandler.request("DELETE", Endpoints.THREAD_MEMBER(channelID, userID), true);
4088
+ }
4089
+
4090
+ /**
4091
+ * Leaves a voice channel
4092
+ * @arg {String} channelID The ID of the voice channel
4093
+ */
4094
+ leaveVoiceChannel(channelID) {
4095
+ if (!channelID || !this.channelGuildMap[channelID]) {
4096
+ return;
4097
+ }
4098
+ this.closeVoiceConnection(this.channelGuildMap[channelID]);
4099
+ }
4100
+
4101
+ /**
4102
+ * Pin a message
4103
+ * @arg {String} channelID The ID of the channel
4104
+ * @arg {String} messageID The ID of the message
4105
+ * @returns {Promise}
4106
+ */
4107
+ pinMessage(channelID, messageID) {
4108
+ return this.requestHandler.request("PUT", Endpoints.CHANNEL_PIN(channelID, messageID), true);
4109
+ }
4110
+
4111
+ /**
4112
+ * Begin pruning a guild
4113
+ * @arg {String} guildID The ID of the guild
4114
+ * @arg {Number} [options] The options to pass to prune members
4115
+ * @arg {Boolean} [options.computePruneCount=true] Whether or not the number of pruned members should be returned. Discord discourages setting this to true for larger guilds
4116
+ * @arg {Number} [options.days=7] The number of days of inactivity to prune for
4117
+ * @arg {Array<String>} [options.includeRoles] An array of role IDs that members must have to be considered for pruning
4118
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
4119
+ * @returns {Promise<Number?>} If computePruneCount was true, resolves with the number of pruned members
4120
+ */
4121
+ pruneMembers(guildID, options = {}) {
4122
+ return this.requestHandler.request("POST", Endpoints.GUILD_PRUNE(guildID), true, {
4123
+ days: options.days,
4124
+ compute_prune_count: options.computePruneCount,
4125
+ include_roles: options.includeRoles,
4126
+ reason: options.reason,
4127
+ }).then((data) => data.pruned);
4128
+ }
4129
+
4130
+ /**
4131
+ * Purge previous messages in a channel with an optional filter (bot accounts only)
4132
+ * @arg {String} channelID The ID of the channel
4133
+ * @arg {Object} options Options for the request. If this is a number ([DEPRECATED] behavior), it is treated as `options.limit`
4134
+ * @arg {String} [options.after] Get messages after this message ID
4135
+ * @arg {String} [options.before] Get messages before this message ID
4136
+ * @arg {Function} [options.filter] Optional filter function that returns a boolean when passed a Message object
4137
+ * @arg {Number} options.limit The max number of messages to search through, -1 for no limit
4138
+ * @arg {String} [options.reason] The reason to be displayed in audit logs
4139
+ * @arg {Function} [filter] [DEPRECATED] Optional filter function that returns a boolean when passed a Message object
4140
+ * @arg {String} [before] [DEPRECATED] Get messages before this message ID
4141
+ * @arg {String} [after] [DEPRECATED] Get messages after this message ID
4142
+ * @arg {String} [reason] [DEPRECATED] The reason to be displayed in audit logs
4143
+ * @returns {Promise<Number>} Resolves with the number of messages deleted
4144
+ */
4145
+ async purgeChannel(channelID, options, filter, before, after, reason) {
4146
+ if (!options || typeof options !== "object") {
4147
+ options = {
4148
+ limit: options,
4149
+ };
4150
+ }
4151
+ if (after !== undefined) {
4152
+ options.after = after;
4153
+ }
4154
+ if (before !== undefined) {
4155
+ options.before = before;
4156
+ }
4157
+ if (filter !== undefined) {
4158
+ options.filter = filter;
4159
+ }
4160
+ if (reason !== undefined) {
4161
+ options.reason = reason;
4162
+ }
4163
+ if (typeof options.filter === "string") {
4164
+ const filter = options.filter;
4165
+ options.filter = (msg) => msg.content.includes(filter);
4166
+ }
4167
+ let limit = options.limit;
4168
+ if (typeof limit !== "number") {
4169
+ throw new TypeError(`Invalid limit: ${limit}`);
4170
+ }
4171
+ if (limit !== -1 && limit <= 0) {
4172
+ return 0;
4173
+ }
4174
+ const toDelete = [];
4175
+ let deleted = 0;
4176
+ let done = false;
4177
+ const checkToDelete = async () => {
4178
+ const messageIDs = (done && toDelete) || (toDelete.length >= 100 && toDelete.splice(0, 100));
4179
+ if (messageIDs) {
4180
+ deleted += messageIDs.length;
4181
+ await this.deleteMessages(channelID, messageIDs, options.reason);
4182
+ if (done) {
4183
+ return deleted;
4184
+ }
4185
+ await sleep(1000);
4186
+ return checkToDelete();
4187
+ } else if (done) {
4188
+ return deleted;
4189
+ } else {
4190
+ await sleep(250);
4191
+ return checkToDelete();
4192
+ }
4193
+ };
4194
+ const del = async (_before, _after) => {
4195
+ const messages = await this.getMessages(channelID, {
4196
+ limit: 100,
4197
+ before: _before,
4198
+ after: _after,
4199
+ });
4200
+ if (limit !== -1 && limit <= 0) {
4201
+ done = true;
4202
+ return;
4203
+ }
4204
+ for (const message of messages) {
4205
+ if (limit !== -1 && limit <= 0) {
4206
+ break;
4207
+ }
4208
+ if (message.timestamp < Date.now() - 1209600000) { // 14d * 24h * 60m * 60s * 1000ms
4209
+ done = true;
4210
+ return;
4211
+ }
4212
+ if (!options.filter || options.filter(message)) {
4213
+ toDelete.push(message.id);
4214
+ }
4215
+ if (limit !== -1) {
4216
+ limit--;
4217
+ }
4218
+ }
4219
+ if ((limit !== -1 && limit <= 0) || messages.length < 100) {
4220
+ done = true;
4221
+ return;
4222
+ }
4223
+ await del((_before || !_after) && messages[messages.length - 1].id, _after && messages[0].id);
4224
+ };
4225
+ await del(options.before, options.after);
4226
+ return checkToDelete();
4227
+ }
4228
+
4229
+ /**
4230
+ * Remove a user from a group
4231
+ * @arg {String} groupID The ID of the target group
4232
+ * @arg {String} userID The ID of the target user
4233
+ * @returns {Promise}
4234
+ */
4235
+ removeGroupRecipient(groupID, userID) {
4236
+ return this.requestHandler.request("DELETE", Endpoints.CHANNEL_RECIPIENT(groupID, userID), true);
4237
+ }
4238
+
4239
+ /**
4240
+ * Remove a role from a guild member
4241
+ * @arg {String} guildID The ID of the guild
4242
+ * @arg {String} memberID The ID of the member
4243
+ * @arg {String} roleID The ID of the role
4244
+ * @arg {String} [reason] The reason to be displayed in audit logs
4245
+ * @returns {Promise}
4246
+ */
4247
+ removeGuildMemberRole(guildID, memberID, roleID, reason) {
4248
+ return this.requestHandler.request("DELETE", Endpoints.GUILD_MEMBER_ROLE(guildID, memberID, roleID), true, {
4249
+ reason,
4250
+ });
4251
+ }
4252
+
4253
+ /**
4254
+ * Remove a target user from an invite
4255
+ * @arg {String} inviteID The code of the invite
4256
+ * @arg {String} userID The ID of the user to remove
4257
+ * @returns {Promise}
4258
+ */
4259
+ removeInviteTargetUser(inviteID, userID) {
4260
+ return this.requestHandler.request("DELETE", Endpoints.INVITE_TARGET_USER(inviteID, userID), true);
4261
+ }
4262
+
4263
+ /**
4264
+ * Remove a member from a lobby. Removing a user who is no longer a member succeeds
4265
+ * @arg {String} lobbyID The ID of the lobby
4266
+ * @arg {String} userID The ID of the member
4267
+ * @returns {Promise}
4268
+ */
4269
+ removeLobbyMember(lobbyID, userID) {
4270
+ return this.requestHandler.request("DELETE", Endpoints.LOBBY_MEMBER(lobbyID, userID), true);
4271
+ }
4272
+
4273
+ /**
4274
+ * Remove a reaction from a message
4275
+ * @arg {String} channelID The ID of the channel
4276
+ * @arg {String} messageID The ID of the message
4277
+ * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
4278
+ * @arg {String} [userID="@me"] The ID of the user to remove the reaction for
4279
+ * @returns {Promise}
4280
+ */
4281
+ removeMessageReaction(channelID, messageID, reaction, userID) {
4282
+ if (reaction === decodeURI(reaction)) {
4283
+ reaction = encodeURIComponent(reaction);
4284
+ }
4285
+ return this.requestHandler.request("DELETE", Endpoints.CHANNEL_MESSAGE_REACTION_USER(channelID, messageID, reaction, userID || "@me"), true);
4286
+ }
4287
+
4288
+ /**
4289
+ * Remove all reactions from a message for a single emoji.
4290
+ * @arg {String} channelID The ID of the channel
4291
+ * @arg {String} messageID The ID of the message
4292
+ * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
4293
+ * @returns {Promise}
4294
+ */
4295
+ removeMessageReactionEmoji(channelID, messageID, reaction) {
4296
+ if (reaction === decodeURI(reaction)) {
4297
+ reaction = encodeURIComponent(reaction);
4298
+ }
4299
+ return this.requestHandler.request("DELETE", Endpoints.CHANNEL_MESSAGE_REACTION(channelID, messageID, reaction), true);
4300
+ }
4301
+
4302
+ /**
4303
+ * Remove all reactions from a message
4304
+ * @arg {String} channelID The ID of the channel
4305
+ * @arg {String} messageID The ID of the message
4306
+ * @returns {Promise}
4307
+ */
4308
+ removeMessageReactions(channelID, messageID) {
4309
+ return this.requestHandler.request("DELETE", Endpoints.CHANNEL_MESSAGE_REACTIONS(channelID, messageID), true);
4310
+ }
4311
+
4312
+ /**
4313
+ * Search for guild members by partial nickname/username
4314
+ * @arg {String} guildID The ID of the guild
4315
+ * @arg {String} query The query string to match username(s) and nickname(s) against
4316
+ * @arg {Number} [limit=1] The maximum number of members you want returned, capped at 100
4317
+ * @returns {Promise<Array<Member>>}
4318
+ */
4319
+ searchGuildMembers(guildID, query, limit) {
4320
+ return this.requestHandler.request("GET", Endpoints.GUILD_MEMBERS_SEARCH(guildID), true, {
4321
+ query,
4322
+ limit,
4323
+ }).then((members) => {
4324
+ const guild = this.guilds.get(guildID);
4325
+ return members.map((member) => new Member(member, guild, this));
4326
+ });
4327
+ }
4328
+
4329
+ /**
4330
+ * Search the messages of a guild. Requires the `readMessageHistory` permission, and the `messageContent` privileged intent to be enabled for the application.
4331
+ * Note: If the guild is not indexed yet, the promise resolves with `indexed` set to `false` and no results; retry after `retryAfter` seconds
4332
+ * @arg {String} guildID The ID of the guild
4333
+ * @arg {Object} [options] The search options
4334
+ * @arg {Array<String>} [options.attachmentExtensions] Filter messages by attachment extension (e.g. `txt`)
4335
+ * @arg {Array<String>} [options.attachmentFilenames] Filter messages by attachment filename
4336
+ * @arg {Array<String>} [options.authorIDs] Filter messages by these authors
4337
+ * @arg {Array<String>} [options.authorTypes] Filter messages by author type (`user`, `bot` or `webhook`, prefix with `-` to negate)
4338
+ * @arg {Array<String>} [options.channelIDs] Filter messages by these channels
4339
+ * @arg {String} [options.content] Filter messages by content
4340
+ * @arg {Array<String>} [options.embedProviders] Filter messages by embed provider (case-sensitive, e.g. `Tenor`)
4341
+ * @arg {Array<String>} [options.embedTypes] Filter messages by embed type (`image`, `video`, `gif`, `sound` or `article`)
4342
+ * @arg {Array<String>} [options.has] Filter messages by whether they have specific things (`image`, `sound`, `video`, `file`, `sticker`, `embed`, `link`, `poll` or `snapshot`, prefix with `-` to negate)
4343
+ * @arg {Boolean} [options.includeNSFW=false] Whether to include results from age-restricted channels
4344
+ * @arg {Number} [options.limit=25] The max number of messages to return (1-25)
4345
+ * @arg {Array<String>} [options.linkHostnames] Filter messages by link hostname (e.g. `discord.com`)
4346
+ * @arg {String} [options.maxID] Get messages before this message ID
4347
+ * @arg {Boolean} [options.mentionEveryone] Filter messages that do or do not mention @everyone
4348
+ * @arg {Array<String>} [options.mentions] Filter messages that mention these users
4349
+ * @arg {Array<String>} [options.mentionsRoleIDs] Filter messages that mention these roles
4350
+ * @arg {String} [options.minID] Get messages after this message ID
4351
+ * @arg {Number} [options.offset] The number of messages to skip (max 9975)
4352
+ * @arg {Boolean} [options.pinned] Filter messages by whether they are pinned
4353
+ * @arg {Array<String>} [options.repliedToMessageIDs] Filter messages that reply to these messages
4354
+ * @arg {Array<String>} [options.repliedToUserIDs] Filter messages that reply to these users
4355
+ * @arg {Number} [options.slop=2] The max number of words to skip between matching tokens in `content` (max 100)
4356
+ * @arg {String} [options.sortBy="timestamp"] The sorting algorithm to use, either `timestamp` or `relevance`
4357
+ * @arg {String} [options.sortOrder="desc"] The direction to sort, either `asc` or `desc`
4358
+ * @returns {Promise<Object>} An object containing `doingDeepHistoricalIndex`, `documentsIndexed`, `indexed`, `members` (Array of ThreadMember), `messages` (Array of Message), `retryAfter`, `threads` (Array of ThreadChannel) and `totalResults`
4359
+ */
4360
+ searchGuildMessages(guildID, options = {}) {
4361
+ return this.requestHandler.request("GET", Endpoints.GUILD_MESSAGES_SEARCH(guildID), true, {
4362
+ attachment_extension: options.attachmentExtensions,
4363
+ attachment_filename: options.attachmentFilenames,
4364
+ author_id: options.authorIDs,
4365
+ author_type: options.authorTypes,
4366
+ channel_id: options.channelIDs,
4367
+ content: options.content,
4368
+ embed_provider: options.embedProviders,
4369
+ embed_type: options.embedTypes,
4370
+ has: options.has,
4371
+ include_nsfw: options.includeNSFW,
4372
+ limit: options.limit,
4373
+ link_hostname: options.linkHostnames,
4374
+ max_id: options.maxID,
4375
+ mention_everyone: options.mentionEveryone,
4376
+ mentions: options.mentions,
4377
+ mentions_role_id: options.mentionsRoleIDs,
4378
+ min_id: options.minID,
4379
+ offset: options.offset,
4380
+ pinned: options.pinned,
4381
+ replied_to_message_id: options.repliedToMessageIDs,
4382
+ replied_to_user_id: options.repliedToUserIDs,
4383
+ slop: options.slop,
4384
+ sort_by: options.sortBy,
4385
+ sort_order: options.sortOrder,
4386
+ }).then((response) => ({
4387
+ doingDeepHistoricalIndex: !!response.doing_deep_historical_index,
4388
+ documentsIndexed: response.documents_indexed,
4389
+ indexed: response.retry_after === undefined,
4390
+ members: (response.members || []).map((member) => new ThreadMember(member, this)),
4391
+ messages: (response.messages || []).reduce((messages, group) => messages.concat(group), []).map((message) => new Message(message, this)),
4392
+ retryAfter: response.retry_after,
4393
+ threads: (response.threads || []).map((thread) => Channel.from(thread, this)),
4394
+ totalResults: response.total_results || 0,
4395
+ }));
4396
+ }
4397
+
4398
+ /**
4399
+ * Send typing status in a channel
4400
+ * @arg {String} channelID The ID of the channel
4401
+ * @returns {Promise}
4402
+ */
4403
+ sendChannelTyping(channelID) {
4404
+ return this.requestHandler.request("POST", Endpoints.CHANNEL_TYPING(channelID), true);
4405
+ }
4406
+
4407
+ /**
4408
+ * Send a soundboard sound to a connected voice channel
4409
+ * @arg {String} channelID The ID of the connected voice channel
4410
+ * @arg {Object} options The soundboard sound options
4411
+ * @arg {String} options.soundID The ID of the soundboard sound
4412
+ * @arg {String} [options.sourceGuildID] The ID of the guild where the soundboard sound was created, if not in the same guild
4413
+ * @returns {Promise}
4414
+ */
4415
+ sendSoundboardSound(channelID, options) {
4416
+ options.sound_id = options.soundID;
4417
+ options.source_guild_id = options.sourceGuildID;
4418
+ return this.requestHandler.request("POST", Endpoints.SOUNDBOARD_SOUNDS_SEND(channelID), true, options);
4419
+ }
4420
+
4421
+ /**
4422
+ * Set the status of a voice channel. Note: This will not work in stage channels
4423
+ * @arg {String} channelID The ID of the channel
4424
+ * @arg {String} status The new voice channel status
4425
+ * @arg {String} [reason] The reason to be displayed in audit logs
4426
+ * @returns {Promise}
4427
+ */
4428
+ setVoiceChannelStatus(channelID, status, reason) {
4429
+ return this.requestHandler.request("PUT", Endpoints.CHANNEL_VOICE_STATUS(channelID), true, {
4430
+ status,
4431
+ reason,
4432
+ });
4433
+ }
4434
+
4435
+ /**
4436
+ * Force a guild integration to sync
4437
+ * @arg {String} guildID The ID of the guild
4438
+ * @arg {String} integrationID The ID of the integration
4439
+ * @returns {Promise}
4440
+ */
4441
+ syncGuildIntegration(guildID, integrationID) {
4442
+ return this.requestHandler.request("POST", Endpoints.GUILD_INTEGRATION_SYNC(guildID, integrationID), true);
4443
+ }
4444
+
4445
+ /**
4446
+ * Force a guild template to sync
4447
+ * @arg {String} guildID The ID of the guild
4448
+ * @arg {String} code The template code
4449
+ * @returns {Promise<GuildTemplate>}
4450
+ */
4451
+ syncGuildTemplate(guildID, code) {
4452
+ return this.requestHandler.request("PUT", Endpoints.GUILD_TEMPLATE_GUILD(guildID, code), true).then((template) => new GuildTemplate(template, this));
4453
+ }
4454
+
4455
+ /**
4456
+ * Unban a user from a guild
4457
+ * @arg {String} guildID The ID of the guild
4458
+ * @arg {String} userID The ID of the user
4459
+ * @arg {String} [reason] The reason to be displayed in audit logs
4460
+ * @returns {Promise}
4461
+ */
4462
+ unbanGuildMember(guildID, userID, reason) {
4463
+ return this.requestHandler.request("DELETE", Endpoints.GUILD_BAN(guildID, userID), true, {
4464
+ reason,
4465
+ });
4466
+ }
4467
+
4468
+ /**
4469
+ * Unpin a message
4470
+ * @arg {String} channelID The ID of the channel
4471
+ * @arg {String} messageID The ID of the message
4472
+ * @returns {Promise}
4473
+ */
4474
+ unpinMessage(channelID, messageID) {
4475
+ return this.requestHandler.request("DELETE", Endpoints.CHANNEL_PIN(channelID, messageID), true);
4476
+ }
4477
+
4478
+ /**
4479
+ * Validate discovery search term
4480
+ * @arg {String} term The search term to check
4481
+ * @returns {Promise<Object>} An object with a `valid` field which is `true` when valid and `false` when invalid
4482
+ */
4483
+ validateDiscoverySearchTerm(term) {
4484
+ return this.requestHandler.request("GET", Endpoints.DISCOVERY_VALIDATION + `?term=${encodeURI(term)}`, true);
4485
+ }
4486
+
4487
+ _formatAllowedMentions(allowed) {
4488
+ if (!allowed) {
4489
+ return this.options.allowedMentions;
4490
+ }
4491
+ const result = {
4492
+ parse: [],
4493
+ };
4494
+ if (allowed.everyone) {
4495
+ result.parse.push("everyone");
4496
+ }
4497
+ if (allowed.roles === true) {
4498
+ result.parse.push("roles");
4499
+ } else if (Array.isArray(allowed.roles)) {
4500
+ if (allowed.roles.length > 100) {
4501
+ throw new Error("Allowed role mentions cannot exceed 100.");
4502
+ }
4503
+ result.roles = allowed.roles;
4504
+ }
4505
+ if (allowed.users === true) {
4506
+ result.parse.push("users");
4507
+ } else if (Array.isArray(allowed.users)) {
4508
+ if (allowed.users.length > 100) {
4509
+ throw new Error("Allowed user mentions cannot exceed 100.");
4510
+ }
4511
+ result.users = allowed.users;
4512
+ }
4513
+ if (allowed.repliedUser !== undefined) {
4514
+ result.replied_user = allowed.repliedUser;
4515
+ }
4516
+ return result;
4517
+ }
4518
+
4519
+ _formatApplicationIdentity(identity) {
4520
+ return {
4521
+ providerID: identity.provider_id !== undefined ? identity.provider_id : null,
4522
+ providerIssuedUserID: identity.provider_issued_user_id,
4523
+ providerType: identity.provider_type,
4524
+ userID: identity.user_id,
4525
+ };
4526
+ }
4527
+
4528
+ /**
4529
+ * Format the options of an auto moderation rule for the API. Metadata keys already in snake_case are sent as is
4530
+ * @arg {Object} options The rule options
4531
+ * @returns {Object}
4532
+ * @private
4533
+ */
4534
+ _formatAutoModerationRule(options) {
4535
+ const snakeCase = (object, keys) => {
4536
+ if (!object) {
4537
+ return object;
4538
+ }
4539
+ const formatted = Object.assign({}, object);
4540
+ for (const key in keys) {
4541
+ if (formatted[key] !== undefined) {
4542
+ formatted[keys[key]] = formatted[key];
4543
+ delete formatted[key];
4544
+ }
4545
+ }
4546
+ return formatted;
4547
+ };
4548
+ return {
4549
+ actions: options.actions && options.actions.map((action) => Object.assign({}, action, {
4550
+ metadata: snakeCase(action.metadata, {
4551
+ channelID: "channel_id",
4552
+ customMessage: "custom_message",
4553
+ durationSeconds: "duration_seconds",
4554
+ }),
4555
+ })),
4556
+ enabled: options.enabled,
4557
+ event_type: options.eventType,
4558
+ exempt_channels: options.exemptChannels,
4559
+ exempt_roles: options.exemptRoles,
4560
+ name: options.name,
4561
+ reason: options.reason,
4562
+ trigger_metadata: snakeCase(options.triggerMetadata, {
4563
+ allowList: "allow_list",
4564
+ keywordFilter: "keyword_filter",
4565
+ mentionRaidProtectionEnabled: "mention_raid_protection_enabled",
4566
+ mentionTotalLimit: "mention_total_limit",
4567
+ regexPatterns: "regex_patterns",
4568
+ }),
4569
+ trigger_type: options.triggerType,
4570
+ };
4571
+ }
4572
+
4573
+ /**
4574
+ * Format an application command object for the API
4575
+ * @arg {Object} command The command object
4576
+ * @arg {String} method The name of the method that was called, used in deprecation warnings
4577
+ * @returns {Object}
4578
+ * @private
4579
+ */
4580
+ _formatCommand(command, method) {
4581
+ const formatted = formatCommandOption(command);
4582
+ if (formatted.name !== undefined && (formatted.type === undefined || formatted.type === Constants.ApplicationCommandTypes.CHAT_INPUT)) {
4583
+ formatted.name = formatted.name.toLowerCase();
4584
+ if (!formatted.name.match(/^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$/u)) {
4585
+ throw new Error("Slash Command names must match the regular expression \"^[-_\\p{L}\\p{N}\\p{sc=Deva}\\p{sc=Thai}]{1,32}$\"");
4586
+ }
4587
+ }
4588
+ if (formatted.defaultMemberPermissions !== undefined) {
4589
+ const permissions = formatted.defaultMemberPermissions;
4590
+ formatted.default_member_permissions = permissions === null ? null : String(permissions instanceof Permission ? permissions.allow : permissions);
4591
+ delete formatted.defaultMemberPermissions;
4592
+ }
4593
+ if (formatted.defaultPermission !== undefined) {
4594
+ emitDeprecation("DEFAULT_PERMISSION");
4595
+ this.emit("warn", `[DEPRECATED] ${method}() was called with a \`defaultPermission\` parameter. This has been replaced with \`defaultMemberPermissions\``);
4596
+ formatted.default_permission = formatted.defaultPermission;
4597
+ delete formatted.defaultPermission;
4598
+ }
4599
+ if (formatted.dmPermission !== undefined) {
4600
+ formatted.dm_permission = formatted.dmPermission;
4601
+ delete formatted.dmPermission;
4602
+ }
4603
+ if (formatted.integrationTypes !== undefined) {
4604
+ formatted.integration_types = formatted.integrationTypes;
4605
+ delete formatted.integrationTypes;
4606
+ }
4607
+ return formatted;
4608
+ }
4609
+
4610
+ _formatImage(url, format, size) {
4611
+ if (!format || !Constants.ImageFormats.includes(format.toLowerCase())) {
4612
+ format = url.includes("/a_") ? "gif" : this.options.defaultImageFormat;
4613
+ }
4614
+ if (!size || size < Constants.ImageSizeBoundaries.MINIMUM || size > Constants.ImageSizeBoundaries.MAXIMUM || (size & (size - 1))) {
4615
+ size = this.options.defaultImageSize;
4616
+ }
4617
+ return `${Endpoints.CDN_URL}${url}.${format}?size=${size}`;
4618
+ }
4619
+
4620
+ _formatLobby(options) {
4621
+ return {
4622
+ idle_timeout_seconds: options.idleTimeoutSeconds,
4623
+ members: options.members && options.members.map((member) => this._formatLobbyMember(member)),
4624
+ metadata: options.metadata,
4625
+ };
4626
+ }
4627
+
4628
+ _formatLobbyMember(member) {
4629
+ return {
4630
+ additional_name: member.additionalName,
4631
+ flags: member.flags,
4632
+ id: member.id,
4633
+ metadata: member.metadata,
4634
+ remove_member: member.removeMember,
4635
+ };
4636
+ }
4637
+
4638
+ _formatScheduledEventRecurrence(recur) {
4639
+ if (!recur) {
4640
+ return recur;
4641
+ }
4642
+ if (recur.byMonth !== undefined) {
4643
+ recur.by_month = recur.byMonth;
4644
+ delete recur.byMonth;
4645
+ }
4646
+ if (recur.byMonthDay !== undefined) {
4647
+ recur.by_month_day = recur.byMonthDay;
4648
+ delete recur.byMonthDay;
4649
+ }
4650
+ if (recur.byNWeekday !== undefined) {
4651
+ recur.by_n_weekday = recur.byNWeekday;
4652
+ delete recur.byNWeekday;
4653
+ }
4654
+ if (recur.byWeekday !== undefined) {
4655
+ recur.by_weekday = recur.byWeekday;
4656
+ delete recur.byWeekday;
4657
+ }
4658
+ if (recur.byYearDay !== undefined) {
4659
+ recur.by_year_day = recur.byYearDay;
4660
+ delete recur.byYearDay;
4661
+ }
4662
+ return recur;
4663
+ }
4664
+
4665
+ _formatTargetUsersFile(targetUsers) {
4666
+ return {
4667
+ fieldName: "target_users_file",
4668
+ file: Buffer.isBuffer(targetUsers) ? targetUsers : Buffer.from("user_id\n" + targetUsers.join("\n")),
4669
+ name: "target_users.csv",
4670
+ };
4671
+ }
4672
+
4673
+ toString() {
4674
+ return `[Client ${this.user.id}]`;
4675
+ }
4676
+
4677
+ toJSON(props = []) {
4678
+ return Base.prototype.toJSON.call(this, [
4679
+ "application",
4680
+ "bot",
4681
+ "channelGuildMap",
4682
+ "gatewayURL",
4683
+ "groupChannels",
4684
+ "guilds",
4685
+ "guildShardMap",
4686
+ "lastConnect",
4687
+ "lastReconnectDelay",
4688
+ "notes",
4689
+ "options",
4690
+ "presence",
4691
+ "dmChannelMap",
4692
+ "dmChannels",
4693
+ "ready",
4694
+ "reconnectAttempts",
4695
+ "requestHandler",
4696
+ "shards",
4697
+ "startTime",
4698
+ "unavailableGuilds",
4699
+ "userGuildSettings",
4700
+ "users",
4701
+ "userSettings",
4702
+ "voiceConnections",
4703
+ ...props,
4704
+ ]);
4705
+ }
4706
+ }
4707
+
4708
+ module.exports = Client;