mini-interactions 0.0.0-stage → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/MIGRATION.md +126 -0
- package/README.md +303 -2
- package/dist/bot.d.ts +113 -0
- package/dist/bot.js +293 -0
- package/dist/builders/ActionRowBuilder.d.ts +22 -0
- package/dist/builders/ActionRowBuilder.js +33 -0
- package/dist/builders/AutomodRuleBuilder.d.ts +45 -0
- package/dist/builders/AutomodRuleBuilder.js +151 -0
- package/dist/builders/ButtonBuilder.d.ts +53 -0
- package/dist/builders/ButtonBuilder.js +124 -0
- package/dist/builders/ChannelSelectMenuBuilder.d.ts +53 -0
- package/dist/builders/ChannelSelectMenuBuilder.js +105 -0
- package/dist/builders/CheckboxBuilder.d.ts +20 -0
- package/dist/builders/CheckboxBuilder.js +20 -0
- package/dist/builders/CheckboxGroupBuilder.d.ts +25 -0
- package/dist/builders/CheckboxGroupBuilder.js +48 -0
- package/dist/builders/EmbedBuilder.d.ts +33 -0
- package/dist/builders/EmbedBuilder.js +103 -0
- package/dist/builders/FileUploadBuilder.d.ts +17 -0
- package/dist/builders/FileUploadBuilder.js +22 -0
- package/dist/builders/LabelBuilder.d.ts +16 -0
- package/dist/builders/LabelBuilder.js +21 -0
- package/dist/builders/MiniContainerBuilder.d.ts +131 -0
- package/dist/builders/MiniContainerBuilder.js +347 -0
- package/dist/builders/ModalBuilder.d.ts +16 -0
- package/dist/builders/ModalBuilder.js +36 -0
- package/dist/builders/ModalChannelSelectMenuBuilder.d.ts +29 -0
- package/dist/builders/ModalChannelSelectMenuBuilder.js +25 -0
- package/dist/builders/ModalMentionableSelectMenuBuilder.d.ts +53 -0
- package/dist/builders/ModalMentionableSelectMenuBuilder.js +87 -0
- package/dist/builders/ModalRoleSelectMenuBuilder.d.ts +27 -0
- package/dist/builders/ModalRoleSelectMenuBuilder.js +24 -0
- package/dist/builders/ModalStringSelectMenuBuilder.d.ts +62 -0
- package/dist/builders/ModalStringSelectMenuBuilder.js +120 -0
- package/dist/builders/ModalUserSelectMenuBuilder.d.ts +53 -0
- package/dist/builders/ModalUserSelectMenuBuilder.js +96 -0
- package/dist/builders/RadioBuilder.d.ts +22 -0
- package/dist/builders/RadioBuilder.js +36 -0
- package/dist/builders/RoleSelectMenuBuilder.d.ts +47 -0
- package/dist/builders/RoleSelectMenuBuilder.js +92 -0
- package/dist/builders/StringSelectMenuBuilder.d.ts +52 -0
- package/dist/builders/StringSelectMenuBuilder.js +104 -0
- package/dist/builders/StringSelectMenuOptionBuilder.d.ts +46 -0
- package/dist/builders/StringSelectMenuOptionBuilder.js +106 -0
- package/dist/builders/TextInputBuilder.d.ts +23 -0
- package/dist/builders/TextInputBuilder.js +26 -0
- package/dist/builders/index.d.ts +44 -0
- package/dist/builders/index.js +22 -0
- package/dist/builders/shared.d.ts +8 -0
- package/dist/builders/shared.js +11 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +71 -0
- package/dist/commands/CommandBuilder.d.ts +278 -0
- package/dist/commands/CommandBuilder.js +687 -0
- package/dist/commands/ContextMenuCommandBuilder.d.ts +94 -0
- package/dist/commands/ContextMenuCommandBuilder.js +145 -0
- package/dist/core/http/DiscordRestClient.d.ts +400 -0
- package/dist/core/http/DiscordRestClient.js +988 -0
- package/dist/core/interactions/InteractionContext.d.ts +33 -0
- package/dist/core/interactions/InteractionContext.js +61 -0
- package/dist/core/interactions/InteractionVerifier.d.ts +8 -0
- package/dist/core/interactions/InteractionVerifier.js +9 -0
- package/dist/core/messages/DiscordSentMessage.d.ts +32 -0
- package/dist/core/messages/DiscordSentMessage.js +64 -0
- package/dist/core/messages/message-payloads.d.ts +94 -0
- package/dist/core/messages/message-payloads.js +99 -0
- package/dist/core/webhooks/DiscordWebhook.d.ts +14 -0
- package/dist/core/webhooks/DiscordWebhook.js +69 -0
- package/dist/database/MiniDataBuilder.d.ts +61 -0
- package/dist/database/MiniDataBuilder.js +98 -0
- package/dist/database/MiniDatabase.d.ts +67 -0
- package/dist/database/MiniDatabase.js +222 -0
- package/dist/database/MiniDatabaseBuilder.d.ts +58 -0
- package/dist/database/MiniDatabaseBuilder.js +84 -0
- package/dist/database/index.d.ts +5 -0
- package/dist/database/index.js +3 -0
- package/dist/identity/ApplicationIdentityProfile.d.ts +188 -0
- package/dist/identity/ApplicationIdentityProfile.js +207 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.js +34 -0
- package/dist/lobby/Lobby.d.ts +150 -0
- package/dist/lobby/Lobby.js +90 -0
- package/dist/node/MiniInteraction.d.ts +199 -0
- package/dist/node/MiniInteraction.js +861 -0
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.js +1 -0
- package/dist/oauth2/DiscordOAuth.d.ts +49 -0
- package/dist/oauth2/DiscordOAuth.js +113 -0
- package/dist/oauth2/OAuth2Builder.d.ts +296 -0
- package/dist/oauth2/OAuth2Builder.js +435 -0
- package/dist/oauth2/OAuth2Scopes.d.ts +285 -0
- package/dist/oauth2/OAuth2Scopes.js +438 -0
- package/dist/oauth2/OAuthTokenStorage.d.ts +37 -0
- package/dist/oauth2/OAuthTokenStorage.js +109 -0
- package/dist/oauth2/index.d.ts +8 -0
- package/dist/oauth2/index.js +4 -0
- package/dist/router/AutocompleteContext.d.ts +36 -0
- package/dist/router/AutocompleteContext.js +82 -0
- package/dist/router/InteractionRouter.d.ts +82 -0
- package/dist/router/InteractionRouter.js +225 -0
- package/dist/types/ButtonStyle.d.ts +16 -0
- package/dist/types/ButtonStyle.js +17 -0
- package/dist/types/ChannelType.d.ts +2 -0
- package/dist/types/ChannelType.js +2 -0
- package/dist/types/Commands.d.ts +35 -0
- package/dist/types/Commands.js +1 -0
- package/dist/types/ComponentTypes.d.ts +19 -0
- package/dist/types/ComponentTypes.js +1 -0
- package/dist/types/InteractionFlags.d.ts +5 -0
- package/dist/types/InteractionFlags.js +6 -0
- package/dist/types/PermissionFlags.d.ts +56 -0
- package/dist/types/PermissionFlags.js +5 -0
- package/dist/types/RoleConnectionMetadata.d.ts +14 -0
- package/dist/types/RoleConnectionMetadata.js +1 -0
- package/dist/types/RoleConnectionMetadataTypes.d.ts +11 -0
- package/dist/types/RoleConnectionMetadataTypes.js +12 -0
- package/dist/types/SeparatorSpacingSize.d.ts +2 -0
- package/dist/types/SeparatorSpacingSize.js +2 -0
- package/dist/types/checkbox.d.ts +16 -0
- package/dist/types/checkbox.js +12 -0
- package/dist/types/discord.d.ts +2 -0
- package/dist/types/discord.js +1 -0
- package/dist/types/radio.d.ts +12 -0
- package/dist/types/radio.js +10 -0
- package/dist/types/validation.d.ts +14 -0
- package/dist/types/validation.js +40 -0
- package/dist/utils/CommandInteractionOptions.d.ts +66 -0
- package/dist/utils/CommandInteractionOptions.js +364 -0
- package/dist/utils/ContextMenuInteraction.d.ts +76 -0
- package/dist/utils/ContextMenuInteraction.js +152 -0
- package/dist/utils/MessageComponentInteraction.d.ts +148 -0
- package/dist/utils/MessageComponentInteraction.js +259 -0
- package/dist/utils/ModalSubmitInteraction.d.ts +86 -0
- package/dist/utils/ModalSubmitInteraction.js +267 -0
- package/dist/utils/cdn.d.ts +30 -0
- package/dist/utils/cdn.js +60 -0
- package/dist/utils/formatting.d.ts +76 -0
- package/dist/utils/formatting.js +132 -0
- package/dist/utils/interactionMessageHelpers.d.ts +40 -0
- package/dist/utils/interactionMessageHelpers.js +118 -0
- package/dist/utils/localization.d.ts +25 -0
- package/dist/utils/localization.js +38 -0
- package/dist/utils/snowflake.d.ts +19 -0
- package/dist/utils/snowflake.js +32 -0
- package/dist/webhooks/WebhookEvent.d.ts +229 -0
- package/dist/webhooks/WebhookEvent.js +59 -0
- package/dist/webhooks/WebhookEventRouter.d.ts +123 -0
- package/dist/webhooks/WebhookEventRouter.js +160 -0
- package/dist/webhooks/WebhookEventVerifier.d.ts +33 -0
- package/dist/webhooks/WebhookEventVerifier.js +37 -0
- package/dist/webhooks/index.d.ts +6 -0
- package/dist/webhooks/index.js +3 -0
- package/package.json +93 -4
|
@@ -0,0 +1,988 @@
|
|
|
1
|
+
import { assertProfileDataWithinLimits, assertUsernameLength, buildProfileData, mergeProfileData, } from '../../identity/ApplicationIdentityProfile.js';
|
|
2
|
+
import { DiscordSentMessage } from '../messages/DiscordSentMessage.js';
|
|
3
|
+
import { createMessageRequestInit, } from '../messages/message-payloads.js';
|
|
4
|
+
import { DiscordWebhook } from '../webhooks/DiscordWebhook.js';
|
|
5
|
+
/**
|
|
6
|
+
* Thrown when Discord answers a REST call with a non-2xx status.
|
|
7
|
+
*
|
|
8
|
+
* `message` deliberately keeps the historical
|
|
9
|
+
* `[DiscordRestClient] <METHOD> <path> failed: <status>` shape so existing
|
|
10
|
+
* logging and `instanceof Error` checks keep working, while `status` lets
|
|
11
|
+
* callers branch on the code without parsing that string.
|
|
12
|
+
*/
|
|
13
|
+
function sleep(ms) {
|
|
14
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
15
|
+
}
|
|
16
|
+
export class DiscordRestApiError extends Error {
|
|
17
|
+
status;
|
|
18
|
+
method;
|
|
19
|
+
path;
|
|
20
|
+
body;
|
|
21
|
+
constructor(status, method, path, body) {
|
|
22
|
+
super(`[DiscordRestClient] ${method} ${path} failed: ${status}${body ? ` ${body}` : ''}`);
|
|
23
|
+
this.status = status;
|
|
24
|
+
this.method = method;
|
|
25
|
+
this.path = path;
|
|
26
|
+
this.body = body;
|
|
27
|
+
this.name = 'DiscordRestApiError';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export class DiscordRestClient {
|
|
31
|
+
options;
|
|
32
|
+
fetchImpl;
|
|
33
|
+
baseUrl;
|
|
34
|
+
maxRetries;
|
|
35
|
+
/** Bucket id -> observed remaining/reset state. */
|
|
36
|
+
buckets = new Map();
|
|
37
|
+
/** Normalised route -> bucket id, learned from X-RateLimit headers. */
|
|
38
|
+
routeBuckets = new Map();
|
|
39
|
+
constructor(options) {
|
|
40
|
+
this.options = options;
|
|
41
|
+
this.fetchImpl = options.fetchImplementation ?? fetch;
|
|
42
|
+
this.baseUrl = options.apiBaseUrl ?? 'https://discord.com/api/v10';
|
|
43
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
44
|
+
}
|
|
45
|
+
async request(path, init = {}) {
|
|
46
|
+
let lastError;
|
|
47
|
+
const { authenticated = true, ...requestInit } = init;
|
|
48
|
+
const routeKey = this.routeKey(path, requestInit);
|
|
49
|
+
for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
|
|
50
|
+
// Respect the last observed per-bucket budget before spending a call.
|
|
51
|
+
await this.waitForBucket(routeKey);
|
|
52
|
+
let response;
|
|
53
|
+
try {
|
|
54
|
+
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
55
|
+
...requestInit,
|
|
56
|
+
headers: {
|
|
57
|
+
...(authenticated ? { Authorization: `Bot ${this.options.token}` } : {}),
|
|
58
|
+
...getDefaultContentTypeHeader(requestInit.body),
|
|
59
|
+
...(requestInit.headers ?? {}),
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
lastError = this.createRequestError(path, requestInit.method, error);
|
|
65
|
+
if (attempt < this.maxRetries) {
|
|
66
|
+
await sleep(150 * (attempt + 1));
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
// Learn/refresh the bucket budget from every response.
|
|
72
|
+
this.updateRateLimitState(routeKey, response);
|
|
73
|
+
if (response.status === 429) {
|
|
74
|
+
const retryAfterSeconds = await this.readRetryAfter(response);
|
|
75
|
+
if (attempt < this.maxRetries) {
|
|
76
|
+
await sleep(Math.ceil(retryAfterSeconds * 1000));
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
lastError = new DiscordRestApiError(429, requestInit.method ?? 'GET', path, '');
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
if (response.ok) {
|
|
83
|
+
if (response.status === 204)
|
|
84
|
+
return undefined;
|
|
85
|
+
const responseText = await response.text();
|
|
86
|
+
if (!responseText)
|
|
87
|
+
return undefined;
|
|
88
|
+
return JSON.parse(responseText);
|
|
89
|
+
}
|
|
90
|
+
if (response.status >= 500 && attempt < this.maxRetries) {
|
|
91
|
+
await sleep(150 * (attempt + 1));
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const errorBody = await response.text();
|
|
95
|
+
lastError = new DiscordRestApiError(response.status, requestInit.method ?? 'GET', path, errorBody);
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
throw lastError instanceof Error ? lastError : new Error('[DiscordRestClient] unknown request failure');
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Normalises a path into a stable route key: numeric ids become `:id`
|
|
102
|
+
* except for major parameters (channel/guild/webhook roots).
|
|
103
|
+
*/
|
|
104
|
+
routeKey(path, init) {
|
|
105
|
+
const method = (init.method ?? 'GET').toUpperCase();
|
|
106
|
+
const parts = path.split('?')[0].split('/').filter(Boolean);
|
|
107
|
+
const masked = parts.map((part, index) => {
|
|
108
|
+
const previous = parts[index - 1];
|
|
109
|
+
if (previous === 'channels' || previous === 'guilds' || previous === 'webhooks') {
|
|
110
|
+
return part; // major parameter — kept verbatim
|
|
111
|
+
}
|
|
112
|
+
if (part === '@me' || part === '@original')
|
|
113
|
+
return part;
|
|
114
|
+
return /^\d{15,}$/.test(part) ? ':id' : part;
|
|
115
|
+
});
|
|
116
|
+
return `${method} ${masked.join('/')}`;
|
|
117
|
+
}
|
|
118
|
+
async waitForBucket(routeKey) {
|
|
119
|
+
const bucketId = this.routeBuckets.get(routeKey);
|
|
120
|
+
if (!bucketId)
|
|
121
|
+
return;
|
|
122
|
+
const bucket = this.buckets.get(bucketId);
|
|
123
|
+
if (!bucket || bucket.remaining === null || bucket.remaining > 0)
|
|
124
|
+
return;
|
|
125
|
+
const waitMs = bucket.resetAt - Date.now();
|
|
126
|
+
if (waitMs > 0) {
|
|
127
|
+
await sleep(waitMs + 5); // small buffer for clock skew
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
bucket.remaining = null; // stale entry — let it refresh
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
updateRateLimitState(routeKey, response) {
|
|
134
|
+
const bucketId = response.headers.get('x-ratelimit-bucket');
|
|
135
|
+
if (!bucketId)
|
|
136
|
+
return;
|
|
137
|
+
this.routeBuckets.set(routeKey, bucketId);
|
|
138
|
+
const bucket = this.buckets.get(bucketId) ?? { remaining: null, resetAt: 0 };
|
|
139
|
+
const remaining = response.headers.get('x-ratelimit-remaining');
|
|
140
|
+
const resetAfter = response.headers.get('x-ratelimit-reset-after');
|
|
141
|
+
if (remaining !== null)
|
|
142
|
+
bucket.remaining = Number(remaining);
|
|
143
|
+
if (resetAfter !== null)
|
|
144
|
+
bucket.resetAt = Date.now() + Number(resetAfter) * 1000;
|
|
145
|
+
this.buckets.set(bucketId, bucket);
|
|
146
|
+
}
|
|
147
|
+
/** Reads retry_after from the 429 body first (float seconds), then headers. */
|
|
148
|
+
async readRetryAfter(response) {
|
|
149
|
+
try {
|
|
150
|
+
const bodyText = await response.clone().text();
|
|
151
|
+
if (bodyText) {
|
|
152
|
+
const parsed = JSON.parse(bodyText);
|
|
153
|
+
if (typeof parsed.retry_after === 'number')
|
|
154
|
+
return parsed.retry_after;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
// fall through to header parsing
|
|
159
|
+
}
|
|
160
|
+
const headerValue = response.headers.get('retry-after');
|
|
161
|
+
return headerValue !== null ? Number(headerValue) : 1;
|
|
162
|
+
}
|
|
163
|
+
createRequestError(path, method, error) {
|
|
164
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
165
|
+
return new Error(`[DiscordRestClient] ${method ?? 'GET'} ${path} failed: ${message}`, { cause: error instanceof Error ? error : undefined });
|
|
166
|
+
}
|
|
167
|
+
createFollowup(interactionToken, body) {
|
|
168
|
+
return this.request(`/webhooks/${this.options.applicationId}/${interactionToken}`, {
|
|
169
|
+
method: 'POST',
|
|
170
|
+
body: JSON.stringify(body),
|
|
171
|
+
authenticated: false,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
editOriginal(interactionToken, body) {
|
|
175
|
+
return this.request(`/webhooks/${this.options.applicationId}/${interactionToken}/messages/@original`, {
|
|
176
|
+
method: 'PATCH',
|
|
177
|
+
body: JSON.stringify(body),
|
|
178
|
+
authenticated: false,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
/** Deletes the original interaction response. */
|
|
182
|
+
async deleteOriginal(interactionToken) {
|
|
183
|
+
await this.request(`/webhooks/${this.options.applicationId}/${interactionToken}/messages/@original`, {
|
|
184
|
+
method: 'DELETE',
|
|
185
|
+
authenticated: false,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
/** Deletes a follow-up message previously sent for this interaction. */
|
|
189
|
+
async deleteFollowup(interactionToken, messageId) {
|
|
190
|
+
await this.request(`/webhooks/${this.options.applicationId}/${interactionToken}/messages/${messageId}`, { method: 'DELETE', authenticated: false });
|
|
191
|
+
}
|
|
192
|
+
async createFollowupMessage(interactionToken, options) {
|
|
193
|
+
const requestInit = createMessageRequestInit(options);
|
|
194
|
+
const message = await this.request(`/webhooks/${this.options.applicationId}/${interactionToken}`, {
|
|
195
|
+
method: 'POST',
|
|
196
|
+
...requestInit,
|
|
197
|
+
authenticated: false,
|
|
198
|
+
});
|
|
199
|
+
return new DiscordSentMessage(this, message);
|
|
200
|
+
}
|
|
201
|
+
async editOriginalMessage(interactionToken, options) {
|
|
202
|
+
const requestInit = createMessageRequestInit(options);
|
|
203
|
+
const message = await this.request(`/webhooks/${this.options.applicationId}/${interactionToken}/messages/@original`, {
|
|
204
|
+
method: 'PATCH',
|
|
205
|
+
...requestInit,
|
|
206
|
+
authenticated: false,
|
|
207
|
+
});
|
|
208
|
+
return new DiscordSentMessage(this, message);
|
|
209
|
+
}
|
|
210
|
+
async sendMessage(options) {
|
|
211
|
+
const { channelId, ...messageOptions } = options;
|
|
212
|
+
const requestInit = createMessageRequestInit(messageOptions);
|
|
213
|
+
const message = await this.request(`/channels/${channelId}/messages`, {
|
|
214
|
+
method: 'POST',
|
|
215
|
+
...requestInit,
|
|
216
|
+
});
|
|
217
|
+
return new DiscordSentMessage(this, message);
|
|
218
|
+
}
|
|
219
|
+
send(options) {
|
|
220
|
+
return this.sendMessage(options);
|
|
221
|
+
}
|
|
222
|
+
async startThread(options) {
|
|
223
|
+
const { channelId, messageId, reason, ...body } = options;
|
|
224
|
+
return this.request(`/channels/${channelId}/messages/${messageId}/threads`, {
|
|
225
|
+
method: 'POST',
|
|
226
|
+
body: JSON.stringify({
|
|
227
|
+
auto_archive_duration: body.autoArchiveDuration,
|
|
228
|
+
rate_limit_per_user: body.rateLimitPerUser,
|
|
229
|
+
name: body.name,
|
|
230
|
+
}),
|
|
231
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Creates a thread directly in a channel (no source message), e.g. for
|
|
236
|
+
* forum channels or standalone public/private threads.
|
|
237
|
+
*/
|
|
238
|
+
async createThread(options) {
|
|
239
|
+
const { channelId, reason, autoArchiveDuration, rateLimitPerUser, type, invitable, name } = options;
|
|
240
|
+
return this.request(`/channels/${channelId}/threads`, {
|
|
241
|
+
method: 'POST',
|
|
242
|
+
body: JSON.stringify({
|
|
243
|
+
name,
|
|
244
|
+
...(autoArchiveDuration !== undefined ? { auto_archive_duration: autoArchiveDuration } : {}),
|
|
245
|
+
...(rateLimitPerUser !== undefined ? { rate_limit_per_user: rateLimitPerUser } : {}),
|
|
246
|
+
...(type !== undefined ? { type } : {}),
|
|
247
|
+
...(invitable !== undefined ? { invitable } : {}),
|
|
248
|
+
}),
|
|
249
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
async editMessage(channelId, messageId, options) {
|
|
253
|
+
const requestInit = createMessageRequestInit(options);
|
|
254
|
+
const message = await this.request(`/channels/${channelId}/messages/${messageId}`, {
|
|
255
|
+
method: 'PATCH',
|
|
256
|
+
...requestInit,
|
|
257
|
+
});
|
|
258
|
+
return new DiscordSentMessage(this, message);
|
|
259
|
+
}
|
|
260
|
+
async deleteMessage(channelId, messageId, reason) {
|
|
261
|
+
await this.request(`/channels/${channelId}/messages/${messageId}`, {
|
|
262
|
+
method: 'DELETE',
|
|
263
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
async pinMessage(channelId, messageId, reason) {
|
|
267
|
+
await this.request(`/channels/${channelId}/pins/${messageId}`, {
|
|
268
|
+
method: 'PUT',
|
|
269
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
async unpinMessage(channelId, messageId, reason) {
|
|
273
|
+
await this.request(`/channels/${channelId}/pins/${messageId}`, {
|
|
274
|
+
method: 'DELETE',
|
|
275
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
async crosspostMessage(channelId, messageId) {
|
|
279
|
+
return this.request(`/channels/${channelId}/messages/${messageId}/crosspost`, {
|
|
280
|
+
method: 'POST',
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
/** Sends a message through an existing webhook without instantiating {@link DiscordWebhook}. */
|
|
284
|
+
async sendWebhookMessage(webhookId, webhookToken, options) {
|
|
285
|
+
return this.webhook(webhookId, webhookToken).send(options);
|
|
286
|
+
}
|
|
287
|
+
// ---- Message reads & bulk operations (v0.7) ----
|
|
288
|
+
async fetchMessage(channelId, messageId) {
|
|
289
|
+
const message = await this.request(`/channels/${channelId}/messages/${messageId}`);
|
|
290
|
+
return new DiscordSentMessage(this, message);
|
|
291
|
+
}
|
|
292
|
+
/** Lists channel messages; at most one of before/after/around per call. */
|
|
293
|
+
async fetchMessages(channelId, options = {}) {
|
|
294
|
+
const { limit, before, after, around } = options;
|
|
295
|
+
const params = new URLSearchParams();
|
|
296
|
+
if (limit !== undefined)
|
|
297
|
+
params.set('limit', String(limit));
|
|
298
|
+
if (before)
|
|
299
|
+
params.set('before', before);
|
|
300
|
+
if (after)
|
|
301
|
+
params.set('after', after);
|
|
302
|
+
if (around)
|
|
303
|
+
params.set('around', around);
|
|
304
|
+
const query = params.size > 0 ? `?${params.toString()}` : '';
|
|
305
|
+
return this.request(`/channels/${channelId}/messages${query}`);
|
|
306
|
+
}
|
|
307
|
+
/** Bulk-deletes 2–100 messages (all must be younger than 14 days). */
|
|
308
|
+
async bulkDeleteMessages(channelId, messageIds, reason) {
|
|
309
|
+
if (messageIds.length < 2 || messageIds.length > 100) {
|
|
310
|
+
throw new Error('[DiscordRestClient] bulk delete accepts between 2 and 100 messages');
|
|
311
|
+
}
|
|
312
|
+
await this.request(`/channels/${channelId}/messages/bulk-delete`, {
|
|
313
|
+
method: 'POST',
|
|
314
|
+
body: JSON.stringify({ messages: [...messageIds] }),
|
|
315
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
// ---- Typing & reactions (v0.7) ----
|
|
319
|
+
async triggerTyping(channelId) {
|
|
320
|
+
await this.request(`/channels/${channelId}/typing`, { method: 'POST' });
|
|
321
|
+
}
|
|
322
|
+
/** Lists the users who reacted with the given emoji (paginated). */
|
|
323
|
+
async fetchReactors(channelId, messageId, reaction, options = {}) {
|
|
324
|
+
const { limit, after, type } = options;
|
|
325
|
+
const params = new URLSearchParams();
|
|
326
|
+
if (limit !== undefined)
|
|
327
|
+
params.set('limit', String(limit));
|
|
328
|
+
if (after)
|
|
329
|
+
params.set('after', after);
|
|
330
|
+
if (type !== undefined)
|
|
331
|
+
params.set('type', String(type));
|
|
332
|
+
const query = params.size > 0 ? `?${params.toString()}` : '';
|
|
333
|
+
return this.request(`/channels/${channelId}/messages/${messageId}/reactions/${encodeDiscordReaction(reaction)}${query}`).then((result) => result);
|
|
334
|
+
}
|
|
335
|
+
async removeOwnReaction(channelId, messageId, reaction) {
|
|
336
|
+
await this.request(`/channels/${channelId}/messages/${messageId}/reactions/${encodeDiscordReaction(reaction)}/@me`, { method: 'DELETE' });
|
|
337
|
+
}
|
|
338
|
+
async removeUserReaction(channelId, messageId, userId, reaction, reason) {
|
|
339
|
+
await this.request(`/channels/${channelId}/messages/${messageId}/reactions/${encodeDiscordReaction(reaction)}/${userId}`, { method: 'DELETE', headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined });
|
|
340
|
+
}
|
|
341
|
+
async removeAllReactions(channelId, messageId, reason) {
|
|
342
|
+
await this.request(`/channels/${channelId}/messages/${messageId}/reactions`, {
|
|
343
|
+
method: 'DELETE',
|
|
344
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
async removeAllReactionsForEmoji(channelId, messageId, reaction, reason) {
|
|
348
|
+
await this.request(`/channels/${channelId}/messages/${messageId}/reactions/${encodeDiscordReaction(reaction)}`, {
|
|
349
|
+
method: 'DELETE',
|
|
350
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
// ---- Channels (v0.7) ----
|
|
354
|
+
async fetchChannel(channelId) {
|
|
355
|
+
return this.request(`/channels/${channelId}`);
|
|
356
|
+
}
|
|
357
|
+
/** Edits channel fields; thread-only options are sent only when provided. */
|
|
358
|
+
async editChannel(channelId, options, reason) {
|
|
359
|
+
return this.request(`/channels/${channelId}`, {
|
|
360
|
+
method: 'PATCH',
|
|
361
|
+
body: JSON.stringify({
|
|
362
|
+
...(options.name !== undefined ? { name: options.name } : {}),
|
|
363
|
+
...(options.topic !== undefined ? { topic: options.topic } : {}),
|
|
364
|
+
...(options.nsfw !== undefined ? { nsfw: options.nsfw } : {}),
|
|
365
|
+
...(options.rateLimitPerUser !== undefined
|
|
366
|
+
? { rate_limit_per_user: options.rateLimitPerUser }
|
|
367
|
+
: {}),
|
|
368
|
+
...(options.archived !== undefined ? { archived: options.archived } : {}),
|
|
369
|
+
...(options.locked !== undefined ? { locked: options.locked } : {}),
|
|
370
|
+
...(options.autoArchiveDuration !== undefined
|
|
371
|
+
? { auto_archive_duration: options.autoArchiveDuration }
|
|
372
|
+
: {}),
|
|
373
|
+
}),
|
|
374
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
async deleteChannel(channelId, reason) {
|
|
378
|
+
await this.request(`/channels/${channelId}`, {
|
|
379
|
+
method: 'DELETE',
|
|
380
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
/** Follows an announcement channel into the target channel. */
|
|
384
|
+
async followAnnouncementChannel(sourceChannelId, targetChannelId, reason) {
|
|
385
|
+
await this.request(`/channels/${sourceChannelId}/followers`, {
|
|
386
|
+
method: 'POST',
|
|
387
|
+
body: JSON.stringify({ webhook_channel_id: targetChannelId }),
|
|
388
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
// ---- Polls (v0.7) ----
|
|
392
|
+
/** Immediately ends a poll the app authored. */
|
|
393
|
+
async endPoll(channelId, messageId) {
|
|
394
|
+
return this.request(`/channels/${channelId}/polls/${messageId}/expire`, {
|
|
395
|
+
method: 'POST',
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
/** Lists users who voted for a poll answer (up to 100 per call). */
|
|
399
|
+
async fetchPollAnswerVoters(channelId, messageId, answerId) {
|
|
400
|
+
return this.request(`/channels/${channelId}/polls/${messageId}/answers/${answerId}/voters`);
|
|
401
|
+
}
|
|
402
|
+
// ---- Guild basics (v0.8) ----
|
|
403
|
+
async fetchGuild(guildId, withCounts = false) {
|
|
404
|
+
return this.request(`/guilds/${guildId}${withCounts ? '?with_counts=true' : ''}`);
|
|
405
|
+
}
|
|
406
|
+
async listGuildChannels(guildId) {
|
|
407
|
+
return this.request(`/guilds/${guildId}/channels`);
|
|
408
|
+
}
|
|
409
|
+
// ---- Members & moderation (v0.8) ----
|
|
410
|
+
async fetchMember(guildId, userId) {
|
|
411
|
+
return this.request(`/guilds/${guildId}/members/${userId}`);
|
|
412
|
+
}
|
|
413
|
+
async listMembers(guildId, options = {}) {
|
|
414
|
+
const params = new URLSearchParams();
|
|
415
|
+
if (options.limit !== undefined)
|
|
416
|
+
params.set('limit', String(options.limit));
|
|
417
|
+
if (options.after)
|
|
418
|
+
params.set('after', options.after);
|
|
419
|
+
const query = params.size > 0 ? `?${params.toString()}` : '';
|
|
420
|
+
return this.request(`/guilds/${guildId}/members${query}`);
|
|
421
|
+
}
|
|
422
|
+
async kickMember(guildId, userId, reason) {
|
|
423
|
+
await this.request(`/guilds/${guildId}/members/${userId}`, {
|
|
424
|
+
method: 'DELETE',
|
|
425
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
/** Bans a member; `deleteMessageSeconds` removes up to 7 days of messages. */
|
|
429
|
+
async banMember(guildId, userId, options = {}) {
|
|
430
|
+
const { deleteMessageSeconds, reason } = options;
|
|
431
|
+
await this.request(`/guilds/${guildId}/bans/${userId}`, {
|
|
432
|
+
method: 'PUT',
|
|
433
|
+
body: JSON.stringify({
|
|
434
|
+
...(deleteMessageSeconds !== undefined
|
|
435
|
+
? { delete_message_seconds: deleteMessageSeconds }
|
|
436
|
+
: {}),
|
|
437
|
+
}),
|
|
438
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
async unbanMember(guildId, userId, reason) {
|
|
442
|
+
await this.request(`/guilds/${guildId}/bans/${userId}`, {
|
|
443
|
+
method: 'DELETE',
|
|
444
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
async listBans(guildId) {
|
|
448
|
+
return this.request(`/guilds/${guildId}/bans`);
|
|
449
|
+
}
|
|
450
|
+
async editMember(guildId, userId, options, reason) {
|
|
451
|
+
return this.request(`/guilds/${guildId}/members/${userId}`, {
|
|
452
|
+
method: 'PATCH',
|
|
453
|
+
body: JSON.stringify({
|
|
454
|
+
...(options.nick !== undefined ? { nick: options.nick } : {}),
|
|
455
|
+
...(options.roles !== undefined ? { roles: options.roles } : {}),
|
|
456
|
+
...(options.communicationDisabledUntil !== undefined
|
|
457
|
+
? { communication_disabled_until: options.communicationDisabledUntil }
|
|
458
|
+
: {}),
|
|
459
|
+
}),
|
|
460
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
/** Times out a member for the given duration (ms); null clears the timeout. */
|
|
464
|
+
timeoutMember(guildId, userId, durationMs, reason) {
|
|
465
|
+
const communicationDisabledUntil = durationMs === null ? null : new Date(Date.now() + durationMs).toISOString();
|
|
466
|
+
return this.editMember(guildId, userId, { communicationDisabledUntil }, reason);
|
|
467
|
+
}
|
|
468
|
+
// ---- Roles (v0.8) ----
|
|
469
|
+
async listRoles(guildId) {
|
|
470
|
+
return this.request(`/guilds/${guildId}/roles`);
|
|
471
|
+
}
|
|
472
|
+
async createRole(guildId, options, reason) {
|
|
473
|
+
return this.request(`/guilds/${guildId}/roles`, {
|
|
474
|
+
method: 'POST',
|
|
475
|
+
body: JSON.stringify({
|
|
476
|
+
...(options.name !== undefined ? { name: options.name } : {}),
|
|
477
|
+
...(options.permissions !== undefined ? { permissions: options.permissions } : {}),
|
|
478
|
+
...(options.color !== undefined ? { color: options.color } : {}),
|
|
479
|
+
...(options.hoist !== undefined ? { hoist: options.hoist } : {}),
|
|
480
|
+
...(options.mentionable !== undefined ? { mentionable: options.mentionable } : {}),
|
|
481
|
+
...(options.unicodeEmoji !== undefined ? { unicode_emoji: options.unicodeEmoji } : {}),
|
|
482
|
+
}),
|
|
483
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
async editRole(guildId, roleId, options, reason) {
|
|
487
|
+
return this.request(`/guilds/${guildId}/roles/${roleId}`, {
|
|
488
|
+
method: 'PATCH',
|
|
489
|
+
body: JSON.stringify({
|
|
490
|
+
...(options.name !== undefined ? { name: options.name } : {}),
|
|
491
|
+
...(options.permissions !== undefined ? { permissions: options.permissions } : {}),
|
|
492
|
+
...(options.color !== undefined ? { color: options.color } : {}),
|
|
493
|
+
...(options.hoist !== undefined ? { hoist: options.hoist } : {}),
|
|
494
|
+
...(options.mentionable !== undefined ? { mentionable: options.mentionable } : {}),
|
|
495
|
+
...(options.unicodeEmoji !== undefined ? { unicode_emoji: options.unicodeEmoji } : {}),
|
|
496
|
+
}),
|
|
497
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
async deleteRole(guildId, roleId, reason) {
|
|
501
|
+
await this.request(`/guilds/${guildId}/roles/${roleId}`, {
|
|
502
|
+
method: 'DELETE',
|
|
503
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
/** Reorders roles; entries are `{ id, position }` pairs. */
|
|
507
|
+
async reorderRoles(guildId, positions, reason) {
|
|
508
|
+
return this.request(`/guilds/${guildId}/roles`, {
|
|
509
|
+
method: 'PATCH',
|
|
510
|
+
body: JSON.stringify(positions),
|
|
511
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
async addRoleToMember(guildId, userId, roleId, reason) {
|
|
515
|
+
await this.request(`/guilds/${guildId}/members/${userId}/roles/${roleId}`, {
|
|
516
|
+
method: 'PUT',
|
|
517
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
async removeRoleFromMember(guildId, userId, roleId, reason) {
|
|
521
|
+
await this.request(`/guilds/${guildId}/members/${userId}/roles/${roleId}`, {
|
|
522
|
+
method: 'DELETE',
|
|
523
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
// ---- Emoji & stickers (v0.8) ----
|
|
527
|
+
async listGuildEmojis(guildId) {
|
|
528
|
+
return this.request(`/guilds/${guildId}/emojis`);
|
|
529
|
+
}
|
|
530
|
+
async fetchGuildEmoji(guildId, emojiId) {
|
|
531
|
+
return this.request(`/guilds/${guildId}/emojis/${emojiId}`);
|
|
532
|
+
}
|
|
533
|
+
/** Creates an emoji; `imageData` must be a data URI (base64). */
|
|
534
|
+
async createGuildEmoji(guildId, options, reason) {
|
|
535
|
+
return this.request(`/guilds/${guildId}/emojis`, {
|
|
536
|
+
method: 'POST',
|
|
537
|
+
body: JSON.stringify({
|
|
538
|
+
name: options.name,
|
|
539
|
+
image: options.imageData,
|
|
540
|
+
...(options.roles ? { roles: options.roles } : {}),
|
|
541
|
+
}),
|
|
542
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
async editGuildEmoji(guildId, emojiId, options, reason) {
|
|
546
|
+
return this.request(`/guilds/${guildId}/emojis/${emojiId}`, {
|
|
547
|
+
method: 'PATCH',
|
|
548
|
+
body: JSON.stringify({
|
|
549
|
+
...(options.name !== undefined ? { name: options.name } : {}),
|
|
550
|
+
...(options.roles !== undefined ? { roles: options.roles } : {}),
|
|
551
|
+
}),
|
|
552
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
async deleteGuildEmoji(guildId, emojiId, reason) {
|
|
556
|
+
await this.request(`/guilds/${guildId}/emojis/${emojiId}`, {
|
|
557
|
+
method: 'DELETE',
|
|
558
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
async listGuildStickers(guildId) {
|
|
562
|
+
return this.request(`/guilds/${guildId}/stickers`);
|
|
563
|
+
}
|
|
564
|
+
async fetchSticker(stickerId) {
|
|
565
|
+
return this.request(`/stickers/${stickerId}`);
|
|
566
|
+
}
|
|
567
|
+
async deleteGuildSticker(guildId, stickerId, reason) {
|
|
568
|
+
await this.request(`/guilds/${guildId}/stickers/${stickerId}`, {
|
|
569
|
+
method: 'DELETE',
|
|
570
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
// ---- Webhooks (v0.8) ----
|
|
574
|
+
async listChannelWebhooks(channelId) {
|
|
575
|
+
return this.request(`/channels/${channelId}/webhooks`);
|
|
576
|
+
}
|
|
577
|
+
async listGuildWebhooks(guildId) {
|
|
578
|
+
return this.request(`/guilds/${guildId}/webhooks`);
|
|
579
|
+
}
|
|
580
|
+
async createWebhook(channelId, options, reason) {
|
|
581
|
+
return this.request(`/channels/${channelId}/webhooks`, {
|
|
582
|
+
method: 'POST',
|
|
583
|
+
body: JSON.stringify({
|
|
584
|
+
name: options.name,
|
|
585
|
+
...(options.avatar ? { avatar: options.avatar } : {}),
|
|
586
|
+
}),
|
|
587
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
async fetchWebhook(webhookId) {
|
|
591
|
+
return this.request(`/webhooks/${webhookId}`);
|
|
592
|
+
}
|
|
593
|
+
/** Fetches a webhook using only its token — no bot auth required. */
|
|
594
|
+
async fetchWebhookWithToken(webhookId, webhookToken) {
|
|
595
|
+
return this.request(`/webhooks/${webhookId}/${webhookToken}`, {
|
|
596
|
+
authenticated: false,
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
async editWebhook(webhookId, options, reason) {
|
|
600
|
+
return this.request(`/webhooks/${webhookId}`, {
|
|
601
|
+
method: 'PATCH',
|
|
602
|
+
body: JSON.stringify({
|
|
603
|
+
...(options.name !== undefined ? { name: options.name } : {}),
|
|
604
|
+
...(options.avatar !== undefined ? { avatar: options.avatar } : {}),
|
|
605
|
+
...(options.channelId !== undefined ? { channel_id: options.channelId } : {}),
|
|
606
|
+
}),
|
|
607
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
async deleteWebhook(webhookId, reason) {
|
|
611
|
+
await this.request(`/webhooks/${webhookId}`, {
|
|
612
|
+
method: 'DELETE',
|
|
613
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
// ---- Entitlements & SKUs (v0.8) ----
|
|
617
|
+
async listSKUs() {
|
|
618
|
+
return this.request(`/applications/${this.options.applicationId}/skus`);
|
|
619
|
+
}
|
|
620
|
+
async listEntitlements(options = {}) {
|
|
621
|
+
const params = new URLSearchParams();
|
|
622
|
+
if (options.userId)
|
|
623
|
+
params.set('user_id', options.userId);
|
|
624
|
+
if (options.skuIds?.length)
|
|
625
|
+
params.set('sku_ids', options.skuIds.join(','));
|
|
626
|
+
if (options.guildId)
|
|
627
|
+
params.set('guild_id', options.guildId);
|
|
628
|
+
if (options.before)
|
|
629
|
+
params.set('before', options.before);
|
|
630
|
+
if (options.after)
|
|
631
|
+
params.set('after', options.after);
|
|
632
|
+
if (options.limit !== undefined)
|
|
633
|
+
params.set('limit', String(options.limit));
|
|
634
|
+
if (options.excludeEnded !== undefined)
|
|
635
|
+
params.set('exclude_ended', String(options.excludeEnded));
|
|
636
|
+
const query = params.size > 0 ? `?${params.toString()}` : '';
|
|
637
|
+
return this.request(`/applications/${this.options.applicationId}/entitlements${query}`);
|
|
638
|
+
}
|
|
639
|
+
/** Consumes a one-time-purchase entitlement. */
|
|
640
|
+
async consumeEntitlement(entitlementId) {
|
|
641
|
+
await this.request(`/applications/${this.options.applicationId}/entitlements/${entitlementId}/consume`, {
|
|
642
|
+
method: 'POST',
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
// ---- Application command permissions (v0.8) ----
|
|
646
|
+
async getCommandPermissions(guildId, commandId) {
|
|
647
|
+
return this.request(`/applications/${this.options.applicationId}/guilds/${guildId}/commands/${commandId}/permissions`);
|
|
648
|
+
}
|
|
649
|
+
/** Fully replaces a command's permission overrides for a guild. */
|
|
650
|
+
async setCommandPermissions(guildId, commandId, permissions, reason) {
|
|
651
|
+
await this.request(`/applications/${this.options.applicationId}/guilds/${guildId}/commands/${commandId}/permissions`, {
|
|
652
|
+
method: 'PUT',
|
|
653
|
+
body: JSON.stringify({ permissions }),
|
|
654
|
+
headers: reason ? { 'X-Audit-Log-Reason': reason } : undefined,
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
addReaction(channelId, messageId, reaction) {
|
|
658
|
+
return this.request(`/channels/${channelId}/messages/${messageId}/reactions/${encodeDiscordReaction(reaction)}/@me`, {
|
|
659
|
+
method: 'PUT',
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
webhook(id, token) {
|
|
663
|
+
return new DiscordWebhook(this, id, token);
|
|
664
|
+
}
|
|
665
|
+
putApplicationRoleConnectionMetadata(body) {
|
|
666
|
+
return this.request(`/applications/${this.options.applicationId}/role-connections/metadata`, {
|
|
667
|
+
method: 'PUT',
|
|
668
|
+
body: JSON.stringify(body),
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
// ---- Application Identity profiles / Game Stats Widgets ----
|
|
672
|
+
/**
|
|
673
|
+
* Writes a player's Game Stats profile.
|
|
674
|
+
*
|
|
675
|
+
* `data` is **fully replaced** whenever it is present, so omitting a stat
|
|
676
|
+
* deletes it; omit `data` entirely to leave stored stats untouched. Prefer
|
|
677
|
+
* {@link sendGameStats} with `mode: "merge"` when patching individual stats.
|
|
678
|
+
*
|
|
679
|
+
* Requires a bot token, the `application_identities.write` OAuth2 scope on
|
|
680
|
+
* the target user, and a *claimed* game with a configured widget.
|
|
681
|
+
*
|
|
682
|
+
* @returns the created profile on the first write (201), `undefined` on
|
|
683
|
+
* subsequent updates (204).
|
|
684
|
+
* @see {@link https://docs.discord.com/developers/resources/application-identity-profile}
|
|
685
|
+
*/
|
|
686
|
+
updateIdentityProfile(userId, providerIssuedUserId, body) {
|
|
687
|
+
return this.request(`${this.identityPath(userId, providerIssuedUserId)}/profile`, { method: 'PATCH', body: JSON.stringify(body) });
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Reads a player's stored Game Stats profile.
|
|
691
|
+
*
|
|
692
|
+
* `metadata` is returned by reads; the documented update parameters are only
|
|
693
|
+
* `username` and `data`.
|
|
694
|
+
*/
|
|
695
|
+
getIdentityProfile(userId, providerIssuedUserId) {
|
|
696
|
+
return this.request(`${this.identityPath(userId, providerIssuedUserId)}/profile`);
|
|
697
|
+
}
|
|
698
|
+
/** Lists a user's application identities for this application (no profile data). */
|
|
699
|
+
listIdentitiesByUserId(userId) {
|
|
700
|
+
return this.request(`/applications/${this.options.applicationId}/users/${userId}/identities`).then((result) => result.identities ?? []);
|
|
701
|
+
}
|
|
702
|
+
/** Resolves the Discord user behind one of your external IDs (no profile data). */
|
|
703
|
+
listIdentitiesByExternalId(providerType, providerIssuedUserId, providerId) {
|
|
704
|
+
const params = new URLSearchParams();
|
|
705
|
+
if (providerId !== undefined)
|
|
706
|
+
params.set('provider_id', providerId);
|
|
707
|
+
const query = params.size > 0 ? `?${params.toString()}` : '';
|
|
708
|
+
return this.request(`/applications/${this.options.applicationId}/identities/${encodeURIComponent(providerType)}/${encodeURIComponent(providerIssuedUserId)}${query}`).then((result) => result.identities ?? []);
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Deletes one application identity and its profile data.
|
|
712
|
+
*
|
|
713
|
+
* Blocked when it would remove the user's last account-linking identity.
|
|
714
|
+
* Useful when a stale `provider_issued_user_id` prevents writing stats.
|
|
715
|
+
*/
|
|
716
|
+
async deleteIdentity(userId, providerType, providerIssuedUserId, providerId) {
|
|
717
|
+
await this.request(`/applications/${this.options.applicationId}/users/${userId}/identities/${encodeURIComponent(providerType)}/${encodeURIComponent(providerIssuedUserId)}`, {
|
|
718
|
+
method: 'DELETE',
|
|
719
|
+
body: providerId !== undefined ? JSON.stringify({ provider_id: providerId }) : undefined,
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Sends Game Stats for a player, validating Discord's limits client-side.
|
|
724
|
+
*
|
|
725
|
+
* ```ts
|
|
726
|
+
* await rest.sendGameStats({
|
|
727
|
+
* userId, // Discord user id
|
|
728
|
+
* providerIssuedUserId, // your own player id
|
|
729
|
+
* primary: { season: 'Season 3', rank_name: 'Silver', playtime_hours: 69.41 },
|
|
730
|
+
* dynamic: [{ type: 2, name: 'win_streak', value: 5 }],
|
|
731
|
+
* });
|
|
732
|
+
* ```
|
|
733
|
+
*
|
|
734
|
+
* Resolves with `undefined` **without issuing any request** when there is
|
|
735
|
+
* nothing to write — no `username`, `primary` or `dynamic`. An empty PATCH
|
|
736
|
+
* would otherwise still create the Application Identity record.
|
|
737
|
+
*
|
|
738
|
+
* @throws {ApplicationIdentityProfileError} when the payload would exceed the
|
|
739
|
+
* 10 KB / 30-field / length limits, or references a media URL Discord cannot fetch.
|
|
740
|
+
*/
|
|
741
|
+
async sendGameStats(options) {
|
|
742
|
+
const { userId, providerIssuedUserId, username, primary, dynamic, mode = 'replace', allowPrivateMediaUrls, } = options;
|
|
743
|
+
// Nothing to write: skip every request. A PATCH with an empty body would
|
|
744
|
+
// still create the Application Identity record on Discord's side, and merge
|
|
745
|
+
// mode would additionally spend a GET discovering there is nothing to merge.
|
|
746
|
+
if (username === undefined && primary === undefined && dynamic === undefined) {
|
|
747
|
+
return undefined;
|
|
748
|
+
}
|
|
749
|
+
if (username !== undefined)
|
|
750
|
+
assertUsernameLength(username);
|
|
751
|
+
const data = mode === 'merge'
|
|
752
|
+
? mergeProfileData((await this.readIdentityProfileOrUndefined(userId, providerIssuedUserId))?.data, { primary, dynamic })
|
|
753
|
+
: buildProfileData({ primary, dynamic });
|
|
754
|
+
if (data)
|
|
755
|
+
assertProfileDataWithinLimits(data, { allowPrivateMediaUrls });
|
|
756
|
+
const body = {};
|
|
757
|
+
if (username !== undefined)
|
|
758
|
+
body.username = username;
|
|
759
|
+
if (data !== undefined)
|
|
760
|
+
body.data = data;
|
|
761
|
+
return this.updateIdentityProfile(userId, providerIssuedUserId, body);
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Reads a profile for merge mode, treating a missing identity (404) as empty
|
|
765
|
+
* rather than surfacing an error. Branches on the typed status instead of the
|
|
766
|
+
* error message so a message-format change cannot break merge mode.
|
|
767
|
+
*/
|
|
768
|
+
async readIdentityProfileOrUndefined(userId, providerIssuedUserId) {
|
|
769
|
+
try {
|
|
770
|
+
return await this.getIdentityProfile(userId, providerIssuedUserId);
|
|
771
|
+
}
|
|
772
|
+
catch (error) {
|
|
773
|
+
if (error instanceof DiscordRestApiError && error.status === 404)
|
|
774
|
+
return undefined;
|
|
775
|
+
throw error;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
identityPath(userId, providerIssuedUserId) {
|
|
779
|
+
return `/applications/${this.options.applicationId}/users/${userId}/identities/${encodeURIComponent(providerIssuedUserId)}`;
|
|
780
|
+
}
|
|
781
|
+
// ---- Lobbies & Linked Channels ----
|
|
782
|
+
/**
|
|
783
|
+
* Creates a lobby. Social SDK clients cannot join a lobby created this way —
|
|
784
|
+
* see {@link createOrJoinLobby} for the SDK-compatible flow.
|
|
785
|
+
*
|
|
786
|
+
* @see {@link https://docs.discord.com/developers/resources/lobby}
|
|
787
|
+
*/
|
|
788
|
+
createLobby(options = {}) {
|
|
789
|
+
return this.request('/lobbies', {
|
|
790
|
+
method: 'POST',
|
|
791
|
+
body: JSON.stringify({
|
|
792
|
+
...(options.metadata ? { metadata: options.metadata } : {}),
|
|
793
|
+
...(options.members ? { members: options.members } : {}),
|
|
794
|
+
...(options.idleTimeoutSeconds !== undefined
|
|
795
|
+
? { idle_timeout_seconds: options.idleTimeoutSeconds }
|
|
796
|
+
: {}),
|
|
797
|
+
}),
|
|
798
|
+
});
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Creates a lobby for a `secret`, or joins the caller to the existing one.
|
|
802
|
+
*
|
|
803
|
+
* Needs a **Bearer** user token with the `sdk.social_layer` scope, not the bot
|
|
804
|
+
* token — pass it as `userToken`.
|
|
805
|
+
*/
|
|
806
|
+
createOrJoinLobby(userToken, options) {
|
|
807
|
+
return this.request('/lobbies', {
|
|
808
|
+
method: 'PUT',
|
|
809
|
+
body: JSON.stringify({
|
|
810
|
+
secret: options.secret,
|
|
811
|
+
...(options.idleTimeoutSeconds !== undefined
|
|
812
|
+
? { idle_timeout_seconds: options.idleTimeoutSeconds }
|
|
813
|
+
: {}),
|
|
814
|
+
...(options.lobbyMetadata ? { lobby_metadata: options.lobbyMetadata } : {}),
|
|
815
|
+
...(options.memberMetadata ? { member_metadata: options.memberMetadata } : {}),
|
|
816
|
+
}),
|
|
817
|
+
...this.asUser(userToken),
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
/** Reads a lobby, including its `linked_channel` when one is linked. */
|
|
821
|
+
getLobby(lobbyId) {
|
|
822
|
+
return this.request(`/lobbies/${lobbyId}`);
|
|
823
|
+
}
|
|
824
|
+
/** Replaces lobby metadata, its member list and/or its idle timeout. */
|
|
825
|
+
modifyLobby(lobbyId, options = {}) {
|
|
826
|
+
return this.request(`/lobbies/${lobbyId}`, {
|
|
827
|
+
method: 'PATCH',
|
|
828
|
+
body: JSON.stringify({
|
|
829
|
+
...(options.metadata ? { metadata: options.metadata } : {}),
|
|
830
|
+
...(options.members ? { members: options.members } : {}),
|
|
831
|
+
...(options.idleTimeoutSeconds !== undefined
|
|
832
|
+
? { idle_timeout_seconds: options.idleTimeoutSeconds }
|
|
833
|
+
: {}),
|
|
834
|
+
}),
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
/** Deletes a lobby. Safe to call when it is already gone. */
|
|
838
|
+
async deleteLobby(lobbyId) {
|
|
839
|
+
await this.request(`/lobbies/${lobbyId}`, { method: 'DELETE' });
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Adds a user to a lobby, or updates them when they are already a member.
|
|
843
|
+
*
|
|
844
|
+
* Pass `flags: LobbyMemberFlags.CanLinkLobby` to let that user configure the
|
|
845
|
+
* lobby's linked channel — grant it only to the lobby owner/administrator.
|
|
846
|
+
*/
|
|
847
|
+
addLobbyMember(lobbyId, userId, options = {}) {
|
|
848
|
+
return this.request(`/lobbies/${lobbyId}/members/${userId}`, {
|
|
849
|
+
method: 'PUT',
|
|
850
|
+
body: JSON.stringify({
|
|
851
|
+
...(options.metadata !== undefined ? { metadata: options.metadata } : {}),
|
|
852
|
+
...(options.flags !== undefined ? { flags: options.flags } : {}),
|
|
853
|
+
...(options.additional_name !== undefined
|
|
854
|
+
? { additional_name: options.additional_name }
|
|
855
|
+
: {}),
|
|
856
|
+
}),
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
/**
|
|
860
|
+
* Upserts or removes up to 25 members in one request.
|
|
861
|
+
*
|
|
862
|
+
* Members are upserted unless `remove_member: true`. Users failing permission
|
|
863
|
+
* checks — or already at the per-application lobby cap and not already a
|
|
864
|
+
* member — are **silently dropped**, so treat the response as authoritative.
|
|
865
|
+
*/
|
|
866
|
+
bulkUpdateLobbyMembers(lobbyId, members) {
|
|
867
|
+
return this.request(`/lobbies/${lobbyId}/members/bulk`, {
|
|
868
|
+
method: 'POST',
|
|
869
|
+
body: JSON.stringify(members),
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
/** Removes a member. Safe when they already left, but fails if the lobby is gone. */
|
|
873
|
+
async removeLobbyMember(lobbyId, userId) {
|
|
874
|
+
await this.request(`/lobbies/${lobbyId}/members/${userId}`, { method: 'DELETE' });
|
|
875
|
+
}
|
|
876
|
+
/**
|
|
877
|
+
* Links a guild text channel to a lobby.
|
|
878
|
+
*
|
|
879
|
+
* - Needs a **Bearer** user token: the acting user must be a lobby member with
|
|
880
|
+
* {@link LobbyMemberFlags.CanLinkLobby}.
|
|
881
|
+
* - The channel must be a guild text channel, not age-restricted, and not
|
|
882
|
+
* already linked to another lobby.
|
|
883
|
+
* - **Every lobby member can read and post** in the linked channel in-game,
|
|
884
|
+
* even when it is private in Discord. Warn the user performing the link.
|
|
885
|
+
* - Capped at 20 calls per 2 hours per application in development.
|
|
886
|
+
*
|
|
887
|
+
* @returns the lobby, with `linked_channel` populated.
|
|
888
|
+
*/
|
|
889
|
+
linkChannelToLobby(lobbyId, channelId, userToken) {
|
|
890
|
+
return this.request(`/lobbies/${lobbyId}/channel-linking`, {
|
|
891
|
+
method: 'PATCH',
|
|
892
|
+
body: JSON.stringify({ channel_id: channelId }),
|
|
893
|
+
...this.asUser(userToken),
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Unlinks the lobby's channel by sending the same endpoint an empty body.
|
|
898
|
+
*
|
|
899
|
+
* Needs a **Bearer** user token whose user has the `CanLinkLobby` flag — but
|
|
900
|
+
* **no** Discord-side channel permissions.
|
|
901
|
+
*/
|
|
902
|
+
unlinkChannelFromLobby(lobbyId, userToken) {
|
|
903
|
+
return this.request(`/lobbies/${lobbyId}/channel-linking`, {
|
|
904
|
+
method: 'PATCH',
|
|
905
|
+
body: JSON.stringify({}),
|
|
906
|
+
...this.asUser(userToken),
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Sends a message to a lobby. Forwarded to the linked channel when one is
|
|
911
|
+
* linked; if forwarding fails (e.g. AutoMod) the lobby message is still
|
|
912
|
+
* delivered to other members.
|
|
913
|
+
*
|
|
914
|
+
* Needs a **Bearer** user token — the caller must be a lobby member.
|
|
915
|
+
*/
|
|
916
|
+
sendLobbyMessage(lobbyId, options, userToken) {
|
|
917
|
+
return this.request(`/lobbies/${lobbyId}/messages`, {
|
|
918
|
+
method: 'POST',
|
|
919
|
+
body: JSON.stringify({
|
|
920
|
+
content: options.content,
|
|
921
|
+
...(options.metadata ? { metadata: options.metadata } : {}),
|
|
922
|
+
...(options.flags !== undefined ? { flags: options.flags } : {}),
|
|
923
|
+
}),
|
|
924
|
+
...this.asUser(userToken),
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
/** Lists recent lobby messages (1–200, default 50) for a member of the lobby. */
|
|
928
|
+
getLobbyMessages(lobbyId, userToken, options = {}) {
|
|
929
|
+
const query = options.limit !== undefined ? `?limit=${options.limit}` : '';
|
|
930
|
+
return this.request(`/lobbies/${lobbyId}/messages${query}`, {
|
|
931
|
+
...this.asUser(userToken),
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* Creates a single-use invite to the lobby's linked channel for the calling
|
|
936
|
+
* user — the equivalent of the SDK's `JoinLinkedLobbyGuild`.
|
|
937
|
+
*
|
|
938
|
+
* Needs a **Bearer** user token and a linked channel. Expires after one hour.
|
|
939
|
+
* Only users with a real linked Discord account can join; provisional accounts
|
|
940
|
+
* must link first. Note that server admins cannot restrict who may join this
|
|
941
|
+
* way — any lobby member can mint an invite.
|
|
942
|
+
*/
|
|
943
|
+
createLobbyChannelInviteForSelf(lobbyId, userToken) {
|
|
944
|
+
return this.request(`/lobbies/${lobbyId}/members/@me/invites`, {
|
|
945
|
+
method: 'POST',
|
|
946
|
+
...this.asUser(userToken),
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
/** Creates a linked-channel invite on behalf of the application, for one user. */
|
|
950
|
+
createLobbyChannelInviteForUser(lobbyId, userId) {
|
|
951
|
+
return this.request(`/lobbies/${lobbyId}/members/${userId}/invites`, {
|
|
952
|
+
method: 'POST',
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* Switches authenticated requests to a **Bearer** user token.
|
|
957
|
+
*
|
|
958
|
+
* Lobby operations acting on behalf of a user need the user's token with the
|
|
959
|
+
* `sdk.social_layer` scope; the default bot token is rejected. `authenticated:
|
|
960
|
+
* false` suppresses the `Authorization: Bot …` header, and the explicit header
|
|
961
|
+
* is merged last so it wins.
|
|
962
|
+
*/
|
|
963
|
+
asUser(userToken) {
|
|
964
|
+
return { authenticated: false, headers: { Authorization: `Bearer ${userToken}` } };
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
function getDefaultContentTypeHeader(body) {
|
|
968
|
+
// A body-less request (DELETE, a GET with no payload) must not claim to be
|
|
969
|
+
// JSON: strict servers reject a Content-Type that does not match the body.
|
|
970
|
+
if (body === undefined || body === null)
|
|
971
|
+
return {};
|
|
972
|
+
return body instanceof FormData ? {} : { 'Content-Type': 'application/json' };
|
|
973
|
+
}
|
|
974
|
+
function encodeDiscordReaction(reaction) {
|
|
975
|
+
if (typeof reaction !== 'string') {
|
|
976
|
+
return encodeURIComponent(reaction.id ? `${reaction.name}:${reaction.id}` : reaction.name);
|
|
977
|
+
}
|
|
978
|
+
const trimmed = reaction.trim();
|
|
979
|
+
const customEmojiMatch = trimmed.match(/^<a?:([^:>]+):(\d+)>$/);
|
|
980
|
+
if (customEmojiMatch) {
|
|
981
|
+
const [, name, id] = customEmojiMatch;
|
|
982
|
+
return encodeURIComponent(`${name}:${id}`);
|
|
983
|
+
}
|
|
984
|
+
if (/^[^:\s]+:\d+$/.test(trimmed)) {
|
|
985
|
+
return encodeURIComponent(trimmed);
|
|
986
|
+
}
|
|
987
|
+
return encodeURIComponent(trimmed);
|
|
988
|
+
}
|