@zygout/eris 0.0.0-stage → 0.19.0

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