You need to enable JavaScript to run this app. Discord.js给违规静音用户发私信时报"Unexpected identifier"错误
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js给违规静音用户发私信时报"Unexpected identifier"错误

代码报错的核心成因与修复方案

直接触发SyntaxError: Unexpected identifier的语法问题

  • 免罚角色判断的if语句缺失闭合括号:原代码中if(!msg.member.roles.cache.get("777167323232469002")末尾没有加匹配的),JS解析器读到下一行的msg.member.send(...)时,认为前面的if条件还未结束,直接将后续的标识符判定为非预期内容抛出错误。
  • awaitReactions方法参数结构错位:原代码将配置对象{max: 1}与后续的.then()链式调用嵌套错误,没有先把过滤函数、配置对象作为参数完整传入awaitReactions,就在参数括号未闭合的情况下写了Promise链式调用,直接造成解析失败。
  • 全代码块括号层级不匹配:从最外层if到代码结尾,一共缺失2个右花括号、1个方法调用的右括号,块结构完全断裂。

会导致功能失效的逻辑问题(不触发语法报错,但运行后达不到设计预期)

  • 反应收集逻辑未排除机器人自身操作:现有过滤函数只判断emoji是否为对勾,没有过滤机器人自己触发的反应,会导致机器人刚发出私信、自己加上对勾时,就被判定为用户确认,直接提前解除静音。
  • 静音角色添加时机错误:现有代码是在私信发送成功的回调里才加静音角色,如果用户关闭了私信权限,send()方法会直接进入异常分支,静音角色永远不会被加上。
  • 缺少异常兜底:没有处理用户关闭私信、机器人无权限删除消息/添加角色的异常场景,一旦出现权限不足的情况,整个事件回调会直接崩溃。

修复后可正常运行的参考代码

if(msg.content.split(" ").includes("asdf")){
  if(msg.deletable){
    msg.delete().catch(console.error);
    const whitelistRoleId = "777167323232469002";
    if(!msg.member.roles.cache.get(whitelistRoleId)){
      const muteRoleId = "759883236322574376";
      const muteRole = msg.guild.roles.cache.get(muteRoleId);
      // 先添加静音角色,避免私信发送失败漏加
      msg.member.roles.add(muteRole).catch(console.error);
      
      msg.member.send("You have been muted for saying a banned word. Please visit the rules and read all of our rules. React with a checkmark if you agree to all of the rules.")
        .then(async sent => {
          await sent.react("✔️").catch(console.error);
          // 收集有效用户反应
          const collected = await sent.awaitReactions({
            max: 1,
            time: 300000, // 5分钟无确认自动超时
            filter: (reaction, user) => reaction.emoji.name === "✔️" && !user.bot
          });
          if(collected.first()){
            await msg.member.roles.remove(muteRole).catch(console.error);
            await msg.author.send("Thank you for agreeing to follow our rules. Please keep in mind breaking any rules will result in moderator punishment.").catch(console.error);
          }
        })
        .catch(err => {
          console.error("私信发送失败:", err);
          msg.channel.send(`${msg.author} 你已关闭私信权限,我无法发送静音确认通知,请开启私信后联系管理员恢复权限`, { ephemeral: true }).catch(console.error);
        });
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 22:57:07