DiscordJS-v14-Template/commands/Info/modalExample.js

58 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-04-22 17:08:04 -04:00
const { EmbedBuilder } = require('discord.js');
const { ActionRowBuilder, ModalBuilder, TextInputBuilder, TextInputStyle } = require('discord.js');
module.exports = {
name: "modal-example",
description: "Show a demo modal!",
run: async (client, interaction) => {
2024-10-03 18:00:03 -04:00
// Declare a random ID for the modal to ensure unique interactions
const modalId = `modal-${Math.floor(Math.random() * 99999999999999).toString()}`;
2023-04-22 17:08:04 -04:00
2024-10-03 18:00:03 -04:00
// Check if this is a chatInput command interaction
if (!interaction.isChatInputCommand()) return;
2023-04-22 17:08:04 -04:00
2024-10-03 18:00:03 -04:00
// Create the modal
2023-04-22 17:08:04 -04:00
const modal = new ModalBuilder()
2024-10-03 18:00:03 -04:00
.setCustomId(modalId)
2023-04-22 17:08:04 -04:00
.setTitle('This is an example modal');
2024-10-03 18:00:03 -04:00
// Create a text input component for the modal
2023-04-22 17:08:04 -04:00
const modalInputData = new TextInputBuilder()
.setCustomId('modalInput')
.setLabel("What text do you want to send?")
2024-10-03 18:00:03 -04:00
.setStyle(TextInputStyle.Paragraph); // Allows for multi-line text
2023-04-22 17:08:04 -04:00
2024-10-03 18:00:03 -04:00
// Wrap the text input in an action row
const modalInputRow = new ActionRowBuilder().addComponents(modalInputData);
2023-04-22 17:08:04 -04:00
2024-10-03 18:00:03 -04:00
// Add the input row to the modal
modal.addComponents(modalInputRow);
2023-04-22 17:08:04 -04:00
2024-10-03 18:00:03 -04:00
// Show the modal to the user
2023-04-22 17:08:04 -04:00
await interaction.showModal(modal);
2024-10-03 18:00:03 -04:00
// Handle the modal submission within the same interaction listener
client.once('interactionCreate', async (modalInteraction) => {
2023-04-22 17:08:04 -04:00
2024-10-03 18:00:03 -04:00
// Ensure we are handling the correct modal submission
if (!modalInteraction.isModalSubmit() || modalInteraction.customId !== modalId) return;
2023-04-22 17:08:04 -04:00
2024-10-03 18:00:03 -04:00
// Retrieve the data entered by the user
const modalInputDataString = modalInteraction.fields.getTextInputValue('modalInput');
2023-04-22 17:08:04 -04:00
2024-10-03 18:00:03 -04:00
// Create an embed to display the user input
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("Your input!")
.setDescription(`You said: ${modalInputDataString}`)
.setTimestamp()
.setFooter({ text: `Requested by ${modalInteraction.user.tag}`, iconURL: modalInteraction.user.displayAvatarURL() });
2023-04-22 17:08:04 -04:00
2024-10-03 18:00:03 -04:00
// Reply to the modal submission with the embed
await modalInteraction.reply({ embeds: [embed] });
});
2023-04-22 17:08:04 -04:00
}
2024-10-03 18:00:03 -04:00
};