Sehn
Sehn

Reputation: 37

Is there a way to import functions with decorators in python for discord bots

Like said in the title, if it's possible I'd like to be able to import some part of code that contains decorators in the bot code.

from discord.ext import commands

class Updates(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

if __name__ == "__main__":
    token = 'XXXXXXXXXXXXXXXXXXX'
    prefix = '!'
    bot = commands.Bot(command_prefix=commands.when_mentioned_or(
        prefix), description='Useless - Updates')
    bot.add_cog(Updates(bot))
    bot.run(token)

I have like 3 or more sub-modules like that (I have a main file that check for modules that query for the class, here 'Updates') and I have a common part of code :

@commands.Cog.listener()
async def on_command_error(self, ctx, error):
    if isinstance(error, commands.CommandNotFound):
        return
    raise error

@commands.group(name='stop', hidden=True)
@commands.is_owner()
async def stop(self, ctx):

    await ctx.message.add_reaction('\N{THUMBS UP SIGN}')
    await self.bot.logout()
    sys.exit()

@commands.group(name='reload', hidden=True)
@commands.is_owner()
async def reload(self, ctx):

    await ctx.message.add_reaction('\N{THUMBS UP SIGN}')
    await self.bot.logout()
    sys.stdout.flush()
    os.execv(sys.executable, [sys.executable, __file__])

Anyone ?

Upvotes: 0

Views: 258

Answers (1)

chluebi
chluebi

Reputation: 1829

The most efficient way is to use cogs. These are basically classes which function as "groupings" for commands. Such classes can then be added via bot.add_cog(YourCogClass(bot))

A much more thorough explanation can be found here.

Upvotes: 2

Related Questions