@discordeno/rest 19.0.0-next.fe00a6f → 19.0.0-next.ffdef6c

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 (51) 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 +1547 -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 +1505 -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/types/index.d.ts.map +1 -0
  17. package/dist/{invalidBucket.d.ts → types/invalidBucket.d.ts} +5 -0
  18. package/dist/types/invalidBucket.d.ts.map +1 -0
  19. package/dist/types/manager.d.ts.map +1 -0
  20. package/dist/{queue.d.ts → types/queue.d.ts} +12 -1
  21. package/dist/types/queue.d.ts.map +1 -0
  22. package/dist/types/routes.d.ts.map +1 -0
  23. package/dist/{types.d.ts → types/types.d.ts} +808 -317
  24. package/dist/types/types.d.ts.map +1 -0
  25. package/dist/{typings → types/typings}/routes.d.ts +69 -6
  26. package/dist/types/typings/routes.d.ts.map +1 -0
  27. package/package.json +33 -29
  28. package/dist/index.d.ts.map +0 -1
  29. package/dist/index.js +0 -8
  30. package/dist/index.js.map +0 -1
  31. package/dist/invalidBucket.d.ts.map +0 -1
  32. package/dist/invalidBucket.js +0 -82
  33. package/dist/invalidBucket.js.map +0 -1
  34. package/dist/manager.d.ts.map +0 -1
  35. package/dist/manager.js +0 -1139
  36. package/dist/manager.js.map +0 -1
  37. package/dist/queue.d.ts.map +0 -1
  38. package/dist/queue.js +0 -153
  39. package/dist/queue.js.map +0 -1
  40. package/dist/routes.d.ts.map +0 -1
  41. package/dist/routes.js +0 -487
  42. package/dist/routes.js.map +0 -1
  43. package/dist/types.d.ts.map +0 -1
  44. package/dist/types.js +0 -3
  45. package/dist/types.js.map +0 -1
  46. package/dist/typings/routes.d.ts.map +0 -1
  47. package/dist/typings/routes.js +0 -3
  48. package/dist/typings/routes.js.map +0 -1
  49. /package/dist/{index.d.ts → types/index.d.ts} +0 -0
  50. /package/dist/{manager.d.ts → types/manager.d.ts} +0 -0
  51. /package/dist/{routes.d.ts → types/routes.d.ts} +0 -0
package/dist/manager.js DELETED
@@ -1,1139 +0,0 @@
1
- /* eslint-disable @typescript-eslint/restrict-template-expressions */ /* eslint-disable no-const-assign */ import { calculateBits, camelToSnakeCase, camelize, delay, getBotIdFromToken, logger, processReactionString, urlToBase64 } from '@discordeno/utils';
2
- import { createInvalidRequestBucket } from './invalidBucket.js';
3
- import { Queue } from './queue.js';
4
- import { InteractionResponseTypes } from '@discordeno/types';
5
- import { createRoutes } from './routes.js';
6
- // TODO: make dynamic based on package.json file
7
- const version = '19.0.0-alpha.1';
8
- export const DISCORD_API_VERSION = 10;
9
- export const DISCORD_API_URL = 'https://discord.com/api';
10
- export const AUDIT_LOG_REASON_HEADER = 'x-audit-log-reason';
11
- export const RATE_LIMIT_REMAINING_HEADER = 'x-ratelimit-remaining';
12
- export const RATE_LIMIT_RESET_AFTER_HEADER = 'x-ratelimit-reset-after';
13
- export const RATE_LIMIT_GLOBAL_HEADER = 'x-ratelimit-global';
14
- export const RATE_LIMIT_BUCKET_HEADER = 'x-ratelimit-bucket';
15
- export const RATE_LIMIT_LIMIT_HEADER = 'x-ratelimit-limit';
16
- export const RATE_LIMIT_SCOPE_HEADER = 'x-ratelimit-scope';
17
- export function createRestManager(options) {
18
- const applicationId = options.applicationId ? BigInt(options.applicationId) : options.token ? getBotIdFromToken(options.token) : undefined;
19
- if (!applicationId) {
20
- throw new Error('`applicationId` was not provided and was not able to extract the id from the bots token. Please explicitly pass `applicationId` to the rest manager.');
21
- }
22
- const baseUrl = options.proxy?.baseUrl ?? DISCORD_API_URL;
23
- const rest = {
24
- applicationId,
25
- authorization: options.proxy?.authorization,
26
- baseUrl,
27
- deleteQueueDelay: 60000,
28
- globallyRateLimited: false,
29
- invalidBucket: createInvalidRequestBucket({}),
30
- isProxied: !baseUrl.startsWith(DISCORD_API_URL),
31
- maxRetryCount: Infinity,
32
- processingRateLimitedPaths: false,
33
- queues: new Map(),
34
- rateLimitedPaths: new Map(),
35
- token: options.token,
36
- version: options.version ?? DISCORD_API_VERSION,
37
- routes: createRoutes(),
38
- checkRateLimits (url) {
39
- const ratelimited = rest.rateLimitedPaths.get(url);
40
- const global = rest.rateLimitedPaths.get('global');
41
- const now = Date.now();
42
- if (ratelimited && now < ratelimited.resetTimestamp) {
43
- return ratelimited.resetTimestamp - now;
44
- }
45
- if (global && now < global.resetTimestamp) {
46
- return global.resetTimestamp - now;
47
- }
48
- return false;
49
- },
50
- changeToDiscordFormat (obj) {
51
- if (obj === null) return null;
52
- if (typeof obj === 'object') {
53
- if (Array.isArray(obj)) {
54
- return obj.map((item)=>rest.changeToDiscordFormat(item));
55
- }
56
- const newObj = {};
57
- for (const key of Object.keys(obj)){
58
- const value = obj[key];
59
- // Some falsy values should be allowed like null or 0
60
- if (value !== undefined) {
61
- switch(key){
62
- case 'permissions':
63
- case 'allow':
64
- case 'deny':
65
- newObj[key] = calculateBits(value);
66
- continue;
67
- case 'defaultMemberPermissions':
68
- newObj.default_member_permissions = calculateBits(value);
69
- continue;
70
- case 'nameLocalizations':
71
- newObj.name_localizations = value;
72
- continue;
73
- case 'descriptionLocalizations':
74
- newObj.description_localizations = value;
75
- continue;
76
- }
77
- }
78
- newObj[camelToSnakeCase(key)] = rest.changeToDiscordFormat(value);
79
- }
80
- return newObj;
81
- }
82
- if (typeof obj === 'bigint') return obj.toString();
83
- return obj;
84
- },
85
- createRequestBody (method, options) {
86
- const headers = {
87
- 'user-agent': `DiscordBot (https://github.com/discordeno/discordeno, v${version})`
88
- };
89
- if (options?.unauthorized !== false) headers.authorization = `Bot ${rest.token}`;
90
- // IF A REASON IS PROVIDED ENCODE IT IN HEADERS
91
- if (options?.reason !== undefined) {
92
- headers[AUDIT_LOG_REASON_HEADER] = encodeURIComponent(options?.reason);
93
- }
94
- let body;
95
- // TODO: check if we need to add specific check for GET method
96
- // Since GET does not allow bodies
97
- // Have to check for attachments first, since body then has to be send in a different way.
98
- if (options?.files !== undefined) {
99
- const form = new FormData();
100
- for(let i = 0; i < options.files.length; ++i){
101
- form.append(`file${i}`, options.files[i].blob, options.files[i].name);
102
- }
103
- form.append('payload_json', JSON.stringify({
104
- ...options.body,
105
- files: undefined
106
- }));
107
- body = form;
108
- // No need to set the `content-type` header since `fetch` does that automatically for us when we use a `FormData` object.
109
- } else if (options?.body !== undefined) {
110
- if (options.body instanceof FormData) {
111
- body = options.body;
112
- // No need to set the `content-type` header since `fetch` does that automatically for us when we use a `FormData` object.
113
- } else {
114
- body = JSON.stringify(rest.changeToDiscordFormat(options.body));
115
- headers['content-type'] = `application/json`;
116
- }
117
- }
118
- // SOMETIMES SPECIAL HEADERS (E.G. CUSTOM AUTHORIZATION) NEED TO BE USED
119
- if (options?.headers) {
120
- Object.assign(headers, options.headers);
121
- }
122
- return {
123
- body,
124
- headers,
125
- method
126
- };
127
- },
128
- processRateLimitedPaths () {
129
- const now = Date.now();
130
- for (const [key, value] of rest.rateLimitedPaths.entries()){
131
- // rest.debug(
132
- // `[REST - processRateLimitedPaths] Running for of loop. ${
133
- // value.resetTimestamp - now
134
- // }`
135
- // )
136
- // If the time has not reached cancel
137
- if (value.resetTimestamp > now) continue;
138
- // Rate limit is over, delete the rate limiter
139
- rest.rateLimitedPaths.delete(key);
140
- // If it was global, also mark the global value as false
141
- if (key === 'global') rest.globallyRateLimited = false;
142
- }
143
- // ALL PATHS ARE CLEARED CAN CANCEL OUT!
144
- if (rest.rateLimitedPaths.size === 0) {
145
- rest.processingRateLimitedPaths = false;
146
- } else {
147
- rest.processingRateLimitedPaths = true;
148
- // RECHECK IN 1 SECOND
149
- setTimeout(()=>{
150
- // rest.debug('[REST - processRateLimitedPaths] Running setTimeout.')
151
- rest.processRateLimitedPaths();
152
- }, 1000);
153
- }
154
- },
155
- /** Processes the rate limit headers and determines if it needs to be rate limited and returns the bucket id if available */ processHeaders (url, headers) {
156
- let rateLimited = false;
157
- // GET ALL NECESSARY HEADERS
158
- const remaining = headers.get(RATE_LIMIT_REMAINING_HEADER);
159
- const retryAfter = headers.get(RATE_LIMIT_RESET_AFTER_HEADER);
160
- const reset = Date.now() + Number(retryAfter) * 1000;
161
- const global = headers.get(RATE_LIMIT_GLOBAL_HEADER);
162
- // undefined override null needed for typings
163
- const bucketId = headers.get(RATE_LIMIT_BUCKET_HEADER) ?? undefined;
164
- const limit = headers.get(RATE_LIMIT_LIMIT_HEADER);
165
- rest.queues.get(url)?.handleCompletedRequest({
166
- remaining: remaining ? Number(remaining) : undefined,
167
- interval: retryAfter ? Number(retryAfter) * 1000 : undefined,
168
- max: limit ? Number(limit) : undefined
169
- });
170
- // IF THERE IS NO REMAINING RATE LIMIT, MARK IT AS RATE LIMITED
171
- if (remaining === '0') {
172
- rateLimited = true;
173
- // SAVE THE URL AS LIMITED, IMPORTANT FOR NEW REQUESTS BY USER WITHOUT BUCKET
174
- rest.rateLimitedPaths.set(url, {
175
- url,
176
- resetTimestamp: reset,
177
- bucketId
178
- });
179
- // SAVE THE BUCKET AS LIMITED SINCE DIFFERENT URLS MAY SHARE A BUCKET
180
- if (bucketId) {
181
- rest.rateLimitedPaths.set(bucketId, {
182
- url,
183
- resetTimestamp: reset,
184
- bucketId
185
- });
186
- }
187
- }
188
- // IF THERE IS NO REMAINING GLOBAL LIMIT, MARK IT RATE LIMITED GLOBALLY
189
- if (global) {
190
- const retryAfter = headers.get('retry-after');
191
- const globalReset = Date.now() + Number(retryAfter) * 1000;
192
- // rest.debug(
193
- // `[REST = Globally Rate Limited] URL: ${url} | Global Rest: ${globalReset}`
194
- // )
195
- rest.globallyRateLimited = true;
196
- rateLimited = true;
197
- setTimeout(()=>{
198
- rest.globallyRateLimited = false;
199
- }, globalReset);
200
- rest.rateLimitedPaths.set('global', {
201
- url: 'global',
202
- resetTimestamp: globalReset,
203
- bucketId
204
- });
205
- if (bucketId) {
206
- rest.rateLimitedPaths.set(bucketId, {
207
- url: 'global',
208
- resetTimestamp: globalReset,
209
- bucketId
210
- });
211
- }
212
- }
213
- if (rateLimited && !rest.processingRateLimitedPaths) {
214
- rest.processRateLimitedPaths();
215
- }
216
- return rateLimited ? bucketId : undefined;
217
- },
218
- async sendRequest (options) {
219
- const url = `${rest.baseUrl}/v${rest.version}${options.route}`;
220
- const payload = rest.createRequestBody(options.method, options.requestBodyOptions);
221
- logger.debug(`sending request to ${url}`, 'with payload:', {
222
- ...payload,
223
- headers: {
224
- ...payload.headers,
225
- authorization: 'Bot tokenhere'
226
- }
227
- });
228
- const response = await fetch(url, payload).catch(async (error)=>{
229
- logger.error(error);
230
- // Mark request and completed
231
- rest.invalidBucket.handleCompletedRequest(999, false);
232
- options.reject({
233
- ok: false,
234
- status: 999,
235
- error: 'Possible network or request shape issue occurred. If this is rare, its a network glitch. If it occurs a lot something is wrong.'
236
- });
237
- throw error;
238
- });
239
- logger.debug(`request fetched from ${url} with status ${response.status} & ${response.statusText}`);
240
- // Mark request and completed
241
- rest.invalidBucket.handleCompletedRequest(response.status, response.headers.get(RATE_LIMIT_SCOPE_HEADER) === 'shared');
242
- // Set the bucket id if it was available on the headers
243
- const bucketId = rest.processHeaders(rest.simplifyUrl(options.route, options.method), response.headers);
244
- if (bucketId) options.bucketId = bucketId;
245
- if (response.status < 200 || response.status >= 400) {
246
- logger.debug(`Request to ${url} failed.`);
247
- if (response.status !== 429) {
248
- options.reject({
249
- ok: false,
250
- status: response.status,
251
- body: await response.text()
252
- });
253
- return;
254
- }
255
- logger.debug(`Request to ${url} was ratelimited.`);
256
- // Too many attempts, get rid of request from queue.
257
- if (options.retryCount >= rest.maxRetryCount) {
258
- logger.debug(`Request to ${url} exceeded the maximum allowed retries.`, 'with payload:', payload);
259
- // rest.debug(`[REST - RetriesMaxed] ${JSON.stringify(options)}`)
260
- options.reject({
261
- ok: false,
262
- status: response.status,
263
- error: 'The request was rate limited and it maxed out the retries limit.'
264
- });
265
- return;
266
- }
267
- options.retryCount += 1;
268
- const resetAfter = response.headers.get(RATE_LIMIT_RESET_AFTER_HEADER);
269
- if (resetAfter) await delay(Number(resetAfter) * 1000);
270
- // process the response to prevent mem leak
271
- await response.arrayBuffer();
272
- return await options.retryRequest?.(options);
273
- }
274
- // Discord sometimes sends no response with no content.
275
- options.resolve({
276
- ok: true,
277
- status: response.status,
278
- body: response.status === 204 ? undefined : await response.text()
279
- });
280
- },
281
- simplifyUrl (url, method) {
282
- const parts = url.split('/');
283
- const secondLastPart = parts[parts.length - 2];
284
- if (secondLastPart === 'channels' || secondLastPart === 'guilds') {
285
- return url;
286
- }
287
- if (secondLastPart === 'reactions' || parts[parts.length - 1] === '@me') {
288
- parts.splice(-2);
289
- parts.push('reactions');
290
- } else {
291
- parts.splice(-1);
292
- parts.push('x');
293
- }
294
- if (parts[parts.length - 3] === 'reactions') {
295
- parts.splice(-2);
296
- }
297
- if (method === 'DELETE' && secondLastPart === 'messages') {
298
- return `D${parts.join('/')}`;
299
- }
300
- return parts.join('/');
301
- },
302
- async processRequest (request) {
303
- const url = rest.simplifyUrl(request.route, request.method);
304
- if (request.runThroughQueue === false) {
305
- await rest.sendRequest(request);
306
- return;
307
- }
308
- const queue = rest.queues.get(url);
309
- if (queue !== undefined) {
310
- queue.makeRequest(request);
311
- } else {
312
- // CREATES A NEW QUEUE
313
- const bucketQueue = new Queue(rest, {
314
- url,
315
- deleteQueueDelay: rest.deleteQueueDelay
316
- });
317
- // Add request to queue
318
- bucketQueue.makeRequest(request);
319
- // Save queue
320
- rest.queues.set(url, bucketQueue);
321
- }
322
- },
323
- async makeRequest (method, route, options) {
324
- if (rest.isProxied) {
325
- if (rest.authorization !== undefined) {
326
- options ??= {};
327
- options.headers ??= {};
328
- options.headers.authorization = rest.authorization;
329
- }
330
- const result = await fetch(`${rest.baseUrl}/v${rest.version}${route}`, rest.createRequestBody(method, options));
331
- if (!result.ok) {
332
- const err = await result.json().catch(()=>{});
333
- // Legacy Handling to not break old code or when body is missing
334
- if (!err?.body) throw new Error(`Error: ${err.message ?? result.statusText}`);
335
- throw new Error(JSON.stringify(err));
336
- }
337
- return result.status !== 204 ? await result.json() : undefined;
338
- }
339
- // eslint-disable-next-line no-async-promise-executor
340
- return await new Promise(async (resolve, reject)=>{
341
- const payload = {
342
- route,
343
- method,
344
- requestBodyOptions: options,
345
- retryCount: 0,
346
- retryRequest: async function(payload) {
347
- await rest.processRequest(payload);
348
- },
349
- resolve: (data)=>{
350
- resolve(data.status !== 204 ? JSON.parse(data.body ?? '{}') : undefined);
351
- },
352
- reject,
353
- runThroughQueue: options?.runThroughQueue
354
- };
355
- await rest.processRequest(payload);
356
- });
357
- },
358
- async get (url, options) {
359
- return camelize(await rest.makeRequest('GET', url, options));
360
- },
361
- async post (url, options) {
362
- return camelize(await rest.makeRequest('POST', url, options));
363
- },
364
- async delete (url, options) {
365
- camelize(await rest.makeRequest('DELETE', url, options));
366
- },
367
- async patch (url, options) {
368
- return camelize(await rest.makeRequest('PATCH', url, options));
369
- },
370
- async put (url, options) {
371
- return camelize(await rest.makeRequest('PUT', url, options));
372
- },
373
- async addReaction (channelId, messageId, reaction) {
374
- reaction = processReactionString(reaction);
375
- await rest.put(rest.routes.channels.reactions.bot(channelId, messageId, reaction));
376
- },
377
- async addReactions (channelId, messageId, reactions, ordered = false) {
378
- if (!ordered) {
379
- await Promise.all(reactions.map(async (reaction)=>{
380
- await rest.addReaction(channelId, messageId, reaction);
381
- }));
382
- return;
383
- }
384
- for (const reaction of reactions){
385
- await rest.addReaction(channelId, messageId, reaction);
386
- }
387
- },
388
- async addRole (guildId, userId, roleId, reason) {
389
- await rest.put(rest.routes.guilds.roles.member(guildId, userId, roleId), {
390
- reason
391
- });
392
- },
393
- async addThreadMember (channelId, userId) {
394
- await rest.put(rest.routes.channels.threads.user(channelId, userId));
395
- },
396
- async createAutomodRule (guildId, body, reason) {
397
- return await rest.post(rest.routes.guilds.automod.rules(guildId), {
398
- body,
399
- reason
400
- });
401
- },
402
- async createChannel (guildId, body, reason) {
403
- return await rest.post(rest.routes.guilds.channels(guildId), {
404
- body,
405
- reason
406
- });
407
- },
408
- async createEmoji (guildId, body, reason) {
409
- return await rest.post(rest.routes.guilds.emojis(guildId), {
410
- body,
411
- reason
412
- });
413
- },
414
- async createGlobalApplicationCommand (body) {
415
- return await rest.post(rest.routes.interactions.commands.commands(rest.applicationId), {
416
- body
417
- });
418
- },
419
- async createGuild (body) {
420
- return await rest.post(rest.routes.guilds.all(), {
421
- body
422
- });
423
- },
424
- async createGuildApplicationCommand (body, guildId) {
425
- return await rest.post(rest.routes.interactions.commands.guilds.all(rest.applicationId, guildId), {
426
- body
427
- });
428
- },
429
- async createGuildFromTemplate (templateCode, body) {
430
- if (body.icon) {
431
- body.icon = await urlToBase64(body.icon);
432
- }
433
- return await rest.post(rest.routes.guilds.templates.code(templateCode), {
434
- body
435
- });
436
- },
437
- async createGuildSticker (guildId, options, reason) {
438
- const form = new FormData();
439
- form.append('file', options.file.blob, options.file.name);
440
- form.append('name', options.name);
441
- form.append('description', options.description);
442
- form.append('tags', options.tags);
443
- return await rest.post(rest.routes.guilds.stickers(guildId), {
444
- body: form,
445
- reason
446
- });
447
- },
448
- async createGuildTemplate (guildId, body) {
449
- return await rest.post(rest.routes.guilds.templates.all(guildId), {
450
- body
451
- });
452
- },
453
- async createForumThread (channelId, body, reason) {
454
- return await rest.post(rest.routes.channels.forum(channelId), {
455
- body,
456
- files: body.files,
457
- reason
458
- });
459
- },
460
- async createInvite (channelId, body = {}, reason) {
461
- return await rest.post(rest.routes.channels.invites(channelId), {
462
- body,
463
- reason
464
- });
465
- },
466
- async createRole (guildId, body, reason) {
467
- return await rest.post(rest.routes.guilds.roles.all(guildId), {
468
- body,
469
- reason
470
- });
471
- },
472
- async createScheduledEvent (guildId, body, reason) {
473
- return await rest.post(rest.routes.guilds.events.events(guildId), {
474
- body,
475
- reason
476
- });
477
- },
478
- async createStageInstance (body, reason) {
479
- return await rest.post(rest.routes.channels.stages(), {
480
- body,
481
- reason
482
- });
483
- },
484
- async createWebhook (channelId, options, reason) {
485
- return await rest.post(rest.routes.channels.webhooks(channelId), {
486
- body: {
487
- name: options.name,
488
- avatar: options.avatar ? await urlToBase64(options.avatar) : undefined
489
- },
490
- reason
491
- });
492
- },
493
- async deleteAutomodRule (guildId, ruleId, reason) {
494
- await rest.delete(rest.routes.guilds.automod.rule(guildId, ruleId), {
495
- reason
496
- });
497
- },
498
- async deleteChannel (channelId, reason) {
499
- await rest.delete(rest.routes.channels.channel(channelId), {
500
- reason
501
- });
502
- },
503
- async deleteChannelPermissionOverride (channelId, overwriteId, reason) {
504
- await rest.delete(rest.routes.channels.overwrite(channelId, overwriteId), {
505
- reason
506
- });
507
- },
508
- async deleteEmoji (guildId, id, reason) {
509
- await rest.delete(rest.routes.guilds.emoji(guildId, id), {
510
- reason
511
- });
512
- },
513
- async deleteFollowupMessage (token, messageId) {
514
- await rest.delete(rest.routes.interactions.responses.message(rest.applicationId, token, messageId), {
515
- unauthorized: true
516
- });
517
- },
518
- async deleteGlobalApplicationCommand (commandId) {
519
- await rest.delete(rest.routes.interactions.commands.command(rest.applicationId, commandId));
520
- },
521
- async deleteGuild (guildId) {
522
- await rest.delete(rest.routes.guilds.guild(guildId));
523
- },
524
- async deleteGuildApplicationCommand (commandId, guildId) {
525
- await rest.delete(rest.routes.interactions.commands.guilds.one(rest.applicationId, guildId, commandId));
526
- },
527
- async deleteGuildSticker (guildId, stickerId, reason) {
528
- await rest.delete(rest.routes.guilds.sticker(guildId, stickerId), {
529
- reason
530
- });
531
- },
532
- async deleteGuildTemplate (guildId, templateCode) {
533
- await rest.delete(rest.routes.guilds.templates.guild(guildId, templateCode));
534
- },
535
- async deleteIntegration (guildId, integrationId, reason) {
536
- await rest.delete(rest.routes.guilds.integration(guildId, integrationId), {
537
- reason
538
- });
539
- },
540
- async deleteInvite (inviteCode, reason) {
541
- await rest.delete(rest.routes.guilds.invite(inviteCode), {
542
- reason
543
- });
544
- },
545
- async deleteMessage (channelId, messageId, reason) {
546
- await rest.delete(rest.routes.channels.message(channelId, messageId), {
547
- reason
548
- });
549
- },
550
- async deleteMessages (channelId, messageIds, reason) {
551
- await rest.post(rest.routes.channels.bulk(channelId), {
552
- body: {
553
- messages: messageIds.slice(0, 100).map((id)=>id.toString())
554
- },
555
- reason
556
- });
557
- },
558
- async deleteOriginalInteractionResponse (token) {
559
- await rest.delete(rest.routes.interactions.responses.original(rest.applicationId, token), {
560
- unauthorized: true
561
- });
562
- },
563
- async deleteOwnReaction (channelId, messageId, reaction) {
564
- reaction = processReactionString(reaction);
565
- await rest.delete(rest.routes.channels.reactions.bot(channelId, messageId, reaction));
566
- },
567
- async deleteReactionsAll (channelId, messageId) {
568
- await rest.delete(rest.routes.channels.reactions.all(channelId, messageId));
569
- },
570
- async deleteReactionsEmoji (channelId, messageId, reaction) {
571
- reaction = processReactionString(reaction);
572
- await rest.delete(rest.routes.channels.reactions.emoji(channelId, messageId, reaction));
573
- },
574
- async deleteRole (guildId, roleId, reason) {
575
- await rest.delete(rest.routes.guilds.roles.one(guildId, roleId), {
576
- reason
577
- });
578
- },
579
- async deleteScheduledEvent (guildId, eventId) {
580
- await rest.delete(rest.routes.guilds.events.event(guildId, eventId));
581
- },
582
- async deleteStageInstance (channelId, reason) {
583
- await rest.delete(rest.routes.channels.stage(channelId), {
584
- reason
585
- });
586
- },
587
- async deleteUserReaction (channelId, messageId, userId, reaction) {
588
- reaction = processReactionString(reaction);
589
- await rest.delete(rest.routes.channels.reactions.user(channelId, messageId, reaction, userId));
590
- },
591
- async deleteWebhook (webhookId, reason) {
592
- await rest.delete(rest.routes.webhooks.id(webhookId), {
593
- reason
594
- });
595
- },
596
- async deleteWebhookMessage (webhookId, token, messageId, options) {
597
- await rest.delete(rest.routes.webhooks.message(webhookId, token, messageId, options));
598
- },
599
- async deleteWebhookWithToken (webhookId, token) {
600
- await rest.delete(rest.routes.webhooks.webhook(webhookId, token));
601
- },
602
- async editApplicationCommandPermissions (guildId, commandId, bearerToken, permissions) {
603
- return await rest.put(rest.routes.interactions.commands.permission(rest.applicationId, guildId, commandId), {
604
- body: {
605
- permissions
606
- },
607
- headers: {
608
- authorization: `Bearer ${bearerToken}`
609
- }
610
- });
611
- },
612
- async editAutomodRule (guildId, ruleId, body, reason) {
613
- return await rest.patch(rest.routes.guilds.automod.rule(guildId, ruleId), {
614
- body,
615
- reason
616
- });
617
- },
618
- async editBotProfile (options) {
619
- const avatar = options?.botAvatarURL ? await urlToBase64(options?.botAvatarURL) : options?.botAvatarURL;
620
- return await rest.patch(rest.routes.userBot(), {
621
- body: {
622
- username: options.username?.trim(),
623
- avatar
624
- }
625
- });
626
- },
627
- async editChannel (channelId, body, reason) {
628
- return await rest.patch(rest.routes.channels.channel(channelId), {
629
- body,
630
- reason
631
- });
632
- },
633
- async editChannelPermissionOverrides (channelId, body, reason) {
634
- await rest.put(rest.routes.channels.overwrite(channelId, body.id), {
635
- body,
636
- reason
637
- });
638
- },
639
- async editChannelPositions (guildId, body) {
640
- await rest.patch(rest.routes.guilds.channels(guildId), {
641
- body
642
- });
643
- },
644
- async editEmoji (guildId, id, body, reason) {
645
- return await rest.patch(rest.routes.guilds.emoji(guildId, id), {
646
- body,
647
- reason
648
- });
649
- },
650
- async editFollowupMessage (token, messageId, body) {
651
- return await rest.patch(rest.routes.interactions.responses.message(rest.applicationId, token, messageId), {
652
- body,
653
- files: body.files,
654
- unauthorized: true
655
- });
656
- },
657
- async editGlobalApplicationCommand (commandId, body) {
658
- return await rest.patch(rest.routes.interactions.commands.command(rest.applicationId, commandId), {
659
- body
660
- });
661
- },
662
- async editGuild (guildId, body, reason) {
663
- return await rest.patch(rest.routes.guilds.guild(guildId), {
664
- body,
665
- reason
666
- });
667
- },
668
- async editGuildApplicationCommand (commandId, guildId, body) {
669
- return await rest.patch(rest.routes.interactions.commands.guilds.one(rest.applicationId, guildId, commandId), {
670
- body
671
- });
672
- },
673
- async editGuildMfaLevel (guildId, mfaLevel, reason) {
674
- await rest.post(rest.routes.guilds.mfa(guildId), {
675
- body: {
676
- level: mfaLevel
677
- },
678
- reason
679
- });
680
- },
681
- async editGuildSticker (guildId, stickerId, body, reason) {
682
- return await rest.patch(rest.routes.guilds.sticker(guildId, stickerId), {
683
- body,
684
- reason
685
- });
686
- },
687
- async editGuildTemplate (guildId, templateCode, body) {
688
- return await rest.patch(rest.routes.guilds.templates.guild(guildId, templateCode), {
689
- body
690
- });
691
- },
692
- async editMessage (channelId, messageId, body) {
693
- return await rest.patch(rest.routes.channels.message(channelId, messageId), {
694
- body,
695
- files: body.files
696
- });
697
- },
698
- async editOriginalInteractionResponse (token, body) {
699
- return await rest.patch(rest.routes.interactions.responses.original(rest.applicationId, token), {
700
- body,
701
- files: body.files
702
- });
703
- },
704
- async editOriginalWebhookMessage (webhookId, token, options) {
705
- return await rest.patch(rest.routes.webhooks.original(webhookId, token, options), {
706
- body: {
707
- type: InteractionResponseTypes.UpdateMessage,
708
- data: options
709
- },
710
- files: options.files,
711
- unauthorized: true
712
- });
713
- },
714
- async editOwnVoiceState (guildId, options) {
715
- await rest.patch(rest.routes.guilds.voice(guildId), {
716
- body: {
717
- ...options,
718
- request_to_speak_timestamp: options.requestToSpeakTimestamp ? new Date(options.requestToSpeakTimestamp).toISOString() : options.requestToSpeakTimestamp
719
- }
720
- });
721
- },
722
- async editScheduledEvent (guildId, eventId, body, reason) {
723
- return await rest.patch(rest.routes.guilds.events.event(guildId, eventId), {
724
- body,
725
- reason
726
- });
727
- },
728
- async editRole (guildId, roleId, body, reason) {
729
- return await rest.patch(rest.routes.guilds.roles.one(guildId, roleId), {
730
- body,
731
- reason
732
- });
733
- },
734
- async editRolePositions (guildId, body, reason) {
735
- return await rest.patch(rest.routes.guilds.roles.all(guildId), {
736
- body,
737
- reason
738
- });
739
- },
740
- async editStageInstance (channelId, topic, reason) {
741
- return await rest.patch(rest.routes.channels.stage(channelId), {
742
- body: {
743
- topic
744
- },
745
- reason
746
- });
747
- },
748
- async editUserVoiceState (guildId, options) {
749
- await rest.patch(rest.routes.guilds.voice(guildId, options.userId), {
750
- body: options
751
- });
752
- },
753
- async editWebhook (webhookId, body, reason) {
754
- return await rest.patch(rest.routes.webhooks.id(webhookId), {
755
- body,
756
- reason
757
- });
758
- },
759
- async editWebhookMessage (webhookId, token, messageId, options) {
760
- return await rest.patch(rest.routes.webhooks.message(webhookId, token, messageId, options), {
761
- body: options,
762
- files: options.files
763
- });
764
- },
765
- async editWebhookWithToken (webhookId, token, body) {
766
- return await rest.patch(rest.routes.webhooks.webhook(webhookId, token), {
767
- body
768
- });
769
- },
770
- async editWelcomeScreen (guildId, body, reason) {
771
- return await rest.patch(rest.routes.guilds.welcome(guildId), {
772
- body,
773
- reason
774
- });
775
- },
776
- async editWidgetSettings (guildId, body, reason) {
777
- return await rest.patch(rest.routes.guilds.widget(guildId), {
778
- body,
779
- reason
780
- });
781
- },
782
- async executeWebhook (webhookId, token, options) {
783
- return await rest.post(rest.routes.webhooks.webhook(webhookId, token, options), {
784
- body: options
785
- });
786
- },
787
- async followAnnouncement (sourceChannelId, targetChannelId) {
788
- return await rest.post(rest.routes.channels.follow(sourceChannelId), {
789
- body: {
790
- webhook_channel_id: targetChannelId
791
- }
792
- });
793
- },
794
- async getActiveThreads (guildId) {
795
- return await rest.get(rest.routes.channels.threads.active(guildId));
796
- },
797
- async getApplicationCommandPermission (guildId, commandId) {
798
- return await rest.get(rest.routes.interactions.commands.permission(rest.applicationId, guildId, commandId));
799
- },
800
- async getApplicationCommandPermissions (guildId) {
801
- return await rest.get(rest.routes.interactions.commands.permissions(rest.applicationId, guildId));
802
- },
803
- async getApplicationInfo () {
804
- return await rest.get(rest.routes.oauth2Application());
805
- },
806
- async getAuditLog (guildId, options) {
807
- return await rest.get(rest.routes.guilds.auditlogs(guildId, options));
808
- },
809
- async getAutomodRule (guildId, ruleId) {
810
- return await rest.get(rest.routes.guilds.automod.rule(guildId, ruleId));
811
- },
812
- async getAutomodRules (guildId) {
813
- return await rest.get(rest.routes.guilds.automod.rules(guildId));
814
- },
815
- async getAvailableVoiceRegions () {
816
- return await rest.get(rest.routes.regions());
817
- },
818
- async getBan (guildId, userId) {
819
- return await rest.get(rest.routes.guilds.members.ban(guildId, userId));
820
- },
821
- async getBans (guildId, options) {
822
- return await rest.get(rest.routes.guilds.members.bans(guildId, options));
823
- },
824
- async getChannel (id) {
825
- return await rest.get(rest.routes.channels.channel(id));
826
- },
827
- async getChannelInvites (channelId) {
828
- return await rest.get(rest.routes.channels.invites(channelId));
829
- },
830
- async getChannels (guildId) {
831
- return await rest.get(rest.routes.guilds.channels(guildId));
832
- },
833
- async getChannelWebhooks (channelId) {
834
- return await rest.get(rest.routes.channels.webhooks(channelId));
835
- },
836
- async getDmChannel (userId) {
837
- return await rest.post(rest.routes.channels.dm(), {
838
- body: {
839
- recipient_id: userId
840
- }
841
- });
842
- },
843
- async getEmoji (guildId, emojiId) {
844
- return await rest.get(rest.routes.guilds.emoji(guildId, emojiId));
845
- },
846
- async getEmojis (guildId) {
847
- return await rest.get(rest.routes.guilds.emojis(guildId));
848
- },
849
- async getFollowupMessage (token, messageId) {
850
- return await rest.get(rest.routes.interactions.responses.message(rest.applicationId, token, messageId), {
851
- unauthorized: true
852
- });
853
- },
854
- async getGatewayBot () {
855
- return await rest.get(rest.routes.gatewayBot());
856
- },
857
- async getGlobalApplicationCommand (commandId) {
858
- return await rest.get(rest.routes.interactions.commands.command(rest.applicationId, commandId));
859
- },
860
- async getGlobalApplicationCommands () {
861
- return await rest.get(rest.routes.interactions.commands.commands(rest.applicationId));
862
- },
863
- async getGuild (guildId, options = {
864
- counts: true
865
- }) {
866
- return await rest.get(rest.routes.guilds.guild(guildId, options.counts));
867
- },
868
- async getGuildApplicationCommand (commandId, guildId) {
869
- return await rest.get(rest.routes.interactions.commands.guilds.one(rest.applicationId, guildId, commandId));
870
- },
871
- async getGuildApplicationCommands (guildId) {
872
- return await rest.get(rest.routes.interactions.commands.guilds.all(rest.applicationId, guildId));
873
- },
874
- async getGuildPreview (guildId) {
875
- return await rest.get(rest.routes.guilds.preview(guildId));
876
- },
877
- async getGuildTemplate (templateCode) {
878
- return await rest.get(rest.routes.guilds.templates.code(templateCode));
879
- },
880
- async getGuildTemplates (guildId) {
881
- return await rest.get(rest.routes.guilds.templates.all(guildId));
882
- },
883
- async getGuildWebhooks (guildId) {
884
- return await rest.get(rest.routes.guilds.webhooks(guildId));
885
- },
886
- async getIntegrations (guildId) {
887
- return await rest.get(rest.routes.guilds.integrations(guildId));
888
- },
889
- async getInvite (inviteCode, options) {
890
- return await rest.get(rest.routes.guilds.invite(inviteCode, options));
891
- },
892
- async getInvites (guildId) {
893
- return await rest.get(rest.routes.guilds.invites(guildId));
894
- },
895
- async getMessage (channelId, messageId) {
896
- return await rest.get(rest.routes.channels.message(channelId, messageId));
897
- },
898
- async getMessages (channelId, options) {
899
- return await rest.get(rest.routes.channels.messages(channelId, options));
900
- },
901
- async getNitroStickerPacks () {
902
- return await rest.get(rest.routes.nitroStickerPacks());
903
- },
904
- async getOriginalInteractionResponse (token) {
905
- return await rest.get(rest.routes.interactions.responses.original(rest.applicationId, token), {
906
- unauthorized: true
907
- });
908
- },
909
- async getPinnedMessages (channelId) {
910
- return await rest.get(rest.routes.channels.pins(channelId));
911
- },
912
- async getPrivateArchivedThreads (channelId, options) {
913
- return await rest.get(rest.routes.channels.threads.private(channelId, options));
914
- },
915
- async getPrivateJoinedArchivedThreads (channelId, options) {
916
- return await rest.get(rest.routes.channels.threads.joined(channelId, options));
917
- },
918
- async getPruneCount (guildId, options) {
919
- return await rest.get(rest.routes.guilds.prune(guildId, options));
920
- },
921
- async getPublicArchivedThreads (channelId, options) {
922
- return await rest.get(rest.routes.channels.threads.public(channelId, options));
923
- },
924
- async getRoles (guildId) {
925
- return await rest.get(rest.routes.guilds.roles.all(guildId));
926
- },
927
- async getScheduledEvent (guildId, eventId, options) {
928
- return await rest.get(rest.routes.guilds.events.event(guildId, eventId, options?.withUserCount));
929
- },
930
- async getScheduledEvents (guildId, options) {
931
- return await rest.get(rest.routes.guilds.events.events(guildId, options?.withUserCount));
932
- },
933
- async getScheduledEventUsers (guildId, eventId, options) {
934
- return await rest.get(rest.routes.guilds.events.users(guildId, eventId, options));
935
- },
936
- async getSessionInfo () {
937
- return await rest.getGatewayBot();
938
- },
939
- async getStageInstance (channelId) {
940
- return await rest.get(rest.routes.channels.stage(channelId));
941
- },
942
- async getSticker (stickerId) {
943
- return await rest.get(rest.routes.sticker(stickerId));
944
- },
945
- async getGuildSticker (guildId, stickerId) {
946
- return await rest.get(rest.routes.guilds.sticker(guildId, stickerId));
947
- },
948
- async getGuildStickers (guildId) {
949
- return await rest.get(rest.routes.guilds.stickers(guildId));
950
- },
951
- async getThreadMember (channelId, userId) {
952
- return await rest.get(rest.routes.channels.threads.user(channelId, userId));
953
- },
954
- async getThreadMembers (channelId) {
955
- return await rest.get(rest.routes.channels.threads.members(channelId));
956
- },
957
- async getReactions (channelId, messageId, reaction, options) {
958
- return await rest.get(rest.routes.channels.reactions.message(channelId, messageId, reaction, options));
959
- },
960
- async getUser (id) {
961
- return await rest.get(rest.routes.user(id));
962
- },
963
- async getVanityUrl (guildId) {
964
- return await rest.get(rest.routes.guilds.vanity(guildId));
965
- },
966
- async getVoiceRegions (guildId) {
967
- return await rest.get(rest.routes.guilds.regions(guildId));
968
- },
969
- async getWebhook (webhookId) {
970
- return await rest.get(rest.routes.webhooks.id(webhookId));
971
- },
972
- async getWebhookMessage (webhookId, token, messageId, options) {
973
- return await rest.get(rest.routes.webhooks.message(webhookId, token, messageId, options));
974
- },
975
- async getWebhookWithToken (webhookId, token) {
976
- return await rest.get(rest.routes.webhooks.webhook(webhookId, token));
977
- },
978
- async getWelcomeScreen (guildId) {
979
- return await rest.get(rest.routes.guilds.welcome(guildId));
980
- },
981
- async getWidget (guildId) {
982
- return await rest.get(rest.routes.guilds.widgetJson(guildId));
983
- },
984
- async getWidgetSettings (guildId) {
985
- return await rest.get(rest.routes.guilds.widget(guildId));
986
- },
987
- async joinThread (channelId) {
988
- await rest.put(rest.routes.channels.threads.me(channelId));
989
- },
990
- async leaveGuild (guildId) {
991
- await rest.delete(rest.routes.guilds.leave(guildId));
992
- },
993
- async leaveThread (channelId) {
994
- await rest.delete(rest.routes.channels.threads.me(channelId));
995
- },
996
- async publishMessage (channelId, messageId) {
997
- return await rest.post(rest.routes.channels.crosspost(channelId, messageId));
998
- },
999
- async removeRole (guildId, userId, roleId, reason) {
1000
- await rest.delete(rest.routes.guilds.roles.member(guildId, userId, roleId), {
1001
- reason
1002
- });
1003
- },
1004
- async removeThreadMember (channelId, userId) {
1005
- await rest.delete(rest.routes.channels.threads.user(channelId, userId));
1006
- },
1007
- async sendFollowupMessage (token, options) {
1008
- return await rest.post(rest.routes.webhooks.webhook(rest.applicationId, token), {
1009
- body: options,
1010
- files: options.files,
1011
- unauthorized: true
1012
- });
1013
- },
1014
- async sendInteractionResponse (interactionId, token, options) {
1015
- return await rest.post(rest.routes.interactions.responses.callback(interactionId, token), {
1016
- body: options,
1017
- files: options.data?.files,
1018
- runThroughQueue: false,
1019
- unauthorized: true
1020
- });
1021
- },
1022
- async sendMessage (channelId, body) {
1023
- return await rest.post(rest.routes.channels.messages(channelId), {
1024
- body,
1025
- files: body.files
1026
- });
1027
- },
1028
- async startThreadWithMessage (channelId, messageId, body, reason) {
1029
- return await rest.post(rest.routes.channels.threads.message(channelId, messageId), {
1030
- body,
1031
- reason
1032
- });
1033
- },
1034
- async startThreadWithoutMessage (channelId, body, reason) {
1035
- return await rest.post(rest.routes.channels.threads.all(channelId), {
1036
- body,
1037
- reason
1038
- });
1039
- },
1040
- async syncGuildTemplate (guildId) {
1041
- return await rest.put(rest.routes.guilds.templates.all(guildId));
1042
- },
1043
- async banMember (guildId, userId, body, reason) {
1044
- await rest.put(rest.routes.guilds.members.ban(guildId, userId), {
1045
- body,
1046
- reason
1047
- });
1048
- },
1049
- async editBotMember (guildId, body, reason) {
1050
- return await rest.patch(rest.routes.guilds.members.bot(guildId), {
1051
- body,
1052
- reason
1053
- });
1054
- },
1055
- async editMember (guildId, userId, body, reason) {
1056
- return await rest.patch(rest.routes.guilds.members.member(guildId, userId), {
1057
- body,
1058
- reason
1059
- });
1060
- },
1061
- async getMember (guildId, userId) {
1062
- return await rest.get(rest.routes.guilds.members.member(guildId, userId));
1063
- },
1064
- async getMembers (guildId, options) {
1065
- return await rest.get(rest.routes.guilds.members.members(guildId, options));
1066
- },
1067
- async kickMember (guildId, userId, reason) {
1068
- await rest.delete(rest.routes.guilds.members.member(guildId, userId), {
1069
- reason
1070
- });
1071
- },
1072
- async pinMessage (channelId, messageId, reason) {
1073
- await rest.put(rest.routes.channels.pin(channelId, messageId), {
1074
- reason
1075
- });
1076
- },
1077
- async pruneMembers (guildId, body, reason) {
1078
- return await rest.post(rest.routes.guilds.members.prune(guildId), {
1079
- body,
1080
- reason
1081
- });
1082
- },
1083
- async searchMembers (guildId, query, options) {
1084
- return await rest.get(rest.routes.guilds.members.search(guildId, query, options));
1085
- },
1086
- async unbanMember (guildId, userId, reason) {
1087
- await rest.delete(rest.routes.guilds.members.ban(guildId, userId), {
1088
- reason
1089
- });
1090
- },
1091
- async unpinMessage (channelId, messageId, reason) {
1092
- await rest.delete(rest.routes.channels.pin(channelId, messageId), {
1093
- reason
1094
- });
1095
- },
1096
- async triggerTypingIndicator (channelId) {
1097
- await rest.post(rest.routes.channels.typing(channelId));
1098
- },
1099
- async upsertGlobalApplicationCommands (body) {
1100
- return await rest.put(rest.routes.interactions.commands.commands(rest.applicationId), {
1101
- body
1102
- });
1103
- },
1104
- async upsertGuildApplicationCommands (guildId, body) {
1105
- return await rest.put(rest.routes.interactions.commands.guilds.all(rest.applicationId, guildId), {
1106
- body
1107
- });
1108
- },
1109
- preferSnakeCase (enabled) {
1110
- const camelizer = enabled ? (x)=>x : camelize;
1111
- rest.get = async (url, options)=>{
1112
- return camelizer(await rest.makeRequest('GET', url, options));
1113
- };
1114
- rest.post = async (url, options)=>{
1115
- return camelizer(await rest.makeRequest('POST', url, options));
1116
- };
1117
- rest.delete = async (url, options)=>{
1118
- camelizer(await rest.makeRequest('DELETE', url, options));
1119
- };
1120
- rest.patch = async (url, options)=>{
1121
- return camelizer(await rest.makeRequest('PATCH', url, options));
1122
- };
1123
- rest.put = async (url, options)=>{
1124
- return camelizer(await rest.makeRequest('PUT', url, options));
1125
- };
1126
- return rest;
1127
- }
1128
- };
1129
- return rest;
1130
- }
1131
- var HttpResponseCode;
1132
- (function(HttpResponseCode) {
1133
- HttpResponseCode[HttpResponseCode[/** Minimum value of a code in oder to consider that it was successful. */ "Success"] = 200] = "Success";
1134
- HttpResponseCode[HttpResponseCode[/** Request completed successfully, but Discord returned an empty body. */ "NoContent"] = 204] = "NoContent";
1135
- HttpResponseCode[HttpResponseCode[/** Minimum value of a code in order to consider that something went wrong. */ "Error"] = 400] = "Error";
1136
- HttpResponseCode[HttpResponseCode[/** This request got rate limited. */ "TooManyRequests"] = 429] = "TooManyRequests";
1137
- })(HttpResponseCode || (HttpResponseCode = {}));
1138
-
1139
- //# sourceMappingURL=manager.js.map