Overview
RaidBot follows a modular architecture with clear separation of concerns. The codebase consists of 68 JavaScript files organized into logical directories.Root Directory
Core Files
Main application entry point (413 lines)Responsibilities:
- Initialize Discord client with required intents
- Load state from database on startup
- Register slash commands
- Route interactions to handlers
- Handle graceful shutdown
bot.js
State management layer (800+ lines)Hybrid state management with in-memory caches backed by SQLite:
activeRaids- Map of active raid data by message IDraidChannels- Guild → channel ID mappingsguildSettings- Guild configuration cacheraidStats- User participation statistics
state.js
Automated reminder and auto-close system (400+ lines)Runs every 60 seconds to:
- Send creator reminders before raid starts
- Send participant reminders to all signups
- Auto-close full raids at configured threshold
- Auto-close museum raids at start time
- Check and spawn recurring raids
reminderScheduler.js
Feature Modules
Schedule recurring raids with cron-like patterns (weekly, daily, custom intervals)
User availability tracking with heatmap aggregation for 50+ users
Time slot polling system with live vote tracking
Per-guild raid template customization (enable/disable, rename)
Audit logging for admin actions and signup modifications
Bot status updates with active raid count
Commands Directory
18 slash command handlers implementing Discord.js command builders.Command Structure
commands/example.js
Key Commands
create.js - Interactive raid creation (1,100+ lines)
create.js - Interactive raid creation (1,100+ lines)
Modal-based raid creation flow with natural language time parsing.Features:
- Template selection for different raid types
- Natural language time input (“tomorrow 7pm”, “next Friday 6:30pm”)
- Optional duration and strategy fields
- Automatic reaction setup based on template
commands/create.js
raid.js - Raid management panel (1,500+ lines)
raid.js - Raid management panel (1,500+ lines)
Comprehensive raid management with action buttons.Actions:
- Close signups (manual close with analytics)
- Reopen signups (with confirmation)
- Delete raid (with cascade cleanup)
- Change time (reschedule with notifications)
- Mark attendance (track no-shows)
commands/raid.js
stats.js - Unified analytics (600+ lines)
stats.js - Unified analytics (600+ lines)
Comprehensive statistics with multiple views.Views:
- User stats (personal participation, role distribution)
- Server stats (leaderboard, top roles)
- Weekly/monthly trends
- Inactive member detection
- CSV export for external analysis
commands/stats.js
recurring.js - Scheduled raids (1,200+ lines)
recurring.js - Scheduled raids (1,200+ lines)
Manage recurring raid schedules with spawn time customization.Subcommands:
create- Set up recurring schedulelist- View active schedulesdelete- Remove scheduletoggle- Enable/disable without deletingtrigger- Manually spawn next raid
commands/recurring.js
Full Command List
| File | Command | Lines | Description |
|---|---|---|---|
availability.js | /availability | 900+ | User availability tracking and heatmaps |
changelog.js | /changelog | 100 | View release notes |
create.js | /create | 1,100+ | Interactive raid/museum creation |
help.js | /help | 500+ | Command documentation |
leaderboard.js | /leaderboard | 300+ | Server participation leaderboard |
permissionspanel.js | /permissions | 250+ | Role-based permission configuration |
ping.js | /ping | 50 | Bot health check |
poll.js | /poll | 400+ | Time slot polling |
raid.js | /raid | 1,500+ | Raid management panel |
raidinfo.js | /raidinfo | 400+ | List/view/export raids |
raidsignup.js | /raidsignup | 1,200+ | Admin signup modifications |
recurring.js | /recurring | 1,200+ | Recurring raid schedules |
setchannel.js | /setchannel | 400+ | Configure raid channels |
settings.js | /settings | 450+ | Reminder and auto-close settings |
stats.js | /stats | 600+ | Unified analytics |
templates.js | /templates | 750+ | Template customization |
testalert.js | /testalert | 50 | Test performance alerts |
Command registry that exports all commands:
commands/index.js
Registers slash commands with Discord API:
commands/registerCommands.js
Raids Directory
Core raid logic and reaction handling.Concurrency-safe reaction processing (600+ lines)Handles all reaction-based signups with mutex locks to prevent race conditions:Features:
raids/reactionHandlers.js
- Per-raid mutex locks prevent concurrent modifications
- Rate limiting (5 reactions per 10 seconds per user)
- Automatic waitlist management with DM notifications
- Support for raid, museum, key boss, and challenge mode signups
Raid state recovery on bot restart (1,100+ lines)Reinitializes all active raids from database:
raids/reinitialize.js
Utils Directory
18 utility modules providing shared functionality.Core Utilities
logger.js - Structured logging (210 lines)
logger.js - Structured logging (210 lines)
Contextual logging with multiple severity levels.Features:
utils/logger.js
- DEBUG, INFO, WARN, ERROR levels
- Structured JSON output
- File rotation at 5MB
- Child loggers with context
circuitBreaker.js - Fault tolerance (220 lines)
circuitBreaker.js - Fault tolerance (220 lines)
Circuit breaker pattern for Discord API resilience.States:
utils/circuitBreaker.js
- CLOSED - Normal operation
- OPEN - Reject immediately
- HALF_OPEN - Testing recovery
rateLimiter.js - Rate limiting (124 lines)
rateLimiter.js - Rate limiting (124 lines)
Sliding window rate limiting for reactions and commands.
utils/rateLimiter.js
raidHelpers.js - Raid utilities (800+ lines)
raidHelpers.js - Raid utilities (800+ lines)
Embed generation and raid manipulation functions.
utils/raidHelpers.js
Full Utility List
| File | Purpose | Key Functions |
|---|---|---|
alerts.js | Performance monitoring | initializeAlerts(), sendAlert() |
analytics.js | Stats aggregation | calculateTrends(), getInactiveMembers() |
circuitBreaker.js | Fault tolerance | withCircuitBreaker(), sendDMWithBreaker() |
config.js | Configuration loading | Loads config.json or environment variables |
dmRetry.js | DM delivery retry | sendDMWithRetry() |
errorMessages.js | User-friendly errors | formatError(), getErrorMessage() |
idGenerator.js | Raid ID generation | generateRaidId() (A1-Z9 format) |
logger.js | Structured logging | logger.info(), logger.error() |
metrics.js | Prometheus metrics | incrementCounter(), recordHistogram() |
raidFormatters.js | Time/link formatting | formatTimeLabel(), buildMessageLink() |
raidHelpers.js | Raid manipulation | updateRaidEmbed(), closeRaidSignup() |
raidTypes.js | Type checking | isTeamBased(), getTeamTypeLabel() |
rateLimiter.js | Rate limiting | reactionLimiter.isAllowed() |
timezoneHelper.js | Timezone conversion | parseTimezone(), convertToUTC() |
userLabels.js | User display names | getUserLabel(), getUserLabels() |
validators.js | Input validation | validateTimezone(), validateDays() |
waitlistNotifications.js | Waitlist promotion | processWaitlistOpenings() |
Database Directory
SQLite database layer with migrations and utilities.Database connection and schema management (174 lines)
db/database.js
Database schema definition (200+ lines)Tables:
guilds- Guild configurationraids- Active and historical raidssignups- Normalized signup datauser_stats- Global user statisticsguild_user_stats- Per-guild statisticsrecurring_raids- Scheduled raidsavailability- User availability windowspolls- Time slot pollsadmin_roles- Permission configuration
schema.sql
JSON to SQLite migration script (500+ lines)Imports legacy JSON data files into SQLite database:
Utility Scripts
| File | Purpose |
|---|---|
import-csv-stats.js | Import stats from CSV files |
repair-stats.js | Recalculate stats from raid history |
restore-stats.js | Restore stats from backup |
Tests Directory
15 test files using Node.js built-in test runner.tests/example.test.js
Test Coverage
| File | Tests | Coverage Area |
|---|---|---|
statePersistence.test.js | State management | activeRaids persistence |
waitlistNotifications.test.js | Waitlist logic | Promotion and DM sending |
reactionHandlers.test.js | Reaction handling | Signup processing |
rateLimiter.test.js | Rate limiting | Sliding window algorithm |
validators.test.js | Input validation | Timezone, time, role validation |
chrono.test.js | Time parsing | Natural language dates |
permissions.test.js | Access control | Role-based permissions |
poll.test.js | Polling system | Vote recording |
availability.test.js | Availability | Time window parsing |
Data Directory
Runtime data storage (excluded from git).Configuration
Bot configuration (not in repo, created from example):
config.json
Dependencies and scripts:
package.json
Navigation Tips
Next Steps
Architecture
Understand the system design
Testing
Write and run tests
Contributing
Start contributing code