python - 为多个 discord.py 机器人命令设置相同的冷却时间?
问题描述
这是写在discord.py
.
我有多个类似于以下的命令:
@bot.command(name ="hi")
async def hi(ctx):
link = ["https://google.com", "https://youtube.com"]
chosen = random.choice(link)
url = chosen
embed = discord.Embed(title="Your Link", description=f"[Click Here]({url})", color=0x00ff00)
if ctx.message.guild == None:
await ctx.author.send('You can not use this command in your DM!')
pass
else:
await ctx.author.send(embed=embed)
如果有人使用其中一个命令,则应为所有命令制定冷却时间(例如,如果!hi
使用,冷却时间将应用于两个!hi
AND !bye
。
我知道你可以使用@commands.cooldown(1, 600, commands.BucketType.user)
,但这只会对当前命令应用冷却时间。
解决方案
这是cooldowns
在代码中定义装饰器的方式:
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
我们可以修改它,以便我们只创建一个Cooldown
在命令之间共享的对象:
def shared_cooldown(rate, per, type=BucketType.default):
cooldown = Cooldown(rate, per, type=type)
def decorator(func):
if isinstance(func, Command):
func._buckets = CooldownMapping(cooldown)
else:
func.__commands_cooldown__ = cooldown
return func
return decorator
我们将通过调用它来获取装饰器,然后将其应用于命令:
my_cooldown = shared_cooldown(1, 600, commands.BucketType.user)
@bot.command()
@my_cooldown
async def hi(ctx):
await ctx.send("Hi")
@bot.command()
@my_cooldown
async def bye(ctx):
await ctx.send("Bye")
推荐阅读
- javascript - 在选择一个选项时不发送文本框值
- firebase - FireBase Ping 延迟
- python - 如何从 HTML 中的该属性中提取字符串?
- mysql - SELECT /*!N SQL_NO_CACHE */ * FROM `table` - 这是什么?
- heroku - 我无法让 libvips 在 heroku 上编译
- c# - SetActive 的反应不同
- ghc - 堆栈如何确定使用哪个 ghc?
- javascript - 不确定我对 React Redux 应用程序中特定部分的处理方法?
- html - HTML 元素颜色、颜色和宽度 CSS 属性不起作用
- java - Jetty 中的 JSR-356 javax websockets(嵌入式和非嵌入式)