【问题标题】:discord.py rewrite | Allow only one instance of a commanddiscord.py 重写 |只允许一个命令的一个实例
【发布时间】:2021-10-22 12:52:29
【问题描述】:

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

有没有办法确保只有一个命令实例在运行?如果有,请告诉我。我需要这种快速修复的方法,因此不胜感激。

【问题讨论】:

    标签: python discord.py-rewrite


    【解决方案1】:

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

    from discord.ext.commands import cooldown
    
    @bot.command()
    @cooldown(1, 1000)  # 1000 second cooldown
    async def comm(ctx):
        ...
        comm.reset_cooldown(ctx)
    

    【讨论】:

    • 这可能是一个小问题,但是我在导入后得到了错误No module named 'commands。我对from commands import cooldown 做错了什么?
    • 哎呀,我使用的模块已经导入了命令。那应该是discord.ext.commands
    【解决方案2】:

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

    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
    

    我希望这很清楚。这是我第一次帮助别人。 我的机器人也有这个。让我知道我是否可以为您提供更多帮助!

    【讨论】:

    • 对所有命令使用相同的名称并不好,因为这样您就不能在以后的代码中访问 Command 对象(用于定义组或特定于命令的错误处理程序之类的东西) )
    • @PatrickHaugh 我并不是要对所有命令使用相同的名称。只是命令的占位符。我将相应地编辑我的答案。感谢您的关注!
    【解决方案3】:

    在您的命令上使用 @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,那么当实例超过指定数量时,它将返回 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 2021-04-09
      • 2012-08-27
      相关资源
      最近更新 更多