【问题标题】:How to make a cooldown system with discord.py?如何使用 discord.py 制作冷却系统?
【发布时间】:2020-11-25 11:48:58
【问题描述】:

假设我有两个命令...

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

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

我该怎么做?

我目前正在使用这个:

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

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

【问题讨论】:

  • 看来你可能需要自己检查一下,因为我认为 dpy 没有开箱即用的检查
  • 对如何开始或这样做有任何想法吗? @Minion3665
  • 我不完全确定,但我可以解决。让我看看我能不能做到,一会儿给你写一个答案
  • 如果你能做到这一点,我真的很感激,我正在尝试检查是否有可能找到是否有人已经处于冷却状态!

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


【解决方案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")

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

【讨论】:

  • @minion3635 我收到一条错误消息,提示函数属性没有属性冷却时间
  • @SDG8 你有一个叫做冷却的功能吗?似乎引用的行是@cooldowns.cooldown(...),并且该错误表明您有一个称为相同事物的函数。
  • 它是你给我的确切代码,我只是更改了 20 和 await ctx.send 值
  • 其他都一样
  • 那么您是否将def cooldown@bot.commands 放在同一个文件中?
猜你喜欢
  • 2022-01-18
  • 2021-05-13
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
  • 2021-03-30
  • 1970-01-01
  • 2021-05-02
相关资源
最近更新 更多