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

Som*_* Me 3 javascript node.js discord.js

如何才能使用户单击消息中的按钮后,该按钮被禁用,而其他按钮仍然可单击?我正在使用 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] })
Run Code Online (Sandbox Code Playgroud)

我尝试创建消息组件收集器来检查单击的按钮的 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] });
    }
});
Run Code Online (Sandbox Code Playgroud)

小智 5

.addComponents()只会添加到现有的组件中。由于组件是一个数组,因此您需要更改row.components[0].setDisabled(true)(for but_1) 和row.components[1].setDisabled(true)(for but_2) 并使用更改后的 row 编辑回复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] });
})
Run Code Online (Sandbox Code Playgroud)