【问题标题】:Starting discord.py command cooldown only if condition is met仅在满足条件时才启动 discord.py 命令冷却
【发布时间】:2021-05-04 06:17:17
【问题描述】:

我希望仅当满足函数中的条件时才开始我的命令之一的冷却,如下所示:

@bot.command
async def move(ctx, destination):
    destinations=["d1", "d2", "d3"] # List of valid arguments for the command
    if destination in destinations:
        movement(destination) # Function to actually move, not important for the question
        # Start cooldown only here
    else:
        await ctx.send("This is not a valid destination")

这样,如果用户输入错误的目的地,他们将不会受到冷却时间的惩罚。我怎样才能做到这一点?

EDIT1:通常会使用 discord.py 的内置 @commands.cooldown 装饰器,这里是源代码:

def cooldown(rate, per, type=BucketType.default):
    def decorator(func):
        if isinstance(func, Command):
            func._buckets = CooldownMapping(Cooldown(rate, per, type))
        else:
            func.__commands_cooldown__ = Cooldown(rate, per, type)
        return func
    return decorator

但这适用于整个命令。(它通常放在@bot.command 装饰器之后)

【问题讨论】:

  • 你如何处理冷却时间?你使用函数吗?
  • @ImranD 编辑了消息以包含冷却装饰器的来源,有关其元素的更多信息在 discord.py 文档中

标签: python discord.py


【解决方案1】:

可能有很多方法可以制作自己的冷却时间,这里有一个简单的方法可以解决问题。其背后的想法是让机器人“记住”某人上次使用此特定命令的时间,并在允许玩家移动之前检查该时间。

from datetime import datetime, timedelta    

on_cooldown = {} # Dictionary with user IDs as keys and datetime as values
destinations=["d1", "d2", "d3"] # List of valid arguments for the command
move_cooldown = 5 # cooldown of the move command in seconds

@bot.command()
async def move(ctx, destination):

    if destination in destinations:
        author = ctx.author.id

        try:
            # calculate the amount of time since the last (successful) use of the command
            last_move = datetime.now() - on_cooldown[author] 
        except KeyError:
            # the key doesn't exist, the player used the command for the first time
            # or the bot has been shut down since
            last_move = None
            on_cooldown[author] = datetime.now()

        if last_move is None or last_move.seconds > move_cooldown:
            # move(...)
            on_cooldown[author] = datetime.now() # the player successfully moved so we start his cooldown again
            await ctx.send("You moved!")
        else:
            await ctx.send("You're still on cooldown.")    

    else:
        await ctx.send("This is not a valid destination")

注意:您可能需要也可能不需要删除 @bot.command 装饰器之后的括号。

【讨论】:

    【解决方案2】:

    如果这是你要找的,我想知道,但是有一种方法可以让冷却只有在这段代码正确解析代码后才激活:

    @bot.command(cooldown_after_parsing=True)
    @commands.cooldown(rate, per, type=<BucketType.default: 0>)
    

    你可以找到commands.cooldown here的文档

    还有cooldown_after_parsing的文档here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-13
      • 2021-03-30
      • 2021-03-11
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 2021-04-25
      • 2021-05-15
      相关资源
      最近更新 更多