python-3.x - 我想为我在 discord.py 中的所有命令添加一个检查。有没有捷径可以做到这一点?
问题描述
我想在 discord.py 中的所有命令之前添加相同的检查。我必须在每个命令中都这样做。有没有一种方法可以只为所有命令添加一次检查?
例子:
@commands.command(name="ping")
async def _ping(self,ctx):
db = firebase.database()
isEnabled = db.child('Disabled').child(str(ctx.guild.id)).child(ctx.command).get()
if isEnabled.val() is None:
lat = round((self.bot.latency)*1000)
if lat < 150:
em = discord.Embed(title=":ping_pong: | Pong!",description=f":green_circle: Current Latency : `{lat}`ms",color=discord.Color.green())
elif lat >= 150:
em = discord.Embed(title=":ping_pong: | Pong!",description=f":yellow_circle: Current Latency : `{lat}`ms",color=discord.Color.from_rgb(255,255,0))
else:
em = discord.Embed(title=":ping_pong: | Pong!",description=f":red_circle: Current Latency : `{lat}`ms",color=discord.Color.red())
await ctx.send(embed=em)
else:
em = discord.Embed(description="This command is disabled in your server. Ask admin to enable it",color=discord.Color.random())
await ctx.send(embed=em)
在这里,我首先检查命令是否被禁用,因为我必须在每个命令中做同样的事情,除了我在做什么之外,还有其他方法吗?
请帮助我。
解决方案
是的,您可以使用bot.check
适用于所有命令的装饰器
例子:
@bot.check
async def globally_block_dms(ctx):
return ctx.guild is not None # no dms
您可以使用 ctx.guild 和 ctx.guild.id 检查该命令是否被禁用
推荐阅读
- javascript - vue.js 中多个导入和注册的组件
- ios - 使用 fastlane 匹配方法在本地 iOS 设备上运行 react-native 应用程序
- c# - Richtextbox.Document.Blocks 中的 C# WPF 调度程序
- android - 折叠图像时,NestedScrollView 内的 RecyclerView 不会向上滚动
- ansible - 访问 Jinja 模板中的已注册变量
- c - 如何获取 uint32_t 的 uint8_t 数据
- visual-studio - 在 VS 2017 社区中更改行号分隔符颜色
- javascript - 悬停时播放的隐藏音频
- javascript - 如何在 JavaScript 中使用 import 而不会产生副作用或通过其他任何方式执行?
- javascript - 元素变化时如何执行函数?(没有 setInterval)