absolute failure
absolute failure

Reputation: 45

How do I make a modular Discord bot in Python?

I am using discord.py and I want every function to be a python file in itself. So I am creating the bot in main.py and importing it to the python files I require it in and creating the commands there. Then processing the commands using bot.process_commands in main.py. This however isn't working.

Is there a way I can even do this or does everything has to be in one file?

Upvotes: 0

Views: 1317

Answers (1)

Nyghl
Nyghl

Reputation: 168

Nope, you don't have do everything in one file. You can use something called Cogs. You can watch the tutorials, read discord.py's official documentation or read my explanation.

Cogs Explanation:

You are just opening side-files that you can load to the bot. For example, a help_commands.py file that will hold all of the help commands.

To load the commands, they need to be grouped in a Cog class. You need to define a Main Class that inherits from the Cog class:

class My_Help_Cog(commands.Cog): My_Help_Cog will be our main Cog class that will be loaded to the bot.

Now we need a way to add this Cog to the bot. For that, discord.py uses a function called setup. In order to take your Cog, discord.py calls that setup function when you try to load the bot from the main file.

So let's define a setup function to the end of our code.

def setup(bot):
    bot.add_cog(My_Help_Cog(Bot))

A whole example:

help_commands.py

import discord
from discord.ext import commands

class My_Help_Cog(commands.Cog, name="Help Commands"): # Our Main Cog class for writing our code. | name= is optional.
    def __init__(self, bot, *args, **kwargs):
        self.bot = bot # So we can access the bot in the class whenever we like.
    
    # All the code goes here, if you know OOP i assume you already understood.

def setup(bot): # Defining the setup so cog loader can understand what we want to add to the bot.
    bot.add_cog(My_Help_Cog(Bot) # Adding to the bot part.

However, Cogs have a caveat. When you're in Cogs, you are doing some things a little differently.

For example; when we define commands, we are no longer using the @client.command() (or @bot.command()) decorator to define commands. Instead, you are using @commands.command() for the command decorator.

Same goes for the events, you now register to events via @commands.Cog.listener() instead of @bot.event.

Also, since we are in a Class, you need to pass self as your first parameter to everything in your Class.

So, we designed our Cog and the last part is just loading it on the main file. For this, you can use bot's load_extension method in your main file:

bot.load_extension("cog's location.") # In our example, just "help_commands.py" for the location.

There are more methods for interacting with the cogs. A few of them:

Upvotes: 2

Related Questions