discord.py 重写 |只允许一个命令的一个实例

discord.py rewrite | Allow only one instance of a command

在使用我的机器人时,我发现多人可以同时使用同一个命令。由于它的性质,我只希望一次 运行 一个命令。

有没有办法确保只有一个命令实例运行?如果有,请告诉我。我需要这种固定的快速排序,因此非常感谢您的帮助。

您可以为所有超时时间较长的用户设置冷却时间,然后在命令结束时重置冷却时间:

from discord.ext.commands import cooldown

@bot.command()
@cooldown(1, 1000)  # 1000 second cooldown
async def comm(ctx):
    ...
    comm.reset_cooldown(ctx)

使用全局变量也是一种选择。

global set_active
set_active = 0
...
...
@bot.command("turn_on")
async def "Your command name"(ctx):
    global set_active
    #start command
    if set_active == 1:
        await ctx.send("This is already active")
    else/elif:
        ......
    #end command
    set_active = 1

@bot.command("turn_off")
async def "Your command name"(ctx):
    global set_active
    #start command
    ......
    #end command
    set_active = 0

我希望这是清楚的。这是我第一次帮助别人。 我的机器人里也有这个。如果我能为您提供更多帮助,请告诉我!

在您的命令中使用 @commands.max_concurrecy(number, per=, wait=False) 装饰器。

示例:

@commands.command()
@commands.max_concurrency(1, per=commands.BucketType.default, wait=False)
async def poll(self, ctx, *question):
    '''
    Code
    '''

当使用 max_concurrency 装饰器时,如果你设置了 wait=False 那么当实例超过指定的数量时它会 return MaxConcurrencyReached 错误。错误处理与上述相同命令的示例如下所示

示例:

@poll.error
async def poll_handler(self, ctx, error):
    if isinstance(error, commands.MaxConcurrencyReached):
         (Whatever you want to do here)

如果 wait=True 则命令将在队列中等待,直到可以 运行。

记得在你的机器人中也有这一行 from discord.ext import commands