feat: general component improvements (#5787)

This commit is contained in:
monbrey
2021-06-09 22:59:12 +10:00
committed by GitHub
parent 0156f693e0
commit c4f1c75efa
18 changed files with 111 additions and 48 deletions

View File

@@ -1,21 +1,27 @@
'use strict'; 'use strict';
const { Events, InteractionTypes } = require('../../../util/Constants'); const { Events, InteractionTypes, MessageComponentTypes } = require('../../../util/Constants');
const Structures = require('../../../util/Structures'); const Structures = require('../../../util/Structures');
module.exports = (client, { d: data }) => { module.exports = (client, { d: data }) => {
let interaction; let InteractionType;
switch (data.type) { switch (data.type) {
case InteractionTypes.APPLICATION_COMMAND: { case InteractionTypes.APPLICATION_COMMAND:
const CommandInteraction = Structures.get('CommandInteraction'); InteractionType = Structures.get('CommandInteraction');
interaction = new CommandInteraction(client, data);
break; break;
} case InteractionTypes.MESSAGE_COMPONENT:
case InteractionTypes.MESSAGE_COMPONENT: { switch (data.data.component_type) {
const MessageComponentInteraction = Structures.get('MessageComponentInteraction'); case MessageComponentTypes.BUTTON:
interaction = new MessageComponentInteraction(client, data); InteractionType = Structures.get('ButtonInteraction');
break;
default:
client.emit(
Events.DEBUG,
`[INTERACTION] Received component interaction with unknown type: ${data.data.component_type}`,
);
return;
}
break; break;
}
default: default:
client.emit(Events.DEBUG, `[INTERACTION] Received interaction with unknown type: ${data.type}`); client.emit(Events.DEBUG, `[INTERACTION] Received interaction with unknown type: ${data.type}`);
return; return;
@@ -26,5 +32,5 @@ module.exports = (client, { d: data }) => {
* @event Client#interaction * @event Client#interaction
* @param {Interaction} interaction The interaction which was created * @param {Interaction} interaction The interaction which was created
*/ */
client.emit(Events.INTERACTION_CREATE, interaction); client.emit(Events.INTERACTION_CREATE, new InteractionType(client, data));
}; };

View File

@@ -70,6 +70,7 @@ module.exports = {
BaseGuildEmoji: require('./structures/BaseGuildEmoji'), BaseGuildEmoji: require('./structures/BaseGuildEmoji'),
BaseGuildVoiceChannel: require('./structures/BaseGuildVoiceChannel'), BaseGuildVoiceChannel: require('./structures/BaseGuildVoiceChannel'),
BaseMessageComponent: require('./structures/BaseMessageComponent'), BaseMessageComponent: require('./structures/BaseMessageComponent'),
ButtonInteraction: require('./structures/ButtonInteraction'),
CategoryChannel: require('./structures/CategoryChannel'), CategoryChannel: require('./structures/CategoryChannel'),
Channel: require('./structures/Channel'), Channel: require('./structures/Channel'),
ClientApplication: require('./structures/ClientApplication'), ClientApplication: require('./structures/ClientApplication'),

View File

@@ -3,6 +3,7 @@
const BaseMessageComponent = require('./BaseMessageComponent'); const BaseMessageComponent = require('./BaseMessageComponent');
const MessageEmbed = require('./MessageEmbed'); const MessageEmbed = require('./MessageEmbed');
const { RangeError } = require('../errors'); const { RangeError } = require('../errors');
const { MessageComponentTypes } = require('../util/Constants');
const DataResolver = require('../util/DataResolver'); const DataResolver = require('../util/DataResolver');
const MessageFlags = require('../util/MessageFlags'); const MessageFlags = require('../util/MessageFlags');
const Util = require('../util/Util'); const Util = require('../util/Util');
@@ -152,7 +153,11 @@ class APIMessage {
} }
const embeds = embedLikes.map(e => new MessageEmbed(e).toJSON()); const embeds = embedLikes.map(e => new MessageEmbed(e).toJSON());
const components = this.options.components?.map(c => BaseMessageComponent.create(c).toJSON()); const components = this.options.components?.map(c =>
BaseMessageComponent.create(
Array.isArray(c) ? { type: MessageComponentTypes.ACTION_ROW, components: c } : c,
).toJSON(),
);
let username; let username;
let avatarURL; let avatarURL;

View File

@@ -22,13 +22,15 @@ class BaseMessageComponent {
*/ */
/** /**
* Components that can be sent in a message * Components that can be sent in a message. This can be:
* * MessageActionRow
* * MessageButton
* @typedef {MessageActionRow|MessageButton} MessageComponent * @typedef {MessageActionRow|MessageButton} MessageComponent
*/ */
/** /**
* Data that can be resolved to a MessageComponentType. This can be: * Data that can be resolved to a MessageComponentType. This can be:
* * {@link MessageComponentType} * * MessageComponentType
* * string * * string
* * number * * number
* @typedef {string|number|MessageComponentType} MessageComponentTypeResolvable * @typedef {string|number|MessageComponentType} MessageComponentTypeResolvable

View File

@@ -0,0 +1,11 @@
'use strict';
const MessageComponentInteraction = require('./MessageComponentInteraction');
/**
* Represents a button interaction.
* @exxtends {MessageComponentInteraction}
*/
class ButtonInteraction extends MessageComponentInteraction {}
module.exports = ButtonInteraction;

View File

@@ -3,6 +3,14 @@
const Base = require('./Base'); const Base = require('./Base');
const SnowflakeUtil = require('../util/SnowflakeUtil'); const SnowflakeUtil = require('../util/SnowflakeUtil');
/**
* Represents raw emoji data from the API
* @typedef {Object} RawEmoji
* @property {?Snowflake} id ID of this emoji
* @property {?string} name Name of this emoji
* @property {?boolean} animated Whether this emoji is animated
*/
/** /**
* Represents an emoji, see {@link GuildEmoji} and {@link ReactionEmoji}. * Represents an emoji, see {@link GuildEmoji} and {@link ReactionEmoji}.
* @extends {Base} * @extends {Base}

View File

@@ -120,6 +120,14 @@ class Interaction extends Base {
isMessageComponent() { isMessageComponent() {
return InteractionTypes[this.type] === InteractionTypes.MESSAGE_COMPONENT; return InteractionTypes[this.type] === InteractionTypes.MESSAGE_COMPONENT;
} }
/**
* Indicates whether this interaction is a button interaction.
* @returns {boolean}
*/
isButton() {
return InteractionTypes[this.type] === InteractionTypes.MESSAGE_COMPONENT && this.componentType === 'BUTTON';
}
} }
module.exports = Interaction; module.exports = Interaction;

View File

@@ -538,8 +538,8 @@ class Message extends Base {
* @property {MessageAttachment[]} [attachments] An array of attachments to keep, * @property {MessageAttachment[]} [attachments] An array of attachments to keep,
* all attachments will be kept if omitted * all attachments will be kept if omitted
* @property {FileOptions[]|BufferResolvable[]|MessageAttachment[]} [files] Files to add to the message * @property {FileOptions[]|BufferResolvable[]|MessageAttachment[]} [files] Files to add to the message
* @property {MessageActionRow[]} [components] Action rows containing interactive components for the message * @property {MessageActionRow[]|MessageActionRowOptions[]|MessageActionRowComponentResolvable[][]} [components]
* (buttons, select menus) * Action rows containing interactive components for the message (buttons, select menus)
*/ */
/** /**

View File

@@ -4,24 +4,24 @@ const BaseMessageComponent = require('./BaseMessageComponent');
const { MessageComponentTypes } = require('../util/Constants'); const { MessageComponentTypes } = require('../util/Constants');
/** /**
* Represents an ActionRow containing message components. * Represents an action row containing message components.
* @extends {BaseMessageComponent} * @extends {BaseMessageComponent}
*/ */
class MessageActionRow extends BaseMessageComponent { class MessageActionRow extends BaseMessageComponent {
/** /**
* Components that can be placed in a MessageActionRow * Components that can be placed in an action row
* * MessageButton * * MessageButton
* @typedef {MessageButton} MessageActionRowComponent * @typedef {MessageButton} MessageActionRowComponent
*/ */
/** /**
* Options for components that can be placed in a MessageActionRow * Options for components that can be placed in an action row
* * MessageButtonOptions * * MessageButtonOptions
* @typedef {MessageButtonOptions} MessageActionRowComponentOptions * @typedef {MessageButtonOptions} MessageActionRowComponentOptions
*/ */
/** /**
* Data that can be resolved into a components that can be placed in a MessageActionRow * Data that can be resolved into a components that can be placed in an action row
* * MessageActionRowComponent * * MessageActionRowComponent
* * MessageActionRowComponentOptions * * MessageActionRowComponentOptions
* @typedef {MessageActionRowComponent|MessageActionRowComponentOptions} MessageActionRowComponentResolvable * @typedef {MessageActionRowComponent|MessageActionRowComponentOptions} MessageActionRowComponentResolvable
@@ -30,7 +30,7 @@ class MessageActionRow extends BaseMessageComponent {
/** /**
* @typedef {BaseMessageComponentOptions} MessageActionRowOptions * @typedef {BaseMessageComponentOptions} MessageActionRowOptions
* @property {MessageActionRowComponentResolvable[]} [components] * @property {MessageActionRowComponentResolvable[]} [components]
* The components to place in this ActionRow * The components to place in this action row
*/ */
/** /**
@@ -40,14 +40,14 @@ class MessageActionRow extends BaseMessageComponent {
super({ type: 'ACTION_ROW' }); super({ type: 'ACTION_ROW' });
/** /**
* The components in this MessageActionRow * The components in this action row
* @type {MessageActionRowComponent[]} * @type {MessageActionRowComponent[]}
*/ */
this.components = (data.components ?? []).map(c => BaseMessageComponent.create(c, null, true)); this.components = (data.components ?? []).map(c => BaseMessageComponent.create(c, null, true));
} }
/** /**
* Adds components to the row. * Adds components to the action row.
* @param {...MessageActionRowComponentResolvable[]} components The components to add * @param {...MessageActionRowComponentResolvable[]} components The components to add
* @returns {MessageActionRow} * @returns {MessageActionRow}
*/ */

View File

@@ -6,7 +6,7 @@ const { MessageButtonStyles, MessageComponentTypes } = require('../util/Constant
const Util = require('../util/Util'); const Util = require('../util/Util');
/** /**
* Represents a Button message component. * Represents a button message component.
* @extends {BaseMessageComponent} * @extends {BaseMessageComponent}
*/ */
class MessageButton extends BaseMessageComponent { class MessageButton extends BaseMessageComponent {
@@ -15,7 +15,7 @@ class MessageButton extends BaseMessageComponent {
* @property {string} [label] The text to be displayed on this button * @property {string} [label] The text to be displayed on this button
* @property {string} [customID] A unique string to be sent in the interaction when clicked * @property {string} [customID] A unique string to be sent in the interaction when clicked
* @property {MessageButtonStyleResolvable} [style] The style of this button * @property {MessageButtonStyleResolvable} [style] The style of this button
* @property {Emoji} [emoji] The emoji to be displayed to the left of the text * @property {EmojiIdentifierResolvable} [emoji] The emoji to be displayed to the left of the text
* @property {string} [url] Optional URL for link-style buttons * @property {string} [url] Optional URL for link-style buttons
* @property {boolean} [disabled=false] Disables the button to prevent interactions * @property {boolean} [disabled=false] Disables the button to prevent interactions
*/ */
@@ -50,9 +50,9 @@ class MessageButton extends BaseMessageComponent {
/** /**
* Emoji for this button * Emoji for this button
* @type {?Emoji|string} * @type {?RawEmoji}
*/ */
this.emoji = data.emoji ?? null; this.emoji = data.emoji ? Util.resolvePartialEmoji(data.emoji) : null;
/** /**
* The URL this button links to, if it is a Link style button * The URL this button links to, if it is a Link style button
@@ -93,8 +93,7 @@ class MessageButton extends BaseMessageComponent {
* @returns {MessageButton} * @returns {MessageButton}
*/ */
setEmoji(emoji) { setEmoji(emoji) {
if (/^\d{17,19}$/.test(emoji)) this.emoji = { id: emoji }; this.emoji = Util.resolvePartialEmoji(emoji);
else this.emoji = Util.parseEmoji(`${emoji}`);
return this; return this;
} }
@@ -119,7 +118,8 @@ class MessageButton extends BaseMessageComponent {
} }
/** /**
* Sets the URL of this button. MessageButton#style should be LINK * Sets the URL of this button.
* <note>MessageButton#style must be LINK when setting a URL</note>
* @param {string} url The URL of this button * @param {string} url The URL of this button
* @returns {MessageButton} * @returns {MessageButton}
*/ */
@@ -146,14 +146,14 @@ class MessageButton extends BaseMessageComponent {
/** /**
* Data that can be resolved to a MessageButtonStyle. This can be * Data that can be resolved to a MessageButtonStyle. This can be
* * {@link MessageButtonStyle} * * MessageButtonStyle
* * string * * string
* * number * * number
* @typedef {string|number|MessageButtonStyle} MessageButtonStyleResolvable * @typedef {string|number|MessageButtonStyle} MessageButtonStyleResolvable
*/ */
/** /**
* Resolves the style of a MessageButton * Resolves the style of a button
* @param {MessageButtonStyleResolvable} style The style to resolve * @param {MessageButtonStyleResolvable} style The style to resolve
* @returns {MessageButtonStyle} * @returns {MessageButtonStyle}
* @private * @private

View File

@@ -21,13 +21,13 @@ class MessageComponentInteraction extends Interaction {
this.message = data.message ? this.channel?.messages.add(data.message) ?? data.message : null; this.message = data.message ? this.channel?.messages.add(data.message) ?? data.message : null;
/** /**
* The custom ID of the component which was clicked * The custom ID of the component which was interacted with
* @type {string} * @type {string}
*/ */
this.customID = data.data.custom_id; this.customID = data.data.custom_id;
/** /**
* The type of component that was interacted with * The type of component which was interacted with
* @type {string} * @type {string}
*/ */
this.componentType = MessageComponentInteraction.resolveType(data.data.component_type); this.componentType = MessageComponentInteraction.resolveType(data.data.component_type);

View File

@@ -40,7 +40,7 @@ class MessageComponentInteractionCollector extends Collector {
this.channel = this.message ? this.message.channel : source; this.channel = this.message ? this.message.channel : source;
/** /**
* The users which have interacted to buttons on this collector * The users which have interacted to components on this collector
* @type {Collection} * @type {Collection}
*/ */
this.users = new Collection(); this.users = new Collection();

View File

@@ -101,8 +101,8 @@ class Webhook {
* @property {string} [content] See {@link BaseMessageOptions#content} * @property {string} [content] See {@link BaseMessageOptions#content}
* @property {FileOptions[]|BufferResolvable[]|MessageAttachment[]} [files] See {@link BaseMessageOptions#files} * @property {FileOptions[]|BufferResolvable[]|MessageAttachment[]} [files] See {@link BaseMessageOptions#files}
* @property {MessageMentionOptions} [allowedMentions] See {@link BaseMessageOptions#allowedMentions} * @property {MessageMentionOptions} [allowedMentions] See {@link BaseMessageOptions#allowedMentions}
* @property {MessageActionRow[]} [components] Action rows containing interactive components for the message * @property {MessageActionRow[]|MessageActionRowOptions[]|MessageActionRowComponentResolvable[][]} [components]
* (buttons, select menus) * Action rows containing interactive components for the message (buttons, select menus)
*/ */
/** /**

View File

@@ -11,13 +11,13 @@ const APIMessage = require('../APIMessage');
*/ */
class InteractionResponses { class InteractionResponses {
/** /**
* Options for deferring the reply to a {@link CommandInteraction}. * Options for deferring the reply to an {@link Interaction}.
* @typedef {Object} InteractionDeferOptions * @typedef {Object} InteractionDeferOptions
* @property {boolean} [ephemeral] Whether the reply should be ephemeral * @property {boolean} [ephemeral] Whether the reply should be ephemeral
*/ */
/** /**
* Options for a reply to an interaction. * Options for a reply to an {@link Interaction}.
* @typedef {BaseMessageOptions} InteractionReplyOptions * @typedef {BaseMessageOptions} InteractionReplyOptions
* @property {boolean} [ephemeral] Whether the reply should be ephemeral * @property {boolean} [ephemeral] Whether the reply should be ephemeral
* @property {MessageEmbed[]|Object[]} [embeds] An array of embeds for the message * @property {MessageEmbed[]|Object[]} [embeds] An array of embeds for the message
@@ -140,10 +140,10 @@ class InteractionResponses {
} }
/** /**
* Defers an update to the message to which the button was attached * Defers an update to the message to which the component was attached
* @returns {Promise<void>} * @returns {Promise<void>}
* @example * @example
* // Defer to update the button to a loading state * // Defer updating and reset the component's loading state
* interaction.deferUpdate() * interaction.deferUpdate()
* .then(console.log) * .then(console.log)
* .catch(console.error); * .catch(console.error);
@@ -163,7 +163,7 @@ class InteractionResponses {
* @param {string|APIMessage|WebhookEditMessageOptions} options The options for the reply * @param {string|APIMessage|WebhookEditMessageOptions} options The options for the reply
* @returns {Promise<void>} * @returns {Promise<void>}
* @example * @example
* // Remove the buttons from the message * // Remove the components from the message
* interaction.update("A button was clicked", { components: [] }) * interaction.update("A button was clicked", { components: [] })
* .then(console.log) * .then(console.log)
* .catch(console.error); * .catch(console.error);

View File

@@ -63,8 +63,8 @@ class TextBasedChannel {
* @property {string|boolean} [code] Language for optional codeblock formatting to apply * @property {string|boolean} [code] Language for optional codeblock formatting to apply
* @property {boolean|SplitOptions} [split=false] Whether or not the message should be split into multiple messages if * @property {boolean|SplitOptions} [split=false] Whether or not the message should be split into multiple messages if
* it exceeds the character limit. If an object is provided, these are the options for splitting the message * it exceeds the character limit. If an object is provided, these are the options for splitting the message
* @property {MessageActionRow[]} [components] Action rows containing interactive components for the message * @property {MessageActionRow[]|MessageActionRowOptions[]|MessageActionRowComponentResolvable[][]} [components]
* (buttons, select menus) * Action rows containing interactive components for the message (buttons, select menus)
*/ */
/** /**

View File

@@ -21,6 +21,7 @@
* * **`User`** * * **`User`**
* * **`CommandInteraction`** * * **`CommandInteraction`**
* * **`MessageComponentInteraction`** * * **`MessageComponentInteraction`**
* * **`ButtonInteraction`**
* @typedef {string} ExtendableStructure * @typedef {string} ExtendableStructure
*/ */
@@ -113,6 +114,7 @@ const structures = {
User: require('../structures/User'), User: require('../structures/User'),
CommandInteraction: require('../structures/CommandInteraction'), CommandInteraction: require('../structures/CommandInteraction'),
MessageComponentInteraction: require('../structures/MessageComponentInteraction'), MessageComponentInteraction: require('../structures/MessageComponentInteraction'),
ButtonInteraction: require('../structures/ButtonInteraction'),
}; };
module.exports = Structures; module.exports = Structures;

View File

@@ -267,6 +267,20 @@ class Util {
return { animated: Boolean(m[1]), name: m[2], id: m[3] || null }; return { animated: Boolean(m[1]), name: m[2], id: m[3] || null };
} }
/**
* Resolves a partial emoji object from an {@link EmojiIdentifierResolvable}, without checking a Client.
* @param {EmojiIdentifierResolvable} emoji Emoji identifier to resolve
* @returns {?RawEmoji}
* @private
*/
static resolvePartialEmoji(emoji) {
if (!emoji) return null;
if (typeof emoji === 'string') return /^\d{17,19}$/.test(emoji) ? { id: emoji } : Util.parseEmoji(emoji);
const { id, name, animated } = emoji;
if (!id && !name) return null;
return { id, name, animated };
}
/** /**
* Shallow-copies an object with its class/prototype intact. * Shallow-copies an object with its class/prototype intact.
* @param {Object} obj Object to clone * @param {Object} obj Object to clone

14
typings/index.d.ts vendored
View File

@@ -294,6 +294,10 @@ declare module 'discord.js' {
public static resolve(bit?: BitFieldResolvable<any, number | bigint>): number | bigint; public static resolve(bit?: BitFieldResolvable<any, number | bigint>): number | bigint;
} }
export class ButtonInteraction extends MessageComponentInteraction {
public componentType: 'BUTTON';
}
export class CategoryChannel extends GuildChannel { export class CategoryChannel extends GuildChannel {
public readonly children: Collection<Snowflake, GuildChannel>; public readonly children: Collection<Snowflake, GuildChannel>;
public type: 'category'; public type: 'category';
@@ -1114,6 +1118,7 @@ declare module 'discord.js' {
public type: InteractionType; public type: InteractionType;
public user: User; public user: User;
public version: number; public version: number;
public isButton(): this is ButtonInteraction;
public isCommand(): this is CommandInteraction; public isCommand(): this is CommandInteraction;
public isMessageComponent(): this is MessageComponentInteraction; public isMessageComponent(): this is MessageComponentInteraction;
} }
@@ -1267,7 +1272,7 @@ declare module 'discord.js' {
constructor(data?: MessageButton | MessageButtonOptions); constructor(data?: MessageButton | MessageButtonOptions);
public customID: string | null; public customID: string | null;
public disabled: boolean; public disabled: boolean;
public emoji: string | RawEmoji | null; public emoji: RawEmoji | null;
public label: string | null; public label: string | null;
public style: MessageButtonStyle | null; public style: MessageButtonStyle | null;
public type: 'BUTTON'; public type: 'BUTTON';
@@ -1888,6 +1893,7 @@ declare module 'discord.js' {
public static moveElementInArray(array: any[], element: any, newIndex: number, offset?: boolean): number; public static moveElementInArray(array: any[], element: any, newIndex: number, offset?: boolean): number;
public static parseEmoji(text: string): { animated: boolean; name: string; id: Snowflake | null } | null; public static parseEmoji(text: string): { animated: boolean; name: string; id: Snowflake | null } | null;
public static resolveColor(color: ColorResolvable): number; public static resolveColor(color: ColorResolvable): number;
public static resolvePartialEmoji(emoji: EmojiIdentifierResolvable): Partial<RawEmoji> | null;
public static verifyString(data: string, error?: typeof Error, errorMessage?: string, allowEmpty?: boolean): string; public static verifyString(data: string, error?: typeof Error, errorMessage?: string, allowEmpty?: boolean): string;
public static setPosition<T extends Channel | Role>( public static setPosition<T extends Channel | Role>(
item: T, item: T,
@@ -3309,7 +3315,7 @@ declare module 'discord.js' {
interface MessageButtonOptions extends BaseMessageComponentOptions { interface MessageButtonOptions extends BaseMessageComponentOptions {
customID?: string; customID?: string;
disabled?: boolean; disabled?: boolean;
emoji?: RawEmoji; emoji?: EmojiIdentifierResolvable;
label?: string; label?: string;
style: MessageButtonStyleResolvable; style: MessageButtonStyleResolvable;
url?: string; url?: string;
@@ -3346,7 +3352,7 @@ declare module 'discord.js' {
files?: (FileOptions | BufferResolvable | Stream | MessageAttachment)[]; files?: (FileOptions | BufferResolvable | Stream | MessageAttachment)[];
flags?: BitFieldResolvable<MessageFlagsString, number>; flags?: BitFieldResolvable<MessageFlagsString, number>;
allowedMentions?: MessageMentionOptions; allowedMentions?: MessageMentionOptions;
components?: MessageActionRow[] | MessageActionRowOptions[]; components?: MessageActionRow[] | MessageActionRowOptions[] | MessageActionRowComponentResolvable[][];
} }
interface MessageEmbedAuthor { interface MessageEmbedAuthor {
@@ -3439,7 +3445,7 @@ declare module 'discord.js' {
nonce?: string | number; nonce?: string | number;
content?: string; content?: string;
embed?: MessageEmbed | MessageEmbedOptions; embed?: MessageEmbed | MessageEmbedOptions;
components?: MessageActionRow[] | MessageActionRowOptions[]; components?: MessageActionRow[] | MessageActionRowOptions[] | MessageActionRowComponentResolvable[][];
allowedMentions?: MessageMentionOptions; allowedMentions?: MessageMentionOptions;
files?: (FileOptions | BufferResolvable | Stream | MessageAttachment)[]; files?: (FileOptions | BufferResolvable | Stream | MessageAttachment)[];
code?: string | boolean; code?: string | boolean;