我如何设置双/高级冷却的命令在不和谐.py



这是一个具有基本冷却时间的基本命令:

@client.command()
@commands.cooldown(5, 57600, commands.BucketType.user)
async def ping(ctx)
await ctx.send("pong")

因此,基本上,当用户使用命令的前缀(例如"!k"(时;ping";机器人程序将发送";乒乓球"聊天。这是一个非常基本的命令,但接下来是冷却装饰器。冷却后:

@commands.cooldown(5, 57600, commands.BucketType.user)

我们可以看出,该命令可以在57600秒(16小时(之间使用5次,但如果我希望一个命令每16小时只使用5次并且每次使用该命令之间还有另一个冷却时间,该怎么办?让我解释一下。。。

每16小时可以使用该命令5次

但当你使用该命令时,你必须等待1个小时才能再次使用

这样,你就不能在一分钟内直接使用命令5次

把它想象成一棵每小时长一个苹果,但每天只长5个苹果的树。。。如何防止用户直接使用该命令5次?谢谢-

Discord.py不允许每个命令进行多次冷却检查,因此您必须使用自定义冷却处理程序。
class CooldownManager:
def __init__(self, executions_allowed: int, cooldown_time: float):
self.state = {}
self.executions_allowed = executions_allowed
self.cooldown_time = cooldown_time
def time_left(self, key) -> float:
"""Attempt to execute. Return 0 if ready, or the number of seconds until you're allowed to execute again."""
if key not in self.state.keys():
self.state[key] = []
if len(self.state[key]) > 0:
# Clean up executions that have aged away
# self.state[key] is sorted with the newest first
for i in range(len(self.state[key])-1, -1, -1):
if self.state[key][i] + self.cooldown_time < time.time():
del self.state[key][i]
if len(self.state[key]) < self.executions_allowed:
self.state[key].append(time.time())
return 0
next_available_execution = self.state[key][len(self.state)-1] + self.cooldown_time
return next_available_execution - time.time()
else:
self.state[key].append(time.time())
return 0
def assert_cooldown(self, data):
"""Run this at the beginning of the command."""
time_left = self.time_left(data)
if time_left > 0:
raise commands.CommandOnCooldown('', retry_after=time_left)

cm1 = CooldownManager(1, 4.0)  # execute once every 4 seconds
cm2 = CooldownManager(3, 120.0)  # execute up to 3x every 2 minutes
@client.command(name='test')
async def multicooldown(ctx):
# Check both cooldowns. This raises `CommandOnCooldown` just like the vanilla cooldown handler, so you can catch that later in your command error check.
cm1.assert_cooldown(ctx.author.id)  # This is basically the bucket type. You can use things like ctx.author.id, ctx.guild.id, etc
cm2.assert_cooldown(ctx.author.id)
# Do whatever you want here
await ctx.send('test')

最新更新