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

discord.js计时脚本多用户启动计时仅最后一位用户数据生效问题求助

问题根源

你当前使用了全局单一的date变量存储计时开始时间,后续触发start指令的用户会直接覆盖该变量的值,因此只会保留最后一名启动计时用户的时间数据,所有用户触发stop时也只会读取到这个被覆盖的全局值。

修复方案

改用对象按照用户ID独立存储每个用户的计时开始时间,互不干扰,修改代码如下:

  1. 在指令处理逻辑的外层提前声明存储用户计时数据的对象:
// 全局位置声明,不要放在case判断内部
const userTimers = {};
  1. 修改start、stop分支的逻辑:
case 'start':
  userTimers[message.author.id] = new Date();
  message.channel.send(`<@!${message.author.id}> started the time count, don't forget to stop it! `)
  break;

case 'stop':
  const startTime = userTimers[message.author.id];
  let result = require('pretty-ms')(startTime ? (new Date() - startTime) : 0);
  // 停止后删除已结束的计时记录,释放内存
  delete userTimers[message.author.id];
  message.channel.send(`<@!${message.author.id}> stopped the time. His time was ` + result)
  break;

额外优化建议

  • 可以新增未启动计时就触发stop的判断逻辑,匹配场景下提示用户尚未启动计时,避免返回0时长的异常结果。
  • 如果需要支持服务重启后计时数据不丢失,可以将userTimers对象定期序列化写入本地JSON文件或数据库,服务启动时读取恢复即可。

内容的提问来源于stack exchange,提问作者I need Help

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:15:04