如何使用discord.py制作冷却系统?

时间:2020-08-05 10:05:45

标签: python python-3.x discord discord.py

假设我有两个命令...

  • hi 1向用户发送一次喜好,并开始500秒的冷却时间
  • hi 2向用户发送两次喜声并开始冷却1000秒

现在,当我键入hi 1时,它应该不会响应我。 就像一个共享的冷却系统!

我该怎么做?

我当前正在使用此

hi 2

这使我可以使用多个命令,而无需停止上一个命令的冷却。

1 个答案:

答案 0 :(得分:1)

您可以使用custom check来确保命令处于冷却状态时不使用命令。 ./q63262849/cooldowns.py

import datetime
from discord.ext import commands

on_cooldown = {}  # A dictionary mapping user IDs to cooldown ends


def cooldown(seconds):
    def predicate(context):
        if (cooldown_end := on_cooldown.get(context.author.id)) is None or cooldown_end < datetime.datetime.now():  # If there's no cooldown or it's over
            if context.valid and context.invoked_with in (*context.command.aliases, context.command.name):  # If the command is being run as itself (not by help, which runs checks and would end up creating more cooldowns if this didn't exist)
                on_cooldown[context.author.id] = datetime.datetime.now() + datetime.timedelta(seconds=seconds)  # Add the datetime of the cooldown's end to the dictionary
            return True  # And allow the command to run
        else:
            raise commands.CommandOnCooldown(commands.BucketType.user, (cooldown_end - datetime.datetime.now()).seconds)  # Otherwise, raise the cooldown error to say the command is on cooldown

    return commands.check(predicate)

然后可以将其导入

./main.py

from q63262849 import cooldowns

并用作命令的修饰符

./main.py

@bot.command()
@cooldowns.cooldown(10)
async def cooldown1(ctx):
    await ctx.send("Ran cooldown 1")


@bot.command()
@cooldowns.cooldown(20)
async def cooldown2(ctx):
    await ctx.send("Ran cooldown 2")

值得注意的是,该方法仍然存在一些问题,特别是如果另一个以后的检查失败,则该检查仍将命令置于冷却状态,但是可以通过将该检查放在其他所有检查之后运行来解决这些问题。