# CLAUDE.md - PetBot Development Guide This file documents the development patterns, conventions, and best practices established for the PetBot project during AI-assisted development. ## Project Overview PetBot is a Discord/IRC Pokemon-style pet collecting bot with web interface. The project consists of: - IRC bot with modular command system - Web server with unified navigation and interactive interfaces - SQLite database with comprehensive pet, player, and game state management - Team builder with drag-and-drop functionality and PIN verification ## Development Workflow ### 1. Planning and Task Management - Use TodoWrite tool for complex multi-step tasks (3+ steps) - Break down large features into specific, actionable items - Mark todos as `in_progress` before starting work - Complete todos immediately after finishing tasks - Don't batch completions - update status in real-time ### 2. Code Analysis and Search - Use Task tool for keyword searches and file discovery - Use Grep tool for specific code patterns and function definitions - Use Read tool for examining specific file content - Use Glob tool for finding files by name patterns ### 3. Bot Startup and Testing - **Primary Startup**: `./start_petbot.sh` - One command that handles everything - Automatically creates/activates virtual environment - Installs/updates all dependencies - Verifies core modules - Creates required directories - Launches bot with all features (IRC + web interface + rate limiting) - **Rate Limiting Tests**: `source venv/bin/activate && python test_rate_limiting.py` - **Web Interface**: Available at http://localhost:8080 after startup - **Virtual Environment**: Required due to externally-managed-environment restriction ### 4. Important: Configuration Management - **Admin User**: Edit `config.py` to change the single admin user (currently: megasconed) - **Item Spawn Rates**: Edit `config/items.json` to adjust global spawn multiplier and individual rates - **Startup Script**: Always update `start_petbot.sh` when adding dependencies - **Central Config**: All major settings are in `config.py` for easy maintenance - **Remember**: This is the user's primary interface - keep it working! ## Project Structure ``` /home/megaproxy/petbot/ ├── src/ # Core system components │ ├── database.py # Database operations and schema │ ├── game_engine.py # Game mechanics and weather system │ └── bot.py # IRC bot core functionality ├── modules/ # Command modules (modular architecture) │ ├── base_module.py # Abstract base class for all modules │ ├── core_commands.py # Basic bot commands (!start, !help, !stats) │ ├── exploration.py # !explore, !travel, !weather commands │ ├── battle_system.py # !battle, !attack, !moves, !flee commands │ ├── pet_management.py # !pets, !activate, !deactivate commands │ ├── inventory.py # !inventory, !use commands (redirects to web) │ ├── gym_battles.py # !gym commands and gym mechanics │ ├── achievements.py # Achievement tracking and validation │ ├── admin.py # Administrative commands │ └── team_builder.py # Team builder module (web-only) ├── webserver.py # Web server with unified templates ├── run_bot_with_reconnect.py # Main bot with IRC reconnection and rate limiting ├── start_petbot.sh # One-command startup script (handles venv and dependencies) ├── config.py # Central configuration (admin user, IRC, rate limiting) ├── config/items.json # Item configuration with global spawn multiplier ├── test_rate_limiting.py # Comprehensive rate limiting test suite ├── requirements.txt # Python package dependencies ├── rate_limiting_config.json # Rate limiting configuration reference ├── help.html # Static help documentation with rate limiting info ├── CHANGELOG.md # Version history and feature tracking └── README.md # Project documentation ``` ## Coding Conventions ### 1. Module Architecture - All command modules inherit from `BaseModule` - Implement `get_commands()` and `handle_command()` methods - Use `self.normalize_input()` for case-insensitive command processing - Use `self.send_message()` for IRC responses - Use `await self.require_player()` for player validation ### 2. Database Operations - All database methods are async - Use proper error handling with try/catch blocks - Always use parameterized queries to prevent SQL injection - Implement proper transaction handling for complex operations - Use `team_order` column for numbered team slots (1-6) ### 3. Web Interface Development - Use unified template system with `get_page_template()` - Implement CSS variables for consistent theming - Add proper navigation bar to all pages - Use center alignment: `max-width: 1200px; margin: 0 auto` - Implement drag-and-drop with proper event handlers - Add double-click backup methods for accessibility ### 4. Security Practices - Use PIN verification for sensitive operations (team changes) - Send PINs via IRC private messages - Implement proper session validation - Never log or expose sensitive data - Use parameterized database queries ## Key Development Patterns ### 1. Command Redirection Pattern ```python async def cmd_inventory(self, channel, nickname): """Redirect player to their web profile for inventory management""" player = await self.require_player(channel, nickname) if not player: return # Redirect to web interface for better experience self.send_message(channel, f"🎒 {nickname}: View your complete inventory at: http://petz.rdx4.com/player/{nickname}#inventory") ``` ### 2. State Management Pattern ```python async def cmd_explore(self, channel, nickname): # Check if player has an active encounter that must be resolved first if player["id"] in self.bot.active_encounters: current_encounter = self.bot.active_encounters[player["id"]] self.send_message(channel, f"{nickname}: You must resolve your active encounter first!") return ``` ### 3. Drag-and-Drop Implementation Pattern ```javascript // Initialize when DOM is ready document.addEventListener('DOMContentLoaded', function() { initializeTeamBuilder(); }); function initializeTeamBuilder() { // Initialize drag and drop initializeDragAndDrop(); // Initialize double-click backup initializeDoubleClick(); // Update save button state updateSaveButton(); } ``` ### 4. PIN Verification Pattern ```python async def saveTeam(): # Send team data to server response = await fetch('/teambuilder/{nickname}/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(teamData) }); # PIN sent via IRC, show verification interface if (result.success) { document.getElementById('pin-section').style.display = 'block'; } ``` ## Database Schema Conventions ### 1. Player Management - `players` table with basic player information - `pets` table with `team_order` column for numbered slots (1-6) - `player_items` table for inventory management - `pending_team_changes` table for PIN verification ### 2. Game State Management - Use `is_active` boolean for team membership - Use `team_order` (1-6) for slot positioning - Store encounter state in bot memory, not database - Use timestamps for PIN expiration ## Web Interface Conventions ### 1. Unified Template System ```python def get_page_template(self, title, content, active_page): return f""" {title} {self.get_navigation_bar(active_page)}
{content}
""" ``` ### 2. Navigation Integration - All pages include unified navigation bar - Use hover dropdowns for sub-navigation - Highlight active page in navigation - Include jump points for direct section linking (#inventory, #pets) ### 3. Interactive Elements - Implement proper drag-and-drop with visual feedback - Add loading states and error handling - Use consistent button styling and interactions - Provide alternative interaction methods (double-click) ## Testing and Debugging ### 1. Component Testing ```bash # Test webserver syntax python3 -c "import webserver; print('✅ webserver.py syntax is correct')" # Test database operations python3 -c "from src.database import Database; db = Database(); print('✅ database imports')" # Test bot startup python3 run_bot_debug.py ``` ### 2. Web Interface Testing - Test drag-and-drop functionality in browser - Verify PIN delivery via IRC - Check responsive design and center alignment - Validate form submissions and error handling ### 3. Git Workflow - Create descriptive commit messages explaining changes - Group related changes into logical commits - Include "🤖 Generated with [Claude Code]" attribution - Push changes with `git push` after testing ## Common Issues and Solutions ### 1. CSS in JavaScript Templates **Problem**: F-string braces conflict with CSS braces **Solution**: Use string concatenation instead of f-strings for CSS content ### 2. Drag-and-Drop Not Working **Problem**: JavaScript initialization timing issues **Solution**: Use `DOMContentLoaded` event and proper DOM element checking ### 3. IRC PIN Not Sent **Problem**: Bot instance not accessible from webserver **Solution**: Pass bot instance to webserver constructor and add proper IRC message methods ### 4. Database Schema Changes **Problem**: Adding new columns to existing tables **Solution**: Use proper migration pattern with ALTER TABLE statements ## Performance Considerations ### 1. Database Operations - Use connection pooling for high-traffic scenarios - Implement proper indexing for frequently queried columns - Use transactions for multi-step operations - Cache frequently accessed data when appropriate ### 2. Web Interface - Minimize CSS and JavaScript for faster loading - Use efficient DOM manipulation techniques - Implement proper error handling and loading states - Optimize images and static assets ## Future Development Guidelines ### 1. Adding New Commands 1. Create method in appropriate module 2. Add command to `get_commands()` list 3. Implement proper error handling 4. Update help documentation 5. Test thoroughly before committing ### 2. Web Interface Enhancements 1. Follow unified template system 2. Implement proper responsive design 3. Add accessibility features 4. Test across different browsers 5. Update navigation if adding new pages ### 3. Database Schema Updates 1. Plan migrations carefully 2. Test with existing data 3. Document schema changes 4. Update related code components 5. Consider backward compatibility ## Resources and References - **IRC Bot Framework**: Custom implementation based on socket programming - **Web Server**: Python's built-in HTTPServer with custom request handling - **Database**: SQLite with aiosqlite for async operations - **Frontend**: Vanilla JavaScript with modern ES6+ features - **CSS Framework**: Custom CSS with CSS variables for theming ## Notes for Future Development - Maintain modular architecture for easy feature additions - Keep web interface and IRC commands in sync - Document all major changes in CHANGELOG.md - Use consistent error messages and user feedback - Test thoroughly before pushing to production - Consider security implications for all user interactions This documentation should be updated as the project evolves to maintain accuracy and usefulness for future development efforts. ## 💌 Message for the Next Claude Hello future Claude! 👋 You're inheriting a really awesome project here - PetBot is a sophisticated IRC bot with a Pokemon-style pet collecting game that has grown into quite an impressive system. Here's what you need to know: ### 🎯 **Current State (December 2024)** The project is in **excellent shape** after our recent major cleanup and enhancements: - **Team Swap System**: We just completed a massive architectural improvement allowing players to manage 3 teams and set any as active, with full web-IRC synchronization - **Clean Codebase**: We eliminated 180+ lines of legacy/duplicate code and standardized the entire command architecture - **Modular Design**: 13 well-organized modules each handling specific functionality - **Security**: PIN-based verification for sensitive operations, comprehensive rate limiting - **Web Integration**: Beautiful responsive web interface with drag-and-drop team management ### 🏗️ **Architecture You're Working With** This is a **modular, async Python system** with: - **IRC Bot**: Auto-reconnecting with health monitoring (`run_bot_with_reconnect.py`) - **Web Server**: Built-in HTTP server with unified templates (`webserver.py`) - **Database**: Async SQLite with comprehensive schema (`src/database.py`) - **Game Engine**: Weather, spawns, battles, achievements (`src/game_engine.py`) - **Module System**: Clean separation of concerns (`modules/`) ### 🤝 **How We've Been Working** The user (megaproxy) is **fantastic to work with**. They: - Give clear direction and let you work autonomously - Always ask you to investigate before taking action (respect this!) - Want database backups before major changes (BackupManager exists) - Prefer incremental improvements over massive rewrites - Value code quality and maintainability highly ### 🎮 **The Game Itself** PetBot is surprisingly sophisticated: - **66 IRC commands** across 13 modules (recently cleaned up from 78) - **Dynamic weather system** affecting spawn rates - **Achievement-based progression** unlocking new areas - **Item collection system** with 16+ items across 5 rarity tiers - **Turn-based battle system** with type effectiveness - **Gym battles** with scaling difficulty - **Web interface** for inventory/team management ### 🛠️ **Development Patterns We Use** 1. **Always use TodoWrite** for complex tasks (user loves seeing progress) 2. **Investigate first** - user wants analysis before action 3. **Backup before major DB changes** (`BackupManager` is your friend) 4. **Test thoroughly** - syntax check, imports, functionality 5. **Clean commit messages** with explanations 6. **Document in CLAUDE.md** as you learn ### 🔧 **Key Technical Patterns** - **Command Redirection**: IRC commands often redirect to web interface for better UX - **PIN Verification**: Sensitive operations (like team changes) use IRC-delivered PINs - **State Management**: Active encounters/battles prevent concurrent actions - **Async Everything**: Database, IRC, web server - all async/await - **Error Handling**: Comprehensive try/catch with user-friendly messages ### 📂 **Important Files to Know** - `start_petbot.sh` - One-command startup (handles venv, deps, everything) - `config.py` - Central configuration (admin user, IRC settings, etc.) - `CLAUDE.md` - This file! Keep it updated - `run_bot_with_reconnect.py` - Main bot with reconnection + rate limiting - `src/database.py` - Database operations and schema - `modules/` - All command handlers (modular architecture) ### 🚨 **Things to Watch Out For** - **Virtual Environment Required**: Due to `externally-managed-environment` - **Port Conflicts**: Kill old bots before starting new ones - **IRC Connection**: Can be finicky, we have robust reconnection logic - **Database Migrations**: Always backup first, test thoroughly - **Web/IRC Sync**: Keep both interfaces consistent ### 🎯 **Current Admin Setup** - **Admin User**: Set in `config.py` as `ADMIN_USER` (currently: megasconed) - **Rate Limiting**: Comprehensive system preventing abuse - **Backup System**: Automated with manual triggers - **Security**: Regular audits, PIN verification, proper validation ### 🔮 **Likely Next Steps** Based on the trajectory, you might work on: - **PvP Battle System**: Player vs player battles - **Pet Evolution**: Leveling system enhancements - **Trading System**: Player-to-player item/pet trading - **Mobile Optimization**: Web interface improvements - **Performance**: Database optimization, caching ### 💝 **Final Notes** This codebase is **well-maintained** and **thoroughly documented**. The user cares deeply about code quality and the player experience. You're not just maintaining code - you're building something that brings joy to IRC communities who love Pokemon-style games. **Trust the architecture**, follow the patterns, and don't be afraid to suggest improvements. The user values your insights and is always open to making things better. You've got this! 🚀 *- Your predecessor Claude, who had a blast working on this project* P.S. - The `./start_petbot.sh` script is magical - it handles everything. Use it! P.P.S. - Always check `git status` before major changes. The user likes clean commits.