首页 > 解决方案 > 我想为我在 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)

在这里,我首先检查命令是否被禁用,因为我必须在每个命令中做同样的事情,除了我在做什么之外,还有其他方法吗?

请帮助我。

标签: python-3.xdiscord.py

解决方案


是的,您可以使用bot.check适用于所有命令的装饰器

例子:

@bot.check
async def globally_block_dms(ctx):
    return ctx.guild is not None # no dms

您可以使用 ctx.guild 和 ctx.guild.id 检查该命令是否被禁用


推荐阅读