-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
messageInteraction.ts
461 lines (420 loc) · 16.7 KB
/
messageInteraction.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import {
AnyComponent,
InitialCallbackResponse,
InteractionResponseFlags,
InteractionResponseType
} from '../../constants';
import { BaseSlashCreator, ComponentRegisterCallback } from '../../creator';
import { RespondFunction } from '../../server';
import {
convertCallbackResponse,
formatAllowedMentions,
FormattedAllowedMentions,
MessageAllowedMentions
} from '../../util';
import { CreatePollOptions, Message, MessageEmbedOptions } from '../message';
import { BaseInteractionContext } from './baseInteraction';
/** Represents a interaction context that handles messages. */
export class MessageInteractionContext<
ServerContext extends any = unknown
> extends BaseInteractionContext<ServerContext> {
/** Whether the initial response was sent. */
initiallyResponded = false;
/** Whether there is a deferred message available. */
deferred = false;
/** The original message ID, automatically set when editing/fetching original message. */
messageID?: string;
/** @hidden */
protected _respond: RespondFunction;
/** @hidden */
protected _timeout?: any;
/**
* @param creator The instantiating creator.
* @param data The interaction data.
* @param respond The response function for the interaction.
* @param serverContext The context of the server.
*/
constructor(creator: BaseSlashCreator, data: any, respond: RespondFunction, serverContext: ServerContext) {
super(creator, data, serverContext);
this._respond = respond;
}
/**
* Fetches a message.
* @param messageID The ID of the message, defaults to the original message
*/
async fetch(messageID = '@original'): Promise<Message> {
const data = await this.creator.api.fetchInteractionMessage(
this.creator.options.applicationID,
this.interactionToken,
messageID
);
if (messageID === '@original') this.messageID = data.id;
return new Message(data, this.creator, this);
}
/**
* Sends a message, if it already made an initial response, this will create a follow-up message.
* If the context has created a deferred message, it will edit that deferred message,
* and future calls to this function create follow ups.
* This will return `true` or a {@link InitialCallbackResponse} if it's an initial response, otherwise a {@link Message} will be returned.
* Note that when making a follow-up message, the `ephemeral` option is ignored.
* @param content The content of the message
* @returns `true` or a {@link InitialCallbackResponse} if the initial response passed, otherwise a {@link Message} of the follow-up message.
*/
async send(content: string | MessageOptions): Promise<true | InitialCallbackResponse | Message> {
if (this.expired) throw new Error('This interaction has expired');
const options = typeof content === 'string' ? { content } : content;
if (typeof options !== 'object') throw new Error('Message options is not an object.');
if (!options.content && !options.embeds && !options.files && !options.poll)
throw new Error('No valid options were given.');
if (options.ephemeral && !options.flags) options.flags = InteractionResponseFlags.EPHEMERAL;
const allowedMentions = options.allowedMentions
? formatAllowedMentions(options.allowedMentions, this.creator.allowedMentions as FormattedAllowedMentions)
: this.creator.allowedMentions;
if (!this.initiallyResponded) {
this.initiallyResponded = true;
clearTimeout(this._timeout);
const response = await this._respond({
status: 200,
body: {
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
tts: options.tts,
content: options.content,
embeds: options.embeds,
flags: options.flags,
allowed_mentions: allowedMentions,
components: options.components,
attachments: options.attachments,
poll: options.poll
}
},
files: options.files
});
return response ? convertCallbackResponse(response, this) : true;
} else if (this.initiallyResponded && this.deferred) return this.editOriginal(content);
else return this.sendFollowUp(options);
}
/**
* Sends a follow-up message.
* @param content The content of the message
*/
async sendFollowUp(content: string | MessageOptions): Promise<Message> {
if (this.expired) throw new Error('This interaction has expired');
const options = typeof content === 'string' ? { content } : content;
if (typeof options !== 'object') throw new Error('Message options is not an object.');
if (!options.content && !options.embeds && !options.files && !options.poll)
throw new Error('No valid options were given.');
if (options.ephemeral && !options.flags) options.flags = InteractionResponseFlags.EPHEMERAL;
const allowedMentions = options.allowedMentions
? formatAllowedMentions(options.allowedMentions, this.creator.allowedMentions as FormattedAllowedMentions)
: this.creator.allowedMentions;
const data = await this.creator.api.followUpMessage(
this.creator.options.applicationID,
this.interactionToken,
{
tts: options.tts,
content: options.content,
embeds: options.embeds,
allowed_mentions: allowedMentions,
components: options.components,
flags: options.flags,
attachments: options.attachments,
poll: options.poll
},
options.files
);
return new Message(data, this.creator, this);
}
/**
* Edits a message.
* @param messageID The message's ID
* @param content The content of the message
*/
async edit(messageID: string, content: string | EditMessageOptions): Promise<Message> {
if (this.expired) throw new Error('This interaction has expired');
const options = typeof content === 'string' ? { content } : content;
if (typeof options !== 'object') throw new Error('Message options is not an object.');
if (
!options.content &&
!options.embeds &&
!options.components &&
!options.files &&
!options.attachments &&
!options.poll
)
throw new Error('No valid options were given.');
const allowedMentions = options.allowedMentions
? formatAllowedMentions(options.allowedMentions, this.creator.allowedMentions as FormattedAllowedMentions)
: this.creator.allowedMentions;
const data = await this.creator.api.updateInteractionMessage(
this.creator.options.applicationID,
this.interactionToken,
messageID,
{
content: options.content,
embeds: options.embeds,
allowed_mentions: allowedMentions,
components: options.components,
flags: options.flags,
attachments: options.attachments,
poll: options.poll
},
options.files
);
return new Message(data, this.creator, this);
}
/**
* Edits the original message.
* Note: This will error with ephemeral messages or deferred ephemeral messages.
* @param content The content of the message
* @param options The message options
*/
async editOriginal(content: string | EditMessageOptions): Promise<Message> {
this.deferred = false;
const message = await this.edit('@original', content);
this.messageID = message.id;
return message;
}
/**
* Deletes a message. If the message ID was not defined, the original message is used.
* @param messageID The message's ID
*/
async delete(messageID?: string) {
if (this.expired) throw new Error('This interaction has expired');
await this.creator.api.deleteInteractionMessage(
this.creator.options.applicationID,
this.interactionToken,
messageID
);
if (!messageID || messageID === '@original' || messageID === this.messageID) this.messageID = undefined;
}
/**
* Creates a deferred message. To users, this will show as
* "Bot is thinking..." until the deferred message is edited.
* @param ephemeralOrFlags If its a number, the message flags to use, if a boolean, whether to make the deferred message ephemeral.
* @returns Whether the deferred message passed or the callback response if available
*/
async defer(ephemeralOrFlags: number | boolean = 0): Promise<boolean | InitialCallbackResponse> {
const flags =
typeof ephemeralOrFlags === 'boolean'
? ephemeralOrFlags
? InteractionResponseFlags.EPHEMERAL
: 0
: ephemeralOrFlags;
if (!this.initiallyResponded && !this.deferred) {
this.initiallyResponded = true;
this.deferred = true;
clearTimeout(this._timeout);
const response = await this._respond({
status: 200,
body: {
type: InteractionResponseType.DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE,
data: {
flags
}
}
});
return response ? convertCallbackResponse(response, this) : true;
}
return false;
}
/**
* Creates a message that prompts the user for a premium subscription.
* @returns Whether the message passed or the callback response if available
* @deprecated Use `ComponentButtonPremium` instead.
*/
async promptPremium(): Promise<boolean | InitialCallbackResponse> {
if (!this.initiallyResponded && !this.deferred) {
this.initiallyResponded = true;
this.deferred = true;
clearTimeout(this._timeout);
const response = await this._respond({
status: 200,
body: {
type: InteractionResponseType.PREMIUM_REQUIRED,
data: {}
}
});
return response ? convertCallbackResponse(response, this) : true;
}
return false;
}
/**
* Launches the activity this app is associated with.
* @returns Whether the message passed or the callback response if available
*/
async launchActivity(): Promise<boolean | InitialCallbackResponse> {
if (!this.initiallyResponded && !this.deferred) {
this.initiallyResponded = true;
this.deferred = true;
clearTimeout(this._timeout);
const response = await this._respond({
status: 200,
body: {
type: InteractionResponseType.LAUNCH_ACTIVITY,
data: {}
}
});
return response ? convertCallbackResponse(response, this) : true;
}
return false;
}
/**
* Registers a component callback from the initial message.
* This unregisters automatically when the context expires.
* @param custom_id The custom ID of the component to register
* @param callback The callback to use on interaction
* @param expiration The expiration time of the callback in milliseconds. Use null for no expiration (Although, in this case, global components might be more consistent).
* @param onExpired A function to be called when the component expires.
*/
registerComponent(
custom_id: string,
callback: ComponentRegisterCallback,
expiration: number = 1000 * 60 * 15,
onExpired?: () => void
) {
if (!this.initiallyResponded || this.deferred)
throw new Error('You must send a message before registering components');
if (!this.messageID)
throw new Error('Fetch your original message or use deferred messages before registering components');
this.creator._componentCallbacks.set(`${this.messageID}-${custom_id}`, {
callback,
expires: expiration != null ? Date.now() + expiration : undefined,
onExpired
});
if (expiration != null && this.creator.options.componentTimeouts)
setTimeout(() => {
if (this.creator._componentCallbacks.has(`${this.messageID}-${custom_id}`)) {
if (onExpired) onExpired();
this.creator._componentCallbacks.delete(`${this.messageID}-${custom_id}`);
}
}, expiration);
}
/**
* Registers a component callback from a message.
* This unregisters automatically when the context expires.
* @param message_id The message ID of the component to register
* @param custom_id The custom ID of the component to register
* @param callback The callback to use on interaction
* @param expiration The expiration time of the callback in milliseconds. Use null for no expiration (Although, in this case, global components might be more consistent).
* @param onExpired A function to be called when the component expires.
*/
registerComponentFrom(
message_id: string,
custom_id: string,
callback: ComponentRegisterCallback,
expiration: number = 1000 * 60 * 15,
onExpired?: () => void
) {
this.creator._componentCallbacks.set(`${message_id}-${custom_id}`, {
callback,
expires: expiration != null ? Date.now() + expiration : undefined,
onExpired
});
if (expiration != null && this.creator.options.componentTimeouts)
setTimeout(() => {
if (this.creator._componentCallbacks.has(`${message_id}-${custom_id}`)) {
if (onExpired) onExpired();
this.creator._componentCallbacks.delete(`${message_id}-${custom_id}`);
}
}, expiration);
}
/**
* Unregisters a component callback.
* @param custom_id The custom ID of the component to unregister
* @param message_id The message ID of the component to unregister, defaults to initial message ID if any
*/
unregisterComponent(custom_id: string, message_id?: string) {
if (!message_id) {
if (!this.messageID) throw new Error('The initial message ID was not provided by the context!');
else message_id = this.messageID;
}
return this.creator._componentCallbacks.delete(`${message_id}-${custom_id}`);
}
/**
* Registers a wildcard component callback on a message.
* This unregisters automatically when the context expires.
* @param message_id The message ID of the component to register
* @param callback The callback to use on interaction
* @param expiration The expiration time of the callback in milliseconds. Use null for no expiration (Although, in this case, global components might be more consistent).
* @param onExpired A function to be called when the component expires.
*/
registerWildcardComponent(
message_id: string,
callback: ComponentRegisterCallback,
expiration: number = 1000 * 60 * 15,
onExpired?: () => void
) {
if (this.expired) throw new Error('This interaction has expired');
this.creator._componentCallbacks.set(`${message_id}-*`, {
callback,
expires: expiration != null ? this.invokedAt + expiration : undefined,
onExpired
});
if (expiration != null && this.creator.options.componentTimeouts)
setTimeout(() => {
if (this.creator._componentCallbacks.has(`${message_id}-*`)) {
if (onExpired) onExpired();
this.creator._componentCallbacks.delete(`${message_id}-*`);
}
}, expiration);
}
/**
* Unregisters a component callback.
* @param message_id The message ID of the component to unregister, defaults to the invoking message ID.
*/
unregisterWildcardComponent(message_id: string) {
return this.creator._componentCallbacks.delete(`${message_id}-*`);
}
}
/** The options for {@link MessageInteractionContext#edit}. */
export interface EditMessageOptions {
/** The message content. */
content?: string;
/** The embeds of the message. */
embeds?: MessageEmbedOptions[];
/** The mentions allowed to be used in this message. */
allowedMentions?: MessageAllowedMentions;
/** The attachment(s) to send with the message. */
files?: MessageFile[];
/** The components of the message. */
components?: AnyComponent[];
/** The flags to use in the message. */
flags?: number;
/** The attachment data of the message. */
attachments?: MessageAttachmentOptions[];
/** A poll. */
poll?: CreatePollOptions;
}
/** A file within {@link EditMessageOptions}. */
export interface MessageFile {
/** The attachment to send. */
file: any;
/** The name of the file. */
name: string;
}
/** A message attachment describing a file. */
export interface MessageAttachmentOptions {
/** The name of the attachment. */
name?: string;
/** The ID of the attachment. For existing attachments, this must be the ID snowflake of the attachment, otherwise, this will be the index of the files being sent to Discord. */
id: string | number;
/** The title of the attachment. */
title?: string;
/** The description of the attachment. */
description?: string;
/** The duration, in seconds, of the voice message. */
duration_secs?: number;
/** A base64-encoded bytearray that represents a sampled waveform. */
waveform?: string;
}
/** The options for {@link MessageInteractionContext#send} and {@link MessageInteractionContext#sendFollowUp}. */
export interface MessageOptions extends EditMessageOptions {
/** Whether to use TTS for the content. */
tts?: boolean;
/**
* Whether or not the message should be ephemeral.
* Ignored if `flags` is defined.
*/
ephemeral?: boolean;
}