midnight0s
midnight0s

Reputation: 393

Is it possible to split a Discord.py bot across multiple files?

So I have my Discord bot in one file (bot.py) and since it has many commands, my help command has to explain every single command as the bot aims to be functional and also very user-friendly. As you can imagine, this takes up a lot of space. What I would like to do is have the main commands in bot.py, and have all the help commands in a separate file (help.py) Is this possible? If so, how?

Upvotes: 4

Views: 5654

Answers (1)

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15728

Example of extensions

  • File called foo.py
import discord
from discord.ext import commands

@commands.command()
async def baz(ctx):
    await ctx.send("Whatever")


def setup(bot):
    # Every extension should have this function
    bot.add_command(baz)
  • Main file
bot.load_extension("path.foo") # Path to the file, instead of using a slash use a period
  • Cogs (can be in the main file)
class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    def baz(self, ctx):
        await ctx.send("something")

bot.add_cog(MyCog(bot))

Combining cogs and extensions

  • foo.py
import discord
from discord.ext import commands

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

    @commands.command()
    def baz(self, ctx):
        await ctx.send("something")

def setup(bot):
    bot.add_cog(MyCog(bot))
  • main file
bot.load_extension("path.foo")

For more info take a look at the cogs and extensions introductions.

Also I'm assuming you're using commands.Bot and you named your bot instance bot

Upvotes: 5

Related Questions