How would I make a reload command in Python for a discord bot?

13,876

Probably late to this questions, but I will post it anyways

You should checkout how so called "Cogs" work in Discord.py. The bot from Rapptz (the guy who main-maintain Discord.py) has some good examples how to organize your bot into Cogs and how to load/unload/reload them (see cogs/admin.py for that).

@commands.command(hidden=True)
@checks.is_owner()
async def load(self, *, module : str):
    """Loads a module."""
    try:
        self.bot.load_extension(module)
    except Exception as e:
        await self.bot.say('\N{PISTOL}')
        await self.bot.say('{}: {}'.format(type(e).__name__, e))
    else:
        await self.bot.say('\N{OK HAND SIGN}')

@commands.command(hidden=True)
@checks.is_owner()
async def unload(self, *, module : str):
    """Unloads a module."""
    try:
        self.bot.unload_extension(module)
    except Exception as e:
        await self.bot.say('\N{PISTOL}')
        await self.bot.say('{}: {}'.format(type(e).__name__, e))
    else:
        await self.bot.say('\N{OK HAND SIGN}')

@commands.command(name='reload', hidden=True)
@checks.is_owner()
async def _reload(self, *, module : str):
    """Reloads a module."""
    try:
        self.bot.unload_extension(module)
        self.bot.load_extension(module)
    except Exception as e:
        await self.bot.say('\N{PISTOL}')
        await self.bot.say('{}: {}'.format(type(e).__name__, e))
    else:
        await self.bot.say('\N{OK HAND SIGN}')

(Snippet from cogs/admin.py)

Share:
13,876
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin about 2 years

    I am trying to figure out how to make a command that 'reloads' a Discord Bot's commands and allows me to keep the bot running while I am adding new commands.

    This just makes life easier for me so I don't have to reboot the bot.

    I'm using the discord.py library to interact with the discord API.

    How can I achieve this?