Search code examples
pythondiscorddiscord.pypython-asyncio

Discord.py how do I run code from another file?


I want to clean up the code of my Discord bot a little with splitting commands up into different files instead of having just one huge main file. I know that I can "import" code directly from other files simply with import [file], but I fail to make it work with Discord code. If I try something like:

test1.py

await ctx.send("successful")

main.py

@client.command()
asnyc def test(ctx):
   import test1

I always get the error SyntaxError: 'await' outside function. I know that it's because the await is outside any async function, but I don't know how to fix it. If I replace test1.py with something like print("successful"), it prints the correct response to console. I tried looking solutions up already but am rather getting more and more confused by it.


Solution

  • Discord has a system called "extensions" which are specifically designed for splitting up commands into different files. Make sure you put whole functions in files not just parts of functions otherwise Python will give errors. Here's an example taken straight from the docs:

    Main file:

    ...create bot etc...
    bot.load_extension("test")  # use name of python file here
    ...run bot etc...
    

    Other file (called test.py in this example):

    from discord.ext import commands
    
    @commands.command()
    async def hello(ctx):
        await ctx.send('Hello {0.display_name}.'.format(ctx.author))
    
    async def setup(bot):
        bot.add_command(hello)
    

    The key points are: (1) create python file with setup function (2) load the extension.

    For more information see: https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html