node.js - 距离可以使用命令的时间从 60 秒更改为 1 分钟
问题描述
我为我的 discord.js 机器人设置了 5 分钟(300 秒)的冷却时间,但是当有人在 5 分钟内多次使用它时,它会发送如下信息:@Edward,请等待 250.32 秒,直到你可以使用它命令!有什么方法可以将 250.32 秒更改为 4 分 10 秒或接近的时间?我是 Node.js 的菜鸟,因此将不胜感激。
if (!cooldowns.has(command)) {
cooldowns.set(command, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command);
const cooldownAmount = 1 * 300 * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`Please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
解决方案
阅读此讨论。
基本上,您需要将秒除以 60 以获得分钟,然后使用 % 来获取提醒:
const cooldownAmount = 1 * 275.45 * 1000;
const timeLeft = cooldownAmount / 1000;
var quotient = Math.floor(timeLeft / 60); //minutes
var remainder = Math.floor(timeLeft % 60); //seconds
console.log(quotient); // 4
console.log(remainder); // 35
此代码应该适用于您的情况:
if (!cooldowns.has(command)) {
cooldowns.set(command, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command);
const cooldownAmount = 1 * 300 * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
var quotient = Math.floor(timeLeft / 60); //minutes
var remainder = Math.floor(timeLeft % 60); //seconds
return message.reply(`Please wait ${quotient} minutes and ${remainder} seconds before reusing the \`${command}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
推荐阅读
- r - 为什么几个月在 R 中的一种情况下有效,而在另一种情况下无效?
- javascript - 未捕获的类型错误:无法读取 null 的属性 addEventListener
- php - 如何在 guzzle 中应用此 curl 代码?
- python-3.x - 可以将以下代码更改为更快吗
- python - 如何将python`for`循环转换为c++
- c++ - 在字符变量上使用 toupper() 时,所述 char 变量输出多个字符。我将如何防止这种情况?
- c# - 复选框的方法方程问题
- javascript - GatsbyJS 页面从 URL 打开时打开空白(使用博客导航正常工作)
- html - 为什么我的导航栏和页脚没有拉伸到全宽?
- shell - 运行 Hyperledger Fabric 示例“构建您的第一个网络”时“加载 ClientOU 证书失败”