MEDIUM: Split bot.py Event Handlers Into Separate Modules #26

Open
opened 2026-02-16 22:47:40 +02:00 by Koko210 · 0 comments
Owner

bot.py contains all event handlers in one file, making it large and hard to navigate.

Where It Occurs

  • bot/bot.py - All Discord event handlers (on_message, on_ready, on_voice_state_update, etc.)

Why This Is a Problem

  1. Large File: 800+ lines with multiple concerns
  2. Hard to Navigate: Difficult to find specific event handler
  3. Merge Conflicts: Multiple developers modifying same file
  4. Testing: Cannot test event handlers in isolation

What Can Go Wrong

Scenario 1: Merge Conflict

  1. Developer A adds new event handler for reactions
  2. Developer B modifies on_message handler
  3. Both working in bot/bot.py
  4. Merge conflicts when both PRs merge
  5. Time wasted resolving conflicts

Scenario 2: Bug in One Handler Affects Others

  1. Bug introduced in on_ready handler
  2. Developer fixes bug in bot/bot.py
  3. Accidentally breaks on_message handler
  4. Regression not caught in tests

Proposed Fix

Extract event handlers to separate modules:

bot/
├── bot.py                    # Main bot initialization, command registration
├── message_handler.py         # NEW - on_message handler
└── events.py                 # NEW - Other event handlers

Example migration:

# bot/bot.py - SIMPLIFIED
import discord
from discord.ext import commands
from bot.message_handler import handle_message
from bot.events import setup_event_handlers

bot = commands.Bot(...)

# Register message handler
@bot.event
async def on_message(message):
    await handle_message(message, bot)

# Register other event handlers
setup_event_handlers(bot)

# Run bot
bot.run(TOKEN)
# bot/message_handler.py - NEW FILE
from typing import Optional

async def handle_message(message: discord.Message, bot: commands.Bot):
    """Main message handling logic"""
    # Check if message is from bot
    if message.author.bot:
        return
    
    # Check for command prefix
    if message.content.startswith('!'):
        # Let commands.Bot handle commands
        await bot.process_commands(message)
        return
    
    # Handle autonomous messages
    if await should_respond_autonomously(message):
        await send_autonomous_response(message)
# bot/events.py - NEW FILE
import discord
from bot.utils.voice_manager import voice_manager

def setup_event_handlers(bot):
    """Register all non-message event handlers"""
    
    @bot.event
    async def on_ready():
        print(f'{bot.user} has connected to Discord!')
    
    @bot.event
    async def on_voice_state_update(member, before, after):
        """Handle user joining/leaving voice channels"""
        if member.guild.id in voice_manager.active_sessions:
            await voice_manager.handle_voice_state_update(member, before, after)
    
    @bot.event
    async def on_member_join(member):
        """Handle new member joining server"""
        await send_welcome_message(member)
    
    @bot.event
    async def on_command_error(ctx, error):
        """Handle command errors"""
        if isinstance(error, commands.CommandNotFound):
            await ctx.send("Unknown command")
        else:
            await ctx.send(f"Error: {error}")

Severity

MEDIUM - Large bot.py file is hard to maintain and causes merge conflicts.

Files Affected

bot/bot.py (refactor), new files: bot/message_handler.py, bot/events.py

bot.py contains all event handlers in one file, making it large and hard to navigate. ## Where It Occurs - bot/bot.py - All Discord event handlers (on_message, on_ready, on_voice_state_update, etc.) ## Why This Is a Problem 1. Large File: 800+ lines with multiple concerns 2. Hard to Navigate: Difficult to find specific event handler 3. Merge Conflicts: Multiple developers modifying same file 4. Testing: Cannot test event handlers in isolation ## What Can Go Wrong ### Scenario 1: Merge Conflict 1. Developer A adds new event handler for reactions 2. Developer B modifies on_message handler 3. Both working in bot/bot.py 4. Merge conflicts when both PRs merge 5. Time wasted resolving conflicts ### Scenario 2: Bug in One Handler Affects Others 1. Bug introduced in on_ready handler 2. Developer fixes bug in bot/bot.py 3. Accidentally breaks on_message handler 4. Regression not caught in tests ## Proposed Fix Extract event handlers to separate modules: ``` bot/ ├── bot.py # Main bot initialization, command registration ├── message_handler.py # NEW - on_message handler └── events.py # NEW - Other event handlers ``` Example migration: ```python # bot/bot.py - SIMPLIFIED import discord from discord.ext import commands from bot.message_handler import handle_message from bot.events import setup_event_handlers bot = commands.Bot(...) # Register message handler @bot.event async def on_message(message): await handle_message(message, bot) # Register other event handlers setup_event_handlers(bot) # Run bot bot.run(TOKEN) ``` ```python # bot/message_handler.py - NEW FILE from typing import Optional async def handle_message(message: discord.Message, bot: commands.Bot): """Main message handling logic""" # Check if message is from bot if message.author.bot: return # Check for command prefix if message.content.startswith('!'): # Let commands.Bot handle commands await bot.process_commands(message) return # Handle autonomous messages if await should_respond_autonomously(message): await send_autonomous_response(message) ``` ```python # bot/events.py - NEW FILE import discord from bot.utils.voice_manager import voice_manager def setup_event_handlers(bot): """Register all non-message event handlers""" @bot.event async def on_ready(): print(f'{bot.user} has connected to Discord!') @bot.event async def on_voice_state_update(member, before, after): """Handle user joining/leaving voice channels""" if member.guild.id in voice_manager.active_sessions: await voice_manager.handle_voice_state_update(member, before, after) @bot.event async def on_member_join(member): """Handle new member joining server""" await send_welcome_message(member) @bot.event async def on_command_error(ctx, error): """Handle command errors""" if isinstance(error, commands.CommandNotFound): await ctx.send("Unknown command") else: await ctx.send(f"Error: {error}") ``` ## Severity MEDIUM - Large bot.py file is hard to maintain and causes merge conflicts. ## Files Affected bot/bot.py (refactor), new files: bot/message_handler.py, bot/events.py
Sign in to join this conversation.
No Label
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: Koko210/miku-discord#26