You need to enable JavaScript to run this app. 使用discord.js编写Discord机器人欢迎消息时出现Unexpected identifier错误
优惠活动
大模型
产品
解决方案
定价
更多

使用discord.js编写Discord机器人欢迎消息时出现Unexpected identifier错误

报错原因

你收到的SyntaxError: Unexpected identifier是典型的JavaScript语法错误,由代码中不合法的写法、未闭合的括号导致JS解释器无法正常解析后续代码,具体问题点:

  • 重复定义事件回调函数:guildMemberAdd事件第一行已经声明了回调msg => {,第二行多余的msg =>属于无效语法,直接打乱了解析逻辑
  • 多层括号未闭合:embed配置对象、send方法的入参对象、事件回调的大括号全部没有补全闭合,代码逻辑块没有明确边界
  • 可选兼容问题:如果你使用discord.js v12及以上版本,还存在两处API用法错误:获取频道需要调用channels.cache.get而非直接channels.get,avatarURL是方法需要加()执行,v14+版本发送嵌入消息需要用embeds数组包裹单个embed对象。

修复后代码

client.on('guildMemberAdd', member => {
  // 若你使用discord.js v11及以下版本,删除下面的.cache即可
  const welcomeChannel = member.guild.channels.cache.get('861132489584934926')
  // 频道不存在直接退出,避免报错
  if (!welcomeChannel) return

  welcomeChannel.send({
    embeds: [{
      color: 3447003,
      author: {
        name: client.user.username,
        icon_url: client.user.avatarURL()
      },
      title: "Welcome To OP COMMUNITY!",
      description: "Have Fun in the server :)",
      timestamp: new Date(),
      footer: {
        icon_url: client.user.avatarURL(),
        text: "Builded by Oplikoo#9999"
      }
    }]
  })
})

client.login('你的机器人令牌')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 04:45:03