所以我目前正在开发Discord Bot,我对如何为命令制作冷却计时器有疑问。所以我想要它,所以如果他们使用命令,那么他们会被添加到列表中,并且必须等待数秒才能使用该命令。我对如何做到这一点有点了解,但我主要是为不同的人提供多个降温计时器。所以我们可以作为参考。 User1使用该命令,现在他必须等待5秒才能再次使用它。然后User2使用该命令,他还必须等待5秒。用户2使用用户1冷却3秒钟的命令。所以基本上我都在问我怎样才能制作一个跟踪每个用户时间的计时器。然后,一旦特定用户冷却完成,他就会从列表中删除。我计划将处于冷静状态的用户存储到列表中。
我可能会过度思考这个,很抱歉。
答案 0 :(得分:1)
我这样做的方法是让程序在开始附近声明2个空列表,一个包含DateTimeOffset,另一个包含另一个SocketGuildUser。如果您希望代码更高效且防错,则可以将两者绑定到对象实例列表中。但是为了这个例子:
在程序开始时声明您的列表。
public static List<DateTimeOffset> stackCooldownTimer = new List<DateTimeOffset>();
public static List<SocketGuildUser> stackCooldownTarget = new List<SocketGuildUser>();
这是速率限制代码:
//Check if your user list contains who just used that command.
if (Program.stackCooldownTarget.Contains(Context.User as SocketGuildUser))
{
//If they have used this command before, take the time the user last did something, add 5 seconds, and see if it's greater than this very moment.
if (Program.stackCooldownTimer[Program.stackCooldownTarget.IndexOf(Context.Message.Author as SocketGuildUser)].AddSeconds(5) >= DateTimeOffset.Now)
{
//If enough time hasn't passed, reply letting them know how much longer they need to wait, and end the code.
int secondsLeft = (int) (Program.stackCooldownTimer[Program.stackCooldownTarget.IndexOf(Context.Message.Author as SocketGuildUser)].AddSeconds(5) - DateTimeOffset.Now).TotalSeconds;
await ReplyAsync($"Hey! You have to wait at least {secondsLeft} seconds before you can use that command again!");
return;
}
else
{
//If enough time has passed, set the time for the user to right now.
Program.stackCooldownTimer[Program.stackCooldownTarget.IndexOf(Context.Message.Author as SocketGuildUser)] = DateTimeOffset.Now;
}
}
else
{
//If they've never used this command before, add their username and when they just used this command.
Program.stackCooldownTarget.Add(Context.User as SocketGuildUser);
Program.stackCooldownTimer.Add(DateTimeOffset.Now);
}
从此处输入您希望代码通过的任何内容。