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

纵然是瞬间 提交于 2020-12-16 04:19:11

问题


Whilst using my bot, I discovered that multiple people can use the same command simultaneously. I would only like the command to be ran one at a time, due to it's nature.

Is there a way to ensure there is only one instance of the command running? If there is, please tell me. I need this fixed sort of quickly, so any help is appreciated.


回答1:


You can have a cooldown for all users with some large timeout, then reset the cooldown at the end of the command:

from discord.ext.commands import cooldown

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



回答2:


Using a global variable is also an option.

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

I hope this is clear. It is my first time helping somebody. I have this in my bot too. Let me know if I can help you out more!




回答3:


Use the @commands.max_concurrecy(number, per=, wait=False) decorator on your command.

Example:

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

When using the max_concurrency decorator, if you have wait=False then it will return the MaxConcurrencyReached error when the instances exceeds the number specified. Example of error handling the same command that is above is shown below

Example:

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

If wait=True then the command will wait in a queue until it can be ran.

Remember to have this line as well in your bot from discord.ext import commands



来源:https://stackoverflow.com/questions/54853085/discord-py-rewrite-allow-only-one-instance-of-a-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!