Search code examples
pythondiscorddiscord.pyprefix

Reload discord bot after prefix change (Discord.py)


The problem is I want to dynamically change my prefix with a command. The prefix gets updated in the json file but the only problem is that the bot needs to reload to accept the new prefix. So I need a way to make the bot read the new prefix instantly after updating it in the config.json.

JSON FILE: "command_prefix": "."

UPDATE PREFIX CMD: (The command is in my core cog)

# PREFIX CHANGE COMMAND
    @commands.group(name="prefix", invoke_without_command=True)
    @commands.has_permissions(administrator=True)
    async def prefix(self, ctx):
        current_prefix = get_config_file("command_prefix")

        await ctx.channel.send(f'Current prefix is: **{current_prefix}** \n If you want to change the prefix use subcommand: _set_')

    @prefix.command(name="set")
    @commands.has_permissions(administrator=True)
    async def set(self, ctx, mode):
        mode != None

        with open('config.json', 'r') as f:
            config = json.load(f)

        config["command_prefix"] = mode

        with open('config.json', 'w') as f:
            json.dump(config, f, indent=4)
        
        f.close()
        
        await ctx.channel.send(f'Prefix has been changed to `{mode}`')

Solution

  • When you first initialize a bot, it creates a prefix and uses that prefix only until you recreate the bot. If you want the bot to have a different prefix or update it, you need a callback on the command_prefix argument.

    First create the get_prefix function.

    async def get_prefix(bot, message): # you can also do it by guild with message argument
        return get_config_file("prefix_command")
    

    then in the Bot instance

    bot = commands.Bot(command_prefix=get_prefix)
    

    Note: These both will be in the main file where you create the bot. It will change immediately every time you update the prefix.