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

discord.js冷却处理器问题:如何在命令脚本中移除误触发的冷却时间?

解决方案

核心思路是给命令暴露手动取消本次冷却的工具函数,你可以在命令内任意校验失败的节点调用该函数回退已触发的冷却记录。

修改步骤

  1. 调整冷却存储结构,额外存储定时器ID,支持提前清除冷却定时任务
  2. 封装clearCooldown工具函数注入到命令执行参数中
  3. 异常捕获块默认触发冷却回退,避免执行报错也消耗冷却

修改后的完整代码

const { prefix: defaultPrefix } = require("../../config");
const prefixSchema = require("../../models/prefixSchema");

const languageSchema = require('../../models/languageSchema');
const { translations } = require("../../lang.json");

const discord = require("discord.js")

module.exports = async (Discord, client, message) => {

  if (message.channel.type == 'dm') return;

  let prefix;
  let dbPrefix = await prefixSchema.findOne({ guildID: message.guild.id });

  if (dbPrefix) {
    prefix = dbPrefix.prefix;
  } else {
    prefix = defaultPrefix;
  }
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  const args = message.content.slice(prefix.length).split(/ +/);
  const cmd = args.shift().toLowerCase();

  const command =
    client.commands.get(cmd) ||
    client.commands.find((a) => a.aliases && a.aliases.includes(cmd));

  const jezyk = await languageSchema.findOne({
    guildID: message.guild.id,
  })

  const lang = jezyk.language

  if (!cooldowns.has(command.name)) {
    cooldowns.set(command.name, new discord.Collection());
  }

  const current_time = Date.now();
  const time_stamps = cooldowns.get(command.name);
  const cooldown_amount = (command.cooldown) * 1000;

  if (time_stamps.has(message.author.id)) {
    const expiration_time = time_stamps.get(message.author.id).time + cooldown_amount;

    if (current_time < expiration_time) {
      const time_left = new Date(expiration_time - current_time).toISOString().substr(11, 8)

      const bicon = client.user.displayAvatarURL();
      const cooldown_command = new discord.MessageEmbed()
        .setAuthor(`${translations.ERROR_OCCUR[lang]}`, client.user.avatarURL())
        .setDescription(`${translations.TIMEOUT_DESCRIPTION_1[lang]} **${time_left}** ${translations.TIMEOUT_DESCRIPTION_2[lang]} **${command.name}**!`)
        .setColor(`#FF6347`)
        .setFooter(`${translations.DATE[lang]}`)
        .setTimestamp();
      return message.channel.send(cooldown_command);
    }
  }

  // 定义冷却取消工具函数
  const clearCooldown = () => {
    const userCooldown = time_stamps.get(message.author.id);
    if (userCooldown) {
      clearTimeout(userCooldown.timeoutId);
      time_stamps.delete(message.author.id);
    }
  }

  // 存储时间戳+定时器ID
  const timeoutId = setTimeout(() => time_stamps.delete(message.author.id), cooldown_amount);
  time_stamps.set(message.author.id, {
    time: current_time,
    timeoutId: timeoutId
  });

  try {
    if (command) command.execute(message, args, client, clearCooldown);
  } catch (err) {
    // 执行异常自动取消冷却
    clearCooldown();
    message.reply("wystąpił błąd krytyczny!");
    console.log(err);
  }
};

命令内使用示例

在你的命令脚本中,任意校验失败的位置调用传入的clearCooldown函数即可:

// 命令示例代码
module.exports = {
  name: '示例命令',
  cooldown: 10,
  async execute(message, args, client, clearCooldown) {
    // 参数校验失败取消冷却
    if (!args.length) {
      message.reply('请输入命令参数');
      return clearCooldown();
    }
    // 数据库校验失败取消冷却
    const userData = await 你的数据库模型.findOne({用户ID: message.author.id});
    if (!userData) {
      message.reply('权限校验失败');
      return clearCooldown();
    }
    // 正常执行后续逻辑
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 22:36:01