Node.js 如何添加冷却时间?

Node.js 如何添加冷却时间?,node.js,discord.js,bots,Node.js,Discord.js,Bots,此命令不断被垃圾邮件发送,似乎正在破坏bot bot.on('message', msg=>{ if(msg.content === "h"){ msg.channel.send('hㅤ'); } }) 同样,我如何为这个命令添加冷却时间?我正在使用discord.js,我不确定如何添加冷却时间。以下是我是如何做到这一点的: var usersInTimeout=[]; bot.on('message',msg=>{ 如果(msg.c

此命令不断被垃圾邮件发送,似乎正在破坏bot

bot.on('message', msg=>{
    if(msg.content === "h"){
        msg.channel.send('hㅤ');
    }
 })

同样,我如何为这个命令添加冷却时间?我正在使用discord.js,我不确定如何添加冷却时间。

以下是我是如何做到这一点的:

var usersInTimeout=[];
bot.on('message',msg=>{
如果(msg.content==“h”){
var timeoutDelay=1000*60*60;//所需的冷却时间(毫秒)
if(usersInTimeout.some(user=>user.userID==message.author.id)){//检查用户是否处于超时状态
var userInTimeout=usersInTimeout.find(user=>user.userID==message.author.id);
var remainingTime=millisec(timeoutDelay-(new Date().getTime()-userInTimeout.timeoutStart)).format('hh:mm:ss');
returnmessage.reply(`Time left to use the command:*${remainingTime}**`);
}
//运行以下命令:
msg.channel.send('hㅤ');
usersInTimeout.push({userID:message.author.id,timeoutStart:new Date().getTime()});//将用户添加到超时
setTimeout(()=>{//添加计时器以将其从超时中删除
usersInTimeout.splice(usersInTimeout.indexOf(message.author.id),1);
},超时延迟);
}
});
说明:
在超时时创建一个用户数组,每当命令被触发时,检查用户是否在该数组中,如果他在,则该命令将起作用,并且用户将被添加到
usersInTimeout
数组中,直到在
超时延迟完成后将其从该数组中删除后才能使用该命令

您可以使用在bot中创建冷却功能

const cooldown = new Set();

// Add user to a set and remove them after 5 seconds
cooldown.add(<Message>.author.id);
setTimeout(() => {
   cooldown.delete(<Message>.author.id);
}, 5000);

// Check if user is in the set (i.e. shouldn't be able to use command)
if (cooldown.has(<Message>.author.id)) {
   // Don't let user use the command
} else {
   // Do any logic here and send a message
}
const cooldown = new Set();

// As a function, it can now be called multiple times
// but if you're adding users to the same set then it will stop them from using other commands too
function addToCooldown(ID) {
    cooldown.add(ID);
    setTimeout(() => {
        cooldown.delete(ID);
    }, 5000 /* 5 seconds */);
}

bot.on('message', msg=>{
    if(msg.content === "h"){
        // Send a message if the user is not in the cooldown set
        if (!cooldown.has(msg.author.id)) {
            addToCooldown(msg.author.id);
            msg.channel.send('h');
        }
    }
});