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

Bot上线时在指定频道发送Embed的代码问题求助

问题修复方案

你的代码存在几个关键问题:

  • 不能在send()方法的参数对象内部声明变量,属于语法错误
  • 代码未正确闭合括号(client.on的回调函数、send的参数都缺少闭合的}和))
  • 未导入EmbedBuilder(Discord.js v14及以上版本需要显式导入该类)
  • 未处理频道不存在的异常情况(比如频道ID错误、频道不在缓存中)

修正后的完整代码:

// 导入Discord.js必要模块(v14+版本)
const { Client, EmbedBuilder, GatewayIntentBits } = require('discord.js');

const client = new Client({ 
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] 
});

client.on("ready", async (c) => {
  console.log(`已登录为 ${c.user.tag}`);
  
  // 获取目标频道
  const channel = client.channels.cache.get('你的频道ID');
  if (!channel) {
    console.error("未找到指定频道,请检查ID是否正确");
    return;
  }

  // 构造Embed消息
  const embed = new EmbedBuilder()
    .setTitle("Comandi Principali:")
    .setColor("Random");

  // 发送消息并处理异常
  try {
    await channel.send({ embeds: [embed] });
    console.log("上线通知Embed已发送");
  } catch (error) {
    console.error("发送消息失败:", error);
  }
});

// 登录Bot
client.login('你的Bot令牌');

关键修正点说明:

  • 将Embed的声明移到send()方法外部,通过embeds: [embed]的数组形式传入(Discord.js v14+要求Embed以数组格式传递)
  • 添加频道存在性检查,避免因频道不存在导致Bot崩溃
  • 增加异常捕获逻辑,处理消息发送失败的情况
  • 补充必要的Intent声明(Bot需要对应权限才能发送消息)

内容的提问来源于stack exchange,提问作者contaProgram

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:17:39