A production-ready Discord bot with modern architecture, comprehensive service monitoring, and extensible AI integration capabilities.
Serafina is built with a modern, modular architecture that emphasizes:
- 🔧 Monorepo Structure: Organized workspaces for maintainability
- 🎯 Service-Oriented Design: Loosely coupled, independently deployable services
- 📊 Comprehensive Monitoring: Built-in operations and health monitoring
- 🔒 Production Security: Environment validation and secure defaults
- 🚀 Scalable Infrastructure: Redis support and inter-service communication
- Node.js 20.x (LTS recommended)
- pnpm 9.x (for workspace management)
- Discord Application with bot token
-
Clone and install dependencies
git clone <repository-url> cd serafina-bot pnpm install:all
-
Configure environment
cp .env.example .env # Edit .env with your Discord credentials: # DISCORD_TOKEN=your_bot_token # DISCORD_CLIENT_ID=your_application_id # CLIENT_PUBLIC_KEY=your_public_key
-
Start development
pnpm dev # Development mode (auto-restart) # or pnpm build && pnpm start # Production build
-
Register commands (required after adding new commands)
pnpm register:commands
serafina-bot/
├── apps/
│ └── bot/ # 🤖 Main Discord bot application
│ ├── src/
│ │ ├── index.ts # 🚀 Application entry point
│ │ ├── config/ # ⚙️ Configuration management
│ │ │ ├── schema.ts # Zod validation schemas
│ │ │ └── index.ts # Validated configuration loader
│ │ ├── core/ # 🔧 Core bot functionality
│ │ │ ├── client.ts # Discord client wrapper
│ │ │ ├── lifecycle.ts # Startup/shutdown management
│ │ │ ├── logging.ts # Pino logger factory
│ │ │ └── shared/ # Common types and errors
│ │ ├── commands/ # 🎯 Slash command definitions
│ │ │ ├── index.ts # Command loader & registry
│ │ │ ├── ping.ts # Basic connectivity test
│ │ │ └── status.ts # Bot health & metrics
│ │ ├── events/ # 📡 Discord event handlers
│ │ │ ├── ready.ts # Bot initialization
│ │ │ ├── interactionCreate.ts # Command interactions
│ │ │ └── messageCreate.ts # Message handling
│ │ ├── services/ # 🔗 Business logic services
│ │ │ ├── heartbeat/ # 💓 Presence & health monitoring
│ │ │ ├── interbot/ # 🌐 Cross-bot communication
│ │ │ ├── ai/ # 🤖 AI provider integration
│ │ │ └── infrastructure/ # 🏗️ HTTP/Redis clients
│ │ └── scripts/ # 🛠️ Utility scripts
│ │ └── registerCommands.ts # Command registration
│ ├── package.json # Bot-specific dependencies
│ ├── tsconfig.json # TypeScript configuration
│ └── vitest.config.ts # Test configuration
├── archive/
│ └── legacy/ # 📦 Archived legacy code
├── .env.example # 🔐 Environment template
├── render.yaml # 🚀 Render deployment config
├── Procfile # 🐳 Heroku deployment config
└── package.json # Monorepo root configuration
| Variable | Required | Description |
|---|---|---|
DISCORD_TOKEN |
✅ | Discord bot authentication token |
DISCORD_CLIENT_ID |
✅ | Discord application client ID |
CLIENT_PUBLIC_KEY |
✅ | Discord public key for interaction verification |
OWNER_IDS |
❌ | Comma-separated Discord user IDs with owner permissions |
INTERBOT_TARGETS |
❌ | JSON array of bot endpoints for inter-bot communication |
AI_ENABLED |
❌ | Enable AI features (default: false) |
MISTRAL_API_KEY |
❌ | Mistral AI API key for AI responses |
REDIS_URL |
❌ | Redis URL for caching and pub/sub |
LOG_LEVEL |
❌ | Logging level (fatal/error/warn/info/debug/trace) |
NODE_ENV |
❌ | Environment (development/production/test) |
- 🔒 Runtime Validation: Zod schemas validate all configuration at startup
- 🔄 Hot Reloading: Configuration changes are detected and logged
- 🛡️ Secure Defaults: Sensitive data is excluded from logs
- 📋 Multiple Sources: Environment variables, config files, and defaults
- Description: Test bot responsiveness and latency
- Usage:
/ping - Response: Shows bot and API latency
- Description: Display comprehensive bot and system status
- Usage:
/status - Response: System metrics, uptime, guild count, and configuration status
- 🔄 Ready Events: Automatic initialization and presence updates
- 💬 Message Processing: Smart mention and reply handling
- ⚡ Interaction Management: Robust slash command execution with error handling
- 🛡️ Permission Guards: Owner-only commands and role-based access
- Automatic Presence Updates: Maintains bot activity status
- Health Monitoring: Periodic system health checks
- Graceful Shutdown: Clean service termination
- HTTP Bridge: RESTful communication between bot instances
- Message Routing: Structured message passing with validation
- Service Discovery: Dynamic target registration and health checks
- Mistral AI Support: Primary AI provider with fallback handling
- Contextual Responses: Conversation history awareness
- Configurable Parameters: Temperature, token limits, and model selection
- Error Recovery: Graceful degradation when AI services are unavailable
-
Connect Repository: Link your GitHub repository to Render
-
Configure Service:
- Runtime: Node.js
- Build Command:
pnpm install --frozen-lockfile && pnpm build - Start Command:
pnpm start - Environment Variables: Set required Discord credentials
-
Deploy: Render will automatically deploy on pushes to main branch
# Build for production
pnpm build
# Start production server
NODE_ENV=production pnpm startFROM node:20-alpine
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN npm install -g pnpm && pnpm install --frozen-lockfile
COPY . .
RUN pnpm build
EXPOSE 3000
CMD ["pnpm", "start"]# Development
pnpm dev # Start development server with hot reload
pnpm build # Build for production
pnpm start # Start production server
# Commands
pnpm register:commands # Register slash commands with Discord
# Testing
pnpm test # Run all tests
pnpm test:watch # Watch mode testing
pnpm test:coverage # Generate coverage report
# Code Quality
pnpm lint # Lint code
pnpm typecheck # TypeScript type checking-
Create command file in
apps/bot/src/commands/import { SlashCommandBuilder } from 'discord.js'; export const myCommand = { data: new SlashCommandBuilder() .setName('mycommand') .setDescription('My new command'), async execute({ interaction, client, config, logger }) { await interaction.reply('Hello from my command!'); } }; export default myCommand;
-
Register the command
pnpm register:commands
Services follow a consistent pattern:
export interface MyService {
start(): Promise<void>;
stop(): Promise<void>;
}
export function createMyService(config: AppConfig): MyService {
return {
async start() {
// Initialization logic
},
async stop() {
// Cleanup logic
}
};
}-
Create Discord Application:
- Go to Discord Developer Portal
- Create new application or select existing one
-
Bot Configuration:
- Navigate to "Bot" section
- Copy bot token to
DISCORD_TOKEN - Generate and copy public key to
CLIENT_PUBLIC_KEY
-
OAuth2 Setup (for slash commands):
- Set redirect URIs if using OAuth features
- Copy client ID to
DISCORD_CLIENT_ID
For faster development, set a development guild:
DEV_GUILD_ID=your_guild_idCommands will register immediately to this guild instead of globally (which can take up to an hour).
- Environment Variables: Never commit
.envfiles or tokens - API Keys: Store sensitive keys in environment variables only
- Permission Scoping: Use minimal Discord permissions required
- Rate Limiting: Built-in cooldowns prevent abuse
- Input Validation: All inputs are validated before processing
- Bot Health: Uptime, latency, guild/user counts
- Command Usage: Execution frequency and error rates
- Service Status: Inter-bot communication health
- AI Performance: Response times and error tracking
- Structured Logging: JSON logs with Pino for easy parsing
- Log Levels: Configurable verbosity (fatal/error/warn/info/debug/trace)
- Service Tagging: Logs include service context for debugging
- Error Tracking: Comprehensive error capture with stack traces
- Create Feature Branch:
git checkout -b feature/amazing-feature - Make Changes: Follow TypeScript strict mode and add tests
- Test Thoroughly: Run test suite and manual verification
- Submit PR: Include clear description of changes
- TypeScript Strict: All code must pass strict type checking
- Error Handling: Comprehensive error catching and user feedback
- Documentation: Clear JSDoc comments for public APIs
- Testing: Unit tests for all business logic
- Performance: Consider memory usage and execution time
This project is licensed under the MIT License - see the LICENSE file for details.
- Issues: Report bugs and feature requests via GitHub Issues
- Documentation: Check this README and inline code documentation
- Community: Join our Discord server for support and discussion
Made with ❤️ by the NovaSanctum team