Reputation: 11
I've been trying to make a discord.py bot, but all the commands are in one unique file. Is there any way that I can divide the commands in various .py files? For example: in the main.py file I have
from discord.ext import commands
import discord, os, random, time, keep_alive, save
from discord.utils import get
from discord import Member
TOKEN = os.environ['DISCORD_TOKEN']
JOIN_ROLE = "Unverified"
prefix = "/"
intents = discord.Intents.all()
bot = commands.Bot(prefix, intents = intents)
bot.remove_command('help')
keep_alive.keep_alive()
bot.run(TOKEN)`
and in another file named help.py I have this:
@bot.command()
async def help(ctx):
embed = discord.Embed(title="Help commands", description="Shows various help commands")
embed.add_field(name="Show this help", value = "`/help`", inline = False)
embed.add_field(name="Help random stuff", value="`/helprand`", inline=False)
embed.add_field(name="Help economy", value="`/helpeco`", inline=False)
embed.add_field(name="Help music", value = "`/helpmusic`", inline = False)
await ctx.send(embed=embed)
is there any way with which I can link these 2 files, so that when I type /help it pops up the help command instead of giving me an error?
Thanks to everyone that will help me
Upvotes: 0
Views: 2862
Reputation: 1526
You can use cogs
For example, in help.py
, you create a class which inherits from commands.Cog
and contains a commands.command
:
import discord
from discord.ext import commands
class HelpCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def help(self, ctx):
embed = discord.Embed(title="Help commands", description="Shows various help commands")
embed.add_field(name="Show this help", value = "`/help`", inline = False)
embed.add_field(name="Help random stuff", value="`/helprand`", inline=False)
embed.add_field(name="Help economy", value="`/helpeco`", inline=False)
embed.add_field(name="Help music", value = "`/helpmusic`", inline = False)
await ctx.send(embed=embed)
and then in your main file, you add the HelpCog
to your bot:
from help import HelpCog
...
bot = commands.Bot(prefix, intents = intents, help_command=None)
bot.add_cog(HelpCog(bot))
and remove the following line, because it's better to remove the default help command in the initialization of the commands.Bot
:
bot.remove_command("help")
Upvotes: 2
Reputation: 7566
I don't know about specific discord development, but in standard python parlance, what you are describing is the difference between modules and packages. e.g.
This:
# foo.py
def bar():
print("bar")
def baz():
print("baz")
Would be imported similarly to:
# foo/__init__.py
from foo.bar import bar
from foo.baz import baz
# foo/bar.py
def bar():
print("bar")
# foo/baz.py
def baz():
print("baz")
Where in both cases you could import as from foo import bar, baz
.
Upvotes: 1