如何在 Discord.js 13 中点击按钮后禁用它

3

当用户点击消息中的一个按钮后,如何禁用该按钮而使其他按钮仍可点击?我正在使用 Discord.js v13.1.0,并且以下是我已经编写的代码:

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

let row = new MessageActionRow()
    .addComponents(
        but_1 = new MessageButton()
            .setCustomId('id_1')
            .setLabel('Button 1')
            .setStyle('SECONDARY'),
        but_2 = new MessageButton()
            .setCustomId('id_2')
            .setLabel('Button 2')
            .setStyle('SECONDARY')
    );

interaction.reply({ content: "Click a button", components: [row] })

我尝试创建信息组件收集器以检查所单击按钮的ID并编辑该按钮,但结果发现.addComponents()只会添加另一个按钮而不是编辑它。这就是我所做的:
const filter = i => i.customId === 'id_1' && i.user.id === interaction.user.id;

const collector = interaction.channel.createMessageComponentCollector({ filter, time: 15000 });

collector.on('collect', async i => {
    if (i.customId === 'id_1') {
        row.addComponents(
            but_1.setLabel('Click Registered!')
                .setCustomId('id_1_clicked')
                .setDisabled(true)
       )
       interaction.editReply({ content: "Click a button", components: [row] });
    }
});
1个回答

5

.addComponents() 只会添加到现有的组件中。由于组件是一个数组,因此您需要更改row.components[0].setDisabled(true)(针对but_1)和row.components[1].setDisabled(true)(针对but_2),并使用更改后的行MessageActionRow编辑回复。

collector.on('collect', async i => {
    if (i.customId === 'id_1') {
        row.components[0].setDisabled(true) //disables but_1
    }
    if (i.customId === 'id_2') {
        row.components[1].setDisabled(true) //disables but_2
    }
    interaction.editReply({ content: "Click a button", components: [row] });
})

感谢您的帮助。经过一些研究,我发现这里有一个名为.spliceComponents()的方法。但是按照您提到的方式做会更容易。 - Someone Like Me
@SomeoneLikeMe 你能告诉我你是怎么使用它的吗?或者发一篇帖子。我找不到相关文档。谢谢。 - 1252748

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接