添加Timeout以侦听与Discord.js bot一起发送的消息的相同命令

问题描述 投票:0回答:1

嗨我想让我的机器人忽略为某些命令或消息发送一段时间的相同命令,我怎么能应用或完成这个到我下面的当前命令?谢谢

if (message.content.toLowerCase().startsWith("usa")) {
  message.channel.send("USA");
}
discord.js
1个回答
0
投票
const cooldown = new Set(); //put this outside of your event for catching messages (on top of code)
if (message.content.toLowerCase().startsWith("usa")) {
  if (cooldown.has(message.author.id)) //if author's id is in the variable (i.e: they are in cooldown)
    return message.channel.send("You have a cooldown on this command!"); //return a message saying they can't do this command
  cooldown.add(message.author.id); //if they are not in the cooldown, you need to add them to it so next time, they will be in cooldown
  setTimeout(() => { cooldown.delete(message.author.id); }, 5000); //it will create a timeout and add them to our cooldown list, and after 5000ms (5 seconds), it will remove them from it
  message.channel.send("USA"); //command stuff below
}

Source

代码将创建一个名为cooldown的新列表,它将检查用户ID是否在列表中。如果没有,它会将id添加到列表中,并在指定的时间(5000ms = 5秒)后,将从列表中删除它们的id,当他们尝试再次执行命令而不等待5秒时,它将发送一个失败消息说你不能做这个命令。

© www.soinside.com 2019 - 2024. All rights reserved.