Discord.js v13如何实现点击按钮后仅禁用该被点击的按钮
Discord.js v13 单按钮禁用实现方案
问题根源
你使用addComponents()会新增按钮的原因是:该方法的作用是往当前MessageActionRow实例中追加新组件,而非修改已存在的组件。要实现仅禁用被点击的按钮,只需修改原有组件数组中对应按钮的属性,再重新渲染整行组件即可。
修正后实现代码
const { MessageActionRow, MessageButton } = require('discord.js'); // 初始化按钮行 let row = new MessageActionRow() .addComponents( new MessageButton() .setCustomId('id_1') .setLabel('Button 1') .setStyle('SECONDARY'), new MessageButton() .setCustomId('id_2') .setLabel('Button 2') .setStyle('SECONDARY') ); // 发送带按钮的消息 interaction.reply({ content: "Click a button", components: [row] }) // 过滤器:只监听触发原始交互的用户的按钮点击 const filter = i => i.user.id === interaction.user.id; const collector = interaction.channel.createMessageComponentCollector({ filter, time: 15000 }); collector.on('collect', async i => { // 遍历当前行的所有组件,找到被点击的按钮 row.components.forEach(button => { if (button.customId === i.customId) { // 仅修改被点击按钮的属性 button.setLabel('Click Registered!') .setCustomId(`${i.customId}_clicked`) .setDisabled(true); } }); // 响应交互同时更新消息组件,避免超时报错 await i.update({ content: "Click a button", components: [row] }); });
补充说明
- 上述遍历
row.components的写法可以适配任意数量的按钮,不需要单独判断每个按钮的customId,后续新增按钮时无需修改collect事件内的逻辑 - 如果需要针对不同按钮做差异化的修改逻辑,只需在遍历判断customId时补充对应分支即可
内容的提问来源于stack exchange,提问作者Someone Like Me
相关产品推荐
相关产品推荐

