Discord.js如何通过customId获取同按钮行内指定按钮并禁用?
实现方法
Discord.js 没有内置ButtonInteraction.getButtonByID()这类方法,但你可以通过遍历交互绑定的原消息组件,快速匹配到目标按钮完成修改,也可以自行封装对应工具方法实现你要的调用效果。
核心逻辑
- 通过
ButtonInteraction.message获取按钮所属的原始消息对象,其components属性包含了消息上挂载的所有组件行数据 - 遍历组件行和行内的按钮,匹配对应
customId后修改属性,最后调用interaction.update更新消息即可生效
v13 版本代码示例(你当前用的MessageActionRow/MessageButton属于v13版本)
直接处理的完整示例
collector.on('collect', async (ButtonInteraction) => { const currentId = ButtonInteraction.customId // 处理组件:深拷贝原组件避免污染原始数据 const updatedComponents = ButtonInteraction.message.components.map(rawRow => { // 把原始行数据转成可操作的MessageActionRow实例 const row = MessageActionRow.from(rawRow) // 遍历行内所有按钮 row.components.forEach(button => { // 示例:点击id为R的按钮时,禁用id为wR的按钮 if (currentId === 'R' && button.customId === 'wR') { button.setDisabled(true) } // 其他按钮修改规则可在这里补充 }) return row }) // 更新消息,应用修改后的组件 await ButtonInteraction.update({ components: updatedComponents }) })
封装类似getButtonByID的工具方法
如果你想要更便捷的调用方式,可以封装工具函数:
// 工具函数:根据customId获取按钮实例 function getButtonByCustomId(interaction, targetId) { for (const rawRow of interaction.message.components) { const row = MessageActionRow.from(rawRow) const targetBtn = row.components.find(btn => btn.customId === targetId) if (targetBtn) return targetBtn } return null } // 调用示例 collector.on('collect', async (ButtonInteraction) => { const currentId = ButtonInteraction.customId if (currentId === 'R') { // 直接获取目标按钮 const wRBtn = getButtonByCustomId(ButtonInteraction, 'wR') if (wRBtn) wRBtn.setDisabled(true) } // 最后更新消息即可 await ButtonInteraction.update({ components: ButtonInteraction.message.components }) })
v14 版本适配说明
如果你后续升级到v14版本,只需要替换组件类名和属性取值即可,逻辑完全一致:
const { ActionRowBuilder } = require('discord.js') collector.on('collect', async (ButtonInteraction) => { const currentId = ButtonInteraction.customId const updatedComponents = ButtonInteraction.message.components.map(rawRow => { const row = ActionRowBuilder.from(rawRow) row.components.forEach(button => { if (currentId === 'R' && button.data.custom_id === 'wR') { button.setDisabled(true) } }) return row }) await ButtonInteraction.update({ components: updatedComponents }) })
内容的提问来源于stack exchange,提问作者Bin Floo
相关产品推荐
相关产品推荐

