English | Português
A powerful, feature-rich Discord bot with advanced moderation, music streaming, automated systems, and a comprehensive web dashboard.
- Features
- Tech Stack
- Installation
- Configuration
- Usage
- Commands
- Dashboard
- Security
- Contributing
- Support
- Complete moderation suite with ban, kick, mute, warn commands
- Auto-Moderation system with customizable rules
- Anti-spam protection with progressive penalties
- Anti-links, anti-invites, anti-banned words filters
- Anti-new accounts protection
- Flexible penalty system (warn, mute, kick, ban)
- Warning system with persistent storage and history tracking
- Moderation dashboard with real-time statistics and configuration
- Channel management with lock/unlock and slowmode controls
- Bulk message deletion with purge command
- High-quality music playback via Lavalink
- Multiple sources support:
- YouTube
- Spotify
- SoundCloud
- Custom yt-dlp integration
- Advanced queue management
- Play, skip, stop, pause, resume
- Queue shuffle and loop (song/queue/none)
- Song seek functionality
- Queue visualization and management
- Music controls via buttons for better UX
- Lyrics display with multiple API fallbacks (including Vagalume)
- Song statistics with caching for performance
- Multiple Lavalink nodes with automatic failover
- Complete ticket lifecycle management
- Dashboard panel for creation and configuration
- Ticket statistics and history tracking
- Category organization support
- Automated templates for messages and logging
- Webhook integration for notifications
- User information commands (profile, avatar, guild info)
- Server management tools
- Fun commands and games
- Configuration commands for server-specific settings
- Help system with command categories
- Message filtering with categories
- Discord OAuth2 authentication for secure login
- Server management interface
- Real-time statistics and status
- Bot settings configuration
- Music queue control from the web
- Command and feature management
- Responsive design with Bootstrap 5
- Modern UI components and alerts system
- Role-based access control (RBAC)
- Webhook validation and secure integration
- Input sanitization and validation
- Extended security queries for Node.js
- Secret management via environment variables
- Audit logging with detailed action tracking
| Component | Technology | Version |
|---|---|---|
| Runtime | Node.js | >= 22.12.0 |
| Discord Library | discord.js | v14 |
| Music System | Lavalink Client | v2.9.7 |
| Web Framework | Express | v5.2.1 |
| Template Engine | EJS | v5.0.1 |
| Database | MongoDB + Mongoose | v9.2.1 |
| Session Store | express-session | v1.19.0 |
| Authentication | Passport (Discord) | v0.7.0 |
| Security | Helmet | v8.0.0 |
| Audio Processing | libsodium-wrappers | v0.8.2 |
| Media Sources | play-dl, youtubei.js, yt-dlp | Latest |
- Node.js >= 22.12.0
- npm or yarn
- MongoDB (local or Atlas)
- Discord Bot Token
- (Optional) Spotify API credentials
- (Optional) Lavalink server for music
# Clone the repository
git clone https://github.com/Programador-jr/King.git
cd King
# Install dependencies
npm install
# Copy environment template
cp .env.example .env
# Edit .env with your credentials
nano .envThe Lavalink service is maintained separately in King-Lavalink. Follow that repository's README to install Java, prepare the server, and enable the official youtube-source plugin.
To connect a local copy of this bot to your local Lavalink instance, set these variables in the King's .env, using the same password stored in King-Lavalink/application.yml:
LAVALINK_LOCAL=true
LAVALINK_HOST=127.0.0.1
LAVALINK_PORT=2333
LAVALINK_SECURE=false
LAVALINK_PASSWORD=YOUR_APPLICATION_YML_PASSWORDWith LAVALINK_LOCAL=true, the bot selects only the local node and ignores botconfig/lavalink.json. Remove the variable or set it to false to keep using the configured node list as before. Do not commit the password or use this local configuration on production hosting.
# ============================================
# DISCORD BOT
# ============================================
TOKEN=YOUR_BOT_TOKEN_HERE
PREFIX=k
# ============================================
# DATABASE
# ============================================
MONGO_URI=mongodb+srv://user:password@cluster.mongodb.net/king
DNS_RESULT_ORDER=ipv4first
# Optional custom DNS resolvers (comma-separated IPv4/IPv6 addresses, optionally with ports)
# DNS_SERVERS=1.1.1.1,8.8.8.8
# Set only for temporary diagnostics; promise stack tracking adds runtime overhead
# ANTI_CRASH_TRACE_PROMISES=true
# ============================================
# SPOTIFY INTEGRATION (Optional)
# ============================================
SPOTIFY_API_ENABLED=true
SPOTIFY_CLIENT_ID=YOUR_SPOTIFY_CLIENT_ID
SPOTIFY_CLIENT_SECRET=YOUR_SPOTIFY_CLIENT_SECRET
# ============================================
# DASHBOARD & OAUTH
# ============================================
DASHBOARD_CLIENT_ID=YOUR_DISCORD_CLIENT_ID
DASHBOARD_CLIENT_SECRET=YOUR_DISCORD_CLIENT_SECRET
DASHBOARD_DOMAIN=http://localhost:5000
DASHBOARD_CALLBACK=http://localhost:5000/callback
DASHBOARD_SESSION_SECRET=REPLACE_WITH_GENERATED_SECRET
# Generate with: openssl rand -hex 48
# Uncomment only when running behind one trusted reverse proxy
# DASHBOARD_TRUST_PROXY=1
# ============================================
# MUSIC SOURCES (Optional)
# ============================================
VAGALUME_API_KEY=YOUR_VAGALUME_KEY_HERE
YTDLP_PATH=/path/to/yt-dlp
# ============================================
# ENVIRONMENT
# ============================================
NODE_ENV=production
PORT=5000In production, the dashboard requires a random DASHBOARD_SESSION_SECRET of at least 32 characters, valid Discord OAuth credentials, and an HTTPS callback URL; missing, weak, or placeholder settings stop dashboard startup. In development, an omitted session secret is generated temporarily, invalidating sessions after a restart. If HTTPS is terminated by a trusted reverse proxy, set DASHBOARD_TRUST_PROXY=1 only when the proxy is trusted. Login regenerates the session, and logout destroys it and clears the cookie.
Sessions currently use an in-memory store. They do not survive process restarts and are not shared across multiple dashboard instances. Use one dashboard instance until a persistent store compatible with the deployment topology is configured; the repository does not define a production session-store backend yet.
Dashboard requests use session-backed CSRF tokens on state-changing methods, plus same-origin checks when browsers send Origin or Fetch Metadata headers. The Top.gg webhook keeps its provider authentication flow and skips browser CSRF checks. The dashboard applies in-memory rate limits per process: 20 login/callback requests per 15 minutes, 30 queue controls and 30 ticket actions per minute, 60 other mutations per minute, and 120 Top.gg webhook requests per minute. JSON and URL-encoded bodies are limited to 256 KB; URL-encoded forms accept up to 200 parameters. Oversized requests return 413, cross-origin or invalid-CSRF requests return 403, and rate limits return 429. Helmet's CSP allows the existing inline dashboard scripts and event handlers together with the Bootstrap, Font Awesome, and Google Fonts assets; removing inline-script allowances requires migrating those legacy handlers first.
Stores non-sensitive bot settings:
{
"token": "YOUR_BOT_TOKEN",
"prefix": "k",
"defaultColor": "#2b2d31",
"errorColor": "#ed4245",
"successColor": "#57f287"
}Dashboard structural settings:
{
"antiCrash": true,
"port": 5000,
"https": false,
"domain": "localhost"
}When antiCrash is enabled, an uncaught exception or unhandled rejection is logged with sensitive values redacted and terminates the process with exit code 1. Run the bot under a process manager or container restart policy if automatic recovery is required. Promise creation stack tracking is disabled normally; enable ANTI_CRASH_TRACE_PROMISES=true only while diagnosing an issue because it adds runtime overhead. TLS behavior is left to Node.js without global monkey-patching.
- Go to Discord Developer Portal
- Create a New Application
- Go to OAuth2 > Redirects
- Add your callback URL:
- Local:
http://localhost:5000/callback - Production:
https://yourdomain.com/callback
- Local:
- Copy Client ID and Client Secret to
.env
# Production
npm start
# Development (with auto-reload)
npm run devThe bot will:
- Connect to Discord
- Load all commands and events
- Connect to Lavalink for music
- Start the web dashboard on
http://localhost:5000
- Open
http://localhost:5000in your browser - Click "Login with Discord"
- Authorize the application
- Access your server's settings
- Configure moderation, music, and bot features
play- Play a song from YouTube, Spotify, or SoundCloudskip- Skip current songstop- Stop music and clear queuepause- Pause current playbackresume- Resume paused songqueue- View current queueloop- Toggle loop modes (off, song, queue)shuffle- Shuffle queueseek- Jump to specific time in songlyrics- Get lyrics for current or specified song
ban- Ban a user from serverkick- Remove user from servermute- Mute a user (timeout)unmute- Remove mute from userwarn- Issue warning to userunwarn- Remove specific warningwarnings- View user's warningsclearwarnings- Remove all user warningslock- Lock channel for publicunlock- Unlock channelslowmode- Set channel message rate limitpurge- Delete bulk messages
q/queue- Display current queueremove- Remove song from queueclear- Clear entire queuemove- Move song position in queue
bassboost- Enable bass boostnightcore- Nightcore effectvaporwave- Vaporwave effectclear- Remove all filters
create- Create support ticketclose- Close active ticketadd- Add user to ticketremove- Remove user from ticketsettings- Configure ticket system
help- Show help informationbotinfo- Bot statistics and infoserverinfo- Server informationuserinfo- User profile informationavatar- Get user's avatar
automod- Configure auto-moderationprefix- Change command prefixsettings- Manage server settings
- Secure Discord OAuth2 login
- Session management with express-session
- Role-based access control
- Home - Overview and quick stats
- Server Settings - Configure bot behavior
- Moderation - Set up AutoMod rules and warnings
- Music - Queue controls and filter management
- Tickets - Create and manage ticket panels
- Logs - View action history and audit trail
Ticket access policy: ticket owners may close or reopen their own tickets; members with a configured ticketRoles support role or Manage Guild/Administrator permission may close and reopen any ticket. Only support staff and administrators may delete a closed ticket. Discord interactions and dashboard APIs enforce the same policy.
- Never commit
.envfile - It contains sensitive credentials - Rotate tokens regularly - If exposed, regenerate immediately
- Use strong secrets - For
DASHBOARD_SESSION_SECRET - MongoDB authentication - Use strong passwords and IP whitelist
- HTTPS in production - Always use SSL/TLS
- Helmet enabled - Security headers middleware active
- Input validation - All user inputs are sanitized
- RBAC system - Granular permission management
- All secrets in
.env(never in code) - Different credentials per environment
- Webhook URL validation
- Role-based bypass system for AutoMod
# Check Node version
node --version # Should be >= 22.12.0
# Clear cache and reinstall
rm -rf node_modules package-lock.json
npm install
# Check environment variables
cat .env# Verify MongoDB URI
# Check: IP whitelist in MongoDB Atlas
# Check: Network connectivity
# Try: DNS_RESULT_ORDER=ipv4first in .env# Verify Lavalink server is running
# Check: Bot has voice permissions
# Check: User is in voice channel
# Logs: Check console for Lavalink errors# Check: Dashboard server is running on PORT 5000
# Check: OAuth credentials are correct
# Check: Callback URL matches Discord settings
# Logs: Check console for Express errorsContributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Issues - Open an issue on GitHub
- Discussions - Join our GitHub Discussions
- Discord - Check our support channel
Give this project a if it helped you! It means a lot.