@discordeno/rest 19.0.0-next.40c19da → 19.0.0-next.4142946

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 (49) hide show
  1. package/README.md +15 -1
  2. package/dist/cjs/index.cjs +25 -0
  3. package/dist/cjs/invalidBucket.cjs +86 -0
  4. package/dist/cjs/manager.cjs +1445 -0
  5. package/dist/cjs/queue.cjs +165 -0
  6. package/dist/cjs/routes.cjs +550 -0
  7. package/dist/cjs/types.cjs +6 -0
  8. package/dist/cjs/typings/routes.cjs +6 -0
  9. package/dist/esm/index.js +8 -0
  10. package/dist/esm/invalidBucket.js +82 -0
  11. package/dist/esm/manager.js +1403 -0
  12. package/dist/esm/queue.js +155 -0
  13. package/dist/esm/routes.js +540 -0
  14. package/dist/esm/types.js +3 -0
  15. package/dist/esm/typings/routes.js +3 -0
  16. package/dist/{index.d.ts → types/index.d.ts} +1 -0
  17. package/dist/types/index.d.ts.map +1 -0
  18. package/dist/{invalidBucket.d.ts → types/invalidBucket.d.ts} +11 -7
  19. package/dist/types/invalidBucket.d.ts.map +1 -0
  20. package/dist/types/manager.d.ts +12 -0
  21. package/dist/types/manager.d.ts.map +1 -0
  22. package/dist/{queue.d.ts → types/queue.d.ts} +12 -1
  23. package/dist/types/queue.d.ts.map +1 -0
  24. package/dist/types/routes.d.ts +3 -0
  25. package/dist/types/routes.d.ts.map +1 -0
  26. package/dist/{types.d.ts → types/types.d.ts} +696 -299
  27. package/dist/types/types.d.ts.map +1 -0
  28. package/dist/{typings → types/typings}/routes.d.ts +46 -7
  29. package/dist/types/typings/routes.d.ts.map +1 -0
  30. package/package.json +33 -30
  31. package/dist/index.d.ts.map +0 -1
  32. package/dist/index.js +0 -7
  33. package/dist/index.js.map +0 -1
  34. package/dist/invalidBucket.d.ts.map +0 -1
  35. package/dist/invalidBucket.js +0 -84
  36. package/dist/invalidBucket.js.map +0 -1
  37. package/dist/manager.d.ts +0 -3
  38. package/dist/manager.d.ts.map +0 -1
  39. package/dist/manager.js +0 -1464
  40. package/dist/manager.js.map +0 -1
  41. package/dist/queue.d.ts.map +0 -1
  42. package/dist/queue.js +0 -153
  43. package/dist/queue.js.map +0 -1
  44. package/dist/types.d.ts.map +0 -1
  45. package/dist/types.js +0 -3
  46. package/dist/types.js.map +0 -1
  47. package/dist/typings/routes.d.ts.map +0 -1
  48. package/dist/typings/routes.js +0 -3
  49. package/dist/typings/routes.js.map +0 -1
package/dist/manager.js DELETED
@@ -1,1464 +0,0 @@
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, findFiles, getBotIdFromToken, isGetMessagesAfter, isGetMessagesAround, isGetMessagesBefore, isGetMessagesLimit, logger, processReactionString, urlToBase64 } from '@discordeno/utils';
3
- import fetch from 'node-fetch';
4
- import { createInvalidRequestBucket } from './invalidBucket.js';
5
- import { Queue } from './queue.js';
6
- // TODO: make dynamic based on package.json file
7
- const version = '19.0.0-alpha.1';
8
- export function createRestManager(options) {
9
- // Falsy token string check
10
- if (!options.token) throw new Error('You must provide a valid token.');
11
- 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,
17
- globallyRateLimited: false,
18
- processingRateLimitedPaths: false,
19
- deleteQueueDelay: 60000,
20
- queues: new Map(),
21
- 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.limit) url += `&limit=${options.limit}`;
222
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
223
- if (options.userId) url += `&user_id=${options.userId}`;
224
- }
225
- return url;
226
- },
227
- automod: {
228
- rule: (guildId, ruleId)=>{
229
- return `/guilds/${guildId}/auto-moderation/rules/${ruleId}`;
230
- },
231
- rules: (guildId)=>{
232
- return `/guilds/${guildId}/auto-moderation/rules`;
233
- }
234
- },
235
- channels: (guildId)=>{
236
- return `/guilds/${guildId}/channels`;
237
- },
238
- emoji: (guildId, emojiId)=>{
239
- return `/guilds/${guildId}/emojis/${emojiId}`;
240
- },
241
- emojis: (guildId)=>{
242
- return `/guilds/${guildId}/emojis`;
243
- },
244
- events: {
245
- events: (guildId, withUserCount)=>{
246
- let url = `/guilds/${guildId}/scheduled-events?`;
247
- if (withUserCount !== undefined) {
248
- url += `with_user_count=${withUserCount.toString()}`;
249
- }
250
- return url;
251
- },
252
- event: (guildId, eventId, withUserCount)=>{
253
- let url = `/guilds/${guildId}/scheduled-events/${eventId}`;
254
- if (withUserCount !== undefined) {
255
- url += `with_user_count=${withUserCount.toString()}`;
256
- }
257
- return url;
258
- },
259
- users: (guildId, eventId, options)=>{
260
- let url = `/guilds/${guildId}/scheduled-events/${eventId}/users?`;
261
- if (options) {
262
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
263
- if (options.limit !== undefined) url += `limit=${options.limit}`;
264
- if (options.withMember !== undefined) {
265
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
266
- url += `&with_member=${options.withMember.toString()}`;
267
- }
268
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
269
- if (options.after !== undefined) url += `&after=${options.after}`;
270
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
271
- if (options.before !== undefined) url += `&before=${options.before}`;
272
- }
273
- return url;
274
- }
275
- },
276
- guild (guildId, withCounts) {
277
- let url = `/guilds/${guildId}?`;
278
- if (withCounts !== undefined) {
279
- url += `with_counts=${withCounts.toString()}`;
280
- }
281
- return url;
282
- },
283
- integration (guildId, integrationId) {
284
- return `/guilds/${guildId}/integrations/${integrationId}`;
285
- },
286
- integrations: (guildId)=>{
287
- return `/guilds/${guildId}/integrations?include_applications=true`;
288
- },
289
- invite (inviteCode, options) {
290
- let url = `/invites/${inviteCode}?`;
291
- if (options) {
292
- if (options.withCounts !== undefined) {
293
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
294
- url += `with_counts=${options.withCounts.toString()}`;
295
- }
296
- if (options.withExpiration !== undefined) {
297
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
298
- url += `&with_expiration=${options.withExpiration.toString()}`;
299
- }
300
- if (options.scheduledEventId) {
301
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
302
- url += `&guild_scheduled_event_id=${options.scheduledEventId}`;
303
- }
304
- }
305
- return url;
306
- },
307
- invites: (guildId)=>{
308
- return `/guilds/${guildId}/invites`;
309
- },
310
- leave: (guildId)=>{
311
- return `/users/@me/guilds/${guildId}`;
312
- },
313
- members: {
314
- ban: (guildId, userId)=>{
315
- return `/guilds/${guildId}/bans/${userId}`;
316
- },
317
- bans: (guildId, options)=>{
318
- let url = `/guilds/${guildId}/bans?`;
319
- if (options) {
320
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
321
- if (options.limit) url += `limit=${options.limit}`;
322
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
323
- if (options.after) url += `&after=${options.after}`;
324
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
325
- if (options.before) url += `&before=${options.before}`;
326
- }
327
- return url;
328
- },
329
- bot: (guildId)=>{
330
- return `/guilds/${guildId}/members/@me`;
331
- },
332
- member: (guildId, userId)=>{
333
- return `/guilds/${guildId}/members/${userId}`;
334
- },
335
- members: (guildId, options)=>{
336
- let url = `/guilds/${guildId}/members?`;
337
- if (options !== undefined) {
338
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
339
- if (options.limit) url += `limit=${options.limit}`;
340
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
341
- if (options.after) url += `&after=${options.after}`;
342
- }
343
- return url;
344
- },
345
- search: (guildId, query, options)=>{
346
- let url = `/guilds/${guildId}/members/search?query=${encodeURIComponent(query)}`;
347
- if (options) {
348
- if (options.limit !== undefined) url += `&limit=${options.limit}`;
349
- }
350
- return url;
351
- },
352
- prune: (guildId, options)=>{
353
- let url = `/guilds/${guildId}/prune?`;
354
- if (options) {
355
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
356
- if (options.days) url += `days=${options.days}`;
357
- if (Array.isArray(options.includeRoles)) {
358
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
359
- url += `&include_roles=${options.includeRoles.join(',')}`;
360
- } else if (options.includeRoles) {
361
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
362
- url += `&include_roles=${options.includeRoles}`;
363
- }
364
- }
365
- return url;
366
- }
367
- },
368
- mfa: (guildId)=>`/guilds/${guildId}/mfa`,
369
- preview: (guildId)=>{
370
- return `/guilds/${guildId}/preview`;
371
- },
372
- prune: (guildId, options)=>{
373
- let url = `/guilds/${guildId}/prune?`;
374
- if (options) {
375
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
376
- if (options.days) url += `days=${options.days}`;
377
- if (Array.isArray(options.includeRoles)) {
378
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
379
- url += `&include_roles=${options.includeRoles.join(',')}`;
380
- } else if (options.includeRoles) {
381
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
382
- url += `&include_roles=${options.includeRoles}`;
383
- }
384
- }
385
- return url;
386
- },
387
- roles: {
388
- one: (guildId, roleId)=>{
389
- return `/guilds/${guildId}/roles/${roleId}`;
390
- },
391
- all: (guildId)=>{
392
- return `/guilds/${guildId}/roles`;
393
- },
394
- member: (guildId, memberId, roleId)=>{
395
- return `/guilds/${guildId}/members/${memberId}/roles/${roleId}`;
396
- }
397
- },
398
- stickers: (guildId)=>{
399
- return `/guilds/${guildId}/stickers`;
400
- },
401
- sticker: (guildId, stickerId)=>{
402
- return `/guilds/${guildId}/stickers/${stickerId}`;
403
- },
404
- voice: (guildId, userId)=>{
405
- return `/guilds/${guildId}/voice-states/${userId ?? '@me'}`;
406
- },
407
- templates: {
408
- code: (code)=>{
409
- return `/guilds/templates/${code}`;
410
- },
411
- guild: (guildId, code)=>{
412
- return `/guilds/${guildId}/templates/${code}`;
413
- },
414
- all: (guildId)=>{
415
- return `/guilds/${guildId}/templates`;
416
- }
417
- },
418
- vanity: (guildId)=>{
419
- return `/guilds/${guildId}/vanity-url`;
420
- },
421
- regions: (guildId)=>{
422
- return `/guilds/${guildId}/regions`;
423
- },
424
- webhooks: (guildId)=>{
425
- return `/guilds/${guildId}/webhooks`;
426
- },
427
- welcome: (guildId)=>{
428
- return `/guilds/${guildId}/welcome-screen`;
429
- },
430
- widget: (guildId)=>{
431
- return `/guilds/${guildId}/widget`;
432
- },
433
- widgetJson: (guildId)=>{
434
- return `/guilds/${guildId}/widget.json`;
435
- }
436
- },
437
- sticker: (stickerId)=>{
438
- return `/stickers/${stickerId}`;
439
- },
440
- regions: ()=>{
441
- return '/voice/regions';
442
- },
443
- // Interaction Endpoints
444
- interactions: {
445
- commands: {
446
- // Application Endpoints
447
- commands: (applicationId)=>{
448
- return `/applications/${applicationId}/commands`;
449
- },
450
- guilds: {
451
- all (applicationId, guildId) {
452
- return `/applications/${applicationId}/guilds/${guildId}/commands`;
453
- },
454
- one (applicationId, guildId, commandId, withLocalizations) {
455
- let url = `/applications/${applicationId}/guilds/${guildId}/commands/${commandId}?`;
456
- if (withLocalizations !== undefined) {
457
- url += `with_localizations=${withLocalizations.toString()}`;
458
- }
459
- return url;
460
- }
461
- },
462
- permissions: (applicationId, guildId)=>{
463
- return `/applications/${applicationId}/guilds/${guildId}/commands/permissions`;
464
- },
465
- permission: (applicationId, guildId, commandId)=>{
466
- return `/applications/${applicationId}/guilds/${guildId}/commands/${commandId}/permissions`;
467
- },
468
- command: (applicationId, commandId, withLocalizations)=>{
469
- let url = `/applications/${applicationId}/commands/${commandId}?`;
470
- if (withLocalizations !== undefined) {
471
- url += `withLocalizations=${withLocalizations.toString()}`;
472
- }
473
- return url;
474
- }
475
- },
476
- responses: {
477
- // Interaction Endpoints
478
- callback: (interactionId, token)=>{
479
- return `/interactions/${interactionId}/${token}/callback`;
480
- },
481
- original: (interactionId, token)=>{
482
- return `/webhooks/${interactionId}/${token}/messages/@original`;
483
- },
484
- message: (applicationId, token, messageId)=>{
485
- return `/webhooks/${applicationId}/${token}/messages/${messageId}`;
486
- }
487
- }
488
- },
489
- // User endpoints
490
- user (userId) {
491
- return `/users/${userId}`;
492
- },
493
- userBot () {
494
- return '/users/@me';
495
- },
496
- oauth2Application () {
497
- return 'oauth2/applications/@me';
498
- },
499
- gatewayBot () {
500
- return '/gateway/bot';
501
- },
502
- nitroStickerPacks () {
503
- return '/sticker-packs';
504
- }
505
- },
506
- checkRateLimits (url) {
507
- const ratelimited = rest.rateLimitedPaths.get(url);
508
- const global = rest.rateLimitedPaths.get('global');
509
- const now = Date.now();
510
- if (ratelimited && now < ratelimited.resetTimestamp) {
511
- return ratelimited.resetTimestamp - now;
512
- }
513
- if (global && now < global.resetTimestamp) {
514
- return global.resetTimestamp - now;
515
- }
516
- return false;
517
- },
518
- changeToDiscordFormat (obj) {
519
- if (obj === null) return null;
520
- if (typeof obj === 'object') {
521
- if (Array.isArray(obj)) {
522
- return obj.map((item)=>rest.changeToDiscordFormat(item));
523
- }
524
- const newObj = {};
525
- for (const key of Object.keys(obj)){
526
- // Keys that dont require snake casing
527
- if ([
528
- 'permissions',
529
- 'allow',
530
- 'deny'
531
- ].includes(key)) {
532
- newObj[key] = calculateBits(obj[key]);
533
- continue;
534
- }
535
- if (key === 'defaultMemberPermissions') {
536
- newObj.default_member_permissions = calculateBits(obj[key]);
537
- continue;
538
- }
539
- newObj[camelToSnakeCase(key)] = rest.changeToDiscordFormat(obj[key]);
540
- }
541
- return newObj;
542
- }
543
- if (typeof obj === 'bigint') return obj.toString();
544
- return obj;
545
- },
546
- createRequest (options) {
547
- const headers = {
548
- 'user-agent': `DiscordBot (https://github.com/discordeno/discordeno, v${version})`
549
- };
550
- if (!options.unauthorized) headers.authorization = `Bot ${rest.token}`;
551
- // SOMETIMES SPECIAL HEADERS (E.G. CUSTOM AUTHORIZATION) NEED TO BE USED
552
- if (options.headers) {
553
- for(const key in options.headers){
554
- headers[key.toLowerCase()] = options.headers[key];
555
- }
556
- }
557
- // GET METHODS SHOULD NOT HAVE A BODY
558
- if (options.method === 'GET') {
559
- options.body = undefined;
560
- }
561
- // IF A REASON IS PROVIDED ENCODE IT IN HEADERS
562
- if (options.body?.reason) {
563
- headers['X-Audit-Log-Reason'] = encodeURIComponent(options.body.reason);
564
- options.body.reason = undefined;
565
- }
566
- if (options.body) {
567
- const { file } = options.body;
568
- if (file) {
569
- const files = findFiles(file);
570
- const form = new FormData();
571
- // WHEN CREATING A STICKER, DISCORD WANTS FORM DATA ONLY
572
- if (options.url?.endsWith('/stickers') && options.method === 'POST') {
573
- form.append('file', files[0].blob, files[0].name);
574
- form.append('name', options.body.name);
575
- form.append('description', options.body.description);
576
- form.append('tags', options.body.tags);
577
- } else {
578
- for(let i = 0; i < files.length; i++){
579
- form.append(`file${i}`, files[i].blob, files[i].name);
580
- }
581
- if (file) options.body.file = undefined;
582
- form.append('payload_json', JSON.stringify(rest.changeToDiscordFormat(options.body)));
583
- }
584
- options.body.file = form;
585
- } else if (options.body && ![
586
- 'GET',
587
- 'DELETE'
588
- ].includes(options.method)) {
589
- headers['Content-Type'] = 'application/json';
590
- }
591
- }
592
- return {
593
- headers,
594
- body: options.body?.file ?? JSON.stringify(rest.changeToDiscordFormat(options.body)),
595
- method: options.method
596
- };
597
- },
598
- processRateLimitedPaths () {
599
- const now = Date.now();
600
- for (const [key, value] of rest.rateLimitedPaths.entries()){
601
- // rest.debug(
602
- // `[REST - processRateLimitedPaths] Running for of loop. ${
603
- // value.resetTimestamp - now
604
- // }`
605
- // )
606
- // If the time has not reached cancel
607
- if (value.resetTimestamp > now) continue;
608
- // Rate limit is over, delete the rate limiter
609
- rest.rateLimitedPaths.delete(key);
610
- // If it was global, also mark the global value as false
611
- if (key === 'global') rest.globallyRateLimited = false;
612
- }
613
- // ALL PATHS ARE CLEARED CAN CANCEL OUT!
614
- if (rest.rateLimitedPaths.size === 0) {
615
- rest.processingRateLimitedPaths = false;
616
- } else {
617
- rest.processingRateLimitedPaths = true;
618
- // RECHECK IN 1 SECOND
619
- setTimeout(()=>{
620
- // rest.debug('[REST - processRateLimitedPaths] Running setTimeout.')
621
- rest.processRateLimitedPaths();
622
- }, 1000);
623
- }
624
- },
625
- /** Processes the rate limit headers and determines if it needs to be rate limited and returns the bucket id if available */ processHeaders (url, headers) {
626
- let rateLimited = false;
627
- // GET ALL NECESSARY HEADERS
628
- const remaining = headers.get('x-ratelimit-remaining');
629
- const retryAfter = headers.get('x-ratelimit-reset-after');
630
- const reset = Date.now() + Number(retryAfter) * 1000;
631
- const global = headers.get('x-ratelimit-global');
632
- // undefined override null needed for typings
633
- const bucketId = headers.get('x-ratelimit-bucket') ?? undefined;
634
- const limit = headers.get('x-ratelimit-limit');
635
- rest.queues.get(url)?.handleCompletedRequest({
636
- remaining: remaining ? Number(remaining) : undefined,
637
- interval: retryAfter ? Number(retryAfter) * 1000 : undefined,
638
- max: limit ? Number(limit) : undefined
639
- });
640
- // IF THERE IS NO REMAINING RATE LIMIT, MARK IT AS RATE LIMITED
641
- if (remaining === '0') {
642
- rateLimited = true;
643
- // SAVE THE URL AS LIMITED, IMPORTANT FOR NEW REQUESTS BY USER WITHOUT BUCKET
644
- rest.rateLimitedPaths.set(url, {
645
- url,
646
- resetTimestamp: reset,
647
- bucketId
648
- });
649
- // SAVE THE BUCKET AS LIMITED SINCE DIFFERENT URLS MAY SHARE A BUCKET
650
- if (bucketId) {
651
- rest.rateLimitedPaths.set(bucketId, {
652
- url,
653
- resetTimestamp: reset,
654
- bucketId
655
- });
656
- }
657
- }
658
- // IF THERE IS NO REMAINING GLOBAL LIMIT, MARK IT RATE LIMITED GLOBALLY
659
- if (global) {
660
- const retryAfter = headers.get('retry-after');
661
- const globalReset = Date.now() + Number(retryAfter) * 1000;
662
- // rest.debug(
663
- // `[REST = Globally Rate Limited] URL: ${url} | Global Rest: ${globalReset}`
664
- // )
665
- rest.globallyRateLimited = true;
666
- rateLimited = true;
667
- setTimeout(()=>{
668
- rest.globallyRateLimited = false;
669
- }, globalReset);
670
- rest.rateLimitedPaths.set('global', {
671
- url: 'global',
672
- resetTimestamp: globalReset,
673
- bucketId
674
- });
675
- if (bucketId) {
676
- rest.rateLimitedPaths.set(bucketId, {
677
- url: 'global',
678
- resetTimestamp: globalReset,
679
- bucketId
680
- });
681
- }
682
- }
683
- if (rateLimited && !rest.processingRateLimitedPaths) {
684
- rest.processRateLimitedPaths();
685
- }
686
- return rateLimited ? bucketId : undefined;
687
- },
688
- async sendRequest (options) {
689
- const url = options.url.startsWith('https://') ? options.url : `${rest.baseUrl}/v${rest.version}${options.url}`;
690
- const payload = rest.createRequest({
691
- method: options.method,
692
- url: options.url,
693
- body: options.body,
694
- ...options.options
695
- });
696
- logger.debug(`sending request to ${url}`, 'with payload:', {
697
- ...payload,
698
- headers: {
699
- ...payload.headers,
700
- authorization: 'Bot tokenhere'
701
- }
702
- });
703
- const response = await fetch(url, payload);
704
- logger.debug(`request fetched from ${url} with status ${response.status} & ${response.statusText}`);
705
- // Set the bucket id if it was available on the headers
706
- const bucketId = rest.processHeaders(rest.simplifyUrl(options.url, options.method), response.headers);
707
- if (bucketId) options.bucketId = bucketId;
708
- if (response.status < 200 || response.status >= 400) {
709
- logger.debug(`Request to ${url} failed.`);
710
- if (response.status === 429) {
711
- logger.debug(`Request to ${url} was ratelimited.`);
712
- // Too many attempts, get rid of request from queue.
713
- if (options.retryCount++ >= rest.maxRetryCount) {
714
- logger.debug(`Request to ${url} exceeded the maximum allowed retries.`, 'with payload:', payload);
715
- // rest.debug(`[REST - RetriesMaxed] ${JSON.stringify(options)}`)
716
- // Remove item from queue to prevent retry
717
- options.reject({
718
- ok: false,
719
- status: response.status,
720
- error: 'The options was rate limited and it maxed out the retries limit.'
721
- });
722
- return;
723
- }
724
- // Rate limited, add back to queue
725
- rest.invalidBucket.handleCompletedRequest(response.status, response.headers.get('X-RateLimit-Scope') === 'shared');
726
- const resetAfter = response.headers.get('x-ratelimit-reset-after');
727
- if (resetAfter) await delay(Number(resetAfter) * 1000);
728
- // process the response to prevent mem leak
729
- await response.json();
730
- return await options.retryRequest?.(options);
731
- }
732
- options.reject({
733
- ok: false,
734
- status: response.status,
735
- body: JSON.stringify(await response.json())
736
- });
737
- return;
738
- }
739
- const is204 = response.status === 204;
740
- const json = is204 ? undefined : await response.json();
741
- // Discord sometimes sends no response with 204 code
742
- options.resolve({
743
- ok: true,
744
- status: response.status,
745
- body: JSON.stringify(json)
746
- });
747
- },
748
- // Credits: github.com/abalabahaha/eris lib/rest/RequestHandler.js#L397
749
- // Modified for our use-case
750
- simplifyUrl (url, method) {
751
- let route = url.replace(/\/([a-z-]+)\/(?:[0-9]{17,19})/g, function(match, p) {
752
- return [
753
- 'channels',
754
- 'guilds'
755
- ].includes(p) ? match : `/${p}/x`;
756
- }).replace(/\/reactions\/[^/]+/g, '/reactions/x');
757
- // GENERAL /reactions and /reactions/emoji/@me share the buckets
758
- if (route.includes('/reactions')) {
759
- route = route.substring(0, route.indexOf('/reactions') + '/reactions'.length);
760
- }
761
- // Delete Message endpoint has its own rate limit
762
- if (method === 'DELETE' && route.endsWith('/messages/x')) {
763
- route = method + route;
764
- }
765
- return route;
766
- },
767
- processRequest (request) {
768
- const route = request.url.substring(request.url.indexOf('api/'));
769
- const parts = route.split('/');
770
- // Remove the api/
771
- parts.shift();
772
- // Removes the /v#/
773
- if (parts[0]?.startsWith('v')) parts.shift();
774
- // Set the full url to discord api in case it was recieved in a proxy rest
775
- request.url = `${rest.baseUrl}/v${rest.version}/${parts.join('/')}`;
776
- const url = rest.simplifyUrl(request.url, request.method);
777
- const queue = rest.queues.get(url);
778
- if (queue !== undefined) {
779
- queue.makeRequest(request);
780
- } else {
781
- // CREATES A NEW QUEUE
782
- const bucketQueue = new Queue(rest, {
783
- url,
784
- deleteQueueDelay: rest.deleteQueueDelay
785
- });
786
- // Add request to queue
787
- bucketQueue.makeRequest(request);
788
- // Save queue
789
- rest.queues.set(url, bucketQueue);
790
- }
791
- },
792
- async makeRequest (method, url, body, options) {
793
- if (!rest.baseUrl.startsWith('https://discord.com') && url[0] === '/') {
794
- // Special handling for sending blobs across http to proxy
795
- if (body?.file) {
796
- if (!Array.isArray(body.file)) {
797
- body.file = [
798
- body.file
799
- ];
800
- }
801
- // convert blobs to string before sending to proxy
802
- body.file = await Promise.all(body.file.map(async (f)=>{
803
- const url = encode(await f.blob.arrayBuffer());
804
- return {
805
- name: f.name,
806
- blob: `data:${f.blob.type};base64,${url}`
807
- };
808
- }));
809
- }
810
- const headers = {
811
- Authorization: rest.authorization ?? ""
812
- };
813
- if (body) {
814
- headers['Content-Type'] = 'application/json';
815
- }
816
- const result = await fetch(`${rest.baseUrl}${url}`, {
817
- body: body ? JSON.stringify(body) : undefined,
818
- headers,
819
- method
820
- });
821
- if (!result.ok) {
822
- const err = await result.json().catch(()=>{});
823
- // Legacy Handling to not break old code or when body is missing
824
- if (!err?.body) throw new Error(`Error: ${err.message ?? result.statusText}`);
825
- throw new Error(JSON.stringify(err));
826
- }
827
- return result.status !== 204 ? await result.json() : undefined;
828
- }
829
- return await new Promise((resolve, reject)=>{
830
- const payload = {
831
- url,
832
- method,
833
- body,
834
- retryCount: 0,
835
- retryRequest: async function(options) {
836
- rest.processRequest(payload);
837
- },
838
- resolve: (data)=>{
839
- resolve(data.status !== 204 ? JSON.parse(data.body ?? '{}') : undefined);
840
- },
841
- reject,
842
- options
843
- };
844
- rest.processRequest(payload);
845
- });
846
- },
847
- async get (url) {
848
- return camelize(await rest.makeRequest('GET', url));
849
- },
850
- async post (url, body) {
851
- return camelize(await rest.makeRequest('POST', url, body));
852
- },
853
- async delete (url, body) {
854
- camelize(await rest.makeRequest('DELETE', url, body));
855
- },
856
- async patch (url, body) {
857
- return camelize(await rest.makeRequest('PATCH', url, body));
858
- },
859
- async put (url, body, options) {
860
- return camelize(await rest.makeRequest('PUT', url, body, options));
861
- },
862
- async addReaction (channelId, messageId, reaction) {
863
- reaction = processReactionString(reaction);
864
- await rest.put(rest.routes.channels.reactions.bot(channelId, messageId, reaction));
865
- },
866
- async addReactions (channelId, messageId, reactions, ordered = false) {
867
- if (!ordered) {
868
- await Promise.all(reactions.map(async (reaction)=>{
869
- await rest.addReaction(channelId, messageId, reaction);
870
- }));
871
- return;
872
- }
873
- for (const reaction of reactions){
874
- await rest.addReaction(channelId, messageId, reaction);
875
- }
876
- },
877
- async addRole (guildId, userId, roleId, reason) {
878
- await rest.put(rest.routes.guilds.roles.member(guildId, userId, roleId), {
879
- reason
880
- });
881
- },
882
- async addThreadMember (channelId, userId) {
883
- await rest.put(rest.routes.channels.threads.user(channelId, userId));
884
- },
885
- async createAutomodRule (guildId, options) {
886
- return await rest.post(rest.routes.guilds.automod.rules(guildId), options);
887
- },
888
- async createChannel (guildId, options) {
889
- return await rest.post(rest.routes.guilds.channels(guildId), options);
890
- },
891
- async createEmoji (guildId, options) {
892
- return await rest.post(rest.routes.guilds.emojis(guildId), options);
893
- },
894
- async createGlobalApplicationCommand (command) {
895
- return await rest.post(rest.routes.interactions.commands.commands(rest.applicationId), command);
896
- },
897
- async createGuild (options) {
898
- return await rest.post(rest.routes.guilds.all(), options);
899
- },
900
- async createGuildApplicationCommand (command, guildId) {
901
- return await rest.post(rest.routes.interactions.commands.guilds.all(rest.applicationId, guildId), command);
902
- },
903
- async createGuildFromTemplate (templateCode, options) {
904
- if (options.icon) {
905
- options.icon = await urlToBase64(options.icon);
906
- }
907
- return await rest.post(rest.routes.guilds.templates.code(templateCode), options);
908
- },
909
- async createGuildSticker (guildId, options) {
910
- return await rest.post(rest.routes.guilds.stickers(guildId), options);
911
- },
912
- async createGuildTemplate (guildId, options) {
913
- return await rest.post(rest.routes.guilds.templates.all(guildId), options);
914
- },
915
- async createForumThread (channelId, options) {
916
- return await rest.post(rest.routes.channels.forum(channelId), options);
917
- },
918
- async createInvite (channelId, options = {}) {
919
- return await rest.post(rest.routes.channels.invites(channelId), options);
920
- },
921
- async createRole (guildId, options, reason) {
922
- return await rest.post(rest.routes.guilds.roles.all(guildId), {
923
- ...options,
924
- reason
925
- });
926
- },
927
- async createScheduledEvent (guildId, options) {
928
- return await rest.post(rest.routes.guilds.events.events(guildId), options);
929
- },
930
- async createStageInstance (options) {
931
- return await rest.post(rest.routes.channels.stages(), options);
932
- },
933
- async createWebhook (channelId, options) {
934
- return await rest.post(rest.routes.channels.webhooks(channelId), {
935
- name: options.name,
936
- avatar: options.avatar ? await urlToBase64(options.avatar) : undefined,
937
- reason: options.reason
938
- });
939
- },
940
- async deleteAutomodRule (guildId, ruleId, reason) {
941
- await rest.delete(rest.routes.guilds.automod.rule(guildId, ruleId), {
942
- reason
943
- });
944
- },
945
- async deleteChannel (channelId, reason) {
946
- await rest.delete(rest.routes.channels.channel(channelId), {
947
- reason
948
- });
949
- },
950
- async deleteChannelPermissionOverride (channelId, overwriteId, reason) {
951
- await rest.delete(rest.routes.channels.overwrite(channelId, overwriteId), reason ? {
952
- reason
953
- } : undefined);
954
- },
955
- async deleteEmoji (guildId, id, reason) {
956
- await rest.delete(rest.routes.guilds.emoji(guildId, id), {
957
- reason
958
- });
959
- },
960
- async deleteFollowupMessage (token, messageId) {
961
- await rest.delete(rest.routes.interactions.responses.message(rest.applicationId, token, messageId));
962
- },
963
- async deleteGlobalApplicationCommand (commandId) {
964
- await rest.delete(rest.routes.interactions.commands.command(rest.applicationId, commandId));
965
- },
966
- async deleteGuild (guildId) {
967
- await rest.delete(rest.routes.guilds.guild(guildId));
968
- },
969
- async deleteGuildApplicationCommand (commandId, guildId) {
970
- await rest.delete(rest.routes.interactions.commands.guilds.one(rest.applicationId, guildId, commandId));
971
- },
972
- async deleteGuildSticker (guildId, stickerId, reason) {
973
- await rest.delete(rest.routes.guilds.sticker(guildId, stickerId), reason ? {
974
- reason
975
- } : undefined);
976
- },
977
- async deleteGuildTemplate (guildId, templateCode) {
978
- await rest.delete(rest.routes.guilds.templates.guild(guildId, templateCode));
979
- },
980
- async deleteIntegration (guildId, integrationId) {
981
- await rest.delete(rest.routes.guilds.integration(guildId, integrationId));
982
- },
983
- async deleteInvite (inviteCode, reason) {
984
- await rest.delete(rest.routes.guilds.invite(inviteCode), reason ? {
985
- reason
986
- } : undefined);
987
- },
988
- async deleteMessage (channelId, messageId, reason) {
989
- await rest.delete(rest.routes.channels.message(channelId, messageId), {
990
- reason
991
- });
992
- },
993
- async deleteMessages (channelId, messageIds, reason) {
994
- await rest.post(rest.routes.channels.bulk(channelId), {
995
- messages: messageIds.slice(0, 100).map((id)=>id.toString()),
996
- reason
997
- });
998
- },
999
- async deleteOriginalInteractionResponse (token) {
1000
- await rest.delete(rest.routes.interactions.responses.original(rest.applicationId, token));
1001
- },
1002
- async deleteOwnReaction (channelId, messageId, reaction) {
1003
- reaction = processReactionString(reaction);
1004
- await rest.delete(rest.routes.channels.reactions.bot(channelId, messageId, reaction));
1005
- },
1006
- async deleteReactionsAll (channelId, messageId) {
1007
- await rest.delete(rest.routes.channels.reactions.all(channelId, messageId));
1008
- },
1009
- async deleteReactionsEmoji (channelId, messageId, reaction) {
1010
- reaction = processReactionString(reaction);
1011
- await rest.delete(rest.routes.channels.reactions.emoji(channelId, messageId, reaction));
1012
- },
1013
- async deleteRole (guildId, roleId) {
1014
- await rest.delete(rest.routes.guilds.roles.one(guildId, roleId));
1015
- },
1016
- async deleteScheduledEvent (guildId, eventId) {
1017
- await rest.delete(rest.routes.guilds.events.event(guildId, eventId));
1018
- },
1019
- async deleteStageInstance (channelId, reason) {
1020
- await rest.delete(rest.routes.channels.stage(channelId), reason ? {
1021
- reason
1022
- } : undefined);
1023
- },
1024
- async deleteUserReaction (channelId, messageId, userId, reaction) {
1025
- reaction = processReactionString(reaction);
1026
- await rest.delete(rest.routes.channels.reactions.user(channelId, messageId, reaction, userId));
1027
- },
1028
- async deleteWebhook (webhookId, reason) {
1029
- await rest.delete(rest.routes.webhooks.id(webhookId), {
1030
- reason
1031
- });
1032
- },
1033
- async deleteWebhookMessage (webhookId, token, messageId, options) {
1034
- await rest.delete(rest.routes.webhooks.message(webhookId, token, messageId, options));
1035
- },
1036
- async deleteWebhookWithToken (webhookId, token) {
1037
- await rest.delete(rest.routes.webhooks.webhook(webhookId, token));
1038
- },
1039
- async editApplicationCommandPermissions (guildId, commandId, bearerToken, options) {
1040
- return await rest.put(rest.routes.interactions.commands.permission(rest.applicationId, guildId, commandId), {
1041
- permissions: options
1042
- }, {
1043
- headers: {
1044
- authorization: `Bearer ${bearerToken}`
1045
- }
1046
- });
1047
- },
1048
- async editAutomodRule (guildId, ruleId, options) {
1049
- return await rest.patch(rest.routes.guilds.automod.rule(guildId, ruleId), options);
1050
- },
1051
- async editBotProfile (options) {
1052
- const avatar = options?.botAvatarURL ? await urlToBase64(options?.botAvatarURL) : options?.botAvatarURL;
1053
- return await rest.patch(rest.routes.userBot(), {
1054
- username: options.username?.trim(),
1055
- avatar
1056
- });
1057
- },
1058
- async editChannel (channelId, options) {
1059
- return await rest.patch(rest.routes.channels.channel(channelId), options);
1060
- },
1061
- async editChannelPermissionOverrides (channelId, options) {
1062
- await rest.put(rest.routes.channels.overwrite(channelId, options.id), options);
1063
- },
1064
- async editChannelPositions (guildId, channelPositions) {
1065
- await rest.patch(rest.routes.guilds.channels(guildId), channelPositions);
1066
- },
1067
- async editEmoji (guildId, id, options) {
1068
- return await rest.patch(rest.routes.guilds.emoji(guildId, id), options);
1069
- },
1070
- async editFollowupMessage (token, messageId, options) {
1071
- return await rest.patch(rest.routes.interactions.responses.message(rest.applicationId, token, messageId), options);
1072
- },
1073
- async editGlobalApplicationCommand (commandId, options) {
1074
- return await rest.patch(rest.routes.interactions.commands.command(rest.applicationId, commandId), options);
1075
- },
1076
- async editGuild (guildId, options) {
1077
- return await rest.patch(rest.routes.guilds.guild(guildId), options);
1078
- },
1079
- async editGuildApplicationCommand (commandId, guildId, options) {
1080
- return await rest.patch(rest.routes.interactions.commands.guilds.one(rest.applicationId, guildId, commandId), options);
1081
- },
1082
- async editGuildMfaLevel (guildId, mfaLevel, reason) {
1083
- await rest.post(rest.routes.guilds.mfa(guildId), {
1084
- level: mfaLevel,
1085
- reason
1086
- });
1087
- },
1088
- async editGuildSticker (guildId, stickerId, options) {
1089
- return await rest.patch(rest.routes.guilds.sticker(guildId, stickerId), options);
1090
- },
1091
- async editGuildTemplate (guildId, templateCode, options) {
1092
- return await rest.patch(rest.routes.guilds.templates.guild(guildId, templateCode), options);
1093
- },
1094
- async editMessage (channelId, messageId, options) {
1095
- return await rest.patch(rest.routes.channels.message(channelId, messageId), options);
1096
- },
1097
- async editOriginalInteractionResponse (token, options) {
1098
- return await rest.patch(rest.routes.interactions.responses.original(rest.applicationId, token), options);
1099
- },
1100
- async editOriginalWebhookMessage (webhookId, token, options) {
1101
- return await rest.patch(rest.routes.webhooks.original(webhookId, token, options), {
1102
- type: InteractionResponseTypes.UpdateMessage,
1103
- data: options
1104
- });
1105
- },
1106
- async editOwnVoiceState (guildId, options) {
1107
- await rest.patch(rest.routes.guilds.voice(guildId), {
1108
- channel_id: options.channelId,
1109
- suppress: options.suppress,
1110
- request_to_speak_timestamp: options.requestToSpeakTimestamp ? new Date(options.requestToSpeakTimestamp).toISOString() : options.requestToSpeakTimestamp
1111
- });
1112
- },
1113
- async editScheduledEvent (guildId, eventId, options) {
1114
- return await rest.patch(rest.routes.guilds.events.event(guildId, eventId), options);
1115
- },
1116
- async editRole (guildId, roleId, options) {
1117
- return await rest.patch(rest.routes.guilds.roles.one(guildId, roleId), options);
1118
- },
1119
- async editRolePositions (guildId, options) {
1120
- return await rest.patch(rest.routes.guilds.roles.all(guildId), options);
1121
- },
1122
- async editStageInstance (channelId, data) {
1123
- return await rest.patch(rest.routes.channels.stage(channelId), {
1124
- topic: data.topic
1125
- });
1126
- },
1127
- async editUserVoiceState (guildId, options) {
1128
- await rest.patch(rest.routes.guilds.voice(guildId, options.userId), {
1129
- channel_id: options.channelId,
1130
- suppress: options.suppress,
1131
- user_id: options.userId
1132
- });
1133
- },
1134
- async editWebhook (webhookId, options) {
1135
- return await rest.patch(rest.routes.webhooks.id(webhookId), options);
1136
- },
1137
- async editWebhookMessage (webhookId, token, messageId, options) {
1138
- return await rest.patch(rest.routes.webhooks.message(webhookId, token, messageId, options), options);
1139
- },
1140
- async editWebhookWithToken (webhookId, token, options) {
1141
- return await rest.patch(rest.routes.webhooks.webhook(webhookId, token), options);
1142
- },
1143
- async editWelcomeScreen (guildId, options) {
1144
- return await rest.patch(rest.routes.guilds.welcome(guildId), options);
1145
- },
1146
- async editWidgetSettings (guildId, options) {
1147
- return await rest.patch(rest.routes.guilds.widget(guildId), options);
1148
- },
1149
- async executeWebhook (webhookId, token, options) {
1150
- return await rest.post(rest.routes.webhooks.webhook(webhookId, token, options), options);
1151
- },
1152
- async followAnnouncement (sourceChannelId, targetChannelId) {
1153
- return await rest.post(rest.routes.channels.follow(sourceChannelId), {
1154
- webhook_channel_id: targetChannelId
1155
- });
1156
- },
1157
- async getActiveThreads (guildId) {
1158
- return await rest.get(rest.routes.channels.threads.active(guildId));
1159
- },
1160
- async getApplicationCommandPermission (guildId, commandId) {
1161
- return await rest.get(rest.routes.interactions.commands.permission(rest.applicationId, guildId, commandId));
1162
- },
1163
- async getApplicationCommandPermissions (guildId) {
1164
- return await rest.get(rest.routes.interactions.commands.permissions(rest.applicationId, guildId));
1165
- },
1166
- async getApplicationInfo () {
1167
- return await rest.get(rest.routes.oauth2Application());
1168
- },
1169
- async getAuditLog (guildId, options) {
1170
- return await rest.get(rest.routes.guilds.auditlogs(guildId, options));
1171
- },
1172
- async getAutomodRule (guildId, ruleId) {
1173
- return await rest.get(rest.routes.guilds.automod.rule(guildId, ruleId));
1174
- },
1175
- async getAutomodRules (guildId) {
1176
- return await rest.get(rest.routes.guilds.automod.rules(guildId));
1177
- },
1178
- async getAvailableVoiceRegions () {
1179
- return await rest.get(rest.routes.regions());
1180
- },
1181
- async getBan (guildId, userId) {
1182
- return await rest.get(rest.routes.guilds.members.ban(guildId, userId));
1183
- },
1184
- async getBans (guildId, options) {
1185
- return await rest.get(rest.routes.guilds.members.bans(guildId, options));
1186
- },
1187
- async getChannel (id) {
1188
- return await rest.get(rest.routes.channels.channel(id));
1189
- },
1190
- async getChannelInvites (channelId) {
1191
- return await rest.get(rest.routes.channels.invites(channelId));
1192
- },
1193
- async getChannels (guildId) {
1194
- return await rest.get(rest.routes.guilds.channels(guildId));
1195
- },
1196
- async getChannelWebhooks (channelId) {
1197
- return await rest.get(rest.routes.channels.webhooks(channelId));
1198
- },
1199
- async getDmChannel (userId) {
1200
- return await rest.post(rest.routes.channels.dm(), {
1201
- recipient_id: userId.toString()
1202
- });
1203
- },
1204
- async getEmoji (guildId, emojiId) {
1205
- return await rest.get(rest.routes.guilds.emoji(guildId, emojiId));
1206
- },
1207
- async getEmojis (guildId) {
1208
- return await rest.get(rest.routes.guilds.emojis(guildId));
1209
- },
1210
- async getFollowupMessage (token, messageId) {
1211
- return await rest.get(rest.routes.interactions.responses.message(rest.applicationId, token, messageId));
1212
- },
1213
- async getGatewayBot () {
1214
- return await rest.get(rest.routes.gatewayBot());
1215
- },
1216
- async getGlobalApplicationCommand (commandId) {
1217
- return await rest.get(rest.routes.interactions.commands.command(rest.applicationId, commandId));
1218
- },
1219
- async getGlobalApplicationCommands () {
1220
- return await rest.get(rest.routes.interactions.commands.commands(rest.applicationId));
1221
- },
1222
- async getGuild (guildId, options = {
1223
- counts: true
1224
- }) {
1225
- return await rest.get(rest.routes.guilds.guild(guildId, options.counts));
1226
- },
1227
- async getGuildApplicationCommand (commandId, guildId) {
1228
- return await rest.get(rest.routes.interactions.commands.guilds.one(rest.applicationId, guildId, commandId));
1229
- },
1230
- async getGuildApplicationCommands (guildId) {
1231
- return await rest.get(rest.routes.interactions.commands.guilds.all(rest.applicationId, guildId));
1232
- },
1233
- async getGuildPreview (guildId) {
1234
- return await rest.get(rest.routes.guilds.preview(guildId));
1235
- },
1236
- async getGuildTemplate (templateCode) {
1237
- return await rest.get(rest.routes.guilds.templates.code(templateCode));
1238
- },
1239
- async getGuildTemplates (guildId) {
1240
- return await rest.get(rest.routes.guilds.templates.all(guildId));
1241
- },
1242
- async getGuildWebhooks (guildId) {
1243
- return await rest.get(rest.routes.guilds.webhooks(guildId));
1244
- },
1245
- async getIntegrations (guildId) {
1246
- return await rest.get(rest.routes.guilds.integrations(guildId));
1247
- },
1248
- async getInvite (inviteCode, options) {
1249
- return await rest.get(rest.routes.guilds.invite(inviteCode, options));
1250
- },
1251
- async getInvites (guildId) {
1252
- return await rest.get(rest.routes.guilds.invites(guildId));
1253
- },
1254
- async getMessage (channelId, messageId) {
1255
- return await rest.get(rest.routes.channels.message(channelId, messageId));
1256
- },
1257
- async getMessages (channelId, options) {
1258
- return await rest.get(rest.routes.channels.messages(channelId, options));
1259
- },
1260
- async getNitroStickerPacks () {
1261
- return await rest.get(rest.routes.nitroStickerPacks());
1262
- },
1263
- async getOriginalInteractionResponse (token) {
1264
- return await rest.get(rest.routes.interactions.responses.original(rest.applicationId, token));
1265
- },
1266
- async getPinnedMessages (channelId) {
1267
- return await rest.get(rest.routes.channels.pins(channelId));
1268
- },
1269
- async getPrivateArchivedThreads (channelId, options) {
1270
- return await rest.get(rest.routes.channels.threads.private(channelId, options));
1271
- },
1272
- async getPrivateJoinedArchivedThreads (channelId, options) {
1273
- return await rest.get(rest.routes.channels.threads.joined(channelId, options));
1274
- },
1275
- async getPruneCount (guildId, options) {
1276
- return await rest.get(rest.routes.guilds.prune(guildId, options));
1277
- },
1278
- async getPublicArchivedThreads (channelId, options) {
1279
- return await rest.get(rest.routes.channels.threads.public(channelId, options));
1280
- },
1281
- async getRoles (guildId) {
1282
- return await rest.get(rest.routes.guilds.roles.all(guildId));
1283
- },
1284
- async getScheduledEvent (guildId, eventId, options) {
1285
- return await rest.get(rest.routes.guilds.events.event(guildId, eventId, options?.withUserCount));
1286
- },
1287
- async getScheduledEvents (guildId, options) {
1288
- return await rest.get(rest.routes.guilds.events.events(guildId, options?.withUserCount));
1289
- },
1290
- async getScheduledEventUsers (guildId, eventId, options) {
1291
- return await rest.get(rest.routes.guilds.events.users(guildId, eventId, options));
1292
- },
1293
- async getSessionInfo () {
1294
- return await rest.getGatewayBot();
1295
- },
1296
- async getStageInstance (channelId) {
1297
- return await rest.get(rest.routes.channels.stage(channelId));
1298
- },
1299
- async getSticker (stickerId) {
1300
- return await rest.get(rest.routes.sticker(stickerId));
1301
- },
1302
- async getGuildSticker (guildId, stickerId) {
1303
- return await rest.get(rest.routes.guilds.sticker(guildId, stickerId));
1304
- },
1305
- async getGuildStickers (guildId) {
1306
- return await rest.get(rest.routes.guilds.stickers(guildId));
1307
- },
1308
- async getThreadMember (channelId, userId) {
1309
- return await rest.get(rest.routes.channels.threads.user(channelId, userId));
1310
- },
1311
- async getThreadMembers (channelId) {
1312
- return await rest.get(rest.routes.channels.threads.members(channelId));
1313
- },
1314
- async getReactions (channelId, messageId, reaction, options) {
1315
- return await rest.get(rest.routes.channels.reactions.message(channelId, messageId, reaction, options));
1316
- },
1317
- async getUser (id) {
1318
- return await rest.get(rest.routes.user(id));
1319
- },
1320
- async getVanityUrl (guildId) {
1321
- return await rest.get(rest.routes.guilds.vanity(guildId));
1322
- },
1323
- async getVoiceRegions (guildId) {
1324
- return await rest.get(rest.routes.guilds.regions(guildId));
1325
- },
1326
- async getWebhook (webhookId) {
1327
- return await rest.get(rest.routes.webhooks.id(webhookId));
1328
- },
1329
- async getWebhookMessage (webhookId, token, messageId, options) {
1330
- return await rest.get(rest.routes.webhooks.message(webhookId, token, messageId, options));
1331
- },
1332
- async getWebhookWithToken (webhookId, token) {
1333
- return await rest.get(rest.routes.webhooks.webhook(webhookId, token));
1334
- },
1335
- async getWelcomeScreen (guildId) {
1336
- return await rest.get(rest.routes.guilds.welcome(guildId));
1337
- },
1338
- async getWidget (guildId) {
1339
- return await rest.get(rest.routes.guilds.widgetJson(guildId));
1340
- },
1341
- async getWidgetSettings (guildId) {
1342
- return await rest.get(rest.routes.guilds.widget(guildId));
1343
- },
1344
- async joinThread (channelId) {
1345
- await rest.put(rest.routes.channels.threads.me(channelId));
1346
- },
1347
- async leaveGuild (guildId) {
1348
- await rest.delete(rest.routes.guilds.leave(guildId));
1349
- },
1350
- async leaveThread (channelId) {
1351
- await rest.delete(rest.routes.channels.threads.me(channelId));
1352
- },
1353
- async publishMessage (channelId, messageId) {
1354
- return await rest.post(rest.routes.channels.crosspost(channelId, messageId));
1355
- },
1356
- async removeRole (guildId, userId, roleId, reason) {
1357
- await rest.delete(rest.routes.guilds.roles.member(guildId, userId, roleId), {
1358
- reason
1359
- });
1360
- },
1361
- async removeThreadMember (channelId, userId) {
1362
- await rest.delete(rest.routes.channels.threads.user(channelId, userId));
1363
- },
1364
- async sendFollowupMessage (token, options) {
1365
- return await new Promise((resolve, reject)=>{
1366
- rest.sendRequest({
1367
- url: rest.routes.webhooks.webhook(rest.applicationId, token),
1368
- method: 'POST',
1369
- body: options,
1370
- retryCount: 0,
1371
- retryRequest: async function(options) {
1372
- // TODO: should change to reprocess queue item
1373
- await rest.sendRequest(options);
1374
- },
1375
- resolve: (data)=>{
1376
- resolve(data.status !== 204 ? JSON.parse(data.body ?? '{}') : undefined);
1377
- },
1378
- reject
1379
- });
1380
- });
1381
- },
1382
- async sendInteractionResponse (interactionId, token, options) {
1383
- await new Promise((resolve, reject)=>{
1384
- rest.sendRequest({
1385
- url: rest.routes.interactions.responses.callback(interactionId, token),
1386
- method: 'POST',
1387
- body: options,
1388
- retryCount: 0,
1389
- retryRequest: async function(options) {
1390
- // TODO: should change to reprocess queue item
1391
- await rest.sendRequest(options);
1392
- },
1393
- resolve: (data)=>{
1394
- resolve(data.status !== 204 ? JSON.parse(data.body ?? '{}') : undefined);
1395
- },
1396
- reject
1397
- });
1398
- });
1399
- },
1400
- async sendMessage (channelId, options) {
1401
- return await rest.post(rest.routes.channels.messages(channelId), options);
1402
- },
1403
- async startThreadWithMessage (channelId, messageId, options) {
1404
- return await rest.post(rest.routes.channels.threads.message(channelId, messageId), options);
1405
- },
1406
- async startThreadWithoutMessage (channelId, options) {
1407
- return await rest.post(rest.routes.channels.threads.all(channelId), options);
1408
- },
1409
- async syncGuildTemplate (guildId) {
1410
- return await rest.put(rest.routes.guilds.templates.all(guildId));
1411
- },
1412
- async banMember (guildId, userId, options) {
1413
- await rest.put(rest.routes.guilds.members.ban(guildId, userId), options);
1414
- },
1415
- async editBotMember (guildId, options) {
1416
- return await rest.patch(rest.routes.guilds.members.bot(guildId), options);
1417
- },
1418
- async editMember (guildId, userId, options) {
1419
- return await rest.patch(rest.routes.guilds.members.member(guildId, userId), options);
1420
- },
1421
- async getMember (guildId, userId) {
1422
- return await rest.get(rest.routes.guilds.members.member(guildId, userId));
1423
- },
1424
- async getMembers (guildId, options) {
1425
- return await rest.get(rest.routes.guilds.members.members(guildId, options));
1426
- },
1427
- async kickMember (guildId, userId, reason) {
1428
- await rest.delete(rest.routes.guilds.members.member(guildId, userId), {
1429
- reason
1430
- });
1431
- },
1432
- async pinMessage (channelId, messageId, reason) {
1433
- await rest.put(rest.routes.channels.pin(channelId, messageId), reason ? {
1434
- reason
1435
- } : undefined);
1436
- },
1437
- async pruneMembers (guildId, options) {
1438
- return await rest.post(rest.routes.guilds.members.prune(guildId), options);
1439
- },
1440
- async searchMembers (guildId, query, options) {
1441
- return await rest.get(rest.routes.guilds.members.search(guildId, query, options));
1442
- },
1443
- async unbanMember (guildId, userId) {
1444
- await rest.delete(rest.routes.guilds.members.ban(guildId, userId));
1445
- },
1446
- async unpinMessage (channelId, messageId, reason) {
1447
- await rest.delete(rest.routes.channels.pin(channelId, messageId), reason ? {
1448
- reason
1449
- } : undefined);
1450
- },
1451
- async triggerTypingIndicator (channelId) {
1452
- await rest.post(rest.routes.channels.typing(channelId));
1453
- },
1454
- async upsertGlobalApplicationCommands (commands) {
1455
- return await rest.put(rest.routes.interactions.commands.commands(rest.applicationId), commands);
1456
- },
1457
- async upsertGuildApplicationCommands (guildId, commands) {
1458
- return await rest.put(rest.routes.interactions.commands.guilds.all(rest.applicationId, guildId), commands);
1459
- }
1460
- };
1461
- return rest;
1462
- }
1463
-
1464
- //# sourceMappingURL=manager.js.map