我希望它是您在slashcommand示例中键入的地方:"/银行",它将显示两个不同的按钮"进攻""防守",然后当您单击其中一个按钮时,它将弹出另一个设置按钮来单击.现在它在我做/银行的地方工作,它会用两个按钮来回复进攻和防守,它会用你点击的按钮来回复.但我想用另一个设置按钮来回答.

//这是我的按钮命令

const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageActionRow, MessageButton, MessageEmbed } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('bank')
        .setDescription('Replies with some buttons!'),
    async execute(interaction) {
        const row = new MessageActionRow()
            .addComponents(
                new MessageButton()
                    .setCustomId('offense')
                    .setLabel('Offense')
                    .setStyle('SUCCESS'),

                    new MessageButton()
                    .setCustomId(' defense')
                    .setLabel('Defense')
                    .setStyle('DANGER'),
            );

            const embed = new MessageEmbed()
            .setColor('#0099ff')
            .setTitle('Map: BANK ')
            .setURL('https://discord.js.org')
            .setImage('https://i.imgur.com/s54Riow.jpeg')
            .setDescription('Choose your team shitter');

            await interaction.reply({  ephemeral: true, embeds: [embed], components: [row] });

    },
};

这是我的


module.exports = {
    name: 'interactionCreate',
    async execute(interaction, client) {
        if(interaction.isButton())
        interaction.reply("you clicked" + interaction.customId);
        console.log(interaction);

        if (!interaction.isCommand()) return;
        if (!interaction.isButton()) return;

        const command = client.command.get(interaction.commandName);
        if(!command) return;

        try{
            await command.execute(interaction);
        }catch(error){
            console.error(error);
            await interaction.reply({content : "There was an error while executing action"})
        }

        console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
    },
};

这是我的索引.js公司

// Require the necessary discord.js classes
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Intents } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

client.commands = new Collection();

// command files 
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    client.commands.set(command.data.name, command);
}

// event files
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
    const filePath = path.join(eventsPath, file);
    const event = require(filePath);
    if (event.once) {
        client.once(event.name, (...args) => event.execute(...args));
    } else {
        client.on(event.name, (...args) => event.execute(...args));
    }
}
// When the client is ready, run this code (only once)
client.once('ready', c => {
    console.log(`Ready! Logged in as ${c.user.tag}`);
});

// When any message is sent in any channel it'll all be logged into the terminal
client.on('message', async msg => {
    if(!msg.content.startsWith(config.prefix)) return;

    var command = msg.content.substring(1);

    if(!client.commands.has(command)) return;

    try{
        await client.commands.get(command).execute(msg);
    } catch(error) {
        console.error(error);
        await msg.reply({content: "there was an error", epthemeral: true})
    }
});

// interaction files
client.on('interactionCreate', async interaction => {
    if (!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName);

    if (!command) return;

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
    }
});

// Login to Discord with your client's token
client.login(token);

这是我的部署命令.js公司

const fs = require('node:fs');
const path = require('node:path');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');

const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));


for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    commands.push(command.data.toJSON());
}

const rest = new REST({ version: '9' }).setToken(token);

(async () => {
    try {
        console.log('Started refreshing application (/) commands.');

        await rest.put(
            Routes.applicationGuildCommands(clientId, guildId),
            { body: commands },
        );

        console.log('Successfully reloaded application (/) commands.');
    } catch (error) {
        console.error(error);
    }
})();

推荐答案

我们将在你的interactionCreate.js个收集按钮的地方工作.

我们需要与新消息进行update次交互.docs

我注意到您的index.jsinteractionCreate.js中有重复的代码.这就是运行斜杠命令的地方.建议您删除interactionCreate.js中的if (!interaction.isCommand()) return;index.js侦听器.只有一个文件处理interactionCreate事件.我将在示例中这样做.

您还可以找到problem in the future,因为在blank.js中,交互customId内部有一个空间.

一个侦听器示例

const { MessageButton, MessageActionRow } = require('discord.js');

module.exports = {
    name: 'interactionCreate',
    async execute(interaction, client) {
        if (interaction.isCommand()) { // Checks if the interaction is a command and runs the `
        const command = client.command.get(interaction.commandName);
        if(!command) return;

        try{
            await command.execute(interaction);
        }catch(error){
            console.error(error);
            await interaction.reply({content : "There was an error while executing action"})
        }

        console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
        return;

    } else if (interaction.isButton()) { // Checks if the interaction is a button
        interaction.reply("you clicked" + interaction.customId);
        console.log(interaction);

        if (interaction.customId === 'offense') { // Check for the customId of the button
            console.log(`${interaction.user.tag} in #${interaction.channel.name} clicked the offense button.`);
        
            const ActionRow = new MessageActionRow().setComponents(new MessageButton() // Create the button inside of an action Row
              .setCustomId('CustomId')
              .setLabel('Label')
              .setStyle('PRIMARY'));
        
            return interaction.update({ // update the interaction with the new action row
              content: 'Hey',
              components: [ActionRow],
              ephemeral: true
            });
        
        }
    }
    },
};

使用原始示例

module.exports = {
    name: 'interactionCreate',
    async execute(interaction, client) {
        if(interaction.isButton()) {
        interaction.reply("you clicked" + interaction.customId);
        console.log(interaction);


        if (interaction.customId === 'offense') { // Check for the customId of the button
            console.log(`${interaction.user.tag} in #${interaction.channel.name} clicked the offense button.`);
        
            const ActionRow = new MessageActionRow().setComponents(new MessageButton() // Create the button inside of an action Row
              .setCustomId('CustomId')
              .setLabel('Label')
              .setStyle('PRIMARY'));
        
            return interaction.update({ // update the interaction with the new action row
              content: 'Hey',
              components: [ActionRow],
              ephemeral: true
            });
        
        }
        return;
    }

        if (!interaction.isCommand()) return;
        if (!interaction.isButton()) return;

        const command = client.command.get(interaction.commandName);
        if(!command) return;

        try{
            await command.execute(interaction);
        }catch(error){
            console.error(error);
            await interaction.reply({content : "There was an error while executing action"})
        }

        console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
    },
};

如果需要获取原始邮件中发送的嵌入内容,可以使用<interaction>.embeds获取嵌入内容,然后根据自己的喜好进行编辑.

现在if you don't want to edit the interaction and reply with a new message记住,如果你的原始信息是短暂的,那么你can't delete it.您可以使用replying methods.

解释

我们正在判断building the button时使用的customId.在我们创建action row并添加新message button之后.然后,我们将updating个原始消息内容与不同的组件组合在一起.

如果遇到任何问题,请随时发表 comments

Javascript相关问答推荐

如何在不指定宽度和高度的情况下显示来自网址的下一张图像

除了在Angular 16中使用快照之外,什么是可行且更灵活的替代方案?

如何使用JavaScript动态地将CSS应用于ToDo列表?

zoom svg以适应圆

为什么我的includes声明需要整个字符串?

如何在RTK上设置轮询,每24小时

django无法解析余数:[0] from carray[0]'

Chart.js V4切换图表中的每个条,同时每个条下有不同的标签.怎么做?

从mat—country—select获取整个Country数组

如何解决CORS政策的问题

useNavigation更改URL,但不呈现或显示组件

Angular material 拖放堆叠的牌副,悬停时自动展开&

在grafana情节,避免冲突的情节和传说

空的结果抓取网站与Fetch和Cheerio

手机上的渲染错误文本必须在文本组件中渲染,但在浏览器上没有问题<><>

如何在模块层面提供服务?

如何在JavaScript文件中使用Json文件

使用领域Web SDK的Vite+Vue应用程序中的Web程序集(WASM)错误

面对代码中的错误作为前端与后端的集成

FileReader()不能处理Firefox和GiB文件