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

如何解决Discord.js中bt!sendlove命令无提及用户时崩溃问题

问题修复方案

你的代码崩溃的核心原因有两个:

  • 你在使用变量之后才声明它们,判断userToMention === ""的时候,这个变量还没定义,直接会触发报错
  • message.mentions.users.first()返回的是用户对象或者undefined,不是空字符串,所以用=== ""判断是否存在用户完全不生效

直接按下面的逻辑修改就能解决问题:

client.on("messageCreate", (message) => {
  if (message.content.startsWith("bt!sendlove")) {
    // 先获取提及的用户,放在最前面
    const userToMention = message.mentions.users.first();
    
    // 判断是否有提及用户:如果userToMention是undefined,说明没@人
    if (!userToMention) {
      // 先添加反应,再发送提示
      message.react('❌')
        .then(() => message.channel.send("Invalid command use."))
        .then(() => message.channel.send("Please use the correct format: `bt!sendlove @User`"));
      // 用return终止函数,后面的代码就不会执行了
      return;
    }

    // 到这里说明已经有有效提及用户了,继续后续逻辑
    const userToUser = userToMention.username;
    const messageAuthor = message.author.username;
    
    // 你的其他代码...
  }
});

关键改动说明:

  • 把获取提及用户的代码移到判断之前,确保变量存在
  • 用!userToMention判断是否未提及用户(因为没有用户时返回undefined,取反就是true)
  • 在提示代码后加return,直接终止当前函数执行,避免后续访问userToMention.username这类会导致崩溃的代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:12:40