You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js v14按钮使用表情ID时崩溃问题求助

按钮添加表情ID后程序崩溃的解决方案

问题根源

  1. 表情ID传递格式错误
    你在btn2中使用<1008747826714521610>这种带尖括号的格式是Discord聊天框里的表情输入写法,但discord.js的setEmoji方法不支持这种格式。直接传入带尖括号的字符串会被识别为无效参数,触发API请求失败导致程序崩溃。

  2. 按钮交互判断逻辑错误
    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 14:29:09