@discordeno/rest 19.0.0-next.dea9d1d → 19.0.0-next.dfa7ff4

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 +1535 -0
  5. package/dist/cjs/queue.cjs +164 -0
  6. package/dist/cjs/routes.cjs +589 -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 +1493 -0
  12. package/dist/esm/queue.js +154 -0
  13. package/dist/esm/routes.js +579 -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} +735 -152
  27. package/dist/types/types.d.ts.map +1 -0
  28. package/dist/{typings → types/typings}/routes.d.ts +69 -8
  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 -1577
  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,1577 +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, 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.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
- },
508
- checkRateLimits (url) {
509
- const ratelimited = rest.rateLimitedPaths.get(url);
510
- const global = rest.rateLimitedPaths.get('global');
511
- const now = Date.now();
512
- if (ratelimited && now < ratelimited.resetTimestamp) {
513
- return ratelimited.resetTimestamp - now;
514
- }
515
- if (global && now < global.resetTimestamp) {
516
- return global.resetTimestamp - now;
517
- }
518
- return false;
519
- },
520
- changeToDiscordFormat (obj) {
521
- if (obj === null) return null;
522
- if (typeof obj === 'object') {
523
- if (Array.isArray(obj)) {
524
- return obj.map((item)=>rest.changeToDiscordFormat(item));
525
- }
526
- const newObj = {};
527
- 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;
540
- }
541
- newObj[camelToSnakeCase(key)] = rest.changeToDiscordFormat(obj[key]);
542
- }
543
- return newObj;
544
- }
545
- if (typeof obj === 'bigint') return obj.toString();
546
- return obj;
547
- },
548
- createRequestBody (method, options) {
549
- const headers = {
550
- 'user-agent': `DiscordBot (https://github.com/discordeno/discordeno, v${version})`
551
- };
552
- if (!options?.unauthorized) headers.authorization = `Bot ${rest.token}`;
553
- // IF A REASON IS PROVIDED ENCODE IT IN HEADERS
554
- if (options?.reason !== undefined) {
555
- headers['x-audit-log-reason'] = encodeURIComponent(options?.reason);
556
- }
557
- let body;
558
- // TODO: check if we need to add specific check for GET method
559
- // Since GET does not allow bodies
560
- // Have to check for attachments first, since body then has to be send in a different way.
561
- if (options?.files !== undefined) {
562
- const form = new FormData();
563
- for(let i = 0; i < options.files.length; ++i){
564
- form.append(`file${i}`, options.files[i].blob, options.files[i].name);
565
- }
566
- form.append('payload_json', JSON.stringify({
567
- ...options.body,
568
- files: undefined
569
- }));
570
- body = form;
571
- // No need to set the `content-type` header since `fetch` does that automatically for us when we use a `FormData` object.
572
- } else if (options?.body !== undefined) {
573
- if (options.body instanceof FormData) {
574
- body = options.body;
575
- // No need to set the `content-type` header since `fetch` does that automatically for us when we use a `FormData` object.
576
- } else {
577
- body = JSON.stringify(rest.changeToDiscordFormat(options.body));
578
- headers['content-type'] = `application/json`;
579
- }
580
- }
581
- // SOMETIMES SPECIAL HEADERS (E.G. CUSTOM AUTHORIZATION) NEED TO BE USED
582
- if (options?.headers) {
583
- Object.assign(headers, options.headers);
584
- }
585
- return {
586
- body,
587
- headers,
588
- method
589
- };
590
- },
591
- processRateLimitedPaths () {
592
- const now = Date.now();
593
- for (const [key, value] of rest.rateLimitedPaths.entries()){
594
- // rest.debug(
595
- // `[REST - processRateLimitedPaths] Running for of loop. ${
596
- // value.resetTimestamp - now
597
- // }`
598
- // )
599
- // If the time has not reached cancel
600
- if (value.resetTimestamp > now) continue;
601
- // Rate limit is over, delete the rate limiter
602
- rest.rateLimitedPaths.delete(key);
603
- // If it was global, also mark the global value as false
604
- if (key === 'global') rest.globallyRateLimited = false;
605
- }
606
- // ALL PATHS ARE CLEARED CAN CANCEL OUT!
607
- if (rest.rateLimitedPaths.size === 0) {
608
- rest.processingRateLimitedPaths = false;
609
- } else {
610
- rest.processingRateLimitedPaths = true;
611
- // RECHECK IN 1 SECOND
612
- setTimeout(()=>{
613
- // rest.debug('[REST - processRateLimitedPaths] Running setTimeout.')
614
- rest.processRateLimitedPaths();
615
- }, 1000);
616
- }
617
- },
618
- /** Processes the rate limit headers and determines if it needs to be rate limited and returns the bucket id if available */ processHeaders (url, headers) {
619
- let rateLimited = false;
620
- // GET ALL NECESSARY HEADERS
621
- const remaining = headers.get('x-ratelimit-remaining');
622
- const retryAfter = headers.get('x-ratelimit-reset-after');
623
- const reset = Date.now() + Number(retryAfter) * 1000;
624
- const global = headers.get('x-ratelimit-global');
625
- // undefined override null needed for typings
626
- const bucketId = headers.get('x-ratelimit-bucket') ?? undefined;
627
- const limit = headers.get('x-ratelimit-limit');
628
- rest.queues.get(url)?.handleCompletedRequest({
629
- remaining: remaining ? Number(remaining) : undefined,
630
- interval: retryAfter ? Number(retryAfter) * 1000 : undefined,
631
- max: limit ? Number(limit) : undefined
632
- });
633
- // IF THERE IS NO REMAINING RATE LIMIT, MARK IT AS RATE LIMITED
634
- if (remaining === '0') {
635
- rateLimited = true;
636
- // SAVE THE URL AS LIMITED, IMPORTANT FOR NEW REQUESTS BY USER WITHOUT BUCKET
637
- rest.rateLimitedPaths.set(url, {
638
- url,
639
- resetTimestamp: reset,
640
- bucketId
641
- });
642
- // SAVE THE BUCKET AS LIMITED SINCE DIFFERENT URLS MAY SHARE A BUCKET
643
- if (bucketId) {
644
- rest.rateLimitedPaths.set(bucketId, {
645
- url,
646
- resetTimestamp: reset,
647
- bucketId
648
- });
649
- }
650
- }
651
- // IF THERE IS NO REMAINING GLOBAL LIMIT, MARK IT RATE LIMITED GLOBALLY
652
- if (global) {
653
- const retryAfter = headers.get('retry-after');
654
- const globalReset = Date.now() + Number(retryAfter) * 1000;
655
- // rest.debug(
656
- // `[REST = Globally Rate Limited] URL: ${url} | Global Rest: ${globalReset}`
657
- // )
658
- rest.globallyRateLimited = true;
659
- rateLimited = true;
660
- setTimeout(()=>{
661
- rest.globallyRateLimited = false;
662
- }, globalReset);
663
- rest.rateLimitedPaths.set('global', {
664
- url: 'global',
665
- resetTimestamp: globalReset,
666
- bucketId
667
- });
668
- if (bucketId) {
669
- rest.rateLimitedPaths.set(bucketId, {
670
- url: 'global',
671
- resetTimestamp: globalReset,
672
- bucketId
673
- });
674
- }
675
- }
676
- if (rateLimited && !rest.processingRateLimitedPaths) {
677
- rest.processRateLimitedPaths();
678
- }
679
- return rateLimited ? bucketId : undefined;
680
- },
681
- async sendRequest (options) {
682
- const url = options.url.startsWith('https://') ? options.url : `${rest.baseUrl}/v${rest.version}${options.url}`;
683
- const payload = rest.createRequestBody(options.method, options.requestBodyOptions);
684
- logger.debug(`sending request to ${url}`, 'with payload:', {
685
- ...payload,
686
- headers: {
687
- ...payload.headers,
688
- authorization: 'Bot tokenhere'
689
- }
690
- });
691
- const response = await fetch(url, payload);
692
- logger.debug(`request fetched from ${url} with status ${response.status} & ${response.statusText}`);
693
- // Set the bucket id if it was available on the headers
694
- const bucketId = rest.processHeaders(rest.simplifyUrl(options.url, options.method), response.headers);
695
- if (bucketId) options.bucketId = bucketId;
696
- if (response.status < 200 || response.status >= 400) {
697
- logger.debug(`Request to ${url} failed.`);
698
- if (response.status === 429) {
699
- logger.debug(`Request to ${url} was ratelimited.`);
700
- // Too many attempts, get rid of request from queue.
701
- if (options.retryCount++ >= rest.maxRetryCount) {
702
- logger.debug(`Request to ${url} exceeded the maximum allowed retries.`, 'with payload:', payload);
703
- // rest.debug(`[REST - RetriesMaxed] ${JSON.stringify(options)}`)
704
- // Remove item from queue to prevent retry
705
- options.reject({
706
- ok: false,
707
- status: response.status,
708
- error: 'The options was rate limited and it maxed out the retries limit.'
709
- });
710
- return;
711
- }
712
- // Rate limited, add back to queue
713
- rest.invalidBucket.handleCompletedRequest(response.status, response.headers.get('X-RateLimit-Scope') === 'shared');
714
- const resetAfter = response.headers.get('x-ratelimit-reset-after');
715
- if (resetAfter) await delay(Number(resetAfter) * 1000);
716
- // process the response to prevent mem leak
717
- await response.json();
718
- return await options.retryRequest?.(options);
719
- }
720
- options.reject({
721
- ok: false,
722
- status: response.status,
723
- body: JSON.stringify(await response.json())
724
- });
725
- return;
726
- }
727
- const is204 = response.status === 204;
728
- const json = is204 ? undefined : await response.json();
729
- // Discord sometimes sends no response with 204 code
730
- options.resolve({
731
- ok: true,
732
- status: response.status,
733
- body: JSON.stringify(json)
734
- });
735
- },
736
- simplifyUrl (url, method) {
737
- const parts = url.split('/');
738
- const secondLastPart = parts[parts.length - 2];
739
- if (secondLastPart === 'channels' || secondLastPart === 'guilds') {
740
- return url;
741
- }
742
- if (secondLastPart === 'reactions' || parts[parts.length - 1] === '@me') {
743
- parts.splice(-2);
744
- parts.push('reactions');
745
- } else {
746
- parts.splice(-1);
747
- parts.push('x');
748
- }
749
- if (parts[parts.length - 3] === 'reactions') {
750
- parts.splice(-2);
751
- }
752
- if (method === 'DELETE' && secondLastPart === 'messages') {
753
- return `D${parts.join('/')}`;
754
- }
755
- return parts.join('/');
756
- },
757
- processRequest (request) {
758
- const route = request.url.substring(request.url.indexOf('api/'));
759
- const parts = route.split('/');
760
- // Remove the api/
761
- parts.shift();
762
- // Removes the /v#/
763
- if (parts[0]?.startsWith('v')) parts.shift();
764
- // Set the full url to discord api in case it was recieved in a proxy rest
765
- request.url = `${rest.baseUrl}/v${rest.version}/${parts.join('/')}`;
766
- const url = rest.simplifyUrl(request.url, request.method);
767
- const queue = rest.queues.get(url);
768
- if (queue !== undefined) {
769
- queue.makeRequest(request);
770
- } else {
771
- // CREATES A NEW QUEUE
772
- const bucketQueue = new Queue(rest, {
773
- url,
774
- deleteQueueDelay: rest.deleteQueueDelay
775
- });
776
- // Add request to queue
777
- bucketQueue.makeRequest(request);
778
- // Save queue
779
- rest.queues.set(url, bucketQueue);
780
- }
781
- },
782
- async makeRequest (method, url, options) {
783
- if (!rest.baseUrl.startsWith('https://discord.com') && url[0] === '/') {
784
- // Special handling for sending blobs across http to proxy
785
- // TODO: fix this hacky handling
786
- if (!(options?.body instanceof FormData) && !Array.isArray(options?.body) && options?.body?.file) {
787
- if (!Array.isArray(options.body.file)) {
788
- options.body.file = [
789
- options.body.file
790
- ];
791
- }
792
- // convert blobs to string before sending to proxy
793
- options.body.file = await Promise.all(options.body.file.map(async (f)=>{
794
- const url = encode(await f.blob.arrayBuffer());
795
- return {
796
- name: f.name,
797
- blob: `data:${f.blob.type};base64,${url}`
798
- };
799
- }));
800
- }
801
- const headers = {
802
- Authorization: rest.authorization ?? ''
803
- };
804
- if (options?.body) {
805
- headers['Content-Type'] = 'application/json';
806
- }
807
- const result = await fetch(`${rest.baseUrl}${url}`, {
808
- body: options?.body ? JSON.stringify(options.body) : undefined,
809
- headers,
810
- method
811
- });
812
- if (!result.ok) {
813
- const err = await result.json().catch(()=>{});
814
- // Legacy Handling to not break old code or when body is missing
815
- if (!err?.body) throw new Error(`Error: ${err.message ?? result.statusText}`);
816
- throw new Error(JSON.stringify(err));
817
- }
818
- return result.status !== 204 ? await result.json() : undefined;
819
- }
820
- return await new Promise((resolve, reject)=>{
821
- const payload = {
822
- url,
823
- method,
824
- requestBodyOptions: options,
825
- retryCount: 0,
826
- retryRequest: async function(payload) {
827
- rest.processRequest(payload);
828
- },
829
- resolve: (data)=>{
830
- resolve(data.status !== 204 ? JSON.parse(data.body ?? '{}') : undefined);
831
- },
832
- reject
833
- };
834
- rest.processRequest(payload);
835
- });
836
- },
837
- async get (url, options) {
838
- return camelize(await rest.makeRequest('GET', url, options));
839
- },
840
- async post (url, options) {
841
- return camelize(await rest.makeRequest('POST', url, options));
842
- },
843
- async delete (url, options) {
844
- camelize(await rest.makeRequest('DELETE', url, options));
845
- },
846
- async patch (url, options) {
847
- return camelize(await rest.makeRequest('PATCH', url, options));
848
- },
849
- async put (url, options) {
850
- return camelize(await rest.makeRequest('PUT', url, options));
851
- },
852
- async addReaction (channelId, messageId, reaction) {
853
- reaction = processReactionString(reaction);
854
- await rest.put(rest.routes.channels.reactions.bot(channelId, messageId, reaction));
855
- },
856
- async addReactions (channelId, messageId, reactions, ordered = false) {
857
- if (!ordered) {
858
- await Promise.all(reactions.map(async (reaction)=>{
859
- await rest.addReaction(channelId, messageId, reaction);
860
- }));
861
- return;
862
- }
863
- for (const reaction of reactions){
864
- await rest.addReaction(channelId, messageId, reaction);
865
- }
866
- },
867
- async addRole (guildId, userId, roleId, reason) {
868
- await rest.put(rest.routes.guilds.roles.member(guildId, userId, roleId), {
869
- reason
870
- });
871
- },
872
- async addThreadMember (channelId, userId) {
873
- await rest.put(rest.routes.channels.threads.user(channelId, userId));
874
- },
875
- async createAutomodRule (guildId, body) {
876
- return await rest.post(rest.routes.guilds.automod.rules(guildId), {
877
- body
878
- });
879
- },
880
- async createChannel (guildId, body) {
881
- return await rest.post(rest.routes.guilds.channels(guildId), {
882
- body
883
- });
884
- },
885
- async createEmoji (guildId, body) {
886
- return await rest.post(rest.routes.guilds.emojis(guildId), {
887
- body
888
- });
889
- },
890
- async createGlobalApplicationCommand (body) {
891
- return await rest.post(rest.routes.interactions.commands.commands(rest.applicationId), {
892
- body
893
- });
894
- },
895
- async createGuild (body) {
896
- return await rest.post(rest.routes.guilds.all(), {
897
- body
898
- });
899
- },
900
- async createGuildApplicationCommand (body, guildId) {
901
- return await rest.post(rest.routes.interactions.commands.guilds.all(rest.applicationId, guildId), {
902
- body
903
- });
904
- },
905
- async createGuildFromTemplate (templateCode, body) {
906
- if (body.icon) {
907
- body.icon = await urlToBase64(body.icon);
908
- }
909
- return await rest.post(rest.routes.guilds.templates.code(templateCode), {
910
- body
911
- });
912
- },
913
- async createGuildSticker (guildId, options) {
914
- const form = new FormData();
915
- form.append('file', options.file.blob, options.file.name);
916
- form.append('name', options.name);
917
- form.append('description', options.description);
918
- form.append('tags', options.tags);
919
- return await rest.post(rest.routes.guilds.stickers(guildId), {
920
- body: form
921
- });
922
- },
923
- async createGuildTemplate (guildId, body) {
924
- return await rest.post(rest.routes.guilds.templates.all(guildId), {
925
- body
926
- });
927
- },
928
- async createForumThread (channelId, body) {
929
- return await rest.post(rest.routes.channels.forum(channelId), {
930
- body,
931
- files: body.files
932
- });
933
- },
934
- async createInvite (channelId, body = {}) {
935
- return await rest.post(rest.routes.channels.invites(channelId), {
936
- body
937
- });
938
- },
939
- async createRole (guildId, body, reason) {
940
- return await rest.post(rest.routes.guilds.roles.all(guildId), {
941
- body,
942
- reason
943
- });
944
- },
945
- async createScheduledEvent (guildId, body) {
946
- return await rest.post(rest.routes.guilds.events.events(guildId), {
947
- body
948
- });
949
- },
950
- async createStageInstance (body) {
951
- return await rest.post(rest.routes.channels.stages(), {
952
- body
953
- });
954
- },
955
- async createWebhook (channelId, options, reason) {
956
- return await rest.post(rest.routes.channels.webhooks(channelId), {
957
- body: {
958
- name: options.name,
959
- avatar: options.avatar ? await urlToBase64(options.avatar) : undefined
960
- },
961
- reason
962
- });
963
- },
964
- async deleteAutomodRule (guildId, ruleId, reason) {
965
- await rest.delete(rest.routes.guilds.automod.rule(guildId, ruleId), {
966
- reason
967
- });
968
- },
969
- async deleteChannel (channelId, reason) {
970
- await rest.delete(rest.routes.channels.channel(channelId), {
971
- reason
972
- });
973
- },
974
- async deleteChannelPermissionOverride (channelId, overwriteId, reason) {
975
- await rest.delete(rest.routes.channels.overwrite(channelId, overwriteId), {
976
- reason
977
- });
978
- },
979
- async deleteEmoji (guildId, id, reason) {
980
- await rest.delete(rest.routes.guilds.emoji(guildId, id), {
981
- reason
982
- });
983
- },
984
- async deleteFollowupMessage (token, messageId) {
985
- await rest.delete(rest.routes.interactions.responses.message(rest.applicationId, token, messageId));
986
- },
987
- async deleteGlobalApplicationCommand (commandId) {
988
- await rest.delete(rest.routes.interactions.commands.command(rest.applicationId, commandId));
989
- },
990
- async deleteGuild (guildId) {
991
- await rest.delete(rest.routes.guilds.guild(guildId));
992
- },
993
- async deleteGuildApplicationCommand (commandId, guildId) {
994
- await rest.delete(rest.routes.interactions.commands.guilds.one(rest.applicationId, guildId, commandId));
995
- },
996
- async deleteGuildSticker (guildId, stickerId, reason) {
997
- await rest.delete(rest.routes.guilds.sticker(guildId, stickerId), {
998
- reason
999
- });
1000
- },
1001
- async deleteGuildTemplate (guildId, templateCode) {
1002
- await rest.delete(rest.routes.guilds.templates.guild(guildId, templateCode));
1003
- },
1004
- async deleteIntegration (guildId, integrationId) {
1005
- await rest.delete(rest.routes.guilds.integration(guildId, integrationId));
1006
- },
1007
- async deleteInvite (inviteCode, reason) {
1008
- await rest.delete(rest.routes.guilds.invite(inviteCode), {
1009
- reason
1010
- });
1011
- },
1012
- async deleteMessage (channelId, messageId, reason) {
1013
- await rest.delete(rest.routes.channels.message(channelId, messageId), {
1014
- reason
1015
- });
1016
- },
1017
- async deleteMessages (channelId, messageIds, reason) {
1018
- await rest.post(rest.routes.channels.bulk(channelId), {
1019
- body: {
1020
- messages: messageIds.slice(0, 100).map((id)=>id.toString())
1021
- },
1022
- reason
1023
- });
1024
- },
1025
- async deleteOriginalInteractionResponse (token) {
1026
- await rest.delete(rest.routes.interactions.responses.original(rest.applicationId, token));
1027
- },
1028
- async deleteOwnReaction (channelId, messageId, reaction) {
1029
- reaction = processReactionString(reaction);
1030
- await rest.delete(rest.routes.channels.reactions.bot(channelId, messageId, reaction));
1031
- },
1032
- async deleteReactionsAll (channelId, messageId) {
1033
- await rest.delete(rest.routes.channels.reactions.all(channelId, messageId));
1034
- },
1035
- async deleteReactionsEmoji (channelId, messageId, reaction) {
1036
- reaction = processReactionString(reaction);
1037
- await rest.delete(rest.routes.channels.reactions.emoji(channelId, messageId, reaction));
1038
- },
1039
- async deleteRole (guildId, roleId) {
1040
- await rest.delete(rest.routes.guilds.roles.one(guildId, roleId));
1041
- },
1042
- async deleteScheduledEvent (guildId, eventId) {
1043
- await rest.delete(rest.routes.guilds.events.event(guildId, eventId));
1044
- },
1045
- async deleteStageInstance (channelId, reason) {
1046
- await rest.delete(rest.routes.channels.stage(channelId), {
1047
- reason
1048
- });
1049
- },
1050
- async deleteUserReaction (channelId, messageId, userId, reaction) {
1051
- reaction = processReactionString(reaction);
1052
- await rest.delete(rest.routes.channels.reactions.user(channelId, messageId, reaction, userId));
1053
- },
1054
- async deleteWebhook (webhookId, reason) {
1055
- await rest.delete(rest.routes.webhooks.id(webhookId), {
1056
- reason
1057
- });
1058
- },
1059
- async deleteWebhookMessage (webhookId, token, messageId, options) {
1060
- await rest.delete(rest.routes.webhooks.message(webhookId, token, messageId, options));
1061
- },
1062
- async deleteWebhookWithToken (webhookId, token) {
1063
- await rest.delete(rest.routes.webhooks.webhook(webhookId, token));
1064
- },
1065
- async editApplicationCommandPermissions (guildId, commandId, bearerToken, permissions) {
1066
- return await rest.put(rest.routes.interactions.commands.permission(rest.applicationId, guildId, commandId), {
1067
- body: {
1068
- permissions
1069
- },
1070
- headers: {
1071
- authorization: `Bearer ${bearerToken}`
1072
- }
1073
- });
1074
- },
1075
- async editAutomodRule (guildId, ruleId, body) {
1076
- return await rest.patch(rest.routes.guilds.automod.rule(guildId, ruleId), {
1077
- body
1078
- });
1079
- },
1080
- async editBotProfile (options) {
1081
- const avatar = options?.botAvatarURL ? await urlToBase64(options?.botAvatarURL) : options?.botAvatarURL;
1082
- return await rest.patch(rest.routes.userBot(), {
1083
- body: {
1084
- username: options.username?.trim(),
1085
- avatar
1086
- }
1087
- });
1088
- },
1089
- async editChannel (channelId, body) {
1090
- return await rest.patch(rest.routes.channels.channel(channelId), {
1091
- body
1092
- });
1093
- },
1094
- async editChannelPermissionOverrides (channelId, body) {
1095
- await rest.put(rest.routes.channels.overwrite(channelId, body.id), {
1096
- body
1097
- });
1098
- },
1099
- async editChannelPositions (guildId, body) {
1100
- await rest.patch(rest.routes.guilds.channels(guildId), {
1101
- body
1102
- });
1103
- },
1104
- async editEmoji (guildId, id, body) {
1105
- return await rest.patch(rest.routes.guilds.emoji(guildId, id), {
1106
- body
1107
- });
1108
- },
1109
- async editFollowupMessage (token, messageId, body) {
1110
- return await rest.patch(rest.routes.interactions.responses.message(rest.applicationId, token, messageId), {
1111
- body,
1112
- files: body.files
1113
- });
1114
- },
1115
- async editGlobalApplicationCommand (commandId, body) {
1116
- return await rest.patch(rest.routes.interactions.commands.command(rest.applicationId, commandId), {
1117
- body
1118
- });
1119
- },
1120
- async editGuild (guildId, body) {
1121
- return await rest.patch(rest.routes.guilds.guild(guildId), {
1122
- body
1123
- });
1124
- },
1125
- async editGuildApplicationCommand (commandId, guildId, body) {
1126
- return await rest.patch(rest.routes.interactions.commands.guilds.one(rest.applicationId, guildId, commandId), {
1127
- body
1128
- });
1129
- },
1130
- async editGuildMfaLevel (guildId, mfaLevel, reason) {
1131
- await rest.post(rest.routes.guilds.mfa(guildId), {
1132
- body: {
1133
- level: mfaLevel
1134
- },
1135
- reason
1136
- });
1137
- },
1138
- async editGuildSticker (guildId, stickerId, body) {
1139
- return await rest.patch(rest.routes.guilds.sticker(guildId, stickerId), {
1140
- body
1141
- });
1142
- },
1143
- async editGuildTemplate (guildId, templateCode, body) {
1144
- return await rest.patch(rest.routes.guilds.templates.guild(guildId, templateCode), {
1145
- body
1146
- });
1147
- },
1148
- async editMessage (channelId, messageId, body) {
1149
- return await rest.patch(rest.routes.channels.message(channelId, messageId), {
1150
- body
1151
- });
1152
- },
1153
- async editOriginalInteractionResponse (token, body) {
1154
- return await rest.patch(rest.routes.interactions.responses.original(rest.applicationId, token), {
1155
- body,
1156
- files: body.files
1157
- });
1158
- },
1159
- async editOriginalWebhookMessage (webhookId, token, options) {
1160
- return await rest.patch(rest.routes.webhooks.original(webhookId, token, options), {
1161
- body: {
1162
- type: InteractionResponseTypes.UpdateMessage,
1163
- data: options
1164
- },
1165
- files: options.files
1166
- });
1167
- },
1168
- async editOwnVoiceState (guildId, options) {
1169
- await rest.patch(rest.routes.guilds.voice(guildId), {
1170
- body: {
1171
- ...options,
1172
- request_to_speak_timestamp: options.requestToSpeakTimestamp ? new Date(options.requestToSpeakTimestamp).toISOString() : options.requestToSpeakTimestamp
1173
- }
1174
- });
1175
- },
1176
- async editScheduledEvent (guildId, eventId, body) {
1177
- return await rest.patch(rest.routes.guilds.events.event(guildId, eventId), {
1178
- body
1179
- });
1180
- },
1181
- async editRole (guildId, roleId, body) {
1182
- return await rest.patch(rest.routes.guilds.roles.one(guildId, roleId), {
1183
- body
1184
- });
1185
- },
1186
- async editRolePositions (guildId, body) {
1187
- return await rest.patch(rest.routes.guilds.roles.all(guildId), {
1188
- body
1189
- });
1190
- },
1191
- async editStageInstance (channelId, topic, reason) {
1192
- return await rest.patch(rest.routes.channels.stage(channelId), {
1193
- body: {
1194
- topic
1195
- },
1196
- reason
1197
- });
1198
- },
1199
- async editUserVoiceState (guildId, options) {
1200
- await rest.patch(rest.routes.guilds.voice(guildId, options.userId), {
1201
- body: options
1202
- });
1203
- },
1204
- async editWebhook (webhookId, body) {
1205
- return await rest.patch(rest.routes.webhooks.id(webhookId), {
1206
- body
1207
- });
1208
- },
1209
- async editWebhookMessage (webhookId, token, messageId, options) {
1210
- return await rest.patch(rest.routes.webhooks.message(webhookId, token, messageId, options), {
1211
- body: options,
1212
- files: options.files
1213
- });
1214
- },
1215
- async editWebhookWithToken (webhookId, token, body) {
1216
- return await rest.patch(rest.routes.webhooks.webhook(webhookId, token), {
1217
- body
1218
- });
1219
- },
1220
- async editWelcomeScreen (guildId, body) {
1221
- return await rest.patch(rest.routes.guilds.welcome(guildId), {
1222
- body
1223
- });
1224
- },
1225
- async editWidgetSettings (guildId, body) {
1226
- return await rest.patch(rest.routes.guilds.widget(guildId), {
1227
- body
1228
- });
1229
- },
1230
- async executeWebhook (webhookId, token, options) {
1231
- return await rest.post(rest.routes.webhooks.webhook(webhookId, token, options), {
1232
- body: options
1233
- });
1234
- },
1235
- async followAnnouncement (sourceChannelId, targetChannelId) {
1236
- return await rest.post(rest.routes.channels.follow(sourceChannelId), {
1237
- body: {
1238
- webhook_channel_id: targetChannelId
1239
- }
1240
- });
1241
- },
1242
- async getActiveThreads (guildId) {
1243
- return await rest.get(rest.routes.channels.threads.active(guildId));
1244
- },
1245
- async getApplicationCommandPermission (guildId, commandId) {
1246
- return await rest.get(rest.routes.interactions.commands.permission(rest.applicationId, guildId, commandId));
1247
- },
1248
- async getApplicationCommandPermissions (guildId) {
1249
- return await rest.get(rest.routes.interactions.commands.permissions(rest.applicationId, guildId));
1250
- },
1251
- async getApplicationInfo () {
1252
- return await rest.get(rest.routes.oauth2Application());
1253
- },
1254
- async getAuditLog (guildId, options) {
1255
- return await rest.get(rest.routes.guilds.auditlogs(guildId, options));
1256
- },
1257
- async getAutomodRule (guildId, ruleId) {
1258
- return await rest.get(rest.routes.guilds.automod.rule(guildId, ruleId));
1259
- },
1260
- async getAutomodRules (guildId) {
1261
- return await rest.get(rest.routes.guilds.automod.rules(guildId));
1262
- },
1263
- async getAvailableVoiceRegions () {
1264
- return await rest.get(rest.routes.regions());
1265
- },
1266
- async getBan (guildId, userId) {
1267
- return await rest.get(rest.routes.guilds.members.ban(guildId, userId));
1268
- },
1269
- async getBans (guildId, options) {
1270
- return await rest.get(rest.routes.guilds.members.bans(guildId, options));
1271
- },
1272
- async getChannel (id) {
1273
- return await rest.get(rest.routes.channels.channel(id));
1274
- },
1275
- async getChannelInvites (channelId) {
1276
- return await rest.get(rest.routes.channels.invites(channelId));
1277
- },
1278
- async getChannels (guildId) {
1279
- return await rest.get(rest.routes.guilds.channels(guildId));
1280
- },
1281
- async getChannelWebhooks (channelId) {
1282
- return await rest.get(rest.routes.channels.webhooks(channelId));
1283
- },
1284
- async getDmChannel (userId) {
1285
- return await rest.post(rest.routes.channels.dm(), {
1286
- body: {
1287
- recipient_id: userId
1288
- }
1289
- });
1290
- },
1291
- async getEmoji (guildId, emojiId) {
1292
- return await rest.get(rest.routes.guilds.emoji(guildId, emojiId));
1293
- },
1294
- async getEmojis (guildId) {
1295
- return await rest.get(rest.routes.guilds.emojis(guildId));
1296
- },
1297
- async getFollowupMessage (token, messageId) {
1298
- return await rest.get(rest.routes.interactions.responses.message(rest.applicationId, token, messageId));
1299
- },
1300
- async getGatewayBot () {
1301
- return await rest.get(rest.routes.gatewayBot());
1302
- },
1303
- async getGlobalApplicationCommand (commandId) {
1304
- return await rest.get(rest.routes.interactions.commands.command(rest.applicationId, commandId));
1305
- },
1306
- async getGlobalApplicationCommands () {
1307
- return await rest.get(rest.routes.interactions.commands.commands(rest.applicationId));
1308
- },
1309
- async getGuild (guildId, options = {
1310
- counts: true
1311
- }) {
1312
- return await rest.get(rest.routes.guilds.guild(guildId, options.counts));
1313
- },
1314
- async getGuildApplicationCommand (commandId, guildId) {
1315
- return await rest.get(rest.routes.interactions.commands.guilds.one(rest.applicationId, guildId, commandId));
1316
- },
1317
- async getGuildApplicationCommands (guildId) {
1318
- return await rest.get(rest.routes.interactions.commands.guilds.all(rest.applicationId, guildId));
1319
- },
1320
- async getGuildPreview (guildId) {
1321
- return await rest.get(rest.routes.guilds.preview(guildId));
1322
- },
1323
- async getGuildTemplate (templateCode) {
1324
- return await rest.get(rest.routes.guilds.templates.code(templateCode));
1325
- },
1326
- async getGuildTemplates (guildId) {
1327
- return await rest.get(rest.routes.guilds.templates.all(guildId));
1328
- },
1329
- async getGuildWebhooks (guildId) {
1330
- return await rest.get(rest.routes.guilds.webhooks(guildId));
1331
- },
1332
- async getIntegrations (guildId) {
1333
- return await rest.get(rest.routes.guilds.integrations(guildId));
1334
- },
1335
- async getInvite (inviteCode, options) {
1336
- return await rest.get(rest.routes.guilds.invite(inviteCode, options));
1337
- },
1338
- async getInvites (guildId) {
1339
- return await rest.get(rest.routes.guilds.invites(guildId));
1340
- },
1341
- async getMessage (channelId, messageId) {
1342
- return await rest.get(rest.routes.channels.message(channelId, messageId));
1343
- },
1344
- async getMessages (channelId, options) {
1345
- return await rest.get(rest.routes.channels.messages(channelId, options));
1346
- },
1347
- async getNitroStickerPacks () {
1348
- return await rest.get(rest.routes.nitroStickerPacks());
1349
- },
1350
- async getOriginalInteractionResponse (token) {
1351
- return await rest.get(rest.routes.interactions.responses.original(rest.applicationId, token));
1352
- },
1353
- async getPinnedMessages (channelId) {
1354
- return await rest.get(rest.routes.channels.pins(channelId));
1355
- },
1356
- async getPrivateArchivedThreads (channelId, options) {
1357
- return await rest.get(rest.routes.channels.threads.private(channelId, options));
1358
- },
1359
- async getPrivateJoinedArchivedThreads (channelId, options) {
1360
- return await rest.get(rest.routes.channels.threads.joined(channelId, options));
1361
- },
1362
- async getPruneCount (guildId, options) {
1363
- return await rest.get(rest.routes.guilds.prune(guildId, options));
1364
- },
1365
- async getPublicArchivedThreads (channelId, options) {
1366
- return await rest.get(rest.routes.channels.threads.public(channelId, options));
1367
- },
1368
- async getRoles (guildId) {
1369
- return await rest.get(rest.routes.guilds.roles.all(guildId));
1370
- },
1371
- async getScheduledEvent (guildId, eventId, options) {
1372
- return await rest.get(rest.routes.guilds.events.event(guildId, eventId, options?.withUserCount));
1373
- },
1374
- async getScheduledEvents (guildId, options) {
1375
- return await rest.get(rest.routes.guilds.events.events(guildId, options?.withUserCount));
1376
- },
1377
- async getScheduledEventUsers (guildId, eventId, options) {
1378
- return await rest.get(rest.routes.guilds.events.users(guildId, eventId, options));
1379
- },
1380
- async getSessionInfo () {
1381
- return await rest.getGatewayBot();
1382
- },
1383
- async getStageInstance (channelId) {
1384
- return await rest.get(rest.routes.channels.stage(channelId));
1385
- },
1386
- async getSticker (stickerId) {
1387
- return await rest.get(rest.routes.sticker(stickerId));
1388
- },
1389
- async getGuildSticker (guildId, stickerId) {
1390
- return await rest.get(rest.routes.guilds.sticker(guildId, stickerId));
1391
- },
1392
- async getGuildStickers (guildId) {
1393
- return await rest.get(rest.routes.guilds.stickers(guildId));
1394
- },
1395
- async getThreadMember (channelId, userId) {
1396
- return await rest.get(rest.routes.channels.threads.user(channelId, userId));
1397
- },
1398
- async getThreadMembers (channelId) {
1399
- return await rest.get(rest.routes.channels.threads.members(channelId));
1400
- },
1401
- async getReactions (channelId, messageId, reaction, options) {
1402
- return await rest.get(rest.routes.channels.reactions.message(channelId, messageId, reaction, options));
1403
- },
1404
- async getUser (id) {
1405
- return await rest.get(rest.routes.user(id));
1406
- },
1407
- async getVanityUrl (guildId) {
1408
- return await rest.get(rest.routes.guilds.vanity(guildId));
1409
- },
1410
- async getVoiceRegions (guildId) {
1411
- return await rest.get(rest.routes.guilds.regions(guildId));
1412
- },
1413
- async getWebhook (webhookId) {
1414
- return await rest.get(rest.routes.webhooks.id(webhookId));
1415
- },
1416
- async getWebhookMessage (webhookId, token, messageId, options) {
1417
- return await rest.get(rest.routes.webhooks.message(webhookId, token, messageId, options));
1418
- },
1419
- async getWebhookWithToken (webhookId, token) {
1420
- return await rest.get(rest.routes.webhooks.webhook(webhookId, token));
1421
- },
1422
- async getWelcomeScreen (guildId) {
1423
- return await rest.get(rest.routes.guilds.welcome(guildId));
1424
- },
1425
- async getWidget (guildId) {
1426
- return await rest.get(rest.routes.guilds.widgetJson(guildId));
1427
- },
1428
- async getWidgetSettings (guildId) {
1429
- return await rest.get(rest.routes.guilds.widget(guildId));
1430
- },
1431
- async joinThread (channelId) {
1432
- await rest.put(rest.routes.channels.threads.me(channelId));
1433
- },
1434
- async leaveGuild (guildId) {
1435
- await rest.delete(rest.routes.guilds.leave(guildId));
1436
- },
1437
- async leaveThread (channelId) {
1438
- await rest.delete(rest.routes.channels.threads.me(channelId));
1439
- },
1440
- async publishMessage (channelId, messageId) {
1441
- return await rest.post(rest.routes.channels.crosspost(channelId, messageId));
1442
- },
1443
- async removeRole (guildId, userId, roleId, reason) {
1444
- await rest.delete(rest.routes.guilds.roles.member(guildId, userId, roleId), {
1445
- reason
1446
- });
1447
- },
1448
- async removeThreadMember (channelId, userId) {
1449
- await rest.delete(rest.routes.channels.threads.user(channelId, userId));
1450
- },
1451
- // TODO: why that
1452
- async sendFollowupMessage (token, options) {
1453
- return await new Promise((resolve, reject)=>{
1454
- rest.sendRequest({
1455
- url: rest.routes.webhooks.webhook(rest.applicationId, token),
1456
- method: 'POST',
1457
- requestBodyOptions: {
1458
- body: options,
1459
- files: options.files
1460
- },
1461
- retryCount: 0,
1462
- retryRequest: async function(options) {
1463
- // TODO: should change to reprocess queue item
1464
- await rest.sendRequest(options);
1465
- },
1466
- resolve: (data)=>{
1467
- resolve(data.status !== 204 ? JSON.parse(data.body ?? '{}') : undefined);
1468
- },
1469
- reject
1470
- });
1471
- });
1472
- },
1473
- // TODO: why that
1474
- async sendInteractionResponse (interactionId, token, options) {
1475
- await new Promise((resolve, reject)=>{
1476
- rest.sendRequest({
1477
- url: rest.routes.interactions.responses.callback(interactionId, token),
1478
- method: 'POST',
1479
- requestBodyOptions: {
1480
- body: options
1481
- },
1482
- retryCount: 0,
1483
- retryRequest: async function(options) {
1484
- // TODO: should change to reprocess queue item
1485
- await rest.sendRequest(options);
1486
- },
1487
- resolve: (data)=>{
1488
- resolve(data.status !== 204 ? JSON.parse(data.body ?? '{}') : undefined);
1489
- },
1490
- reject
1491
- });
1492
- });
1493
- },
1494
- async sendMessage (channelId, body) {
1495
- return await rest.post(rest.routes.channels.messages(channelId), {
1496
- body,
1497
- files: body.files
1498
- });
1499
- },
1500
- async startThreadWithMessage (channelId, messageId, body) {
1501
- return await rest.post(rest.routes.channels.threads.message(channelId, messageId), {
1502
- body
1503
- });
1504
- },
1505
- async startThreadWithoutMessage (channelId, body) {
1506
- return await rest.post(rest.routes.channels.threads.all(channelId), {
1507
- body
1508
- });
1509
- },
1510
- async syncGuildTemplate (guildId) {
1511
- return await rest.put(rest.routes.guilds.templates.all(guildId));
1512
- },
1513
- async banMember (guildId, userId, body) {
1514
- await rest.put(rest.routes.guilds.members.ban(guildId, userId), {
1515
- body
1516
- });
1517
- },
1518
- async editBotMember (guildId, body) {
1519
- return await rest.patch(rest.routes.guilds.members.bot(guildId), {
1520
- body
1521
- });
1522
- },
1523
- async editMember (guildId, userId, body) {
1524
- return await rest.patch(rest.routes.guilds.members.member(guildId, userId), {
1525
- body
1526
- });
1527
- },
1528
- async getMember (guildId, userId) {
1529
- return await rest.get(rest.routes.guilds.members.member(guildId, userId));
1530
- },
1531
- async getMembers (guildId, options) {
1532
- return await rest.get(rest.routes.guilds.members.members(guildId, options));
1533
- },
1534
- async kickMember (guildId, userId, reason) {
1535
- await rest.delete(rest.routes.guilds.members.member(guildId, userId), {
1536
- reason
1537
- });
1538
- },
1539
- async pinMessage (channelId, messageId, reason) {
1540
- await rest.put(rest.routes.channels.pin(channelId, messageId), {
1541
- reason
1542
- });
1543
- },
1544
- async pruneMembers (guildId, body) {
1545
- return await rest.post(rest.routes.guilds.members.prune(guildId), {
1546
- body
1547
- });
1548
- },
1549
- async searchMembers (guildId, query, options) {
1550
- return await rest.get(rest.routes.guilds.members.search(guildId, query, options));
1551
- },
1552
- async unbanMember (guildId, userId) {
1553
- await rest.delete(rest.routes.guilds.members.ban(guildId, userId));
1554
- },
1555
- async unpinMessage (channelId, messageId, reason) {
1556
- await rest.delete(rest.routes.channels.pin(channelId, messageId), {
1557
- reason
1558
- });
1559
- },
1560
- async triggerTypingIndicator (channelId) {
1561
- await rest.post(rest.routes.channels.typing(channelId));
1562
- },
1563
- async upsertGlobalApplicationCommands (body) {
1564
- return await rest.put(rest.routes.interactions.commands.commands(rest.applicationId), {
1565
- body
1566
- });
1567
- },
1568
- async upsertGuildApplicationCommands (guildId, body) {
1569
- return await rest.put(rest.routes.interactions.commands.guilds.all(rest.applicationId, guildId), {
1570
- body
1571
- });
1572
- }
1573
- };
1574
- return rest;
1575
- }
1576
-
1577
- //# sourceMappingURL=manager.js.map