feat: awaitModal

This commit is contained in:
March 7th
2022-10-09 19:37:04 +07:00
parent fecfa7d03b
commit a141adf385
17 changed files with 335 additions and 67 deletions

View File

@@ -597,7 +597,7 @@ class ApplicationCommand extends Base {
* @param {Message} message Discord Message
* @param {Array<string>} subCommandArray SubCommand Array
* @param {Array<string>} options The options to Slash Command
* @returns {Promise<InteractionResponseBody>}
* @returns {Promise<InteractionResponse>}
*/
// eslint-disable-next-line consistent-return
async sendSlashCommand(message, subCommandArray = [], options = []) {
@@ -861,6 +861,11 @@ class ApplicationCommand extends Base {
body: data,
files: attachmentsBuffer,
});
this.client._interactionCache.set(nonce, {
channelId: message.channelId,
guildId: message.guildId,
metadata: data,
});
return new Promise((resolve, reject) => {
const handler = data => {
timeout.refresh();
@@ -911,7 +916,7 @@ class ApplicationCommand extends Base {
/**
* Message Context Menu
* @param {Message} message Discord Message
* @returns {Promise<InteractionResponseBody>}
* @returns {Promise<InteractionResponse>}
*/
async sendContextMenu(message) {
if (!(message instanceof Message())) {
@@ -941,6 +946,11 @@ class ApplicationCommand extends Base {
await this.client.api.interactions.post({
body: data,
});
this.client._interactionCache.set(nonce, {
channelId: message.channelId,
guildId: message.guildId,
metadata: data,
});
return new Promise((resolve, reject) => {
const handler = data => {
timeout.refresh();

View File

@@ -3,6 +3,7 @@
const GuildChannel = require('./GuildChannel');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const GuildTextThreadManager = require('../managers/GuildTextThreadManager');
const InteractionManager = require('../managers/InteractionManager');
const MessageManager = require('../managers/MessageManager');
/**
@@ -20,6 +21,12 @@ class BaseGuildTextChannel extends GuildChannel {
*/
this.messages = new MessageManager(this);
/**
* A manager of the interactions sent to this channel
* @type {InteractionManager}
*/
this.interactions = new InteractionManager(this);
/**
* A manager of the threads belonging to this channel
* @type {GuildTextThreadManager}

View File

@@ -4,6 +4,7 @@ const { Collection } = require('@discordjs/collection');
const { joinVoiceChannel, entersState, VoiceConnectionStatus } = require('@discordjs/voice');
const { Channel } = require('./Channel');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const InteractionManager = require('../managers/InteractionManager');
const MessageManager = require('../managers/MessageManager');
const { Status, Opcodes } = require('../util/Constants');
@@ -24,6 +25,12 @@ class DMChannel extends Channel {
* @type {MessageManager}
*/
this.messages = new MessageManager(this);
/**
* A manager of the interactions sent to this channel
* @type {InteractionManager}
*/
this.interactions = new InteractionManager(this);
}
_patch(data) {

View File

@@ -0,0 +1,113 @@
'use strict';
const { setTimeout } = require('node:timers');
const Base = require('./Base');
const { Events } = require('../util/Constants');
const SnowflakeUtil = require('../util/SnowflakeUtil');
/**
* Represents a interaction on Discord.
* @extends {Base}
*/
class InteractionResponse extends Base {
constructor(client, data) {
super(client);
/**
* The id of the channel the interaction was sent in
* @type {Snowflake}
*/
this.channelId = data.channelId;
/**
* The id of the guild the interaction was sent in, if any
* @type {?Snowflake}
*/
this.guildId = data.guildId ?? this.channel?.guild?.id ?? null;
/**
* The interaction data was sent in
* @type {Object}
*/
this.sendData = data.metadata;
this._patch(data);
}
_patch(data) {
if ('id' in data) {
/**
* The interaction response's ID
* @type {Snowflake}
*/
this.id = data.id;
}
if ('nonce' in data) {
/**
* The interaction response's nonce
* @type {Snowflake}
*/
this.nonce = data.nonce;
}
}
/**
* The timestamp the interaction response was created at
* @type {number}
* @readonly
*/
get createdTimestamp() {
return SnowflakeUtil.timestampFrom(this.id);
}
/**
* The time the interaction response was created at
* @type {Date}
* @readonly
*/
get createdAt() {
return new Date(this.createdTimestamp);
}
/**
* The channel that the interaction was sent in
* @type {TextBasedChannels}
* @readonly
*/
get channel() {
return this.client.channels.resolve(this.channelId);
}
/**
* The guild the inteaaction was sent in (if in a guild channel)
* @type {?Guild}
* @readonly
*/
get guild() {
return this.client.guilds.resolve(this.guildId) ?? this.channel?.guild ?? null;
}
/**
* Get Modal send from interaction
* @param {?number} time Time to wait for modal (Default: 120000)
* @returns {Modal}
*/
awaitModal(time = 120_000) {
return new Promise((resolve, reject) => {
const handler = modal => {
timeout.refresh();
if (modal.nonce != this.nonce || modal.id != this.id) return;
clearTimeout(timeout);
this.client.removeListener(Events.INTERACTION_MODAL_CREATE, handler);
this.client.decrementMaxListeners();
resolve(modal);
};
const timeout = setTimeout(() => {
this.client.removeListener(Events.INTERACTION_MODAL_CREATE, handler);
this.client.decrementMaxListeners();
reject(new Error('MODAL_TIMEOUT'));
}, time || 120_000).unref();
this.client.incrementMaxListeners();
this.client.on(Events.INTERACTION_MODAL_CREATE, handler);
});
}
}
module.exports = InteractionResponse;

View File

@@ -1043,7 +1043,7 @@ class Message extends Base {
/**
* Click specific button
* @param {MessageButton|string} button Button ID
* @returns {Promise<InteractionResponseBody>}
* @returns {Promise<InteractionResponse>}
*/
clickButton(button) {
let buttonID;
@@ -1066,7 +1066,7 @@ class Message extends Base {
* Select specific menu or First Menu
* @param {string|Array<string>} menuID Select Menu specific id or auto select first Menu
* @param {Array<string>} options Menu Options
* @returns {Promise<InteractionResponseBody>}
* @returns {Promise<InteractionResponse>}
*/
async selectMenu(menuID, options = []) {
if (!this.components[0]) throw new TypeError('MESSAGE_NO_COMPONENTS');
@@ -1100,7 +1100,7 @@ class Message extends Base {
* Send context Menu v2
* @param {Snowflake} botId Bot id
* @param {string} commandName Command name in Context Menu
* @returns {Promise<InteractionResponseBody>}
* @returns {Promise<InteractionResponse>}
*/
async contextMenu(botId, commandName) {
if (!botId) throw new Error('Bot ID is required');

View File

@@ -168,27 +168,33 @@ class MessageButton extends BaseMessageComponent {
/**
* Click the button
* @param {Message} message Discord Message
* @returns {Promise<InteractionResponseBody>}
* @returns {Promise<InteractionResponse>}
*/
async click(message) {
const nonce = SnowflakeUtil.generate();
if (!(message instanceof Message())) throw new Error('[UNKNOWN_MESSAGE] Please pass a valid Message');
if (!this.customId || this.style == 5 || this.disabled) return false; // Button URL, Disabled
await message.client.api.interactions.post({
const data = {
type: 3, // ?
nonce,
guild_id: message.guild?.id ?? null, // In DMs
channel_id: message.channel.id,
message_id: message.id,
application_id: message.applicationId ?? message.author.id,
session_id: message.client.session_id,
message_flags: message.flags.bitfield,
data: {
type: 3, // ?
nonce,
guild_id: message.guild?.id ?? null, // In DMs
channel_id: message.channel.id,
message_id: message.id,
application_id: message.applicationId ?? message.author.id,
session_id: message.client.session_id,
message_flags: message.flags.bitfield,
data: {
component_type: 2, // Button
custom_id: this.customId,
},
component_type: 2, // Button
custom_id: this.customId,
},
};
await message.client.api.interactions.post({
data,
});
message.client._interactionCache.set(nonce, {
channelId: message.channelId,
guildId: message.guildId,
metadata: data,
});
return new Promise((resolve, reject) => {
const handler = data => {

View File

@@ -215,7 +215,7 @@ class MessageSelectMenu extends BaseMessageComponent {
* Mesage select menu
* @param {Message} message The message this select menu is for
* @param {Array<string>} values The values of the select menu
* @returns {Promise<InteractionResponseBody>}
* @returns {Promise<InteractionResponse>}
*/
async select(message, values = []) {
// Github copilot is the best :))
@@ -242,23 +242,29 @@ class MessageSelectMenu extends BaseMessageComponent {
);
}
const nonce = SnowflakeUtil.generate();
await message.client.api.interactions.post({
const data = {
type: 3, // ?
guild_id: message.guild?.id ?? null, // In DMs
channel_id: message.channel.id,
message_id: message.id,
application_id: message.applicationId ?? message.author.id,
session_id: message.client.session_id,
message_flags: message.flags.bitfield,
data: {
type: 3, // ?
guild_id: message.guild?.id ?? null, // In DMs
channel_id: message.channel.id,
message_id: message.id,
application_id: message.applicationId ?? message.author.id,
session_id: message.client.session_id,
message_flags: message.flags.bitfield,
data: {
component_type: 3, // Select Menu
custom_id: this.customId,
type: 3, // Select Menu
values,
},
nonce,
component_type: 3, // Select Menu
custom_id: this.customId,
type: 3, // Select Menu
values,
},
nonce,
};
await message.client.api.interactions.post({
data,
});
message.client._interactionCache.set(nonce, {
channelId: message.channelId,
guildId: message.guildId,
metadata: data,
});
return new Promise((resolve, reject) => {
const handler = data => {

View File

@@ -59,13 +59,29 @@ class Modal {
this.application = data.application
? {
...data.application,
bot: data.application.bot ? new User(client, data.application.bot) : null,
bot: data.application.bot ? new User(client, data.application.bot, data.application) : null,
}
: null;
this.client = client;
}
/**
* Get Interaction Response
* @type {?InteractionResponse}
* @readonly
*/
get sendFromInteraction() {
if (this.id && this.nonce && this.client) {
const cache = this.client._interactionCache.get(this.nonce);
const channel = cache.guildId
? this.client.guilds.cache.get(cache.guildId)?.channels.cache.get(cache.channelId)
: this.client.channels.cache.get(cache.channelId);
return channel.interactions.cache.get(this.id);
}
return null;
}
/**
* Adds components to the modal.
* @param {...MessageActionRowResolvable[]} components The components to add
@@ -135,24 +151,27 @@ class Modal {
/**
* @typedef {Object} ModalReplyData
* @property {GuildResolvable} [guild] Guild to send the modal to
* @property {TextChannelResolvable} [channel] User to send the modal to
* @property {?GuildResolvable} [guild] Guild to send the modal to
* @property {?TextChannelResolvable} [channel] User to send the modal to
* @property {TextInputComponentReplyData[]} [data] Reply data
*/
/**
* Reply to this modal with data. (Event only)
* @param {ModalReplyData} data Data to send with the modal
* @returns {Promise<InteractionResponseBody>}
* @returns {Promise<InteractionResponse>}
* @example
* // With Event
* client.on('interactionModalCreate', modal => {
* modal.reply('guildId', 'channelId', {
* customId: 'code',
* value: '1+1'
* }, {
* customId: 'message',
* value: 'hello'
* modal.reply({
* data: [
* {
* customId: 'code',
* value: '1+1'
* }, {
* customId: 'message',
* value: 'hello'
* }
* ]
* })
* })
*/
@@ -160,8 +179,9 @@ class Modal {
if (typeof data !== 'object') throw new TypeError('ModalReplyData must be an object');
if (!Array.isArray(data.data)) throw new TypeError('ModalReplyData.data must be an array');
if (!this.application) throw new Error('Modal cannot reply (Missing Application)');
const guild = this.client.guilds.resolveId(data.guild);
const channel = this.client.channels.resolveId(data.channel);
const data_cache = this.sendFromInteraction;
const guild = this.client.guilds.resolveId(data.guild) || data_cache.guildId || null;
const channel = this.client.channels.resolveId(data.channel) || data_cache.channelId;
// Add data to components
// this.components = [ MessageActionRow.components = [ TextInputComponent ] ]
// 5 MessageActionRow / Modal, 1 TextInputComponent / 1 MessageActionRow

View File

@@ -3,6 +3,7 @@
const { Channel } = require('./Channel');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const { RangeError } = require('../errors');
const InteractionManager = require('../managers/InteractionManager');
const MessageManager = require('../managers/MessageManager');
const ThreadMemberManager = require('../managers/ThreadMemberManager');
const Permissions = require('../util/Permissions');
@@ -35,6 +36,12 @@ class ThreadChannel extends Channel {
*/
this.messages = new MessageManager(this);
/**
* A manager of the interactions sent to this channel
* @type {InteractionManager}
*/
this.interactions = new InteractionManager(this);
/**
* A manager of the members that are part of this thread
* @type {ThreadMemberManager}

View File

@@ -16,7 +16,7 @@ const UserFlags = require('../util/UserFlags');
* @extends {Base}
*/
class User extends Base {
constructor(client, data) {
constructor(client, data, application) {
super(client);
/**
* The user's id
@@ -78,7 +78,7 @@ class User extends Base {
* @type {?ClientApplication}
* @readonly
*/
this.application = null;
this.application = application ? new ClientApplication(this.client, application, this) : null;
this._partial = true;
this._patch(data);
}
@@ -100,7 +100,7 @@ class User extends Base {
* @type {?boolean}
*/
this.bot = Boolean(data.bot);
if (this.bot === true) {
if (this.bot === true && !this.application) {
this.application = new ClientApplication(this.client, { id: this.id }, this);
this.botInGuildsCount = null;
}

View File

@@ -3,6 +3,7 @@
const process = require('node:process');
const BaseGuildVoiceChannel = require('./BaseGuildVoiceChannel');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const InteractionManager = require('../managers/InteractionManager');
const MessageManager = require('../managers/MessageManager');
const { VideoQualityModes } = require('../util/Constants');
const Permissions = require('../util/Permissions');
@@ -24,6 +25,12 @@ class VoiceChannel extends BaseGuildVoiceChannel {
*/
this.messages = new MessageManager(this);
/**
* A manager of the interactions sent to this channel
* @type {InteractionManager}
*/
this.interactions = new InteractionManager(this);
/**
* If the guild considers this channel NSFW
* @type {boolean}

View File

@@ -1,6 +1,7 @@
'use strict';
/* eslint-disable import/order */
const InteractionManager = require('../../managers/InteractionManager');
const MessageCollector = require('../MessageCollector');
const MessagePayload = require('../MessagePayload');
const SnowflakeUtil = require('../../util/SnowflakeUtil');
@@ -31,6 +32,12 @@ class TextBasedChannel {
*/
this.messages = new MessageManager(this);
/**
* A manager of the interactions sent to this channel
* @type {InteractionManager}
*/
this.interactions = new InteractionManager(this);
/**
* The channel's last message id, if one was sent
* @type {?Snowflake}
@@ -405,7 +412,7 @@ class TextBasedChannel {
* @param {UserResolvable} bot Bot user
* @param {string} commandString Command name (and sub / group formats)
* @param {...?string|string[]} args Command arguments
* @returns {Promise<InteractionResponseBody>}
* @returns {Promise<InteractionResponse>}
* @example
* // Send Slash to this channel
* // Demo: