discord.js如何实现发送按钮5秒后自动禁用以避免spam重复点击?
问题根因
你当前的代码仅修改了本地内存中row对象的组件属性,没有把更新后的组件配置同步给Discord服务端,因此已经发送出去的消息上的按钮不会发生变化。
修复方案
你需要先捕获发送成功的消息实例,在5秒后主动编辑这条消息,传入禁用按钮后的组件配置即可,修复后的代码如下:
// 注意:执行该代码的上层函数需要标记为async,才能使用await语法 const newEmbed = new Discord.MessageEmbed() .setColor('#2ACAEA') .setTitle("Commands") .setDescription("Page 1 of 2") .addFields( {name: '!jn help', value: 'This command'}, {name: '!jn ping', value: 'Ping the bot.'}, {name: '!jn coinflip', value: 'Flip a coin :D'}, {name: '!jn amiadmin', value: 'Are you an admin? We can see!'} ) .setFooter('Need more help? Join the support discord server.') .setImage('https://i.imgur.com/Ta0yst7.png'); const row = new Discord.MessageActionRow() .addComponents( new Discord.MessageButton() .setCustomId('2') .setLabel('>>') .setStyle('SUCCESS'), ); // 存储发送成功的消息实例 const sentMessage = await message.channel.send({embeds: [newEmbed], components: [row]}); setTimeout(async function () { // 修改按钮状态 row.components[0].setDisabled(true); // 编辑已发送的消息,传入更新后的组件 await sentMessage.edit({components: [row]}); }, 5000);
额外注意事项
- 如果你的代码运行环境不允许使用
async/await,可以用.then()链式调用处理消息发送的回调 - 若运行过程中出现消息已被删除的报错,可以在
edit前加判断确认消息是否还存在,避免抛出未捕获的异常
内容的提问来源于stack exchange,提问作者Nikey368
相关产品推荐
相关产品推荐

