【发布时间】:2021-10-22 12:52:29
【问题描述】:
在使用我的机器人时,我发现多人可以同时使用相同的命令。由于它的性质,我只希望一次运行一个命令。
有没有办法确保只有一个命令实例在运行?如果有,请告诉我。我需要这种快速修复的方法,因此不胜感激。
【问题讨论】:
在使用我的机器人时,我发现多人可以同时使用相同的命令。由于它的性质,我只希望一次运行一个命令。
有没有办法确保只有一个命令实例在运行?如果有,请告诉我。我需要这种快速修复的方法,因此不胜感激。
【问题讨论】:
您可以为所有用户设置一个较大超时的冷却时间,然后在命令结束时重置冷却时间:
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
使用全局变量也是一种选择。
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 对象(用于定义组或特定于命令的错误处理程序之类的东西) )
在您的命令上使用 @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
【讨论】: