Discord.js v14按钮使用表情ID时崩溃问题求助
按钮添加表情ID后程序崩溃的解决方案
问题根源
表情ID传递格式错误
你在btn2中使用<1008747826714521610>这种带尖括号的格式是Discord聊天框里的表情输入写法,但discord.js的setEmoji方法不支持这种格式。直接传入带尖括号的字符串会被识别为无效参数,触发API请求失败导致程序崩溃。按钮交互判断逻辑错误
interaction.isButton是一个方法而非属性,你直接访问if(interaction.isButton)会得到undefined,后续逻辑执行时会抛出错误。
修复后的完整代码
import { Client, GatewayIntentBits, Partials, ActionRowBuilder, ButtonBuilder, ButtonStyle } from "discord.js"; const client = new Client({ 'intents': [ GatewayIntentBits.DirectMessages, GatewayIntentBits.Guilds, GatewayIntentBits.GuildBans, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, ], 'partials': [Partials.Channel] }); client.once('ready', () =>{ console.log(`${client.user.username} Is Online!`); client.user.setActivity(`>>rank`, { type: "WATCHING" }); }); client.on("messageCreate", (message) => { const btn1 = new ButtonBuilder() .setCustomId('btn1') .setLabel('Click Me!') .setStyle(ButtonStyle.Primary) const btn2 = new ButtonBuilder() .setLabel('YT') .setEmoji('1008747826714521610') // 直接传入纯表情ID字符串 .setStyle(ButtonStyle.Link) .setURL('https://www.youtube.com/c/himisa') const btn3 = new ButtonBuilder() .setCustomId('btn2') .setLabel('Click Me!') .setStyle(ButtonStyle.Success) if (message.content === 'hi'){ return message.channel.send({ content: 'HI' , components:[new ActionRowBuilder().addComponents(btn1,btn2,btn3)] }) } }); client.on('interactionCreate', async interaction => { if(interaction.isButton()){ // 调用isButton()方法判断交互类型 await interaction.deferUpdate(); if(interaction.customId === 'btn1'){ await interaction.channel.send('Um Hello'); } } }); client.login('SUPER SECRET TOKEN');
额外优化建议
建议使用ButtonStyle.Primary这类枚举值代替字符串'Primary',既能避免拼写错误,还能获得编辑器的类型提示,进一步提升代码稳定性。
内容的提问来源于stack exchange,提问作者Gaming HMS
相关产品推荐
相关产品推荐

