如何配置createMessageComponentCollector仅允许指定用户点击MessageButton
解决方案
核心问题说明
你当前的代码存在两处导致过滤逻辑失效的错误:
- 逻辑运算符优先级错误:你编写的
m.customId === 'accept' || 'decline'实际执行逻辑为「customId等于accept 或者 字符串'decline'为真」,而字符串'decline'永远为真值,会导致customId的判断完全失效 - 交互对象属性调用错误:MessageComponent交互实例没有
author属性,触发交互的用户信息存放在user字段下,调用m.author.id会直接抛出未定义异常
修正后代码
// filter逻辑:同时满足customId是accept/decline、触发用户是指定的member.id两个条件 const filter = i => (i.customId === 'accept' || i.customId === 'decline') && i.user.id === member.id; const collector = interaction.channel.createMessageComponentCollector({ filter, max: 1, time: 30000 }); collector.on('collect', async (i) => { if (i.customId === 'accept') { await i.deferUpdate(); return await i.editReply({ content: `ACCEPT!`, embeds: [], components: [] }); } else if (i.customId === 'decline') { await i.deferUpdate(); return await i.editReply({ content: `DECLINE!`, embeds: [], components: [] }); } }); // 可选:监听超时事件做兜底处理 collector.on('end', (collected, reason) => { if (reason === 'time') { interaction.editReply({ content: '操作已超时', components: [] }); } })
补充说明
如果需要对非指定用户的点击做提示,可以不用filter判断,在collect事件里先校验用户身份,给不符合的用户回复仅本人可见的提示:
collector.on('collect', async (i) => { if (i.user.id !== member.id) { return i.reply({ content: '这个按钮不是给你操作的', ephemeral: true }); } // 后续原有业务逻辑 })
内容的提问来源于stack exchange,提问作者Nanotect.
相关产品推荐
相关产品推荐

