Commit Graph

53 Commits

Author SHA1 Message Date
Cal Corum
a8fbf55c9e Add sba_logo_url to the config and update /standings formatting 2025-10-21 14:40:03 -05:00
Cal Corum
f6a7967e49 CLAUDE: Fix stale injury records blocking /injury set-new
Added data consistency check to automatically clear stale injury records
where is_active=True but il_return=None. This prevents old injury records
from blocking new injury creation when players should not be injured.

- Detects mismatch between injury table and player il_return field
- Auto-clears stale injury records with warning log
- Allows legitimate injuries with matching il_return to block command
- Logs both warning (stale data found) and info (cleared) for debugging

Fixes issue where Ronald Acuna Jr had active injury record but no il_return.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-21 13:06:17 -05:00
Cal Corum
5e1ccf75ab Allow any user to toggle player stats 2025-10-21 13:06:03 -05:00
Cal Corum
17f05fad90 CLAUDE: Fix UnboundLocalError in /injury clear command
Fixed bug where responder_team variable was only assigned conditionally
but always referenced, causing UnboundLocalError when clearing injuries
for major league players.

- Initialize responder_team = None before conditional check
- Ensures variable is defined for both ML and non-ML teams
- Conditional expression on line 674 now works correctly

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-21 12:59:49 -05:00
Cal Corum
61e5c7999b - Cleaning up IDE errors 2025-10-21 10:58:08 -05:00
Cal Corum
5616cfec3a CLAUDE: Add automatic scorecard unpublishing when voice channels are cleaned up
This enhancement automatically unpublishes scorecards when their associated
voice channels are deleted by the cleanup service, ensuring data synchronization
and reducing unnecessary API calls to Google Sheets for inactive games.

Implementation:
- Added gameplay commands package with scorebug/scorecard functionality
- Created ScorebugService for reading live game data from Google Sheets
- VoiceChannelTracker now stores text_channel_id for voice-to-text association
- VoiceChannelCleanupService integrates ScorecardTracker for automatic cleanup
- LiveScorebugTracker monitors published scorecards and updates displays
- Bot initialization includes gameplay commands and live scorebug tracker

Key Features:
- Voice channels track associated text channel IDs
- cleanup_channel() unpublishes scorecards during normal cleanup
- verify_tracked_channels() unpublishes scorecards for stale entries on startup
- get_voice_channel_for_text_channel() enables reverse lookup
- LiveScorebugTracker logging improved (debug level for missing channels)

Testing:
- Added comprehensive test coverage (2 new tests, 19 total pass)
- Tests verify scorecard unpublishing in cleanup and verification scenarios

Documentation:
- Updated commands/voice/CLAUDE.md with scorecard cleanup integration
- Updated commands/gameplay/CLAUDE.md with background task integration
- Updated tasks/CLAUDE.md with automatic cleanup details

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-21 07:18:21 -05:00
Cal Corum
77d6ca2bb5
Merge pull request #2 from calcorum/feature/chart-reload-command
Feature/chart reload command
2025-10-20 22:10:39 -05:00
Cal Corum
58b0c2d221 CLAUDE: Add multi-image support for charts
Image Version: 2.0.3

Added ability to add charts with multiple images and manage them incrementally.

Service Layer Changes (chart_service.py):
- Added add_image_to_chart() method to append URLs to existing charts
- Added remove_image_from_chart() method to remove specific URLs
- Validation to prevent duplicate URLs in charts
- Protection against removing the last image from a chart

Command Layer Changes (charts.py):
- Modified /chart-manage add to accept comma-separated URLs
  - Parse and strip URLs from comma-delimited string
  - Shows image count in success message
  - Displays first image in response embed
- Added /chart-manage add-image command for incremental additions
- Added /chart-manage remove-image command to remove specific URLs
- All commands use chart autocomplete for easy selection
- Admin/Help Editor permission checks on all management commands

Usage Examples:
  # Add chart with multiple images in one command
  /chart-manage add defense "Defense Chart" gameplay "https://example.com/def1.png, https://example.com/def2.png"

  # Add additional images later
  /chart-manage add-image defense https://example.com/def3.png

  # Remove specific image
  /chart-manage remove-image defense https://example.com/def2.png

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 22:00:19 -05:00
Cal Corum
151e5b9646 CLAUDE: Add /chart-manage reload command to refresh charts from disk
Added new command to resolve caching issue where manual edits to
charts.json were not reflected in the bot without a restart.

Changes:
- Added /chart-manage reload command to ChartManageGroup
- Calls chart_service.reload_charts() to refresh in-memory cache
- Shows success message with chart and category counts
- Requires admin or Help Editor role permissions
- Uses @logged_command decorator for automatic logging

Fixes: Chart updates not appearing until bot restart
Resolves: Permission denied issue with charts.json (ownership fixed separately)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 21:08:43 -05:00
Cal Corum
ca325142d8 CLAUDE: Add comprehensive CLAUDE.md documentation files for AI agent guidance
Adding 17 CLAUDE.md files across the project to provide detailed context
and implementation guidelines for AI development agents:

Root Documentation:
- CLAUDE.md - Main project guide with Git workflow requirements

Component Documentation:
- commands/CLAUDE.md - Command architecture and patterns
- models/CLAUDE.md - Pydantic models and validation
- services/CLAUDE.md - Service layer and API interactions
- tasks/CLAUDE.md - Background tasks and automation
- tests/CLAUDE.md - Testing strategies and patterns
- utils/CLAUDE.md - Utility functions and decorators
- views/CLAUDE.md - Discord UI components and embeds

Command Package Documentation:
- commands/help/CLAUDE.md - Help system implementation
- commands/injuries/CLAUDE.md - Injury management commands
- commands/league/CLAUDE.md - League-wide commands
- commands/players/CLAUDE.md - Player information commands
- commands/profile/CLAUDE.md - User profile commands
- commands/teams/CLAUDE.md - Team information commands
- commands/transactions/CLAUDE.md - Transaction management
- commands/utilities/CLAUDE.md - Utility commands
- commands/voice/CLAUDE.md - Voice channel management

Key Updates:
- Updated .gitignore to track CLAUDE.md files in version control
- Added Git Workflow section requiring branch-based development
- Documented all architectural patterns and best practices
- Included comprehensive command/service implementation guides

These files provide essential context for AI agents working on the codebase,
ensuring consistent patterns, proper error handling, and maintainable code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 20:30:07 -05:00
Cal Corum
64e60232dd
Merge pull request #1 from calcorum/readme-to-claude-auto
Readme to claude auto
2025-10-20 20:25:31 -05:00
Cal Corum
20b79fc8ff CLAUDE: Fix /voice-channel private to fetch current week games instead of week 1
The command was incorrectly using get_team_schedule(weeks=1) which fetches
the first week of the season rather than the current week's games. Changed
to use get_week_schedule(current_week) with proper team filtering.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 20:24:42 -05:00
Cal Corum
36ecd1b3ff CLAUDE: Add /ilmove command for real-time roster moves with organizational affiliate support
Implemented comprehensive /ilmove command system for immediate roster changes (IL moves,
activations, etc.) that execute instantly for the current week, complementing the existing
/dropadd system which schedules moves for next week.

New Features:
- /ilmove command: Interactive transaction builder for THIS week (immediate execution)
- /clearilmove command: Clear current IL move transaction builder
- Dual-mode transaction system: Scheduled (/dropadd) vs Immediate (/ilmove)

Key Fixes:
- Organizational team matching: Minor League players (WVMiL) now correctly recognized as
  valid targets for their Major League organization (WV)
- Transaction POST format: Fixed to use correct batch API format with count/moves structure
- RosterType to team affiliate mapping: Moves to IL now correctly assign players to WVIL
  instead of WV, and moves from MiL correctly reference WVMiL as source team
- Player team updates: Added update_player_team() method for immediate team assignments

Technical Changes:
- commands/transactions/ilmove.py: New command with organizational validation
- commands/transactions/__init__.py: Register ILMoveCommands cog
- services/transaction_service.py: create_transaction_batch() with correct batch format
- services/player_service.py: update_player_team() for immediate updates
- services/transaction_builder.py: RosterType affiliate resolution with async team lookups
- views/transaction_embed.py: Dual-mode support with context-aware instructions

Code Reuse:
- 95% code sharing between /dropadd and /ilmove via shared TransactionBuilder
- Same validation, UI, and move tracking - only submission differs
- Context-aware command_name parameter for dynamic UI instructions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 20:15:12 -05:00
Cal Corum
1575d4f096 CLAUDE: Add /jump command and improve dice rolling with team colors, plus admin and type safety fixes
Added /jump command for baserunner stealing mechanics with pickoff/balk detection.
Enhanced dice rolling commands with team color support in embeds.
Improved /admin-sync with local/global options and prefix command fallback.
Fixed type safety issues in admin commands and injury management.
Updated config for expanded draft rounds and testing mode.

Key changes:
- commands/dice/rolls.py: New /jump and !j commands with special cases for pickoff (d20=1) and balk (d20=2)
- commands/dice/rolls.py: Added team/channel color support to /ab and dice embeds
- commands/dice/rolls.py: Added pitcher position to /fielding command with proper range/error charts
- commands/admin/management.py: Enhanced /admin-sync with local/clear options and !admin-sync prefix fallback
- commands/admin/management.py: Fixed Member type checking and channel type validation
- commands/injuries/management.py: Fixed responder team detection for injury clearing
- models/custom_command.py: Made creator_id optional for execute endpoint compatibility
- config.py: Updated draft_rounds to 32 and enabled testing mode
- services/transaction_builder.py: Adjusted ML roster limit to 26

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 15:10:48 -05:00
Cal Corum
62c658fb57 CLAUDE: Add automated weekly transaction freeze/thaw system
Implements comprehensive automated system for weekly transaction freeze periods
with priority-based contested player resolution.

New Features:
- Weekly freeze/thaw task (Monday 00:00 freeze, Saturday 00:00 thaw)
- Priority resolution for contested transactions (worst teams get first priority)
- Admin league management commands (/freeze-begin, /freeze-end, /advance-week)
- Enhanced API client to handle string-based transaction IDs (moveids)
- Service layer methods for transaction cancellation, unfreezing, and bulk operations
- Offseason mode configuration flag to disable freeze operations

Technical Changes:
- api/client.py: URL-encode object_id parameter to handle colons in moveids
- bot.py: Initialize and shutdown transaction freeze task
- config.py: Add offseason_flag to BotConfig
- services/league_service.py: Add update_current_state() for week/freeze updates
- services/transaction_service.py: Add cancel/unfreeze methods with bulk support
- tasks/transaction_freeze.py: Main freeze/thaw automation with error recovery
- commands/admin/league_management.py: Manual admin controls for freeze system

Infrastructure:
- .gitlab-ci.yml and .gitlab/: GitLab CI/CD pipeline configuration
- .mcp.json: MCP server configuration
- Dockerfile.versioned: Versioned Docker build support
- .dockerignore: Added .gitlab/ to ignore list

Testing:
- tests/test_tasks_transaction_freeze.py: Comprehensive freeze task tests

The system uses team standings to fairly resolve contested players (multiple teams
trying to acquire the same player), with worst-record teams getting priority.
Includes comprehensive error handling, GM notifications, and admin reporting.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 12:16:13 -05:00
Cal Corum
82abf3d9e6 CLAUDE: Add toggleable stats to /player command and injury system improvements
Add interactive PlayerStatsView with toggle buttons to show/hide batting and
pitching statistics independently in the /player command. Stats are hidden by
default with clean, user-friendly buttons (💥 batting,  pitching) that update
the embed in-place. Only the command caller can toggle stats, and buttons
timeout after 5 minutes.

Player Stats Toggle Feature:
- Add views/players.py with PlayerStatsView class
- Update /player command to use interactive view
- Stats hidden by default, shown on button click
- Independent batting/pitching toggles
- User-restricted interactions with timeout handling

Injury System Enhancements:
- Add BatterInjuryModal and PitcherRestModal for injury logging
- Add player_id extraction validator to Injury model
- Fix injury creation to merge API request/response data
- Add responders parameter to BaseView for multi-user interactions

API Client Improvements:
- Handle None values correctly in PATCH query parameters
- Convert None to empty string for nullable fields in database

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 23:26:08 -05:00
Cal Corum
9fca0bc279 CLAUDE: Add confirmation flow and autocomplete to /injury clear
- Added confirmation embed before clearing injury
  - Shows player info, team, expected return, games missed
  - User prompted: "Is {Player} cleared to return?"
  - Buttons: "Clear Injury" / "Cancel"
  - 3-minute timeout for response
  - Team GMs can also confirm/cancel

- Added player autocomplete to /injury clear command
  - Uses same autocomplete as /injury roll
  - Prioritizes user's team players

- Updated commands/injuries/CLAUDE.md documentation
  - Documented new confirmation flow
  - Added autocomplete parameter details
  - Clarified user flow and responders

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 16:26:25 -05:00
Cal Corum
216f8112d2 rename all readme files 2025-10-17 08:00:59 -05:00
Cal Corum
e8b8878781 Fixing get_config replacement issue 2025-10-17 08:00:24 -05:00
Cal Corum
e689aadbd8 CLAUDE: Fix double emoji issue in Discord embeds
Fixed 13 instances where EmbedTemplate methods were receiving titles
with emojis, resulting in double emojis (e.g., "  Command Created").

Changes:
- tasks/custom_command_cleanup.py: Removed emojis from warning/error titles (2 fixes)
- views/help_commands.py: Removed emoji from success title (1 fix)
- views/custom_commands.py: Removed emojis from titles or switched to
  create_base_embed() for custom emojis (10 fixes)

The following template methods auto-add emoji prefixes:
- EmbedTemplate.success() → adds 
- EmbedTemplate.error() → adds 
- EmbedTemplate.warning() → adds ⚠️
- EmbedTemplate.info() → adds ℹ️
- EmbedTemplate.loading() → adds 

For custom emojis, use EmbedTemplate.create_base_embed() with explicit
color parameter.

All 69 related tests passing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 23:09:21 -05:00
Cal Corum
3aa95ef98c CLAUDE: Refine injury roll display and cleanup imports
## Injury Command Enhancements

### Pitcher-Specific Injury Display
- Added rest requirement note for pitcher injuries with game duration
- Shows "X games plus their current rest requirement" for pitchers
- Removed redundant footer text from FATIGUED result
- Cleaner, more concise pitcher injury messaging

### Bot Configuration
- Registered injuries command package in bot.py
- Added proper import and setup for InjuryGroup

### Code Cleanup
- Fixed misplaced import in views/embeds.py (moved to top)
- Standardized import ordering across command files
- Minor formatting improvements

## Files Changed
- commands/injuries/management.py: Pitcher rest requirement display
- bot.py: Injuries package registration
- views/embeds.py: Import cleanup
- Various: Import standardization

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 22:20:13 -05:00
Cal Corum
0c6f7c8ffe CLAUDE: Fix GroupCog interaction bug and GIF display issues
This commit addresses critical bugs in the injury command system and
establishes best practices for Discord command groups.

## Critical Fixes

### 1. GroupCog → app_commands.Group Migration
- **Problem**: `commands.GroupCog` has a duplicate interaction processing bug
  causing "404 Unknown interaction" errors when deferring responses
- **Root Cause**: GroupCog triggers command handler twice, consuming the
  interaction token before the second execution can respond
- **Solution**: Migrated InjuryCog to InjuryGroup using `app_commands.Group`
  pattern (same as ChartManageGroup and ChartCategoryGroup)
- **Result**: Reliable command execution, no more 404 errors

### 2. GiphyService GIF URL Fix
- **Problem**: Giphy service returned web page URLs (https://giphy.com/gifs/...)
  instead of direct image URLs, preventing Discord embed display
- **Root Cause**: Code accessed `data.url` instead of `data.images.original.url`
- **Solution**: Updated both `get_disappointment_gif()` and `get_gif()` methods
  to use correct API response path for embeddable GIF URLs
- **Result**: GIFs now display correctly in Discord embeds

## Documentation

### Command Groups Best Practices (commands/README.md)
Added comprehensive section documenting:
- **Critical Warning**: Never use `commands.GroupCog` - use `app_commands.Group`
- **Technical Explanation**: Why GroupCog fails (duplicate execution bug)
- **Migration Guide**: Step-by-step conversion from GroupCog to Group
- **Comparison Table**: Key differences between the two approaches
- **Working Examples**: References to ChartManageGroup, InjuryGroup patterns

## Architecture Changes

### Injury Commands (`commands/injuries/`)
- Converted from `commands.GroupCog` to `app_commands.Group`
- Registration via `bot.tree.add_command()` instead of `bot.add_cog()`
- Removed workarounds for GroupCog duplicate interaction issues
- Clean defer/response pattern with `@logged_command` decorator

### GiphyService (`services/giphy_service.py`)
- Centralized from `commands/soak/giphy_service.py`
- Now returns direct GIF image URLs for Discord embeds
- Maintains Trump GIF filtering (legacy behavior)
- Added gif_url to log output for debugging

### Configuration (`config.py`)
- Added `giphy_api_key` and `giphy_translate_url` settings
- Environment variable support via `GIPHY_API_KEY`
- Default values provided for out-of-box functionality

## Files Changed
- commands/injuries/: New InjuryGroup with app_commands.Group pattern
- services/giphy_service.py: Centralized service with GIF URL fix
- commands/soak/giphy_service.py: Backwards compatibility wrapper
- commands/README.md: Command groups best practices documentation
- config.py: Giphy configuration settings
- services/__init__.py: GiphyService exports

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 22:15:42 -05:00
Cal Corum
2926664d2d CLAUDE: Remove constants.py and migrate to config-based constants
Eliminates redundant constants.py file by moving all constants to config.py.
All constants (except baseball positions) are now accessible via get_config().

Changes:
- config.py: Added baseball position sets as module-level constants
  * PITCHER_POSITIONS, POSITION_FIELDERS, ALL_POSITIONS remain static
  * All other constants now accessed via BotConfig instance

- constants.py: Deleted (redundant with config.py)

- Updated 27 files to use get_config() instead of constants module:
  * Commands: admin, help, league (3), players, profile, teams (3),
    transactions (3), utilities, voice
  * Services: league, player, team, trade_builder, transaction_builder
  * Utils: autocomplete, team_utils
  * Views: embeds
  * Tests: test_constants, test_services (3 files)
  * Examples: enhanced_player, migration_example

- tests/test_constants.py: Rewritten to test config values
  * All 14 tests pass
  * Now validates BotConfig defaults instead of constants module

Import Changes:
- Old: `from constants import SBA_CURRENT_SEASON`
- New: `from config import get_config` → `get_config().sba_current_season`
- Positions: `from config import PITCHER_POSITIONS, ALL_POSITIONS`

Benefits:
- Single source of truth (config.py only)
- Cleaner architecture - no redundant wrapper
- All constants configurable via environment variables
- Reduced maintenance overhead
- Type safety with Pydantic validation

All configuration tests pass. Core refactoring complete.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 10:52:05 -05:00
Cal Corum
0808d3421c CLAUDE: Convert constants to configurable environment variables
Makes all application constants (except baseball positions) configurable
via environment variables for greater deployment flexibility.

Changes:
- config.py: Added 18 new configurable fields to BotConfig
  * Discord limits (embed/field/description limits)
  * League settings (weeks, games, modern stats era)
  * Current season constants (SBA/PD)
  * API configuration (version, timeout, retries)
  * Draft settings (pick minutes, rounds)
  * Special team IDs (free agent team)
  * Role/channel names (help editor, players, news channel)
  * Base URLs (SBA website)

- constants.py: Refactored to load from config
  * All constants now read from get_config()
  * Position sets remain static (PITCHER_POSITIONS, etc.)
  * Added documentation about configurability

- .env.example: Added all new environment variables
  * Organized into logical sections with headers
  * Includes default values from config.py
  * Clear documentation for each setting

Benefits:
- Environment-specific configuration without code changes
- Easy deployment across dev/staging/production
- Season rollover requires only env variable updates
- Team-specific customization (channels, roles, URLs)
- Docker-friendly configuration management

Backward Compatible: All defaults match previous hardcoded values

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 10:40:22 -05:00
Cal Corum
5924249481 CLAUDE: Add comprehensive Docker deployment infrastructure
Implements production-ready Docker setup with multi-stage builds and
separate development/production configurations.

New Files:
- Dockerfile: Multi-stage build with Python 3.13
  * Builder stage: Compiles dependencies with build tools
  * Runtime stage: Minimal image (~150-200MB) with non-root user
  * Health checks and security hardening
- docker-compose.yml: Production config (pulls from Docker Hub)
  * Image: manticorum67/major-domo-discordapp:latest
  * Resource limits: 512MB RAM, 1 CPU
  * Volumes: /app/data (ro), /app/logs (rw)
- docker-compose.dev.yml: Development config (builds locally)
  * Higher resource limits: 1GB RAM, 2 CPU
  * DEBUG log level by default
- .dockerignore: Excludes unnecessary files from build context
- build-and-push.sh: Interactive build/push script for Docker Hub
- DOCKER.md: Comprehensive deployment guide (13K)
- BUILD_AND_PUSH.md: Docker Hub build/push guide (7.7K)

Configuration Updates:
- config.py: Updated sheets_credentials_path to /app/data location
- requirements.txt: Pinned all package versions for reproducibility
- .env.example: Added Docker-specific configuration

Key Features:
- Multi-stage build for optimized image size
- Non-root user (botuser, UID 1000) for security
- Separate dev/prod compose files
- Volume mounts for persistence (/app/data, /app/logs)
- Health checks and automatic restarts
- Resource limits and log rotation
- Docker Hub integration for production deployments

Docker Hub Repository: manticorum67/major-domo-discordapp

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 00:54:56 -05:00
Cal Corum
2409c27c1d CLAUDE: Add comprehensive scorecard submission system
Implements full Google Sheets scorecard submission with:
- Complete game data extraction (68 play fields, pitching decisions, box score)
- Transaction rollback support at 3 states (plays/game/complete)
- Duplicate game detection with confirmation dialog
- Permission-based submission (GMs only)
- Automated results posting to news channel
- Automatic standings recalculation
- Key plays display with WPA sorting

New Components:
- Play, Decision, Game models with full validation
- SheetsService for Google Sheets integration
- GameService, PlayService, DecisionService for data management
- ConfirmationView for user confirmations
- Discord helper utilities for channel operations

Services Enhanced:
- StandingsService: Added recalculate_standings() method
- CustomCommandsService: Fixed creator endpoint path
- Team/Player models: Added helper methods for display

Configuration:
- Added SHEETS_CREDENTIALS_PATH environment variable
- Added SBA_NETWORK_NEWS_CHANNEL and role constants
- Enabled pygsheets dependency

Documentation:
- Comprehensive README updates across all modules
- Added command, service, model, and view documentation
- Detailed workflow and error handling documentation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 00:21:32 -05:00
Cal Corum
998e09d0c0 CLAUDE: Fix duplicate score display in key plays
Fixed issue where key plays were showing the score twice:
- Before: "Top 3: Player (NYY) homers, NYY up 2-0, NYY up 2-0"
- After: "Top 3: Player (NYY) homers, NYY up 2-0"

Changes:
- Simplified Play.descriptive_text() to use rbi for score calculation
- Removed duplicate score logic in format_key_plays() helper
- Now only shows score after the play is completed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 00:20:56 -05:00
Cal Corum
7aa454f619 CLAUDE: Reorganize data storage and enhance team/roster displays
Standardize data file locations to data/ directory and improve command organization with better UI for team rosters, pagination for team lists, and refactored chart commands into logical command groups.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-15 19:05:51 -05:00
Cal Corum
3c66ada99d CLAUDE: Add pagination and move ID display to /mymoves command
- Fix transaction count bug by filtering transactions >= current week
- Add TransactionPaginationView with "Show Move IDs" button
- Implement intelligent message chunking for long transaction lists
- Remove emojis from individual transaction lines (kept in headers)
- Display 10 transactions per page with navigation buttons
- Show move IDs on demand via ephemeral button (stays under 2000 char limit)
- Update all tests to validate pagination and chunking behavior

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-14 16:51:24 -05:00
Cal Corum
b61cad2478 CLAUDE: Refactor dice roll functions to use DiceRoll dataclass
Replaced dictionary return values with a DiceRoll dataclass for better
type safety and cleaner code.

Changes:
- Added DiceRoll dataclass with fields: dice_notation, num_dice, die_sides, rolls, total
- Updated _parse_and_roll_single_dice() to return Optional[DiceRoll]
- Updated _parse_and_roll_multiple_dice() to return list[DiceRoll]
- Updated _roll_weighted_scout_dice() to return list[DiceRoll]
- Updated _create_multi_roll_embed() to accept list[DiceRoll]
- Updated _create_fielding_embed() to accept list[DiceRoll]
- Changed all dict key access (result['total']) to dataclass attributes (result.total)
- Updated logging statements to use dataclass attributes
- Updated all 34 test cases to use DiceRoll dataclass

Benefits:
- Improved type safety with explicit dataclass types
- Better IDE autocomplete and type checking
- More maintainable code with clear data structures
- No runtime changes - all functionality preserved

All 34 dice command tests pass.
2025-10-14 14:28:19 -05:00
Cal Corum
4cab227109 CLAUDE: Implement /scout command with weighted dice rolling
Added weighted dice rolling system for scouting cards based on card type.

Features:
- New /scout command with card_type parameter (batter or pitcher)
- Weighted first d6 roll:
  - Batter: Always rolls 1-3 on first d6
  - Pitcher: Always rolls 4-6 on first d6
- Remaining dice (2d6 and 1d20) roll normally
- Uses same embed formatting as /ab command
- Comprehensive test coverage (4 new tests)

Implementation:
- Added _roll_weighted_scout_dice() helper method
- Reuses existing dice rolling and embed creation logic
- Follows established command patterns with @logged_command decorator

Tests:
- test_weighted_scout_dice_batter - Verifies batter weighting (20 iterations)
- test_weighted_scout_dice_pitcher - Verifies pitcher weighting (20 iterations)
- test_scout_command_batter - Tests batter slash command
- test_scout_command_pitcher - Tests pitcher slash command

All 34 dice command tests pass.
2025-10-14 14:20:31 -05:00
Cal Corum
c5fecc878f CLAUDE: Remove duplicate emojis from EmbedTemplate method calls
Fixed 14 instances across 6 command files where manual emojis were added
to titles when EmbedTemplate methods already add them automatically.

Changes:
- commands/soak/info.py: Removed 📊 from info() title
- commands/help/main.py: Removed 📚, , ⚠️ from various titles (4 fixes)
- commands/profile/images.py: Removed  from success() title
- commands/voice/channels.py: Removed 📢 from deprecated command titles (2 fixes)
- commands/custom_commands/main.py: Removed , 📝 from titles (3 fixes)
- commands/utilities/charts.py: Removed  from admin command titles (3 fixes)

This prevents double emoji rendering (e.g., "ℹ️ 📊 Last Soak" now shows as "ℹ️ Last Soak")
since EmbedTemplate.success/error/warning/info/loading methods automatically prepend
the appropriate emoji to the title.
2025-10-14 00:43:05 -05:00
Cal Corum
2e1e3361a1 CLAUDE: Fix type annotations in CacheManager for JSON-serializable types
Update CacheManager.get() and CacheManager.set() type annotations to
accept Any JSON-serializable type (dict, list, str, int, bool, None)
instead of just dict.

This fixes type checker warnings in base_service.py where lists are
cached for API responses. The runtime behavior was already correct,
this just aligns the type hints with actual usage.

Changes:
- CacheManager.get() return type: Optional[dict] -> Optional[Any]
- CacheManager.set() data param: dict -> Any
- Updated docstrings to clarify JSON-serializable types

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-14 00:22:01 -05:00
Cal Corum
68c30e565b CLAUDE: Implement soak easter egg with disappointment GIFs and tracking
Add comprehensive "soaking" easter egg feature that detects mentions
and responds with GIFs showing escalating disappointment based on
recency (reversed from legacy - more recent = more disappointed).

Features:
- Detects "soak", "soaking", "soaked", "soaker" (case-insensitive)
- 7 disappointment tiers with 5 varied search phrases each
- Giphy API integration with Trump filter and fallback handling
- JSON-based persistence tracking all mentions with history
- /lastsoak command showing detailed information
- 25 comprehensive unit tests (all passing)

Architecture:
- commands/soak/giphy_service.py - Tiered GIF fetching
- commands/soak/tracker.py - JSON persistence with history
- commands/soak/listener.py - Message detection and response
- commands/soak/info.py - /lastsoak info command
- tests/test_commands_soak.py - Full test coverage

Uses existing Giphy API key from legacy implementation.
Zero new dependencies, follows established patterns.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 23:25:22 -05:00
Cal Corum
5acd378c72 CLAUDE: Add graceful error handling for missing creators in custom commands
Added defensive error handling to prevent crashes when custom command
creators are missing from the database.

Changes Made:

1. services/custom_commands_service.py:
   - Added try/except blocks in get_popular_commands()
   - Added try/except blocks in get_commands_needing_warning()
   - Added try/except blocks in get_commands_eligible_for_deletion()
   - Catches BotException when get_creator_by_id() fails
   - Logs warning with command details and continues processing
   - Skips problematic commands instead of failing entire operation

2. commands/help/main.py:
   - Removed redundant emoji from success message title
   - EmbedTemplate.success() already includes check mark emoji

3. tests/test_models_help_command.py:
   - Updated test assertions to match new message format

4. tests/test_services_help_commands.py:
   - Updated test expectations for error handling behavior

Impact:
- Prevents service crashes when creator data is orphaned or deleted
- Maintains functionality for commands with valid creator data
- Provides visibility into data integrity issues via warning logs
- Ensures automated cleanup tasks can complete successfully

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 17:53:58 -05:00
Cal Corum
bf374c1b98 CLAUDE: Fix /set-image command to use query parameters for API updates
The /set-image command was failing to persist player image updates to the
database. Investigation revealed a mismatch between how the bot sent PATCH
data versus how the database API expected it.

Root Cause:
- Database API endpoint (/api/v3/players/{id}) expects PATCH data as URL
  query parameters, not JSON body
- Bot was sending: PATCH /api/v3/players/12288 {"vanity_card": "url"}
- API expected: PATCH /api/v3/players/12288?vanity_card=url

Changes Made:

1. api/client.py:
   - Added use_query_params parameter to patch() method
   - When enabled, sends data as URL query parameters instead of JSON body
   - Maintains backward compatibility (defaults to JSON body)

2. services/base_service.py:
   - Added use_query_params parameter to patch() method
   - Passes parameter through to API client

3. services/player_service.py:
   - Updated update_player() to use use_query_params=True
   - Added documentation note about query parameter requirement

4. commands/profile/images.py:
   - Fixed autocomplete to use correct utility function
   - Changed from non-existent player_autocomplete_with_team_priority
   - Now uses player_autocomplete from utils/autocomplete.py

Documentation Updates:

5. commands/profile/README.md:
   - Updated API Integration section
   - Documented PATCH endpoint uses query parameters
   - Added note about automatic handling in player_service

6. services/README.md:
   - Added PATCH vs PUT operations documentation
   - Documented use_query_params parameter
   - Included usage examples for both modes

Testing:
- Verified /set-image command now successfully persists image URLs
- Confirmed API returns updated player with vanity_card populated
- Validated both fancy-card and headshot updates work correctly

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 17:52:14 -05:00
Cal Corum
aa7aab3901 CLAUDE: Implement player image management system
Add /set-image command for updating player fancy cards and headshots.

Features:
- Single command with fancy-card/headshot choice parameter
- Comprehensive URL validation (format + accessibility testing)
- Permission system (users can edit org players, admins can edit all)
- Preview embed with confirmation dialog before database update
- Player name autocomplete prioritizing user's team
- HTTP HEAD request to verify URL accessibility and content-type

Implementation:
- New commands/profile/ package with ImageCommands cog
- Two-stage URL validation (format check + accessibility test)
- Permission checking via Team.is_same_organization()
- Interactive confirmation view with 180s timeout
- Updates player.vanity_card or player.headshot field

Testing:
- 23 comprehensive tests covering validation and permissions
- Uses aioresponses for HTTP mocking (project standard)
- Test coverage for admin/user permissions and organization checks

Documentation:
- Comprehensive README.md with usage guide and troubleshooting
- Updated PRE_LAUNCH_ROADMAP.md to mark feature complete

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 13:54:12 -05:00
Cal Corum
90cd377a79 CLAUDE: Mark help system as complete in roadmap
Update PRE_LAUNCH_ROADMAP.md to reflect completion of help system:
- Changed status from "🚧 In progress" to " Complete"
- Updated resource tracking to show help system complete (saved 2-3 hours)
- Updated next steps to focus on remaining features (images, memes, scout)

Remaining pre-launch work: ~6-9 hours (images, memes, scouting)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 13:16:50 -05:00
Cal Corum
bcd6a10aef CLAUDE: Implement custom help commands system
Add comprehensive admin-managed help system for league documentation,
resources, FAQs, and guides. Replaces planned /links command with a
more flexible and powerful solution.

Features:
- Full CRUD operations via Discord commands (/help, /help-create, /help-edit, /help-delete, /help-list)
- Permission-based access control (admins + Help Editor role)
- Markdown-formatted content with category organization
- View tracking and analytics
- Soft delete with restore capability
- Full audit trail (creator, editor, timestamps)
- Autocomplete for topic discovery
- Interactive modals and paginated list views

Implementation:
- New models/help_command.py with Pydantic validation
- New services/help_commands_service.py with full CRUD API integration
- New views/help_commands.py with interactive modals and views
- New commands/help/ package with command handlers
- Comprehensive README.md documentation in commands/help/
- Test coverage for models and services

Configuration:
- Added HELP_EDITOR_ROLE_NAME constant to constants.py
- Updated bot.py to load help commands
- Updated PRE_LAUNCH_ROADMAP.md to mark system as complete
- Updated CLAUDE.md documentation

Requires database migration for help_commands table.
See .claude/DATABASE_MIGRATION_HELP_COMMANDS.md for details.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 13:14:13 -05:00
Cal Corum
7d422f50c5 CLAUDE: Add weather and charts commands with utility infrastructure
- Add /weather command with smart team resolution and D20 rolling system
- Add /charts command with autocomplete and category organization
- Implement ChartService for JSON-based chart management
- Add comprehensive test coverage for new commands
- Update test factories with complete model fixtures
- Enhance voice channel tracker with improved logging
- Update PRE_LAUNCH_ROADMAP.md to reflect completed features
- Minor improvements to imports and service initialization

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 09:59:49 -05:00
Cal Corum
5c7f2d916b CLAUDE: Fix trade system bugs and add smart channel updates
This commit fixes two critical bugs in the trade system and adds a new
feature for automatic channel updates.

## Bug Fixes

### 1. Trade Channel Creation Permission Error (Discord API 50013)
**Issue**: Trade channels failed to create with "Missing Permissions" error

**Root Cause**: Bot was attempting to grant itself manage_channels and
manage_permissions in channel-specific overwrites. Discord prohibits bots
from self-granting elevated permissions in channel overwrites.

**Fix**: Removed manage_channels and manage_permissions from bot's
channel-specific overwrites in trade_channels.py. Server-level permissions
are sufficient for all channel management operations.

**Files Changed**:
- commands/transactions/trade_channels.py (lines 74-77)

### 2. TeamService Method Name AttributeError
**Issue**: Bot crashed with AttributeError when adding players to trades

**Root Cause**: Code called non-existent method team_service.get_team_by_id()
The correct method name is team_service.get_team()

**Fix**: Updated method call in trade_builder.py and all test mocks

**Files Changed**:
- services/trade_builder.py (line 201)
- tests/test_services_trade_builder.py (all test mocks)

## New Features

### Smart Trade Channel Updates
**Feature**: When trade commands are executed outside the dedicated trade
channel, the trade embed is automatically posted to the trade channel
(non-ephemeral) for visibility to all participants.

**Behavior**:
- Commands in trade channel: Only ephemeral response to user
- Commands outside trade channel: Ephemeral response + public post to channel
- Applies to: /trade add-team, /trade add-player, /trade supplementary, /trade view

**Implementation**:
- Added _get_trade_channel() helper method
- Added _is_in_trade_channel() helper method
- Added _post_to_trade_channel() helper method
- Updated 4 trade commands to use smart posting logic

**Files Changed**:
- commands/transactions/trade.py (new helper methods + 4 command updates)

## Documentation Updates

Updated comprehensive documentation for:
- Trade channel permission requirements and troubleshooting
- TeamService correct method names with examples
- Smart channel update feature and behavior
- Bug fix details and prevention strategies

**Files Changed**:
- commands/transactions/README.md
- services/README.md

## Testing

- All 18 trade builder tests pass
- Updated test assertions to match new error message format

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 20:55:19 -05:00
Cal Corum
758be0f166 CLAUDE: Fix trade system issues and enhance documentation
Major fixes and improvements:

Trade System Fixes:
- Fix duplicate player moves in trade embed Player Exchanges section
- Resolve "WVMiL not participating" error for Minor League destinations
- Implement organizational authority model for ML/MiL/IL team relationships
- Update Trade.cross_team_moves to deduplicate using moves_giving only

Team Model Enhancements:
- Rewrite roster_type() method using sname as definitive source per spec
- Fix edge cases like "BHMIL" (Birmingham IL) vs "BHMMIL"
- Update _get_base_abbrev() to use consistent sname-based logic
- Add organizational lookup support in trade participation

Autocomplete System:
- Fix major_league_team_autocomplete invalid roster_type parameter
- Implement client-side filtering using Team.roster_type() method
- Add comprehensive test coverage for all autocomplete functions
- Centralize autocomplete logic to shared utils functions

Test Infrastructure:
- Add 25 new tests for trade models and trade builder
- Add 13 autocomplete function tests with error handling
- Fix existing test failures with proper mocking patterns
- Update dropadd tests to use shared autocomplete functions

Documentation Updates:
- Document trade model enhancements and deduplication fix
- Add autocomplete function documentation with usage examples
- Document organizational authority model and edge case handling
- Update README files with recent fixes and implementation notes

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-06 16:10:13 -05:00
Cal Corum
c01f88e7e3 CLAUDE: Comprehensive bot improvements and test infrastructure
This commit includes various enhancements across the bot architecture:

**New Infrastructure:**
- Added tests/factories.py - Factory classes for creating test data objects
- Added PRE_LAUNCH_ROADMAP.md - Project planning and roadmap documentation

**Model Enhancements:**
- Updated models/roster.py - Enhanced roster data structures
- Updated models/team.py - Improved team model definitions

**Service Layer Improvements:**
- Enhanced services/player_service.py - Better player data handling
- Updated services/roster_service.py - Roster management improvements
- Enhanced services/team_service.py - Team data service refinements
- Updated services/transaction_service.py - Transaction processing enhancements

**Command Updates:**
- Updated commands/teams/info.py - Team information command improvements
- Enhanced commands/voice/tracker.py - Voice channel tracking refinements

**Background Tasks:**
- Updated tasks/custom_command_cleanup.py - Automated cleanup improvements

**View Components:**
- Enhanced views/transaction_embed.py - Transaction embed UI improvements

**Test Coverage Enhancements:**
- Updated tests/test_commands_voice.py - Voice command test improvements
- Enhanced tests/test_dropadd_integration.py - Integration test coverage
- Updated tests/test_services_player_service.py - Player service test coverage
- Enhanced tests/test_services_transaction_builder.py - Transaction builder tests
- Updated tests/test_transactions_integration.py - Transaction integration tests
- Enhanced tests/test_views_transaction_embed.py - UI component test coverage

These changes collectively improve the bot's reliability, maintainability, and test coverage while adding essential infrastructure for continued development.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 11:35:26 -05:00
Cal Corum
25a8b55fca CLAUDE: Enhance /dropadd workflow and remove redundant commands
This commit implements significant improvements to the transaction management system:

**Major Changes:**
1. Enhanced /dropadd command workflow:
   - All responses are now ephemeral for better user privacy
   - Every call now shows the transaction builder (not just first move)
   - Improved autocomplete with team context prioritization (user's players first)

2. Added team ownership validation:
   - Prevents adding players from other teams (except Free Agents with abbrev='FA')
   - Enhanced error messages with specific team information
   - Changed _add_quick_move return type to tuple[bool, str] for better error handling

3. Removed redundant /transactionstatus command:
   - Command functionality fully replaced by /dropadd without parameters
   - Simplified workflow reduces user confusion
   - All related tests updated accordingly

**Technical Improvements:**
- Enhanced player autocomplete with team prioritization and better formatting
- Improved roster detection logic checking actual roster data vs team_id
- Better error handling with specific, actionable error messages
- Updated all test cases to handle new tuple return types
- Added comprehensive test coverage for team ownership validation

**Test Coverage:**
- All 30 tests passing (17 dropadd + 13 transaction embed tests)
- New tests for team ownership validation scenarios
- Updated existing tests for new return type patterns

The /dropadd command now serves as the single point of entry for all transaction operations while providing a cleaner, more intuitive user experience.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 11:33:53 -05:00
Cal Corum
e20677ec72 CLAUDE: Enhance voice channel validation for Major League teams
Update voice channel commands to require Major League team ownership for both public and private channels:

## Key Changes
- **Major League Team Validation**: Added `_get_user_major_league_team()` method to filter teams by `RosterType.MAJOR_LEAGUE`
- **Enhanced Requirements**: Both `/voice-channel public` and `/voice-channel private` now require Major League team ownership
- **Improved Error Messages**: Updated error messages to clearly indicate Major League team requirement
- **Schedule Integration**: Private channels now properly validate Major League teams for weekly game schedules

## Technical Implementation
- **Team Filtering**: Uses `team.roster_type() == RosterType.MAJOR_LEAGUE` to identify 3-character abbreviation teams
- **Service Integration**: Leverages existing team service and roster type logic from team model
- **Backward Compatibility**: Maintains existing `_get_user_team()` method for potential future use

## Team Type Validation
- **Major League**: 3-character abbreviations (NYY, BOS, LAD) - **Required for voice channels**
- **Minor League**: 4+ characters ending in "MIL" (NYYMIL, BOSMIL) - **Not eligible**
- **Injured List**: Ending in "IL" (NYYIL, BOSIL) - **Not eligible**

## Updated Tests
- **Mock Team Updates**: Added `roster_type()` method mocking to test team objects
- **Async Service Mocking**: Fixed team service mocks to return proper async results
- **Error Message Assertions**: Updated test assertions for new error messages
- **Type Safety**: Enhanced mock objects with proper Discord voice channel specifications

## Documentation Updates
- **README.md**: Added comprehensive team validation logic explanation
- **Architecture Documentation**: Detailed team type requirements and rationale
- **Code Examples**: Included implementation snippets for team filtering logic

**Rationale**: Voice channels are for scheduled gameplay between Major League teams. Minor League and Injured List teams don't participate in weekly games, so restricting access ensures proper schedule integration.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-24 23:30:05 -05:00
Cal Corum
8515caaf21 CLAUDE: Implement voice channel management system
Add comprehensive voice channel system for Discord gameplay with:

## New Features
- `/voice-channel public` - Create public voice channels with random codenames
- `/voice-channel private` - Create private team vs team channels with role permissions
- Automatic cleanup after configurable empty duration (default: 5 minutes)
- Restart-resilient JSON persistence for channel tracking
- Background monitoring service with graceful error handling

## Technical Implementation
- **Voice Commands Package** (`commands/voice/`)
  - `channels.py` - Main slash command implementation with modern command groups
  - `cleanup_service.py` - Background service for automatic channel deletion
  - `tracker.py` - JSON-based persistent channel tracking
  - `__init__.py` - Package setup with resilient loading
- **Bot Integration** - Voice cleanup service integrated into bot lifecycle
- **Service Dependencies** - Integration with team, league, and schedule services
- **Permission System** - Team-based Discord role permissions for private channels

## Key Features
- **Public Channels**: Random codenames, open speaking permissions
- **Private Channels**: "{Away} vs {Home}" naming, team role restrictions
- **Auto-cleanup**: Configurable intervals with empty duration thresholds
- **Restart Resilience**: JSON file persistence survives bot restarts
- **Error Handling**: Comprehensive validation and graceful degradation
- **Migration Support**: Deprecated old prefix commands with helpful messages

## Documentation & Testing
- Comprehensive README.md following project patterns
- Full test suite with 15+ test methods covering all scenarios
- Updated CLAUDE.md files with voice command documentation
- Clean IDE diagnostics with proper type safety

## Integration Points
- Team service for user validation and role lookup
- League service for current season/week information
- Schedule service for opponent detection in private channels
- Background task management in bot startup/shutdown

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-24 23:17:39 -05:00
Cal Corum
1dd930e4b3 CLAUDE: Complete dice command system with fielding mechanics
Implements comprehensive dice rolling system for gameplay:

## New Features
- `/roll` and `!roll` commands for XdY dice notation with multiple roll support
- `/ab` and `!atbat` commands for baseball at-bat dice shortcuts (1d6;2d6;1d20)
- `/fielding` and `!f` commands for Super Advanced fielding with full position charts

## Technical Implementation
- Complete dice command package in commands/dice/
- Full range and error charts for all 8 defensive positions (1B,2B,3B,SS,LF,RF,CF,C)
- Pre-populated position choices for user-friendly slash command interface
- Backwards compatibility with prefix commands (!roll, !r, !dice, !ab, !atbat, !f, !fielding, !saf)
- Type-safe implementation following "Raise or Return" pattern

## Testing & Quality
- 30 comprehensive tests with 100% pass rate
- Complete test coverage for all dice functionality, parsing, validation, and error handling
- Integration with bot.py command loading system
- Maintainable data structures replacing verbose original implementation

## User Experience
- Consistent embed formatting across all commands
- Detailed fielding results with range and error analysis
- Support for complex dice combinations and multiple roll formats
- Clear error messages for invalid inputs

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-24 22:30:31 -05:00
Cal Corum
13c61fd8ae Transactions cog in place 2025-09-24 09:32:04 -05:00
Cal Corum
7b41520054 CLAUDE: Major bot enhancements - Admin commands, player stats, standings, schedules
Major Features Added:
• Admin Management System: Complete admin command suite with user moderation, system control, and bot maintenance tools
• Enhanced Player Commands: Added batting/pitching statistics with concurrent API calls and improved embed design
• League Standings: Full standings system with division grouping, playoff picture, and wild card visualization
• Game Schedules: Comprehensive schedule system with team filtering, series organization, and proper home/away indicators

New Admin Commands (12 total):
• /admin-status, /admin-help, /admin-reload, /admin-sync, /admin-clear
• /admin-announce, /admin-maintenance
• /admin-timeout, /admin-untimeout, /admin-kick, /admin-ban, /admin-unban, /admin-userinfo

Enhanced Player Display:
• Team logo positioned beside player name using embed author
• Smart thumbnail priority: fancycard → headshot → team logo fallback
• Concurrent batting/pitching stats fetching for performance
• Rich statistics display with team colors and comprehensive metrics

New Models & Services:
• BattingStats, PitchingStats, TeamStandings, Division, Game models
• StatsService, StandingsService, ScheduleService for data management
• CustomCommand system with CRUD operations and cleanup tasks

Bot Architecture Improvements:
• Admin commands integrated into bot.py with proper loading
• Permission checks and safety guards for moderation commands
• Enhanced error handling and comprehensive audit logging
• All 227 tests passing with new functionality

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-28 15:32:38 -05:00
Cal Corum
e6a30af604 CLAUDE: SUCCESSFUL STARTUP - Discord Bot v2.0 fully operational
 **MAJOR MILESTONE**: Bot successfully starts and loads all commands

🔧 **Key Fixes Applied**:
- Fixed Pydantic configuration (SettingsConfigDict vs ConfigDict)
- Resolved duplicate logging with hybrid propagation approach
- Enhanced console logging with detailed format (function:line)
- Eliminated redundant .log file handler (kept console + JSON)
- Fixed Pylance type errors across views and modals
- Added newline termination to JSON logs for better tool compatibility
- Enabled league commands package in bot.py
- Enhanced command tree hashing for proper type support

📦 **New Components Added**:
- Complete views package (base.py, common.py, embeds.py, modals.py)
- League service and commands integration
- Comprehensive test coverage improvements
- Enhanced decorator functionality with proper signature preservation

🎯 **Architecture Improvements**:
- Hybrid logging: detailed console for dev + structured JSON for monitoring
- Type-safe command tree handling for future extensibility
- Proper optional parameter handling in Pydantic models
- Eliminated duplicate log messages while preserving third-party library logs

🚀 **Ready for Production**: Bot loads all command packages successfully with no errors

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-16 07:36:47 -05:00