添加超时以侦听使用Discord.js机器人发送的消息的相同命令

时间:2019-04-04 15:54:03

标签: discord.js

嗨,我想让我的机器人在一定时间内忽略某些命令或消息中发送的相同命令,我如何将其应用于或完成下面的当前命令?谢谢

if (message.content.toLowerCase().startsWith("usa")) {
  message.channel.send("USA");
}

1 个答案:

答案 0 :(得分: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秒时,它将发送失败消息,提示您无法执行此命令。