Home > Net >  Discord Python cog_check issue
Discord Python cog_check issue

Time:01-06

New to coding. I want to prevent my bot from responding to itself/other bots, and I'm trying to invoke a cog_check but can't make it work properly. Help would be greatly appreciated.

class CommandsMisc(commands.Cog):

    def __init__(self, client):
        self.client = client

    async def cog_check(self, ctx):
        if ctx.author.bot:   # also tried: if ctx.author == self.client.user:
            await exit()

    @commands.Cog.listener("on_message")   # example cog command
    async def print(self, message):
        if '!guide' in message.content:
            await message.reply(Guide_Text)
        else:
            pass

Since some people seem to lack reading comprehension skills, my question is how can I best utilize "cog_check" in Discord.py so that all subsequent commands/listeners in the cog will check whether the message.author is the bot and then won't execute if it is?

CodePudding user response:

It seems like what you want is a custom command decorator. You can do this as follows:

def is_not_bot():
    async def predicate(ctx):
        return not ctx.author.bot
    return commands.check(predicate)

You place this in your cog class, then on any command inside the cog you can use the decorator @is_not_bot()

What does this do, exactly? Well, we create a function which can be used as a command decorator (@is_not_bot()). Inside this, we create a function called predicate. This predicate will return True if the user is not a bot. We then call return commands.check(predicate) inside the parent function. This will allow us to use this as a decorator.

discord.py docs reference

CodePudding user response:

what you can have is a on_message event, which can do checks on the message before processing the command, something like this


bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

# or if you made your subclass of Bot or its variants

class CustomBot(commands.Bot):

    def __init__(self):
        ...

bot = CustomBot()

@bot.event
async def on_message(message):
    if message.author.bot:
        return # this is a bot, so we can early exit

    # any other checks

    await bot.process_commands(message)
  • Related