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

Discord.js指令冷却时间格式化返回错误负值的解决求助

问题解决:Discord.js 指令冷却时间格式化错误

你的代码存在两个核心问题,导致时间显示出现异常负数:

1. 冷却状态存储逻辑错误

你当前在cooldowns集合中存储的是布尔值true,但实际上需要存储用户使用指令时的毫秒时间戳,这样才能准确计算剩余冷却时长。

2. 剩余时间计算单位混乱

原公式混合了毫秒和秒两种时间单位(Date.now()返回毫秒,你却除以1000转成秒,同时和毫秒单位的冷却时长计算),导致结果完全错误。


修正后的完整代码

const { Collection } = require('discord.js');

// 创建集合存储用户冷却状态并设置冷却时间。
const cooldowns = new Collection();
const COOLDOWN_SECONDS = 10; // 替换为所需的冷却时间(秒)。

function formatTime(seconds) {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = Math.floor(seconds % 60);

  return `${hours} hours, ${minutes} minutes and ${remainingSeconds} seconds`;
}

module.exports = {
    name: 'fortune',
    description: 'Get your fortune told!',
    callback: (client, interaction) => {
        // 检查用户是否处于冷却中,若是则通知用户。
        if (cooldowns.has(interaction.user.id)) {
          // 获取用户上次使用指令的时间戳
          const lastUsedTime = cooldowns.get(interaction.user.id);
          // 计算冷却结束时间(上次使用时间 + 冷却时长毫秒)
          const cooldownEndTime = lastUsedTime + COOLDOWN_SECONDS * 1000;
          // 计算剩余冷却时间(毫秒),确保不会出现负数
          const remainingTimeMs = Math.max(cooldownEndTime - Date.now(), 0);
          // 转成秒后传给格式化函数
          const remainingSeconds = Math.ceil(remainingTimeMs / 1000);
          const formattedTime = formatTime(remainingSeconds);
          interaction.reply({ content: `Please wait for ${formattedTime} to use this command again.`, ephemeral: true });
        } else {
            // 无冷却状态,执行指令逻辑。
            const fortunes = [
                'You will find love soon.',
                'You will have a great day today.',
                'You will be successful in your career.'
            ];
            const fortune = fortunes[Math.floor(Math.random() * fortunes.length)];
            interaction.reply(fortune);

            // 设置冷却状态:存储当前时间戳(毫秒)
            cooldowns.set(interaction.user.id, Date.now());
            setTimeout(() => {
                // 指定时间后移除用户的冷却状态。
                cooldowns.delete(interaction.user.id);
            }, COOLDOWN_SECONDS * 1000);
        }
    }
}

关键修改说明

  • 冷却存储:将cooldowns.set(interaction.user.id, true)改为cooldowns.set(interaction.user.id, Date.now()),存储用户使用指令的毫秒时间戳。
  • 剩余时间计算:
    1. 先算出冷却结束时间:lastUsedTime + COOLDOWN_SECONDS * 1000
    2. 用Math.max()确保剩余时间不会为负数(避免冷却结束后仍显示异常值)
    3. 将毫秒转成秒时用Math.ceil()向上取整,保证显示的时间符合预期(比如剩余9.1秒会显示10秒)
  • 原formatTime函数无需修改,完全满足你的输出需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 15:17:25