Different prefix for each Cog?

Viewed 747

Is it possible to set a prefix for each cog?

For example the Cog with admin commands has the prefix pa! and the cog for some fun commands pf!.

Without using on_message.

Edit: I guess I have to go more in detail:

  • My cog for serverstats has a command called 'stats', this command should get triggered when I'm using pa!
  • My cog for fun has a 'stats' command too. This should be triggered when I'm using pf!

My only thought up to now was to set the default prefix to p! and then call the command astats. But I want to have a better way.

4 Answers

To expand on Maxsc's answer, you can define a cog_check method that will be called before every command from the cog:

class FunCommands(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.prefix = "pf!"
    async def cog_check(self, ctx):
        return ctx.prefix == self.prefix

In your main code, you can use a callable that consumes the prefixes from the cogs to determine which prefixes to pay attention to. This would get passed as your command_prefix

def get_prefixes(bot, message):
    cog_prefixes = (cog.prefix for cog in bot.cogs.values() if hasattr(cog, 'prefix'))
    default_prefixes = ("!")
    return (*cog_prefixes, *default_prefixes)

You can check the prefix used in a command using ctx.prefix. So you could run a check like this:

@commands.command()
async def sample_command(self, ctx):
    if ctx.prefix != "pa!":
        return

And previously enabling those prefixes bot = commands.Bot(command_prefix=("pa!", "pf!"))

I think this is an interesting question as I have had the same one for some time. I had an idea for implementing this myself although it does use the on_message function but not just that.

Basically my thought was to override the cog class and add a way for it to denote what prefix it should have. I thought use a custom argument in @commands.command to signify what prefix to use but this was for commands themselves.

Then in the on_message function you will need to determine there what command to call. Possibly the use of a global dict that correlates what prefix to what command.

This was just my own personal brainstorming and you will need to keep in mind if you allow each server to set their own prefixes and how to go about allowing that plus allowing them to set custom prefixes for each command. Good luck I hope this helps

If all of your commands are in the on_message event, you can split the message content with spaces (" ") and check the first element of the splitted list for the prefix and put the avaibale commands under an if statement. This could work, but will be slighly resource heavy depending on the amount of the commands

Related