简体   繁体   English

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

[英]How to make a cooldown system with discord.py?

Let's say I have two commands...假设我有两个命令......

  • hi 1 that sends hi once to user and starts a cooldown of 500 seconds hi 1向用户发送 hi 一次并开始 500 秒的冷却时间
  • hi 2 that sends hi twice to user and starts a cooldown of 1000 seconds hi 2向用户发送 hi 两次并开始 1000 秒的冷却时间

Now when I type hi 1 it should not respond to me when I type hi 2 .现在,当我输入hi 1时,它不应该在我输入hi 2时响应我。 Something like a shared cooldown system!类似于共享冷却系统的东西!

How can I do that?我怎样才能做到这一点?

I am currently using this:我目前正在使用这个:

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

Which allows me to use the multiple commands without stopping for cooldown on a previous command.这使我可以使用多个命令,而无需停止前一个命令的冷却时间。

You could use a custom check to ensure that the commands aren't used while they're on cooldown.您可以使用自定义检查来确保命令在冷却时不被使用。 ./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)

This can then be imported然后可以导入

./main.py

from q63262849 import cooldowns

and used as a decorator for commands并用作命令的装饰器

./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")

It is notable that this approach still has some issues, in particular if another later check fails this check will still put the command on cooldown, however these could be solved by putting this check such that it will run after all the other checks.值得注意的是,这种方法仍然存在一些问题,特别是如果稍后的另一个检查失败,此检查仍会将命令置于冷却状态,但是可以通过放置此检查以使其在所有其他检查之后运行来解决这些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM