@discordeno/rest 19.0.0-next.aba7de6 → 19.0.0-next.abfa0bb

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.
package/dist/manager.js CHANGED
@@ -1,510 +1,40 @@
1
- /* eslint-disable @typescript-eslint/restrict-template-expressions */ /* eslint-disable no-const-assign */ import { InteractionResponseTypes } from '@discordeno/types';
2
- import { calculateBits, camelize, camelToSnakeCase, delay, encode, getBotIdFromToken, isGetMessagesAfter, isGetMessagesAround, isGetMessagesBefore, isGetMessagesLimit, logger, processReactionString, urlToBase64 } from '@discordeno/utils';
3
- import fetch from 'node-fetch';
1
+ /* eslint-disable @typescript-eslint/restrict-template-expressions */ /* eslint-disable no-const-assign */ import { calculateBits, camelToSnakeCase, camelize, delay, getBotIdFromToken, logger, processReactionString, urlToBase64 } from '@discordeno/utils';
4
2
  import { createInvalidRequestBucket } from './invalidBucket.js';
5
3
  import { Queue } from './queue.js';
4
+ import { InteractionResponseTypes } from '@discordeno/types';
5
+ import { createRoutes } from './routes.js';
6
6
  // TODO: make dynamic based on package.json file
7
7
  const version = '19.0.0-alpha.1';
8
+ export const DISCORD_API_VERSION = 10;
9
+ export const DISCORD_API_URL = 'https://discord.com/api';
10
+ export const AUDIT_LOG_REASON_HEADER = 'x-audit-log-reason';
11
+ export const RATE_LIMIT_REMAINING_HEADER = 'x-ratelimit-remaining';
12
+ export const RATE_LIMIT_RESET_AFTER_HEADER = 'x-ratelimit-reset-after';
13
+ export const RATE_LIMIT_GLOBAL_HEADER = 'x-ratelimit-global';
14
+ export const RATE_LIMIT_BUCKET_HEADER = 'x-ratelimit-bucket';
15
+ export const RATE_LIMIT_LIMIT_HEADER = 'x-ratelimit-limit';
16
+ export const RATE_LIMIT_SCOPE_HEADER = 'x-ratelimit-scope';
8
17
  export function createRestManager(options) {
9
- // Falsy token string check
10
- if (!options.token) throw new Error('You must provide a valid token.');
18
+ const applicationId = options.applicationId ? BigInt(options.applicationId) : options.token ? getBotIdFromToken(options.token) : undefined;
19
+ if (!applicationId) {
20
+ throw new Error('`applicationId` was not provided and was not able to extract the id from the bots token. Please explicitly pass `applicationId` to the rest manager.');
21
+ }
22
+ const baseUrl = options.proxy?.baseUrl ?? DISCORD_API_URL;
11
23
  const rest = {
12
- token: options.token,
13
- applicationId: options.applicationId ? BigInt(options.applicationId) : getBotIdFromToken(options.token),
14
- version: options.version ?? 10,
15
- baseUrl: options.proxy?.baseUrl ?? 'https://discord.com/api',
16
- maxRetryCount: Infinity,
24
+ applicationId,
25
+ authorization: options.proxy?.authorization,
26
+ baseUrl,
27
+ deleteQueueDelay: 60000,
17
28
  globallyRateLimited: false,
29
+ invalidBucket: createInvalidRequestBucket({}),
30
+ isProxied: !baseUrl.startsWith(DISCORD_API_URL),
31
+ maxRetryCount: Infinity,
18
32
  processingRateLimitedPaths: false,
19
- deleteQueueDelay: 60000,
20
33
  queues: new Map(),
21
34
  rateLimitedPaths: new Map(),
22
- invalidBucket: createInvalidRequestBucket({}),
23
- authorization: options.proxy?.authorization,
24
- routes: {
25
- webhooks: {
26
- id: (webhookId)=>{
27
- return `/webhooks/${webhookId}`;
28
- },
29
- message: (webhookId, token, messageId, options)=>{
30
- let url = `/webhooks/${webhookId}/${token}/messages/${messageId}?`;
31
- if (options) {
32
- if (options.threadId) url += `thread_id=${options.threadId}`;
33
- }
34
- return url;
35
- },
36
- original: (webhookId, token, options)=>{
37
- let url = `/webhooks/${webhookId}/${token}/messages/@original?`;
38
- if (options) {
39
- if (options.threadId) url += `thread_id=${options.threadId}`;
40
- }
41
- return url;
42
- },
43
- webhook: (webhookId, token, options)=>{
44
- let url = `/webhooks/${webhookId}/${token}?`;
45
- if (options) {
46
- if (options?.wait !== undefined) url += `wait=${options.wait.toString()}`;
47
- if (options.threadId) url += `thread_id=${options.threadId}`;
48
- }
49
- return url;
50
- }
51
- },
52
- // Miscellaneous Endpoints
53
- sessionInfo: ()=>rest.routes.gatewayBot(),
54
- // Channel Endpoints
55
- channels: {
56
- bulk: (channelId)=>{
57
- return `/channels/${channelId}/messages/bulk-delete`;
58
- },
59
- dm: ()=>{
60
- return '/users/@me/channels';
61
- },
62
- pin: (channelId, messageId)=>{
63
- return `/channels/${channelId}/pins/${messageId}`;
64
- },
65
- pins: (channelId)=>{
66
- return `/channels/${channelId}/pins`;
67
- },
68
- reactions: {
69
- bot: (channelId, messageId, emoji)=>{
70
- return `/channels/${channelId}/messages/${messageId}/reactions/${encodeURIComponent(emoji)}/@me`;
71
- },
72
- user: (channelId, messageId, emoji, userId)=>{
73
- return `/channels/${channelId}/messages/${messageId}/reactions/${encodeURIComponent(emoji)}/${userId}`;
74
- },
75
- all: (channelId, messageId)=>{
76
- return `/channels/${channelId}/messages/${messageId}/reactions`;
77
- },
78
- emoji: (channelId, messageId, emoji, options)=>{
79
- let url = `/channels/${channelId}/messages/${messageId}/reactions/${encodeURIComponent(emoji)}?`;
80
- if (options) {
81
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
82
- if (options.after) url += `after=${options.after}`;
83
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
84
- if (options.limit) url += `&limit=${options.limit}`;
85
- }
86
- return url;
87
- },
88
- message: (channelId, messageId, emoji, options)=>{
89
- let url = `/channels/${channelId}/messages/${messageId}/reactions/${encodeURIComponent(emoji)}?`;
90
- if (options) {
91
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
92
- if (options.after) url += `after=${options.after}`;
93
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
94
- if (options.limit) url += `&limit=${options.limit}`;
95
- }
96
- return url;
97
- }
98
- },
99
- webhooks: (channelId)=>{
100
- return `/channels/${channelId}/webhooks`;
101
- },
102
- channel: (channelId)=>{
103
- return `/channels/${channelId}`;
104
- },
105
- follow: (channelId)=>{
106
- return `/channels/${channelId}/followers`;
107
- },
108
- forum: (channelId)=>{
109
- return `/channels/${channelId}/threads?has_message=true`;
110
- },
111
- invites: (channelId)=>{
112
- return `/channels/${channelId}/invites`;
113
- },
114
- message: (channelId, messageId)=>{
115
- return `/channels/${channelId}/messages/${messageId}`;
116
- },
117
- messages: (channelId, options)=>{
118
- let url = `/channels/${channelId}/messages?`;
119
- if (options) {
120
- if (isGetMessagesAfter(options) && options.after) {
121
- url += `after=${options.after}`;
122
- }
123
- if (isGetMessagesBefore(options) && options.before) {
124
- url += `&before=${options.before}`;
125
- }
126
- if (isGetMessagesAround(options) && options.around) {
127
- url += `&around=${options.around}`;
128
- }
129
- if (isGetMessagesLimit(options) && options.limit) {
130
- url += `&limit=${options.limit}`;
131
- }
132
- }
133
- return url;
134
- },
135
- overwrite: (channelId, overwriteId)=>{
136
- return `/channels/${channelId}/permissions/${overwriteId}`;
137
- },
138
- crosspost: (channelId, messageId)=>{
139
- return `/channels/${channelId}/messages/${messageId}/crosspost`;
140
- },
141
- stages: ()=>{
142
- return '/stage-instances';
143
- },
144
- stage: (channelId)=>{
145
- return `/stage-instances/${channelId}`;
146
- },
147
- // Thread Endpoints
148
- threads: {
149
- message: (channelId, messageId)=>{
150
- return `/channels/${channelId}/messages/${messageId}/threads`;
151
- },
152
- all: (channelId)=>{
153
- return `/channels/${channelId}/threads`;
154
- },
155
- active: (guildId)=>{
156
- return `/guilds/${guildId}/threads/active`;
157
- },
158
- members: (channelId)=>{
159
- return `/channels/${channelId}/thread-members`;
160
- },
161
- me: (channelId)=>{
162
- return `/channels/${channelId}/thread-members/@me`;
163
- },
164
- user: (channelId, userId)=>{
165
- return `/channels/${channelId}/thread-members/${userId}`;
166
- },
167
- archived: (channelId)=>{
168
- return `/channels/${channelId}/threads/archived`;
169
- },
170
- public: (channelId, options)=>{
171
- let url = `/channels/${channelId}/threads/archived/public?`;
172
- if (options) {
173
- if (options.before) {
174
- url += `before=${new Date(options.before).toISOString()}`;
175
- }
176
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
177
- if (options.limit) url += `&limit=${options.limit}`;
178
- }
179
- return url;
180
- },
181
- private: (channelId, options)=>{
182
- let url = `/channels/${channelId}/threads/archived/private?`;
183
- if (options) {
184
- if (options.before) {
185
- url += `before=${new Date(options.before).toISOString()}`;
186
- }
187
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
188
- if (options.limit) url += `&limit=${options.limit}`;
189
- }
190
- return url;
191
- },
192
- joined: (channelId, options)=>{
193
- let url = `/channels/${channelId}/users/@me/threads/archived/private?`;
194
- if (options) {
195
- if (options.before) {
196
- url += `before=${new Date(options.before).toISOString()}`;
197
- }
198
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
199
- if (options.limit) url += `&limit=${options.limit}`;
200
- }
201
- return url;
202
- }
203
- },
204
- typing: (channelId)=>{
205
- return `/channels/${channelId}/typing`;
206
- }
207
- },
208
- // Guild Endpoints
209
- guilds: {
210
- all: ()=>{
211
- return '/guilds';
212
- },
213
- auditlogs: (guildId, options)=>{
214
- let url = `/guilds/${guildId}/audit-logs?`;
215
- if (options) {
216
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
217
- if (options.actionType) url += `action_type=${options.actionType}`;
218
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
219
- if (options.before) url += `&before=${options.before}`;
220
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
221
- if (options.after) url += `&after=${options.after}`;
222
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
223
- if (options.limit) url += `&limit=${options.limit}`;
224
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
225
- if (options.userId) url += `&user_id=${options.userId}`;
226
- }
227
- return url;
228
- },
229
- automod: {
230
- rule: (guildId, ruleId)=>{
231
- return `/guilds/${guildId}/auto-moderation/rules/${ruleId}`;
232
- },
233
- rules: (guildId)=>{
234
- return `/guilds/${guildId}/auto-moderation/rules`;
235
- }
236
- },
237
- channels: (guildId)=>{
238
- return `/guilds/${guildId}/channels`;
239
- },
240
- emoji: (guildId, emojiId)=>{
241
- return `/guilds/${guildId}/emojis/${emojiId}`;
242
- },
243
- emojis: (guildId)=>{
244
- return `/guilds/${guildId}/emojis`;
245
- },
246
- events: {
247
- events: (guildId, withUserCount)=>{
248
- let url = `/guilds/${guildId}/scheduled-events?`;
249
- if (withUserCount !== undefined) {
250
- url += `with_user_count=${withUserCount.toString()}`;
251
- }
252
- return url;
253
- },
254
- event: (guildId, eventId, withUserCount)=>{
255
- let url = `/guilds/${guildId}/scheduled-events/${eventId}`;
256
- if (withUserCount !== undefined) {
257
- url += `with_user_count=${withUserCount.toString()}`;
258
- }
259
- return url;
260
- },
261
- users: (guildId, eventId, options)=>{
262
- let url = `/guilds/${guildId}/scheduled-events/${eventId}/users?`;
263
- if (options) {
264
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
265
- if (options.limit !== undefined) url += `limit=${options.limit}`;
266
- if (options.withMember !== undefined) {
267
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
268
- url += `&with_member=${options.withMember.toString()}`;
269
- }
270
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
271
- if (options.after !== undefined) url += `&after=${options.after}`;
272
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
273
- if (options.before !== undefined) url += `&before=${options.before}`;
274
- }
275
- return url;
276
- }
277
- },
278
- guild (guildId, withCounts) {
279
- let url = `/guilds/${guildId}?`;
280
- if (withCounts !== undefined) {
281
- url += `with_counts=${withCounts.toString()}`;
282
- }
283
- return url;
284
- },
285
- integration (guildId, integrationId) {
286
- return `/guilds/${guildId}/integrations/${integrationId}`;
287
- },
288
- integrations: (guildId)=>{
289
- return `/guilds/${guildId}/integrations?include_applications=true`;
290
- },
291
- invite (inviteCode, options) {
292
- let url = `/invites/${inviteCode}?`;
293
- if (options) {
294
- if (options.withCounts !== undefined) {
295
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
296
- url += `with_counts=${options.withCounts.toString()}`;
297
- }
298
- if (options.withExpiration !== undefined) {
299
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
300
- url += `&with_expiration=${options.withExpiration.toString()}`;
301
- }
302
- if (options.scheduledEventId) {
303
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
304
- url += `&guild_scheduled_event_id=${options.scheduledEventId}`;
305
- }
306
- }
307
- return url;
308
- },
309
- invites: (guildId)=>{
310
- return `/guilds/${guildId}/invites`;
311
- },
312
- leave: (guildId)=>{
313
- return `/users/@me/guilds/${guildId}`;
314
- },
315
- members: {
316
- ban: (guildId, userId)=>{
317
- return `/guilds/${guildId}/bans/${userId}`;
318
- },
319
- bans: (guildId, options)=>{
320
- let url = `/guilds/${guildId}/bans?`;
321
- if (options) {
322
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
323
- if (options.limit) url += `limit=${options.limit}`;
324
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
325
- if (options.after) url += `&after=${options.after}`;
326
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
327
- if (options.before) url += `&before=${options.before}`;
328
- }
329
- return url;
330
- },
331
- bot: (guildId)=>{
332
- return `/guilds/${guildId}/members/@me`;
333
- },
334
- member: (guildId, userId)=>{
335
- return `/guilds/${guildId}/members/${userId}`;
336
- },
337
- members: (guildId, options)=>{
338
- let url = `/guilds/${guildId}/members?`;
339
- if (options !== undefined) {
340
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
341
- if (options.limit) url += `limit=${options.limit}`;
342
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
343
- if (options.after) url += `&after=${options.after}`;
344
- }
345
- return url;
346
- },
347
- search: (guildId, query, options)=>{
348
- let url = `/guilds/${guildId}/members/search?query=${encodeURIComponent(query)}`;
349
- if (options) {
350
- if (options.limit !== undefined) url += `&limit=${options.limit}`;
351
- }
352
- return url;
353
- },
354
- prune: (guildId, options)=>{
355
- let url = `/guilds/${guildId}/prune?`;
356
- if (options) {
357
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
358
- if (options.days) url += `days=${options.days}`;
359
- if (Array.isArray(options.includeRoles)) {
360
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
361
- url += `&include_roles=${options.includeRoles.join(',')}`;
362
- } else if (options.includeRoles) {
363
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
364
- url += `&include_roles=${options.includeRoles}`;
365
- }
366
- }
367
- return url;
368
- }
369
- },
370
- mfa: (guildId)=>`/guilds/${guildId}/mfa`,
371
- preview: (guildId)=>{
372
- return `/guilds/${guildId}/preview`;
373
- },
374
- prune: (guildId, options)=>{
375
- let url = `/guilds/${guildId}/prune?`;
376
- if (options) {
377
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
378
- if (options.days) url += `days=${options.days}`;
379
- if (Array.isArray(options.includeRoles)) {
380
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
381
- url += `&include_roles=${options.includeRoles.join(',')}`;
382
- } else if (options.includeRoles) {
383
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
384
- url += `&include_roles=${options.includeRoles}`;
385
- }
386
- }
387
- return url;
388
- },
389
- roles: {
390
- one: (guildId, roleId)=>{
391
- return `/guilds/${guildId}/roles/${roleId}`;
392
- },
393
- all: (guildId)=>{
394
- return `/guilds/${guildId}/roles`;
395
- },
396
- member: (guildId, memberId, roleId)=>{
397
- return `/guilds/${guildId}/members/${memberId}/roles/${roleId}`;
398
- }
399
- },
400
- stickers: (guildId)=>{
401
- return `/guilds/${guildId}/stickers`;
402
- },
403
- sticker: (guildId, stickerId)=>{
404
- return `/guilds/${guildId}/stickers/${stickerId}`;
405
- },
406
- voice: (guildId, userId)=>{
407
- return `/guilds/${guildId}/voice-states/${userId ?? '@me'}`;
408
- },
409
- templates: {
410
- code: (code)=>{
411
- return `/guilds/templates/${code}`;
412
- },
413
- guild: (guildId, code)=>{
414
- return `/guilds/${guildId}/templates/${code}`;
415
- },
416
- all: (guildId)=>{
417
- return `/guilds/${guildId}/templates`;
418
- }
419
- },
420
- vanity: (guildId)=>{
421
- return `/guilds/${guildId}/vanity-url`;
422
- },
423
- regions: (guildId)=>{
424
- return `/guilds/${guildId}/regions`;
425
- },
426
- webhooks: (guildId)=>{
427
- return `/guilds/${guildId}/webhooks`;
428
- },
429
- welcome: (guildId)=>{
430
- return `/guilds/${guildId}/welcome-screen`;
431
- },
432
- widget: (guildId)=>{
433
- return `/guilds/${guildId}/widget`;
434
- },
435
- widgetJson: (guildId)=>{
436
- return `/guilds/${guildId}/widget.json`;
437
- }
438
- },
439
- sticker: (stickerId)=>{
440
- return `/stickers/${stickerId}`;
441
- },
442
- regions: ()=>{
443
- return '/voice/regions';
444
- },
445
- // Interaction Endpoints
446
- interactions: {
447
- commands: {
448
- // Application Endpoints
449
- commands: (applicationId)=>{
450
- return `/applications/${applicationId}/commands`;
451
- },
452
- guilds: {
453
- all (applicationId, guildId) {
454
- return `/applications/${applicationId}/guilds/${guildId}/commands`;
455
- },
456
- one (applicationId, guildId, commandId, withLocalizations) {
457
- let url = `/applications/${applicationId}/guilds/${guildId}/commands/${commandId}?`;
458
- if (withLocalizations !== undefined) {
459
- url += `with_localizations=${withLocalizations.toString()}`;
460
- }
461
- return url;
462
- }
463
- },
464
- permissions: (applicationId, guildId)=>{
465
- return `/applications/${applicationId}/guilds/${guildId}/commands/permissions`;
466
- },
467
- permission: (applicationId, guildId, commandId)=>{
468
- return `/applications/${applicationId}/guilds/${guildId}/commands/${commandId}/permissions`;
469
- },
470
- command: (applicationId, commandId, withLocalizations)=>{
471
- let url = `/applications/${applicationId}/commands/${commandId}?`;
472
- if (withLocalizations !== undefined) {
473
- url += `withLocalizations=${withLocalizations.toString()}`;
474
- }
475
- return url;
476
- }
477
- },
478
- responses: {
479
- // Interaction Endpoints
480
- callback: (interactionId, token)=>{
481
- return `/interactions/${interactionId}/${token}/callback`;
482
- },
483
- original: (interactionId, token)=>{
484
- return `/webhooks/${interactionId}/${token}/messages/@original`;
485
- },
486
- message: (applicationId, token, messageId)=>{
487
- return `/webhooks/${applicationId}/${token}/messages/${messageId}`;
488
- }
489
- }
490
- },
491
- // User endpoints
492
- user (userId) {
493
- return `/users/${userId}`;
494
- },
495
- userBot () {
496
- return '/users/@me';
497
- },
498
- oauth2Application () {
499
- return 'oauth2/applications/@me';
500
- },
501
- gatewayBot () {
502
- return '/gateway/bot';
503
- },
504
- nitroStickerPacks () {
505
- return '/sticker-packs';
506
- }
507
- },
35
+ token: options.token,
36
+ version: options.version ?? DISCORD_API_VERSION,
37
+ routes: createRoutes(),
508
38
  checkRateLimits (url) {
509
39
  const ratelimited = rest.rateLimitedPaths.get(url);
510
40
  const global = rest.rateLimitedPaths.get('global');
@@ -525,66 +55,74 @@ export function createRestManager(options) {
525
55
  }
526
56
  const newObj = {};
527
57
  for (const key of Object.keys(obj)){
528
- // Keys that dont require snake casing
529
- if ([
530
- 'permissions',
531
- 'allow',
532
- 'deny'
533
- ].includes(key)) {
534
- newObj[key] = calculateBits(obj[key]);
535
- continue;
536
- }
537
- if (key === 'defaultMemberPermissions') {
538
- newObj.default_member_permissions = calculateBits(obj[key]);
539
- continue;
58
+ const value = obj[key];
59
+ // Some falsy values should be allowed like null or 0
60
+ if (value !== undefined) {
61
+ switch(key){
62
+ case 'permissions':
63
+ case 'allow':
64
+ case 'deny':
65
+ newObj[key] = calculateBits(value);
66
+ continue;
67
+ case 'defaultMemberPermissions':
68
+ newObj.default_member_permissions = calculateBits(value);
69
+ continue;
70
+ case 'nameLocalizations':
71
+ newObj.name_localizations = value;
72
+ continue;
73
+ case 'descriptionLocalizations':
74
+ newObj.description_localizations = value;
75
+ continue;
76
+ }
540
77
  }
541
- newObj[camelToSnakeCase(key)] = rest.changeToDiscordFormat(obj[key]);
78
+ newObj[camelToSnakeCase(key)] = rest.changeToDiscordFormat(value);
542
79
  }
543
80
  return newObj;
544
81
  }
545
82
  if (typeof obj === 'bigint') return obj.toString();
546
83
  return obj;
547
84
  },
548
- createRequest (options) {
85
+ createRequestBody (method, options) {
549
86
  const headers = {
550
87
  'user-agent': `DiscordBot (https://github.com/discordeno/discordeno, v${version})`
551
88
  };
552
- if (!options.unauthorized) headers.authorization = `Bot ${rest.token}`;
89
+ if (options?.unauthorized !== false) headers.authorization = `Bot ${rest.token}`;
553
90
  // IF A REASON IS PROVIDED ENCODE IT IN HEADERS
554
- if (options.reason !== undefined) {
555
- headers['x-audit-log-reason'] = encodeURIComponent(options.reason);
91
+ if (options?.reason !== undefined) {
92
+ headers[AUDIT_LOG_REASON_HEADER] = encodeURIComponent(options?.reason);
556
93
  }
557
94
  let body;
558
95
  // TODO: check if we need to add specific check for GET method
559
96
  // Since GET does not allow bodies
560
97
  // Have to check for attachments first, since body then has to be send in a different way.
561
- if (options.attachments !== undefined) {
98
+ if (options?.files !== undefined) {
562
99
  const form = new FormData();
563
- for(let i = 0; i < options.attachments.length; ++i){
564
- form.append(`file${i}`, options.attachments[i].blob, options.attachments[i].name);
100
+ for(let i = 0; i < options.files.length; ++i){
101
+ form.append(`file${i}`, options.files[i].blob, options.files[i].name);
565
102
  }
566
- form.append('payload_json', JSON.stringify(options.body));
103
+ form.append('payload_json', JSON.stringify({
104
+ ...options.body,
105
+ files: undefined
106
+ }));
567
107
  body = form;
568
- // TODO: boundary?
569
- // `multipart/form-data; boundary=${form.getBoundary()}`
570
- headers['content-type'] = `multipart/form-data`;
571
- } else if (options.body !== undefined) {
108
+ // No need to set the `content-type` header since `fetch` does that automatically for us when we use a `FormData` object.
109
+ } else if (options?.body !== undefined) {
572
110
  if (options.body instanceof FormData) {
573
111
  body = options.body;
574
- headers['content-type'] = `multipart/form-data`;
112
+ // No need to set the `content-type` header since `fetch` does that automatically for us when we use a `FormData` object.
575
113
  } else {
576
- body = JSON.stringify(options.body);
114
+ body = JSON.stringify(rest.changeToDiscordFormat(options.body));
577
115
  headers['content-type'] = `application/json`;
578
116
  }
579
117
  }
580
118
  // SOMETIMES SPECIAL HEADERS (E.G. CUSTOM AUTHORIZATION) NEED TO BE USED
581
- if (options.headers) {
119
+ if (options?.headers) {
582
120
  Object.assign(headers, options.headers);
583
121
  }
584
122
  return {
585
123
  body,
586
124
  headers,
587
- method: options.method
125
+ method
588
126
  };
589
127
  },
590
128
  processRateLimitedPaths () {
@@ -617,13 +155,13 @@ export function createRestManager(options) {
617
155
  /** Processes the rate limit headers and determines if it needs to be rate limited and returns the bucket id if available */ processHeaders (url, headers) {
618
156
  let rateLimited = false;
619
157
  // GET ALL NECESSARY HEADERS
620
- const remaining = headers.get('x-ratelimit-remaining');
621
- const retryAfter = headers.get('x-ratelimit-reset-after');
158
+ const remaining = headers.get(RATE_LIMIT_REMAINING_HEADER);
159
+ const retryAfter = headers.get(RATE_LIMIT_RESET_AFTER_HEADER);
622
160
  const reset = Date.now() + Number(retryAfter) * 1000;
623
- const global = headers.get('x-ratelimit-global');
161
+ const global = headers.get(RATE_LIMIT_GLOBAL_HEADER);
624
162
  // undefined override null needed for typings
625
- const bucketId = headers.get('x-ratelimit-bucket') ?? undefined;
626
- const limit = headers.get('x-ratelimit-limit');
163
+ const bucketId = headers.get(RATE_LIMIT_BUCKET_HEADER) ?? undefined;
164
+ const limit = headers.get(RATE_LIMIT_LIMIT_HEADER);
627
165
  rest.queues.get(url)?.handleCompletedRequest({
628
166
  remaining: remaining ? Number(remaining) : undefined,
629
167
  interval: retryAfter ? Number(retryAfter) * 1000 : undefined,
@@ -678,13 +216,8 @@ export function createRestManager(options) {
678
216
  return rateLimited ? bucketId : undefined;
679
217
  },
680
218
  async sendRequest (options) {
681
- const url = options.url.startsWith('https://') ? options.url : `${rest.baseUrl}/v${rest.version}${options.url}`;
682
- const payload = rest.createRequest({
683
- method: options.method,
684
- url: options.url,
685
- body: options.options?.body,
686
- ...options.options
687
- });
219
+ const url = `${rest.baseUrl}/v${rest.version}${options.route}`;
220
+ const payload = rest.createRequestBody(options.method, options.requestBodyOptions);
688
221
  logger.debug(`sending request to ${url}`, 'with payload:', {
689
222
  ...payload,
690
223
  headers: {
@@ -692,49 +225,57 @@ export function createRestManager(options) {
692
225
  authorization: 'Bot tokenhere'
693
226
  }
694
227
  });
695
- const response = await fetch(url, payload);
228
+ const response = await fetch(url, payload).catch(async (error)=>{
229
+ logger.error(error);
230
+ // Mark request and completed
231
+ rest.invalidBucket.handleCompletedRequest(999, false);
232
+ options.reject({
233
+ ok: false,
234
+ status: 999,
235
+ error: 'Possible network or request shape issue occurred. If this is rare, its a network glitch. If it occurs a lot something is wrong.'
236
+ });
237
+ throw error;
238
+ });
696
239
  logger.debug(`request fetched from ${url} with status ${response.status} & ${response.statusText}`);
240
+ // Mark request and completed
241
+ rest.invalidBucket.handleCompletedRequest(response.status, response.headers.get(RATE_LIMIT_SCOPE_HEADER) === 'shared');
697
242
  // Set the bucket id if it was available on the headers
698
- const bucketId = rest.processHeaders(rest.simplifyUrl(options.url, options.method), response.headers);
243
+ const bucketId = rest.processHeaders(rest.simplifyUrl(options.route, options.method), response.headers);
699
244
  if (bucketId) options.bucketId = bucketId;
700
245
  if (response.status < 200 || response.status >= 400) {
701
246
  logger.debug(`Request to ${url} failed.`);
702
- if (response.status === 429) {
703
- logger.debug(`Request to ${url} was ratelimited.`);
704
- // Too many attempts, get rid of request from queue.
705
- if (options.retryCount++ >= rest.maxRetryCount) {
706
- logger.debug(`Request to ${url} exceeded the maximum allowed retries.`, 'with payload:', payload);
707
- // rest.debug(`[REST - RetriesMaxed] ${JSON.stringify(options)}`)
708
- // Remove item from queue to prevent retry
709
- options.reject({
710
- ok: false,
711
- status: response.status,
712
- error: 'The options was rate limited and it maxed out the retries limit.'
713
- });
714
- return;
715
- }
716
- // Rate limited, add back to queue
717
- rest.invalidBucket.handleCompletedRequest(response.status, response.headers.get('X-RateLimit-Scope') === 'shared');
718
- const resetAfter = response.headers.get('x-ratelimit-reset-after');
719
- if (resetAfter) await delay(Number(resetAfter) * 1000);
720
- // process the response to prevent mem leak
721
- await response.json();
722
- return await options.retryRequest?.(options);
247
+ if (response.status !== 429) {
248
+ options.reject({
249
+ ok: false,
250
+ status: response.status,
251
+ body: await response.text()
252
+ });
253
+ return;
723
254
  }
724
- options.reject({
725
- ok: false,
726
- status: response.status,
727
- body: JSON.stringify(await response.json())
728
- });
729
- return;
255
+ logger.debug(`Request to ${url} was ratelimited.`);
256
+ // Too many attempts, get rid of request from queue.
257
+ if (options.retryCount >= rest.maxRetryCount) {
258
+ logger.debug(`Request to ${url} exceeded the maximum allowed retries.`, 'with payload:', payload);
259
+ // rest.debug(`[REST - RetriesMaxed] ${JSON.stringify(options)}`)
260
+ options.reject({
261
+ ok: false,
262
+ status: response.status,
263
+ error: 'The request was rate limited and it maxed out the retries limit.'
264
+ });
265
+ return;
266
+ }
267
+ options.retryCount += 1;
268
+ const resetAfter = response.headers.get(RATE_LIMIT_RESET_AFTER_HEADER);
269
+ if (resetAfter) await delay(Number(resetAfter) * 1000);
270
+ // process the response to prevent mem leak
271
+ await response.arrayBuffer();
272
+ return await options.retryRequest?.(options);
730
273
  }
731
- const is204 = response.status === 204;
732
- const json = is204 ? undefined : await response.json();
733
- // Discord sometimes sends no response with 204 code
274
+ // Discord sometimes sends no response with no content.
734
275
  options.resolve({
735
276
  ok: true,
736
277
  status: response.status,
737
- body: JSON.stringify(json)
278
+ body: response.status === 204 ? undefined : await response.text()
738
279
  });
739
280
  },
740
281
  simplifyUrl (url, method) {
@@ -758,16 +299,12 @@ export function createRestManager(options) {
758
299
  }
759
300
  return parts.join('/');
760
301
  },
761
- processRequest (request) {
762
- const route = request.url.substring(request.url.indexOf('api/'));
763
- const parts = route.split('/');
764
- // Remove the api/
765
- parts.shift();
766
- // Removes the /v#/
767
- if (parts[0]?.startsWith('v')) parts.shift();
768
- // Set the full url to discord api in case it was recieved in a proxy rest
769
- request.url = `${rest.baseUrl}/v${rest.version}/${parts.join('/')}`;
770
- const url = rest.simplifyUrl(request.url, request.method);
302
+ async processRequest (request) {
303
+ const url = rest.simplifyUrl(request.route, request.method);
304
+ if (request.runThroughQueue === false) {
305
+ await rest.sendRequest(request);
306
+ return;
307
+ }
771
308
  const queue = rest.queues.get(url);
772
309
  if (queue !== undefined) {
773
310
  queue.makeRequest(request);
@@ -783,36 +320,14 @@ export function createRestManager(options) {
783
320
  rest.queues.set(url, bucketQueue);
784
321
  }
785
322
  },
786
- async makeRequest (method, url, options) {
787
- if (!rest.baseUrl.startsWith('https://discord.com') && url[0] === '/') {
788
- // Special handling for sending blobs across http to proxy
789
- // TODO: fix this hacky handling
790
- if (!(options?.body instanceof FormData) && !Array.isArray(options?.body) && options?.body?.file) {
791
- if (!Array.isArray(options.body.file)) {
792
- options.body.file = [
793
- options.body.file
794
- ];
795
- }
796
- // convert blobs to string before sending to proxy
797
- options.body.file = await Promise.all(options.body.file.map(async (f)=>{
798
- const url = encode(await f.blob.arrayBuffer());
799
- return {
800
- name: f.name,
801
- blob: `data:${f.blob.type};base64,${url}`
802
- };
803
- }));
323
+ async makeRequest (method, route, options) {
324
+ if (rest.isProxied) {
325
+ if (rest.authorization !== undefined) {
326
+ options ??= {};
327
+ options.headers ??= {};
328
+ options.headers.authorization = rest.authorization;
804
329
  }
805
- const headers = {
806
- Authorization: rest.authorization ?? ''
807
- };
808
- if (options?.body) {
809
- headers['Content-Type'] = 'application/json';
810
- }
811
- const result = await fetch(`${rest.baseUrl}${url}`, {
812
- body: options?.body ? JSON.stringify(options.body) : undefined,
813
- headers,
814
- method
815
- });
330
+ const result = await fetch(`${rest.baseUrl}/v${rest.version}${route}`, rest.createRequestBody(method, options));
816
331
  if (!result.ok) {
817
332
  const err = await result.json().catch(()=>{});
818
333
  // Legacy Handling to not break old code or when body is missing
@@ -821,47 +336,39 @@ export function createRestManager(options) {
821
336
  }
822
337
  return result.status !== 204 ? await result.json() : undefined;
823
338
  }
824
- return await new Promise((resolve, reject)=>{
339
+ // eslint-disable-next-line no-async-promise-executor
340
+ return await new Promise(async (resolve, reject)=>{
825
341
  const payload = {
826
- url,
342
+ route,
827
343
  method,
828
- options,
344
+ requestBodyOptions: options,
829
345
  retryCount: 0,
830
346
  retryRequest: async function(payload) {
831
- rest.processRequest(payload);
347
+ await rest.processRequest(payload);
832
348
  },
833
349
  resolve: (data)=>{
834
350
  resolve(data.status !== 204 ? JSON.parse(data.body ?? '{}') : undefined);
835
351
  },
836
- reject
352
+ reject,
353
+ runThroughQueue: options?.runThroughQueue
837
354
  };
838
- rest.processRequest(payload);
355
+ await rest.processRequest(payload);
839
356
  });
840
357
  },
841
- async get (url, body) {
842
- return camelize(await rest.makeRequest('GET', url, {
843
- body
844
- }));
358
+ async get (url, options) {
359
+ return camelize(await rest.makeRequest('GET', url, options));
845
360
  },
846
- async post (url, body) {
847
- return camelize(await rest.makeRequest('POST', url, {
848
- body
849
- }));
361
+ async post (url, options) {
362
+ return camelize(await rest.makeRequest('POST', url, options));
850
363
  },
851
- async delete (url, body) {
852
- camelize(await rest.makeRequest('DELETE', url, {
853
- body
854
- }));
364
+ async delete (url, options) {
365
+ camelize(await rest.makeRequest('DELETE', url, options));
855
366
  },
856
- async patch (url, body) {
857
- return camelize(await rest.makeRequest('PATCH', url, {
858
- body
859
- }));
367
+ async patch (url, options) {
368
+ return camelize(await rest.makeRequest('PATCH', url, options));
860
369
  },
861
- async put (url, body) {
862
- return camelize(await rest.makeRequest('PUT', url, {
863
- body
864
- }));
370
+ async put (url, options) {
371
+ return camelize(await rest.makeRequest('PUT', url, options));
865
372
  },
866
373
  async addReaction (channelId, messageId, reaction) {
867
374
  reaction = processReactionString(reaction);
@@ -886,19 +393,22 @@ export function createRestManager(options) {
886
393
  async addThreadMember (channelId, userId) {
887
394
  await rest.put(rest.routes.channels.threads.user(channelId, userId));
888
395
  },
889
- async createAutomodRule (guildId, body) {
396
+ async createAutomodRule (guildId, body, reason) {
890
397
  return await rest.post(rest.routes.guilds.automod.rules(guildId), {
891
- body
398
+ body,
399
+ reason
892
400
  });
893
401
  },
894
- async createChannel (guildId, body) {
402
+ async createChannel (guildId, body, reason) {
895
403
  return await rest.post(rest.routes.guilds.channels(guildId), {
896
- body
404
+ body,
405
+ reason
897
406
  });
898
407
  },
899
- async createEmoji (guildId, body) {
408
+ async createEmoji (guildId, body, reason) {
900
409
  return await rest.post(rest.routes.guilds.emojis(guildId), {
901
- body
410
+ body,
411
+ reason
902
412
  });
903
413
  },
904
414
  async createGlobalApplicationCommand (body) {
@@ -924,14 +434,15 @@ export function createRestManager(options) {
924
434
  body
925
435
  });
926
436
  },
927
- async createGuildSticker (guildId, options) {
437
+ async createGuildSticker (guildId, options, reason) {
928
438
  const form = new FormData();
929
439
  form.append('file', options.file.blob, options.file.name);
930
440
  form.append('name', options.name);
931
441
  form.append('description', options.description);
932
442
  form.append('tags', options.tags);
933
443
  return await rest.post(rest.routes.guilds.stickers(guildId), {
934
- body: form
444
+ body: form,
445
+ reason
935
446
  });
936
447
  },
937
448
  async createGuildTemplate (guildId, body) {
@@ -939,14 +450,17 @@ export function createRestManager(options) {
939
450
  body
940
451
  });
941
452
  },
942
- async createForumThread (channelId, body) {
453
+ async createForumThread (channelId, body, reason) {
943
454
  return await rest.post(rest.routes.channels.forum(channelId), {
944
- body
455
+ body,
456
+ files: body.files,
457
+ reason
945
458
  });
946
459
  },
947
- async createInvite (channelId, body = {}) {
460
+ async createInvite (channelId, body = {}, reason) {
948
461
  return await rest.post(rest.routes.channels.invites(channelId), {
949
- body
462
+ body,
463
+ reason
950
464
  });
951
465
  },
952
466
  async createRole (guildId, body, reason) {
@@ -955,14 +469,16 @@ export function createRestManager(options) {
955
469
  reason
956
470
  });
957
471
  },
958
- async createScheduledEvent (guildId, body) {
472
+ async createScheduledEvent (guildId, body, reason) {
959
473
  return await rest.post(rest.routes.guilds.events.events(guildId), {
960
- body
474
+ body,
475
+ reason
961
476
  });
962
477
  },
963
- async createStageInstance (body) {
478
+ async createStageInstance (body, reason) {
964
479
  return await rest.post(rest.routes.channels.stages(), {
965
- body
480
+ body,
481
+ reason
966
482
  });
967
483
  },
968
484
  async createWebhook (channelId, options, reason) {
@@ -995,7 +511,9 @@ export function createRestManager(options) {
995
511
  });
996
512
  },
997
513
  async deleteFollowupMessage (token, messageId) {
998
- await rest.delete(rest.routes.interactions.responses.message(rest.applicationId, token, messageId));
514
+ await rest.delete(rest.routes.interactions.responses.message(rest.applicationId, token, messageId), {
515
+ unauthorized: true
516
+ });
999
517
  },
1000
518
  async deleteGlobalApplicationCommand (commandId) {
1001
519
  await rest.delete(rest.routes.interactions.commands.command(rest.applicationId, commandId));
@@ -1014,8 +532,10 @@ export function createRestManager(options) {
1014
532
  async deleteGuildTemplate (guildId, templateCode) {
1015
533
  await rest.delete(rest.routes.guilds.templates.guild(guildId, templateCode));
1016
534
  },
1017
- async deleteIntegration (guildId, integrationId) {
1018
- await rest.delete(rest.routes.guilds.integration(guildId, integrationId));
535
+ async deleteIntegration (guildId, integrationId, reason) {
536
+ await rest.delete(rest.routes.guilds.integration(guildId, integrationId), {
537
+ reason
538
+ });
1019
539
  },
1020
540
  async deleteInvite (inviteCode, reason) {
1021
541
  await rest.delete(rest.routes.guilds.invite(inviteCode), {
@@ -1036,7 +556,9 @@ export function createRestManager(options) {
1036
556
  });
1037
557
  },
1038
558
  async deleteOriginalInteractionResponse (token) {
1039
- await rest.delete(rest.routes.interactions.responses.original(rest.applicationId, token));
559
+ await rest.delete(rest.routes.interactions.responses.original(rest.applicationId, token), {
560
+ unauthorized: true
561
+ });
1040
562
  },
1041
563
  async deleteOwnReaction (channelId, messageId, reaction) {
1042
564
  reaction = processReactionString(reaction);
@@ -1049,8 +571,10 @@ export function createRestManager(options) {
1049
571
  reaction = processReactionString(reaction);
1050
572
  await rest.delete(rest.routes.channels.reactions.emoji(channelId, messageId, reaction));
1051
573
  },
1052
- async deleteRole (guildId, roleId) {
1053
- await rest.delete(rest.routes.guilds.roles.one(guildId, roleId));
574
+ async deleteRole (guildId, roleId, reason) {
575
+ await rest.delete(rest.routes.guilds.roles.one(guildId, roleId), {
576
+ reason
577
+ });
1054
578
  },
1055
579
  async deleteScheduledEvent (guildId, eventId) {
1056
580
  await rest.delete(rest.routes.guilds.events.event(guildId, eventId));
@@ -1085,9 +609,10 @@ export function createRestManager(options) {
1085
609
  }
1086
610
  });
1087
611
  },
1088
- async editAutomodRule (guildId, ruleId, body) {
612
+ async editAutomodRule (guildId, ruleId, body, reason) {
1089
613
  return await rest.patch(rest.routes.guilds.automod.rule(guildId, ruleId), {
1090
- body
614
+ body,
615
+ reason
1091
616
  });
1092
617
  },
1093
618
  async editBotProfile (options) {
@@ -1099,14 +624,16 @@ export function createRestManager(options) {
1099
624
  }
1100
625
  });
1101
626
  },
1102
- async editChannel (channelId, body) {
627
+ async editChannel (channelId, body, reason) {
1103
628
  return await rest.patch(rest.routes.channels.channel(channelId), {
1104
- body
629
+ body,
630
+ reason
1105
631
  });
1106
632
  },
1107
- async editChannelPermissionOverrides (channelId, body) {
633
+ async editChannelPermissionOverrides (channelId, body, reason) {
1108
634
  await rest.put(rest.routes.channels.overwrite(channelId, body.id), {
1109
- body
635
+ body,
636
+ reason
1110
637
  });
1111
638
  },
1112
639
  async editChannelPositions (guildId, body) {
@@ -1114,14 +641,17 @@ export function createRestManager(options) {
1114
641
  body
1115
642
  });
1116
643
  },
1117
- async editEmoji (guildId, id, body) {
644
+ async editEmoji (guildId, id, body, reason) {
1118
645
  return await rest.patch(rest.routes.guilds.emoji(guildId, id), {
1119
- body
646
+ body,
647
+ reason
1120
648
  });
1121
649
  },
1122
650
  async editFollowupMessage (token, messageId, body) {
1123
651
  return await rest.patch(rest.routes.interactions.responses.message(rest.applicationId, token, messageId), {
1124
- body
652
+ body,
653
+ files: body.files,
654
+ unauthorized: true
1125
655
  });
1126
656
  },
1127
657
  async editGlobalApplicationCommand (commandId, body) {
@@ -1129,9 +659,10 @@ export function createRestManager(options) {
1129
659
  body
1130
660
  });
1131
661
  },
1132
- async editGuild (guildId, body) {
662
+ async editGuild (guildId, body, reason) {
1133
663
  return await rest.patch(rest.routes.guilds.guild(guildId), {
1134
- body
664
+ body,
665
+ reason
1135
666
  });
1136
667
  },
1137
668
  async editGuildApplicationCommand (commandId, guildId, body) {
@@ -1147,9 +678,10 @@ export function createRestManager(options) {
1147
678
  reason
1148
679
  });
1149
680
  },
1150
- async editGuildSticker (guildId, stickerId, body) {
681
+ async editGuildSticker (guildId, stickerId, body, reason) {
1151
682
  return await rest.patch(rest.routes.guilds.sticker(guildId, stickerId), {
1152
- body
683
+ body,
684
+ reason
1153
685
  });
1154
686
  },
1155
687
  async editGuildTemplate (guildId, templateCode, body) {
@@ -1164,7 +696,8 @@ export function createRestManager(options) {
1164
696
  },
1165
697
  async editOriginalInteractionResponse (token, body) {
1166
698
  return await rest.patch(rest.routes.interactions.responses.original(rest.applicationId, token), {
1167
- body
699
+ body,
700
+ files: body.files
1168
701
  });
1169
702
  },
1170
703
  async editOriginalWebhookMessage (webhookId, token, options) {
@@ -1172,7 +705,9 @@ export function createRestManager(options) {
1172
705
  body: {
1173
706
  type: InteractionResponseTypes.UpdateMessage,
1174
707
  data: options
1175
- }
708
+ },
709
+ files: options.files,
710
+ unauthorized: true
1176
711
  });
1177
712
  },
1178
713
  async editOwnVoiceState (guildId, options) {
@@ -1183,19 +718,22 @@ export function createRestManager(options) {
1183
718
  }
1184
719
  });
1185
720
  },
1186
- async editScheduledEvent (guildId, eventId, body) {
721
+ async editScheduledEvent (guildId, eventId, body, reason) {
1187
722
  return await rest.patch(rest.routes.guilds.events.event(guildId, eventId), {
1188
- body
723
+ body,
724
+ reason
1189
725
  });
1190
726
  },
1191
- async editRole (guildId, roleId, body) {
727
+ async editRole (guildId, roleId, body, reason) {
1192
728
  return await rest.patch(rest.routes.guilds.roles.one(guildId, roleId), {
1193
- body
729
+ body,
730
+ reason
1194
731
  });
1195
732
  },
1196
- async editRolePositions (guildId, body) {
733
+ async editRolePositions (guildId, body, reason) {
1197
734
  return await rest.patch(rest.routes.guilds.roles.all(guildId), {
1198
- body
735
+ body,
736
+ reason
1199
737
  });
1200
738
  },
1201
739
  async editStageInstance (channelId, topic, reason) {
@@ -1211,14 +749,16 @@ export function createRestManager(options) {
1211
749
  body: options
1212
750
  });
1213
751
  },
1214
- async editWebhook (webhookId, body) {
752
+ async editWebhook (webhookId, body, reason) {
1215
753
  return await rest.patch(rest.routes.webhooks.id(webhookId), {
1216
- body
754
+ body,
755
+ reason
1217
756
  });
1218
757
  },
1219
758
  async editWebhookMessage (webhookId, token, messageId, options) {
1220
759
  return await rest.patch(rest.routes.webhooks.message(webhookId, token, messageId, options), {
1221
- body: options
760
+ body: options,
761
+ files: options.files
1222
762
  });
1223
763
  },
1224
764
  async editWebhookWithToken (webhookId, token, body) {
@@ -1226,14 +766,16 @@ export function createRestManager(options) {
1226
766
  body
1227
767
  });
1228
768
  },
1229
- async editWelcomeScreen (guildId, body) {
769
+ async editWelcomeScreen (guildId, body, reason) {
1230
770
  return await rest.patch(rest.routes.guilds.welcome(guildId), {
1231
- body
771
+ body,
772
+ reason
1232
773
  });
1233
774
  },
1234
- async editWidgetSettings (guildId, body) {
775
+ async editWidgetSettings (guildId, body, reason) {
1235
776
  return await rest.patch(rest.routes.guilds.widget(guildId), {
1236
- body
777
+ body,
778
+ reason
1237
779
  });
1238
780
  },
1239
781
  async executeWebhook (webhookId, token, options) {
@@ -1304,7 +846,9 @@ export function createRestManager(options) {
1304
846
  return await rest.get(rest.routes.guilds.emojis(guildId));
1305
847
  },
1306
848
  async getFollowupMessage (token, messageId) {
1307
- return await rest.get(rest.routes.interactions.responses.message(rest.applicationId, token, messageId));
849
+ return await rest.get(rest.routes.interactions.responses.message(rest.applicationId, token, messageId), {
850
+ unauthorized: true
851
+ });
1308
852
  },
1309
853
  async getGatewayBot () {
1310
854
  return await rest.get(rest.routes.gatewayBot());
@@ -1357,7 +901,9 @@ export function createRestManager(options) {
1357
901
  return await rest.get(rest.routes.nitroStickerPacks());
1358
902
  },
1359
903
  async getOriginalInteractionResponse (token) {
1360
- return await rest.get(rest.routes.interactions.responses.original(rest.applicationId, token));
904
+ return await rest.get(rest.routes.interactions.responses.original(rest.applicationId, token), {
905
+ unauthorized: true
906
+ });
1361
907
  },
1362
908
  async getPinnedMessages (channelId) {
1363
909
  return await rest.get(rest.routes.channels.pins(channelId));
@@ -1457,79 +1003,58 @@ export function createRestManager(options) {
1457
1003
  async removeThreadMember (channelId, userId) {
1458
1004
  await rest.delete(rest.routes.channels.threads.user(channelId, userId));
1459
1005
  },
1460
- // TODO: why that
1461
1006
  async sendFollowupMessage (token, options) {
1462
- return await new Promise((resolve, reject)=>{
1463
- rest.sendRequest({
1464
- url: rest.routes.webhooks.webhook(rest.applicationId, token),
1465
- method: 'POST',
1466
- options: {
1467
- body: options
1468
- },
1469
- retryCount: 0,
1470
- retryRequest: async function(options) {
1471
- // TODO: should change to reprocess queue item
1472
- await rest.sendRequest(options);
1473
- },
1474
- resolve: (data)=>{
1475
- resolve(data.status !== 204 ? JSON.parse(data.body ?? '{}') : undefined);
1476
- },
1477
- reject
1478
- });
1007
+ return await rest.post(rest.routes.webhooks.webhook(rest.applicationId, token), {
1008
+ body: options,
1009
+ files: options.files,
1010
+ unauthorized: true
1479
1011
  });
1480
1012
  },
1481
- // TODO: why that
1482
1013
  async sendInteractionResponse (interactionId, token, options) {
1483
- await new Promise((resolve, reject)=>{
1484
- rest.sendRequest({
1485
- url: rest.routes.interactions.responses.callback(interactionId, token),
1486
- method: 'POST',
1487
- options: {
1488
- body: options
1489
- },
1490
- retryCount: 0,
1491
- retryRequest: async function(options) {
1492
- // TODO: should change to reprocess queue item
1493
- await rest.sendRequest(options);
1494
- },
1495
- resolve: (data)=>{
1496
- resolve(data.status !== 204 ? JSON.parse(data.body ?? '{}') : undefined);
1497
- },
1498
- reject
1499
- });
1014
+ return await rest.post(rest.routes.interactions.responses.callback(interactionId, token), {
1015
+ body: options,
1016
+ files: options.data?.files,
1017
+ runThroughQueue: false,
1018
+ unauthorized: true
1500
1019
  });
1501
1020
  },
1502
1021
  async sendMessage (channelId, body) {
1503
1022
  return await rest.post(rest.routes.channels.messages(channelId), {
1504
- body
1023
+ body,
1024
+ files: body.files
1505
1025
  });
1506
1026
  },
1507
- async startThreadWithMessage (channelId, messageId, body) {
1027
+ async startThreadWithMessage (channelId, messageId, body, reason) {
1508
1028
  return await rest.post(rest.routes.channels.threads.message(channelId, messageId), {
1509
- body
1029
+ body,
1030
+ reason
1510
1031
  });
1511
1032
  },
1512
- async startThreadWithoutMessage (channelId, body) {
1033
+ async startThreadWithoutMessage (channelId, body, reason) {
1513
1034
  return await rest.post(rest.routes.channels.threads.all(channelId), {
1514
- body
1035
+ body,
1036
+ reason
1515
1037
  });
1516
1038
  },
1517
1039
  async syncGuildTemplate (guildId) {
1518
1040
  return await rest.put(rest.routes.guilds.templates.all(guildId));
1519
1041
  },
1520
- async banMember (guildId, userId, body) {
1042
+ async banMember (guildId, userId, body, reason) {
1521
1043
  await rest.put(rest.routes.guilds.members.ban(guildId, userId), {
1522
- body
1044
+ body,
1045
+ reason
1523
1046
  });
1524
1047
  },
1525
- async editBotMember (guildId, body) {
1048
+ async editBotMember (guildId, body, reason) {
1526
1049
  return await rest.patch(rest.routes.guilds.members.bot(guildId), {
1527
- body
1050
+ body,
1051
+ reason
1528
1052
  });
1529
1053
  },
1530
- async editMember (guildId, userId, body) {
1054
+ async editMember (guildId, userId, body, reason) {
1531
1055
  return await rest.patch(rest.routes.guilds.members.member(guildId, userId), {
1532
- body
1056
+ body,
1057
+ reason
1533
1058
  });
1534
1059
  },
1535
1060
  async getMember (guildId, userId) {
@@ -1548,16 +1073,19 @@ export function createRestManager(options) {
1548
1073
  reason
1549
1074
  });
1550
1075
  },
1551
- async pruneMembers (guildId, body) {
1076
+ async pruneMembers (guildId, body, reason) {
1552
1077
  return await rest.post(rest.routes.guilds.members.prune(guildId), {
1553
- body
1078
+ body,
1079
+ reason
1554
1080
  });
1555
1081
  },
1556
1082
  async searchMembers (guildId, query, options) {
1557
1083
  return await rest.get(rest.routes.guilds.members.search(guildId, query, options));
1558
1084
  },
1559
- async unbanMember (guildId, userId) {
1560
- await rest.delete(rest.routes.guilds.members.ban(guildId, userId));
1085
+ async unbanMember (guildId, userId, reason) {
1086
+ await rest.delete(rest.routes.guilds.members.ban(guildId, userId), {
1087
+ reason
1088
+ });
1561
1089
  },
1562
1090
  async unpinMessage (channelId, messageId, reason) {
1563
1091
  await rest.delete(rest.routes.channels.pin(channelId, messageId), {
@@ -1580,5 +1108,12 @@ export function createRestManager(options) {
1580
1108
  };
1581
1109
  return rest;
1582
1110
  }
1111
+ var HttpResponseCode;
1112
+ (function(HttpResponseCode) {
1113
+ HttpResponseCode[HttpResponseCode[/** Minimum value of a code in oder to consider that it was successful. */ "Success"] = 200] = "Success";
1114
+ HttpResponseCode[HttpResponseCode[/** Request completed successfully, but Discord returned an empty body. */ "NoContent"] = 204] = "NoContent";
1115
+ HttpResponseCode[HttpResponseCode[/** Minimum value of a code in order to consider that something went wrong. */ "Error"] = 400] = "Error";
1116
+ HttpResponseCode[HttpResponseCode[/** This request got rate limited. */ "TooManyRequests"] = 429] = "TooManyRequests";
1117
+ })(HttpResponseCode || (HttpResponseCode = {}));
1583
1118
 
1584
1119
  //# sourceMappingURL=manager.js.map