Demotry
Demotry

Reputation: 907

How to make multiple files Python Bot

How to load commands from multiple files Python Bot below is my main.py and other python files with commands. Is this correct method or do i need to change anything? do i need to add token, prefix, bot = commands.Bot, bot.run(token) etc in all files.

main.py

token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
prefix = "?"

import discord
from discord.ext import commands
startup_extensions = ["second", "third"]

bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.command(pass_context=True)
async def hello1(ctx):
    msg = 'Hello {0.author.mention}'.format(ctx.message)
    await bot.say(msg)

bot.run(token)

second.py

import discord
from discord.ext import commands

class Second():
def __init__(self, bot):
    self.bot = bot

@commands.command(pass_context=True)
async def hello2(ctx):
    msg = 'Hello{0.author.mention}'.format(ctx.message)
    await bot.say(msg)

def setup(bot):
bot.add_cog(Second(bot))

third.py

import discord
from discord.ext import commands

class Third():
def __init__(self, bot):
    self.bot = bot

@commands.command(pass_context=True)
async def hello3(ctx):
    msg = 'Hello{0.author.mention}'.format(ctx.message)
    await bot.say(msg)

def setup(bot):
bot.add_cog(Third(bot))

Upvotes: 5

Views: 8094

Answers (1)

Jaxon. B
Jaxon. B

Reputation: 102

Would you could do is setup your file with cogs for example your main file:

import discord
from discord.ext import commands

client = commands.Bot(command_prefix="!") # <- Choose your prefix


# Put all of your cog files in here like 'moderation_commands'
# If you have a folder called 'commands' for example you could do #'commands.moderation_commands'
cog_files = ['commands.moderation_commands']

for cog_file in cog_files: # Cycle through the files in array
    client.load_extension(cog_file) # Load the file
    print("%s has loaded." % cog_file) # Print a success message.

client.run(token) # Run the bot.

Say in your moderation_commands file it would look like:

import discord
from discord.ext import commands

class ModerationCommands(commands.Cog):
    def __init__(self, client):
        self.client = client
    @commands.command(name="kick") # Your command decorator.
    async def my_kick_command(self, ctx) # ctx is a representation of the 
        # command. Like await ctx.send("") Sends a message in the channel
        # Or like ctx.author.id <- The authors ID
        pass # <- Your command code here

def setup(client) # Must have a setup function
    client.add_cog(ModerationCommands(client)) # Add the class to the cog.

You can find more information on cogs here: https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html

Upvotes: 4

Related Questions