-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
InteractionResponses.js
319 lines (288 loc) · 11.4 KB
/
InteractionResponses.js
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
'use strict';
const { isJSONEncodable } = require('@discordjs/builders');
const { InteractionResponseType, MessageFlags, Routes, InteractionType } = require('discord-api-types/v10');
const { DiscordjsError, ErrorCodes } = require('../../errors');
const InteractionCollector = require('../InteractionCollector');
const InteractionResponse = require('../InteractionResponse');
const MessagePayload = require('../MessagePayload');
/**
* @typedef {Object} ModalComponentData
* @property {string} title The title of the modal
* @property {string} customId The custom id of the modal
* @property {ActionRow[]} components The components within this modal
*/
/**
* Interface for classes that support shared interaction response types.
* @interface
*/
class InteractionResponses {
/**
* Options for deferring the reply to an {@link BaseInteraction}.
* @typedef {Object} InteractionDeferReplyOptions
* @property {boolean} [ephemeral] Whether the reply should be ephemeral
* @property {boolean} [fetchReply] Whether to fetch the reply
*/
/**
* Options for deferring and updating the reply to a {@link MessageComponentInteraction}.
* @typedef {Object} InteractionDeferUpdateOptions
* @property {boolean} [fetchReply] Whether to fetch the reply
*/
/**
* Options for a reply to a {@link BaseInteraction}.
* @typedef {BaseMessageOptions} InteractionReplyOptions
* @property {boolean} [tts=false] Whether the message should be spoken aloud
* @property {boolean} [ephemeral] Whether the reply should be ephemeral
* @property {boolean} [fetchReply] Whether to fetch the reply
* @property {MessageFlags} [flags] Which flags to set for the message.
* <info>Only `MessageFlags.SuppressEmbeds` and `MessageFlags.Ephemeral` can be set.</info>
*/
/**
* Options for updating the message received from a {@link MessageComponentInteraction}.
* @typedef {MessageEditOptions} InteractionUpdateOptions
* @property {boolean} [fetchReply] Whether to fetch the reply
*/
/**
* Defers the reply to this interaction.
* @param {InteractionDeferReplyOptions} [options] Options for deferring the reply to this interaction
* @returns {Promise<Message|InteractionResponse>}
* @example
* // Defer the reply to this interaction
* interaction.deferReply()
* .then(console.log)
* .catch(console.error)
* @example
* // Defer to send an ephemeral reply later
* interaction.deferReply({ ephemeral: true })
* .then(console.log)
* .catch(console.error);
*/
async deferReply(options = {}) {
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
this.ephemeral = options.ephemeral ?? false;
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {
type: InteractionResponseType.DeferredChannelMessageWithSource,
data: {
flags: options.ephemeral ? MessageFlags.Ephemeral : undefined,
},
},
auth: false,
});
this.deferred = true;
return options.fetchReply ? this.fetchReply() : new InteractionResponse(this);
}
/**
* Creates a reply to this interaction.
* <info>Use the `fetchReply` option to get the bot's reply message.</info>
* @param {string|MessagePayload|InteractionReplyOptions} options The options for the reply
* @returns {Promise<Message|InteractionResponse>}
* @example
* // Reply to the interaction and fetch the response
* interaction.reply({ content: 'Pong!', fetchReply: true })
* .then((message) => console.log(`Reply sent with content ${message.content}`))
* .catch(console.error);
* @example
* // Create an ephemeral reply with an embed
* const embed = new EmbedBuilder().setDescription('Pong!');
*
* interaction.reply({ embeds: [embed], ephemeral: true })
* .then(() => console.log('Reply sent.'))
* .catch(console.error);
*/
async reply(options) {
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
this.ephemeral = options.ephemeral ?? false;
let messagePayload;
if (options instanceof MessagePayload) messagePayload = options;
else messagePayload = MessagePayload.create(this, options);
const { body: data, files } = await messagePayload.resolveBody().resolveFiles();
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {
type: InteractionResponseType.ChannelMessageWithSource,
data,
},
files,
auth: false,
});
this.replied = true;
return options.fetchReply ? this.fetchReply() : new InteractionResponse(this);
}
/**
* Fetches a reply to this interaction.
* @see Webhook#fetchMessage
* @param {Snowflake|'@original'} [message='@original'] The response to fetch
* @returns {Promise<Message>}
* @example
* // Fetch the initial reply to this interaction
* interaction.fetchReply()
* .then(reply => console.log(`Replied with ${reply.content}`))
* .catch(console.error);
*/
fetchReply(message = '@original') {
return this.webhook.fetchMessage(message);
}
/**
* Options that can be passed into {@link InteractionResponses#editReply}.
* @typedef {WebhookEditMessageOptions} InteractionEditReplyOptions
* @property {MessageResolvable|'@original'} [message='@original'] The response to edit
*/
/**
* Edits a reply to this interaction.
* @see Webhook#editMessage
* @param {string|MessagePayload|InteractionEditReplyOptions} options The new options for the message
* @returns {Promise<Message>}
* @example
* // Edit the initial reply to this interaction
* interaction.editReply('New content')
* .then(console.log)
* .catch(console.error);
*/
async editReply(options) {
if (!this.deferred && !this.replied) throw new DiscordjsError(ErrorCodes.InteractionNotReplied);
const msg = await this.webhook.editMessage(options.message ?? '@original', options);
this.replied = true;
return msg;
}
/**
* Deletes a reply to this interaction.
* @see Webhook#deleteMessage
* @param {MessageResolvable|'@original'} [message='@original'] The response to delete
* @returns {Promise<void>}
* @example
* // Delete the initial reply to this interaction
* interaction.deleteReply()
* .then(console.log)
* .catch(console.error);
*/
async deleteReply(message = '@original') {
await this.webhook.deleteMessage(message);
}
/**
* Send a follow-up message to this interaction.
* @param {string|MessagePayload|InteractionReplyOptions} options The options for the reply
* @returns {Promise<Message>}
*/
followUp(options) {
if (!this.deferred && !this.replied) return Promise.reject(new DiscordjsError(ErrorCodes.InteractionNotReplied));
return this.webhook.send(options);
}
/**
* Defers an update to the message to which the component was attached.
* @param {InteractionDeferUpdateOptions} [options] Options for deferring the update to this interaction
* @returns {Promise<Message|InteractionResponse>}
* @example
* // Defer updating and reset the component's loading state
* interaction.deferUpdate()
* .then(console.log)
* .catch(console.error);
*/
async deferUpdate(options = {}) {
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {
type: InteractionResponseType.DeferredMessageUpdate,
},
auth: false,
});
this.deferred = true;
return options.fetchReply ? this.fetchReply() : new InteractionResponse(this, this.message?.interaction?.id);
}
/**
* Updates the original message of the component on which the interaction was received on.
* @param {string|MessagePayload|InteractionUpdateOptions} options The options for the updated message
* @returns {Promise<Message|void>}
* @example
* // Remove the components from the message
* interaction.update({
* content: "A component interaction was received",
* components: []
* })
* .then(console.log)
* .catch(console.error);
*/
async update(options) {
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
let messagePayload;
if (options instanceof MessagePayload) messagePayload = options;
else messagePayload = MessagePayload.create(this, options);
const { body: data, files } = await messagePayload.resolveBody().resolveFiles();
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {
type: InteractionResponseType.UpdateMessage,
data,
},
files,
auth: false,
});
this.replied = true;
return options.fetchReply ? this.fetchReply() : new InteractionResponse(this, this.message.interaction?.id);
}
/**
* Shows a modal component
* @param {APIModal|ModalData|Modal} modal The modal to show
* @returns {Promise<void>}
*/
async showModal(modal) {
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {
type: InteractionResponseType.Modal,
data: isJSONEncodable(modal) ? modal.toJSON() : this.client.options.jsonTransformer(modal),
},
});
this.replied = true;
}
/**
* An object containing the same properties as {@link CollectorOptions}, but a few less:
* @typedef {Object} AwaitModalSubmitOptions
* @property {CollectorFilter} [filter] The filter applied to this collector
* @property {number} time Time in milliseconds to wait for an interaction before rejecting
*/
/**
* Collects a single modal submit interaction that passes the filter.
* The Promise will reject if the time expires.
* @param {AwaitModalSubmitOptions} options Options to pass to the internal collector
* @returns {Promise<ModalSubmitInteraction>}
* @example
* // Collect a modal submit interaction
* const filter = (interaction) => interaction.customId === 'modal';
* interaction.awaitModalSubmit({ filter, time: 15_000 })
* .then(interaction => console.log(`${interaction.customId} was submitted!`))
* .catch(console.error);
*/
awaitModalSubmit(options) {
if (typeof options.time !== 'number') throw new DiscordjsError(ErrorCodes.InvalidType, 'time', 'number');
const _options = { ...options, max: 1, interactionType: InteractionType.ModalSubmit };
return new Promise((resolve, reject) => {
const collector = new InteractionCollector(this.client, _options);
collector.once('end', (interactions, reason) => {
const interaction = interactions.first();
if (interaction) resolve(interaction);
else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason));
});
});
}
static applyToClass(structure, ignore = []) {
const props = [
'deferReply',
'reply',
'fetchReply',
'editReply',
'deleteReply',
'followUp',
'deferUpdate',
'update',
'showModal',
'awaitModalSubmit',
];
for (const prop of props) {
if (ignore.includes(prop)) continue;
Object.defineProperty(
structure.prototype,
prop,
Object.getOwnPropertyDescriptor(InteractionResponses.prototype, prop),
);
}
}
}
module.exports = InteractionResponses;