I'm refactoring on a Discord bot using discord.py and I've structured my project as follows:
my_discord_bot/
├── main.py
└── bot/
├── __init__.py
├── bot.py
├── commands.py
├── events.py
└── tasks.py
In bot.py, I create the bot instance:
from discord.ext import commands
from discord import Intents
def create_bot():
intents = Intents.default()
intents.members = True
intents.message_content = True
return commands.Bot(command_prefix='!', intents=intents)
bot = create_bot()
To organize my code, I've separated commands, events, and tasks into their respective files. To initialize everything, I've created setup functions in each file:
In commands.py:
def setup_commands(bot):
bot.add_command(command1)
bot.add_command(command2)
# ... more commands
In events.py:
def setup_events(bot):
bot.event(on_ready)
bot.event(on_message)
# ... more events
In tasks.py:
def setup_tasks(bot):
task1.start()
task2.start()
# ... more tasks
Then in main.py, I call these setup functions:
from bot.bot import bot
from bot.commands import setup_commands
from bot.events import setup_events
from bot.tasks import setup_tasks
def main():
setup_commands(bot)
setup_events(bot)
setup_tasks(bot)
bot.run(TOKEN)
if __name__ == "__main__":
main()
My questions are:
- Is this a good pattern for organizing a Discord bot?
- Are there any potential issues or drawbacks to this approach?
- Are there better alternatives for structuring a Discord bot project?
I'm particularly interested in hearing about best practices for larger Discord bot projects and how to maintain good separation of concerns.
tests/task_test.pyand similar, to exercise that target code. \$\endgroup\$