Discord.js v14:按钮点击后如何实现禁用?
如何禁用点击后的Discord按钮?
要实现点击按钮后禁用该按钮,核心是编辑包含按钮的原消息,将目标按钮的disabled属性设为true。以下是针对你代码的修改方案:
修改后的完整代码
client.on("interactionCreate", async (interaction) => { if (interaction.isButton()) { if (interaction.customId === "yes") { const owner_role = await db.get(`Owner-${interaction.guild.id}`); if (!owner_role) { return interaction.reply({ content: `:no: The server's owner haven't set up the bot yet. Please contact them.`, ephemeral: true }) }; if (!interaction.member.roles.cache.has(owner_role)) { return interaction.reply({ content: ":no: You don't have permission to use this command.", ephemeral: true }) }; await interaction.reply(`This suggestion has been approved by ${interaction.user}.`); // 禁用按钮的核心代码 const components = interaction.message.components; // 遍历组件行,找到目标按钮并禁用 components.forEach(row => { row.components.forEach(button => { if (button.customId === "yes") { button.disabled = true; } }); }); // 更新原消息的组件 await interaction.message.edit({ components: components }); } } });
关键说明
- 通过
interaction.message.components获取原消息的所有组件(按钮默认包裹在ActionRow组件行中) - 遍历组件行和其中的按钮,定位到
customId为yes的目标按钮,将其disabled属性设为true - 调用
interaction.message.edit()更新原消息,使禁用效果立即生效 - 注意添加
await关键字,保证异步操作按顺序执行
内容的提问来源于stack exchange,提问作者dnnd ndndbd
相关产品推荐
相关产品推荐

