如何在Discord.js中设置按钮触发相同的Facts命令?
实现按钮触发Facts命令逻辑的步骤
1. 给按钮添加唯一标识ID
首先要给按钮设置专属的customId,让Discord能识别是这个按钮被点击:
const factsRow = new MessageActionRow() .addComponents( new MessageButton() .setLabel('More Facts') .setStyle('primary') .setCustomId('more_facts_btn') // 新增这行,给按钮一个唯一识别ID )
2. 封装重复逻辑为单独函数
把获取事实、生成Embed的代码抽成独立函数,避免命令和按钮逻辑重复编写:
async function getFactsEmbed() { try { const mavlina = new Mavlina() const factsd = await mavlina.facts() return new MessageEmbed() .setColor('#111133') .setTitle("Facts") .setDescription(`${factsd.data}`) } catch (err) { console.log(err.message) return new MessageEmbed() .setColor('#ff0000') .setTitle("出错了") .setDescription("无法获取新的事实,请稍后再试") } }
3. 修改原命令代码调用封装函数
简化原命令逻辑,直接调用上面的函数生成Embed:
if(commandName === 'facts'){ try{ const factsRow = new MessageActionRow() .addComponents( new MessageButton() .setLabel('More Facts') .setStyle('primary') .setCustomId('more_facts_btn') ) const factsEmbed = await getFactsEmbed() interaction.reply({ components: [factsRow], embeds: [ factsEmbed ], ephemeral: true }) }catch(err){ console.log(err.message) } }
4. 监听按钮点击事件
在机器人客户端上添加interactionCreate监听,处理按钮的点击操作:
client.on('interactionCreate', async interaction => { // 过滤非目标按钮的交互 if (!interaction.isButton() || interaction.customId !== 'more_facts_btn') return; try { // 先延迟更新,避免Discord提示交互失败 await interaction.deferUpdate(); // 获取新的事实Embed const newFactsEmbed = await getFactsEmbed(); // 更新原来的临时消息,替换为新内容并保留按钮 await interaction.editReply({ embeds: [newFactsEmbed], components: [interaction.message.components[0]] }); } catch (err) { console.log(err.message); await interaction.editReply({ embeds: [new MessageEmbed().setColor('#ff0000').setTitle("出错了").setDescription("无法更新事实")], components: [interaction.message.components[0]] }); } });
核心说明
setCustomId是识别按钮的关键,每个交互组件都需要唯一ID区分。- 因为原消息是临时的(
ephemeral: true),所以要用interaction.editReply更新原消息,不能发送新消息。 - 添加
deferUpdate可以避免因接口请求耗时导致的交互超时提示,提升用户体验。
内容的提问来源于stack exchange,提问作者AlpHa Coder
相关产品推荐
相关产品推荐

