Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discord.py - Changing prefix with command

I want to make a command where an admin can change the prefix for commands (eg: instead of using "." they can change it to "-" and only "-" will work if they do) I'd be able to setup the permissions to make only admins able to use the command

I've looked around, through the docs & interwebs but haven't found anything and I haven't had any idea on how to do this

like image 982
Jakaboi Avatar asked Jun 27 '19 18:06

Jakaboi


People also ask

What are prefix commands in Discord?

New in version 2.0. The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.

What is command prefix?

A command prefix is a prefix of a command (in the sense of rule 2 of the dodekalogue, i.e., a sequence of words) that is constructed with the expectation that zero or more arguments will be appended to it and that the resulting command will be evaluated.

What is CTX in Discord Python?

A command must always have at least one parameter, ctx , which is the Context as the first one. There are two ways of registering a command. The first one is by using Bot. command() decorator, as seen in the example above. The second is using the command() decorator followed by Bot.


1 Answers

You should use the command_prefix argument for discord.Bot this accepts either a string (meaning one bot wide prefix) or a callable (meaning a function that returns a prefix based on a condition).

Your condition relies on the invoking message. Therefore you can allow guilds to define their own prefixes. I'll use a dict as a simple example:

...

custom_prefixes = {}
#You'd need to have some sort of persistance here,
#possibly using the json module to save and load
#or a database
default_prefixes = ['.']

async def determine_prefix(bot, message):
    guild = message.guild
    #Only allow custom prefixs in guild
    if guild:
        return custom_prefixes.get(guild.id, default_prefixes)
    else:
        return default_prefixes

bot = commands.Bot(command_prefix = determine_prefix, ...)
bot.run()

@commands.command()
@commands.guild_only()
async def setprefix(self, ctx, *, prefixes=""):
    #You'd obviously need to do some error checking here
    #All I'm doing here is if prefixes is not passed then
    #set it to default 
    custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
    await ctx.send("Prefixes set!")

For a great example of this in use, refer to Rapptz (the creator of discord.py)'s very own RoboDanny bot, he made it a public repo for educational purposes as an example. In specific, see prefix_callable function, it's a more robust version of my determine_prefix example.

like image 95
Jab Avatar answered Oct 23 '22 04:10

Jab