python - 仅当满足条件时启动discord.py命令冷却

标签 python discord.py

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

@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")

这样,如果用户输错了目的地,他们就不会受到冷却时间的惩罚。我怎样才能实现这一目标?

编辑1:通常会使用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 装饰器之后)

最佳答案

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

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 装饰器后面的括号。

关于python - 仅当满足条件时启动discord.py命令冷却,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58285467/

相关文章:

python - 通过 API 调用获取信息并进行身份验证

python - Pandas :当字典中有多个键时,通过映射添加列

python - 如何在 Cog Discord.Py 重写中正确定义 'client'

python - QTableView排序时如何保留选择

python - Shorte.st Api python

python - 如何在Python中创建一个所有元素都相同的二维列表?

python-3.x - 在discord.py中获取附加图像的高度

python - 如何获得不和谐公会的成员(discord.py)?

python - 如何使用discord.py创建 "react to role"嵌入消息

python - 将冷却时间/计时器添加到 on_message [Discord.py]