Skip to content

MKWorldWide/Serafina

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

🎮 Serafina — GameDin Discord Bot

A production-ready Discord bot with modern architecture, comprehensive service monitoring, and extensible AI integration capabilities.

License: MIT

🏗️ Architecture Overview

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

🚀 Quick Start

Prerequisites

  • Node.js 20.x (LTS recommended)
  • pnpm 9.x (for workspace management)
  • Discord Application with bot token

Installation

  1. Clone and install dependencies

    git clone <repository-url>
    cd serafina-bot
    pnpm install:all
  2. 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
  3. Start development

    pnpm dev        # Development mode (auto-restart)
    # or
    pnpm build && pnpm start  # Production build
  4. Register commands (required after adding new commands)

    pnpm register:commands

🗂️ Project Structure

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

⚙️ Configuration

Environment Variables

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)

Configuration Features

  • 🔒 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

🤖 Bot Features

Core Commands

/ping

  • Description: Test bot responsiveness and latency
  • Usage: /ping
  • Response: Shows bot and API latency

/status

  • Description: Display comprehensive bot and system status
  • Usage: /status
  • Response: System metrics, uptime, guild count, and configuration status

Event Handling

  • 🔄 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

Service Integration

Heartbeat Service

  • Automatic Presence Updates: Maintains bot activity status
  • Health Monitoring: Periodic system health checks
  • Graceful Shutdown: Clean service termination

Inter-Bot Communication

  • HTTP Bridge: RESTful communication between bot instances
  • Message Routing: Structured message passing with validation
  • Service Discovery: Dynamic target registration and health checks

AI Integration

  • 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

🚀 Deployment

Render (Recommended)

  1. Connect Repository: Link your GitHub repository to Render

  2. Configure Service:

    • Runtime: Node.js
    • Build Command: pnpm install --frozen-lockfile && pnpm build
    • Start Command: pnpm start
    • Environment Variables: Set required Discord credentials
  3. Deploy: Render will automatically deploy on pushes to main branch

Manual Deployment

# Build for production
pnpm build

# Start production server
NODE_ENV=production pnpm start

Docker Deployment

FROM 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

Available Scripts

# 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

Adding New Commands

  1. 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;
  2. Register the command

    pnpm register:commands

Adding New Services

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
    }
  };
}

🔧 Configuration Details

Discord Setup

  1. Create Discord Application:

  2. Bot Configuration:

    • Navigate to "Bot" section
    • Copy bot token to DISCORD_TOKEN
    • Generate and copy public key to CLIENT_PUBLIC_KEY
  3. OAuth2 Setup (for slash commands):

    • Set redirect URIs if using OAuth features
    • Copy client ID to DISCORD_CLIENT_ID

Guild-Specific Commands

For faster development, set a development guild:

DEV_GUILD_ID=your_guild_id

Commands will register immediately to this guild instead of globally (which can take up to an hour).

🔒 Security Considerations

  • Environment Variables: Never commit .env files 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

📊 Monitoring & Observability

Built-in Metrics

  • 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

Logging

  • 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

🤝 Contributing

Development Workflow

  1. Create Feature Branch: git checkout -b feature/amazing-feature
  2. Make Changes: Follow TypeScript strict mode and add tests
  3. Test Thoroughly: Run test suite and manual verification
  4. Submit PR: Include clear description of changes

Code Standards

  • 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

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

  • 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

About

No description, website, or topics provided.

Resources

License

Apache-2.0, Unknown licenses found

Licenses found

Apache-2.0
LICENSE
Unknown
License.md

Code of conduct

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •