A feature-rich, production-ready Discord bot built with TypeScript, Discord.js v14, and modern best practices. Designed for scalability, maintainability, and extensibility.
Features • Installation • Configuration • Documentation • Contributing
- Features
- Prerequisites
- Installation
- Configuration
- Database Setup
- Project Structure
- Commands
- Development
- Architecture
- Contributing
- License
- Modular Architecture: Clean, organized codebase with separation of concerns
- Type Safety: Full TypeScript support with strict type checking
- Command System: Slash commands with prefix and mention support
- Event Handling: Comprehensive event system for Discord events
- Database Support: MongoDB (Mongoose) and PostgreSQL (Prisma) support
- Caching Layer: Redis caching with in-memory fallback
- Error Handling: Comprehensive error handling and logging
- Webhook Logging: Discord webhook integration for error tracking
- Graceful Shutdown: Proper cleanup on bot termination
- Auto-Room Creation: Automatically creates private voice channels
- Room Management: Lock, unlock, hide, unhide voice channels
- User Management: Kick, move, pull users from voice channels
- Channel Controls: Set user limits, rename channels, allow/reject users
- Interactive Controls: Button-based interface for room management
- Activity Integration: Support for Discord activities (YouTube Together, Poker, etc.)
- Member Management: Ban, kick, and mute users
- Permission System: Role-based permission checks
- Audit Logging: Track admin actions
- Bot Management: Reload commands, shutdown, eval, exec
- Blacklist System: User and guild blacklisting
- Command Blacklist: Per-command blacklisting
- No-Prefix System: Allow users to use commands without prefix
- Terminal Access: Execute terminal commands
- Uptime Monitoring: Track bot uptime and performance
- Button Components: 11 interactive button components
- Menu Components: Select menus for various actions
- Rich Embeds: Beautiful, customizable embed messages
- Structured Logging: Pino-based logging with pretty printing
- Webhook Integration: Error logs, connection logs, command logs
- Performance Monitoring: Uptime tracking and performance metrics
- Shard Support: Multi-shard support with shard event monitoring
Before you begin, ensure you have the following installed:
- Node.js 18.0.0 or higher
- npm 9.0.0 or higher (or yarn/pnpm)
- TypeScript 5.3.3 or higher
- MongoDB 4.4+ (recommended) or PostgreSQL 12+ (optional)
- Redis 6.0+ (optional, for caching)
- Discord Bot Token (Get one here)
git clone <your-repo-url>
cd discord-botnpm installCreate a .env file in the root directory:
cp .env.example .env # If you have an example file
# Or create .env manuallySee Configuration section for detailed environment variable documentation.
npm run buildNote: Slash commands are automatically registered when the bot starts. You can also manually deploy commands using:
npm run deployStart the bot:
npm startFor development with auto-reload:
npm run devThe bot starts from the main entry point file: src/index.ts
-
Initialization (
src/index.ts)- Creates the
BotClientinstance - Loads all commands from
src/commands/ - Loads all buttons and menus from
src/components/ - Loads all events from
src/events/ - Connects to the database (MongoDB/PostgreSQL)
- Sets up error handlers and graceful shutdown
- Creates the
-
Command Loading
- Main commands from
src/commands/index.ts - Voice commands from
src/commands/voice/ - Owner commands from
src/commands/owners/ - All commands are registered in the bot's command collection
- Main commands from
-
Event Registration
- Events are loaded and registered with Discord.js
- Key events:
ready,interactionCreate,messageCreate, etc.
-
Database Connection
- Connects to MongoDB or PostgreSQL based on configuration
- Initializes database models (User, Guild, Room, etc.)
-
Bot Login
- Connects to Discord using the bot token
- Triggers the
readyevent when connection is established
-
Ready Event (
src/events/client/ready.ts)- Automatically registers slash commands with Discord API
- Loads guild prefixes into cache
- Initializes no-prefix users
- Sets up command blacklist
- Starts presence manager
- Cleans up VoiceMaster rooms
- Source File:
src/index.ts - Compiled File:
dist/index.js - Development:
npm run dev(runssrc/index.tswith ts-node) - Production:
npm start(runsdist/index.js)
src/index.ts
↓
1. Create BotClient
↓
2. Load Commands (loadCommands())
↓
3. Load Buttons & Menus
↓
4. Load Events (loadEvents())
↓
5. Connect Database (connectDatabase())
↓
6. Setup Error Handlers
↓
7. client.login() → Connect to Discord
↓
8. ready Event Fires
↓
9. Register Slash Commands (registerCommands())
↓
10. Initialize Features (prefixes, no-prefix users, etc.)
↓
11. Bot is Ready! ✅
| Variable | Description | Example |
|---|---|---|
DISCORD_TOKEN |
Your Discord bot token | MTIzNDU2Nzg5MDEyMzQ1Njc4OQ... |
CLIENT_ID |
Your bot's application ID | 123456789012345678 |
OWNER_ID |
Your Discord user ID | 987654321098765432 |
GUILD_ID=111222333444555666 # Guild ID for testing (optional)
PREFIX=! # Command prefix (default: !)
DEVELOPER_IDS=123456789,987654321 # Comma-separated developer IDsDATABASE_TYPE=mongodb # mongodb or postgresql (default: mongodb)
MONGODB_URI=mongodb://localhost:27017/discord-bot
# OR for PostgreSQL:
DATABASE_URL=postgresql://user:password@localhost:5432/discord_botREDIS_URL=redis://localhost:6379 # Redis connection string (optional)SPOTIFY_CLIENT_ID=your_client_id
SPOTIFY_CLIENT_SECRET=your_client_secretNODE_ERROR_LOGS_HOOK=https://discord.com/api/webhooks/...
NODE_DESTROY_LOGS_HOOK=https://discord.com/api/webhooks/...
NODE_CONNECTION_HOOK=https://discord.com/api/webhooks/...
ERROR_LOGS_HOOK=https://discord.com/api/webhooks/...
GUILD_JOIN_LOGS_HOOK=https://discord.com/api/webhooks/...
GUILD_LEAVE_LOGS_HOOK=https://discord.com/api/webhooks/...
COMMAND_LOGS_HOOK=https://discord.com/api/webhooks/...
RUNTIME_LOGS_HOOK=https://discord.com/api/webhooks/...
DM_LOGS_HOOK=https://discord.com/api/webhooks/...NODE_ENV=development # development or production
LOG_LEVEL=info # trace, debug, info, warn, error, fatalSUPPORT_SERVER_URL=https://discord.gg/your-server
INVITE_URL=https://discord.com/api/oauth2/authorize?client_id=...- Open Discord
- Go to User Settings → Advanced
- Enable Developer Mode
- Right-click on your profile
- Select Copy User ID
- Paste it as
OWNER_IDin your.envfile
For detailed environment variable documentation, see ENV_SETUP.md.
- Install MongoDB: https://www.mongodb.com/try/download/community
- Start MongoDB service
- Update
.env:DATABASE_TYPE=mongodb MONGODB_URI=mongodb://localhost:27017/discord-bot
- Create account at https://www.mongodb.com/cloud/atlas
- Create a cluster
- Get connection string
- Update
.env:DATABASE_TYPE=mongodb MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/discord-bot
- Install PostgreSQL: https://www.postgresql.org/download/
- Create database:
CREATE DATABASE discord_bot;
- Run Prisma migrations:
npx prisma generate npx prisma migrate dev
- Update
.env:DATABASE_TYPE=postgresql DATABASE_URL=postgresql://user:password@localhost:5432/discord_bot
The bot includes the following database models:
- User: User data (XP, level, coins, premium status, blacklist)
- Guild: Server settings (prefix, channels, custom settings, blacklist)
- Room: Voice room management (lock, hide, limit, owner)
- VoiceCreator: Voice master system configuration
Models support:
- Advanced database operations with validation
- Transaction support
- Relation validation
- Populated queries
For advanced database usage, see docs/ADVANCED_DATABASE_USAGE.md.
| Command | Description | Usage |
|---|---|---|
/ping |
Check bot latency | /ping |
/help |
Display help information | /help [command] |
/info |
Display bot information | /info |
| Command | Description | Usage | Permissions |
|---|---|---|---|
/ban |
Ban a member | /ban user:<user> reason:<reason> |
Ban Members |
/kick |
Kick a member | /kick user:<user> reason:<reason> |
Kick Members |
/mute |
Mute a member | /mute user:<user> duration:<duration> reason:<reason> |
Manage Roles |
| Command | Description | Usage | Permissions |
|---|---|---|---|
/voicemaster setup |
Setup VoiceMaster system | /voicemaster setup |
Manage Channels |
/voicemaster reset |
Reset VoiceMaster system | /voicemaster reset |
Manage Channels |
| Command | Description | Usage |
|---|---|---|
/vclock |
Lock your voice channel | /vclock |
/vcunlock |
Unlock your voice channel | /vcunlock |
/vchide |
Hide your voice channel | /vchide |
/vcunhide |
Unhide your voice channel | /vcunhide |
/vcrename |
Rename your voice channel | /vcrename name:<name> |
/vclimit |
Set user limit (0-99) | /vclimit limit:<number> |
/vckick |
Kick user from voice | /vckick user:<user> |
/vckickall |
Kick all users from voice | /vckickall |
/vcmove |
Move user to different channel | /vcmove user:<user> channel:<channel> |
/vcmoveall |
Move all users to different channel | /vcmoveall channel:<channel> |
/vcpull |
Pull user to your channel | /vcpull user:<user> |
/vcallow |
Allow user to join voice channel | /vcallow user:<user> |
/vcreject |
Reject user from voice channel | /vcreject user:<user> |
| Command | Description | Usage |
|---|---|---|
/eval |
Evaluate JavaScript code | /eval code:<code> |
/exec |
Execute shell command | /exec command:<command> |
/reload |
Reload a command | /reload command:<command> |
/shutdown |
Shutdown the bot | /shutdown |
/blacklist |
Blacklist a user or guild | /blacklist type:<type> id:<id> reason:<reason> |
/cmdblacklist |
Blacklist a command | /cmdblacklist command:<command> |
/noprefix |
Add/remove no-prefix user | /noprefix user:<user> |
/terminal |
Access terminal | /terminal command:<command> |
/uptimecheck |
Check bot uptime | /uptimecheck |
Note: All commands support slash commands, prefix commands, and mention commands (where applicable).
- Create a new file in
src/commands/<category>/<command>.ts - Extend the
Commandclass - Implement
build()andexecute()methods - Register it in
src/commands/index.ts
Example:
import { SlashCommandBuilder, ChatInputCommandInteraction } from 'discord.js';
import { Command } from '../../structures/Command';
export default class MyCommand extends Command {
constructor() {
super({
name: 'mycommand',
description: 'My command description',
category: 'general',
cooldown: 3000,
});
}
build() {
return new SlashCommandBuilder()
.setName('mycommand')
.setDescription('My command description');
}
async execute(interaction: ChatInputCommandInteraction) {
await interaction.reply('Hello!');
}
}- Create a new file in
src/events/<category>/<event>.ts - Extend the
Eventclass - Implement the
execute()method - Register it in
src/events/index.ts
Example:
import { Client } from 'discord.js';
import { Event } from '../../structures/Event';
export default class MessageCreateEvent extends Event {
constructor() {
super({
name: 'messageCreate',
once: false,
});
}
async execute(message: Message) {
// Your event logic here
}
}- Create a new file in
src/components/buttons/<button>.ts - Extend the
Buttonclass - Implement the
execute()method - Register it in
src/components/buttons/index.ts
- Create a new file in
src/components/menus/<menu>.ts - Extend the
Menuclass - Implement the
execute()method - Register it in
src/components/menus/index.ts
| Script | Description |
|---|---|
npm run build |
Build TypeScript to JavaScript |
npm start |
Start the bot |
npm run dev |
Start with auto-reload (nodemon) |
npm run deploy |
Deploy slash commands |
npm test |
Run tests |
npm run lint |
Lint code |
npm run format |
Format code |
- TypeScript: Strict type checking enabled
- ESLint: Code linting with TypeScript rules
- Prettier: Code formatting
- Jest: Unit testing framework
- Error Handling: Always use try-catch blocks for async operations
- Type Safety: Use TypeScript types and interfaces
- Logging: Use the logger utility for all log messages
- Permissions: Check permissions before executing commands
- Cooldowns: Implement cooldowns for rate limiting
- Validation: Validate user input before processing
- Slash Commands: Primary command interface
- Prefix Commands: Legacy support with
!prefix - Mention Commands: Commands triggered by mentioning the bot
- Cooldown System: Rate limiting per command
- Permission System: Role-based permission checks
- Error Handling: Comprehensive error handling and user feedback
- Client Events: Ready, interactionCreate, messageCreate, etc.
- Guild Events: guildCreate, guildDelete
- Channel Events: channelCreate, channelDelete, channelUpdate
- Voice Events: voiceStateUpdate (for voice master system)
- MongoDB: Primary database (Mongoose ODM)
- PostgreSQL: Alternative database (Prisma ORM)
- Caching: Redis caching with in-memory fallback
- Transactions: Support for database transactions
- Migrations: Database migration support
- Database Service: Database connection and management
- Cache Service: Redis caching with fallback
- Webhook Service: Discord webhook logging
- API Client: External API integration
- Buttons: Interactive button components
- Menus: Select menu components
- Embeds: Rich embed messages
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add some amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
- Follow the existing code style
- Add tests for new features
- Update documentation as needed
- Ensure all tests pass
- Follow semantic commit messages
- Use TypeScript for all new code
- Follow ESLint rules
- Use Prettier for formatting
- Add JSDoc comments for public APIs
This project is licensed under the MIT License - see the LICENSE file for details.
- Discord.js - Discord API library
- TypeScript - Type safety
- Mongoose - MongoDB ODM
- Prisma - PostgreSQL ORM
- Pino - Logging library
- ioredis - Redis client
- Environment Setup Guide - Detailed environment variable documentation
- Advanced Database Usage - Advanced database operations
- Integration Summary - Feature integration summary
- Database Implementation - Database implementation details
- Discord Developer Portal
- Discord.js Documentation
- TypeScript Documentation
- MongoDB Documentation
- Prisma Documentation
For support, please open an issue on GitHub or join our Discord server.
Made with ❤️ by Kirito