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

Discord机器人中对象存储的函数调用后无法执行问题

看起来你的命令映射逻辑是对的——调试日志已经确认client.commands里正确存储了match命令对象,也能读取到它的name和description,但execute函数完全没执行(连最开头的console.log都没输出),这确实有点诡异。我来帮你一步步排查问题:

第一步:确认execute函数是否真的被调用

先给match.js的execute函数加一个强制错误抛出,验证它是否被触发:

execute: function(message, args) {
  console.log('executing match.js');
  throw new Error('This is a test error from match.js'); // 新增这行
  // ... 原有代码
}

然后重新运行bot,发送!match命令。如果控制台打印出这个测试错误,说明execute确实被调用了,问题出在后续的代码里;如果没打印,那就要排查为什么函数没被执行(虽然调试日志显示函数存在,但可能有隐藏的调用问题)。

情况1:execute被调用了,但后续代码没反应

如果看到了测试错误,那问题大概率出在sheet()函数或者message.reply上:

  • 单独测试sheet()函数:在match.js里直接调用sheet()并打印结果,确认它能正常返回数据,不会卡住或静默失败。比如:
    // 在match.js顶部添加测试代码(测试完删掉)
    sheet().then(result => console.log('Sheet result:', result)).catch(err => console.log('Sheet error:', err));
    
    如果sheet()一直处于pending状态(没输出结果也没报错),那它就是卡住的原因,需要排查它的实现逻辑。
  • 替换message.reply为message.channel.send:有些情况下,message.reply可能因为权限、提及格式等问题静默失败,换成message.channel.send试试,看能否发送消息。
  • 改用async/await并完善错误捕获:你的execute里用了Promise链式调用,但内部的catch只捕获了sheet()的错误,如果message.reply出错(比如没有发送权限),这个错误不会被外层的try/catch捕获。改成async/await能让错误处理更清晰:
    // match.js里的execute改成async函数
    execute: async function(message, args) {
      console.log('executing match.js');
      try {
        const result = await sheet();
        await message.channel.send(
          '\n' +
          'Teams: ' + result[0].home + ' vs ' + result[0].away + '\n' +
          'Time: ' + result[0].date + ' ' + result[0].time + '\n' +
          'Competition: ' + result[0].competition + '\n' +
          'Channel: ' + result[0].channel
        );
      } catch (err) {
        console.error('Match command error:', err);
        throw err; // 把错误抛给外层的try/catch,让bot回复用户
      }
    }
    
    同时在index.js里调用execute时加上await:
    try {
      // ... 原有调试代码
      await client.commands.get(command).execute(message, args);
    } catch (e) {
      console.error(e);
      message.reply('Error in executing command.');
    }
    
    这样所有同步和异步错误都会被外层捕获,你能在控制台看到具体的错误信息。

情况2:execute没被调用(测试错误没出现)

如果测试错误没打印,那说明虽然你拿到了命令对象,但execute函数没被执行。这种情况很少见,但可以试试这些:

  • 检查client.commands.get(command).execute的类型:在index.js里加一行console.log(typeof client.commands.get(command).execute),确认输出是function。
  • 直接调用函数的字符串形式:把client.commands.get(command).execute(message, args)改成const execFn = client.commands.get(command).execute; execFn(message, args);,排除调用时的上下文问题。
  • 检查Discord.js版本:如果你用的是v13+,确保已经在开发者门户启用了Message Content Intent,否则bot可能无法正确处理消息内容(不过你能解析出命令,这个可能性较低)。

最后,别忘了测试完把临时的测试代码删掉,恢复原有逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:24:57