如何使用discord.py创建冷却系统?

2024-05-19 01:35:25 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个命令

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

现在,当我键入hi 1时,它不应该在我键入hi 2时响应我。 类似于共享冷却系统的东西

我该怎么做

我目前正在使用:

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

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


Tags: 用户命令键入hicommandsusercooldownbuckettype
1条回答
网友
1楼 · 发布于 2024-05-19 01:35:25

您可以使用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")

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

相关问题 更多 >

    热门问题