UNPKG

discord-optimizer

Version:

Reduce Discord.js bot RAM usage with automatic optimization and restart capabilities

253 lines (186 loc) โ€ข 6.65 kB
# Discord Optimizer [![npm version](https://badge.fury.io/js/discord-optimizer.svg)](https://badge.fury.io/js/discord-optimizer) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Node.js CI](https://github.com/ajauish/discord-optimizer/workflows/Node.js%20CI/badge.svg)](https://github.com/ajauish/discord-optimizer/actions) **Reduce your Discord.js bot's RAM usage with automatic optimization and restart capabilities.** Discord Optimizer is a lightweight, beginner-friendly package that helps manage your Discord bot's memory consumption through intelligent monitoring, automatic cleanup, and smart restart mechanisms. ## ๐Ÿš€ Features - **๐Ÿง  Smart Memory Management** - Automatic cache cleanup and garbage collection - **โšก Auto-Restart Protection** - Graceful restarts when memory limits are reached - **๐Ÿ“Š Real-time Monitoring** - Track memory usage with configurable intervals - **๐Ÿ”” Webhook Alerts** - Get notified when memory usage is high - **๐Ÿ›ก๏ธ Restart Protection** - Prevents multiple simultaneous restarts - **๐ŸŽฏ Zero Configuration** - Works out of the box with sensible defaults - **๐Ÿ“ฑ TypeScript Support** - Full type definitions included - **๐Ÿ”ง Beginner Friendly** - One-line setup, no complex configuration needed ## ๐Ÿ“ฆ Installation ```bash npm install discord-optimizer ``` ## ๐Ÿš€ Quick Start ```typescript import { Client, GatewayIntentBits } from 'discord.js'; import { MemoryGuard } from 'discord-optimizer'; const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] }); // โœจ One line to optimize your bot! const optimizedClient = MemoryGuard.wrap(client, { maxMemory: 256, // 256MB limit autoRestart: true, // Auto-restart when limit reached }); optimizedClient.on('ready', () => { console.log(`Bot is ready and optimized!`); }); optimizedClient.login('your_bot_token'); ``` That's it! Your bot now has intelligent memory management. ## โš™๏ธ Configuration Options ### Basic Configuration ```typescript const optimizedClient = MemoryGuard.wrap(client, { maxMemory: 512, // Memory limit in MB (default: 512) autoRestart: true, // Auto-restart on limit (default: true) optimizations: { clearCache: true, // Clear Discord.js caches (default: true) garbageCollect: true // Force garbage collection (default: true) }, monitoring: { interval: 30000, // Check every 30s (default: 30000) logging: true, // Log memory usage (default: true) webhook: 'https://discord.com/api/webhooks/...' // Optional alerts } }); ``` ### Advanced Configuration ```typescript const optimizedClient = MemoryGuard.wrap(client, { maxMemory: 256, autoRestart: true, optimizations: { clearCache: true, garbageCollect: true }, monitoring: { interval: 15000, // More frequent checks logging: true, webhook: process.env.DISCORD_WEBHOOK_URL } }); // Listen to optimization events optimizedClient.on('memoryLimitExceeded', (usage) => { console.log(`โš ๏ธ Memory limit exceeded: ${usage.heapUsed}MB`); }); optimizedClient.on('cleanup', () => { console.log('๐Ÿงน Memory cleanup performed'); }); optimizedClient.on('restart', () => { console.log('๐Ÿ”„ Bot is restarting due to high memory usage'); }); ``` ## ๐Ÿ› ๏ธ Manual Controls Access memory management tools directly: ```typescript // Get current memory usage const usage = optimizedClient.memoryGuard.getMemoryUsage(); console.log(`Memory: ${usage.heapUsed}MB`); // Force memory cleanup optimizedClient.memoryGuard.forceCleanup(); // Manual restart await optimizedClient.memoryGuard.restart(); ``` ### Example Bot Commands ```typescript optimizedClient.on('messageCreate', (message) => { if (message.content === '!memory') { const usage = optimizedClient.memoryGuard.getMemoryUsage(); message.reply(`๐Ÿ’พ Memory usage: ${usage.heapUsed}MB / ${maxMemory}MB`); } if (message.content === '!cleanup') { optimizedClient.memoryGuard.forceCleanup(); message.reply('๐Ÿงน Memory cleanup performed!'); } }); ``` ## ๐Ÿ“Š Memory Usage Object The `getMemoryUsage()` method returns: ```typescript { rss: 150, // Resident Set Size (total memory) heapUsed: 85, // Used heap memory heapTotal: 120, // Total heap memory external: 12, // External memory (C++ objects) arrayBuffers: 8 // ArrayBuffer memory } // All values in MB ``` ## ๐Ÿ”” Webhook Alerts Get Discord notifications when memory usage is high: ```typescript const optimizedClient = MemoryGuard.wrap(client, { maxMemory: 256, monitoring: { webhook: 'https://discord.com/api/webhooks/YOUR_WEBHOOK_URL' } }); ``` **Alert Types:** - **Warning (80% of limit)**: Yellow embed with current usage - **Critical (100% of limit)**: Red embed with restart/cleanup action ## ๐Ÿ”„ Restart Behavior When memory limits are exceeded: ### With Process Manager (Recommended) ```bash # Using PM2 pm2 start bot.js --name "discord-bot" pm2 restart discord-bot # Auto-restarts on exit ``` ## ๐Ÿงฉ Sharding Support Discord Optimizer works perfectly with sharded bots: ```typescript // In your shard file const client = new Client({ /* options */ }); const optimizedClient = MemoryGuard.wrap(client, { maxMemory: 256, // Per-shard limit monitoring: { logging: true, interval: 30000 } }); ``` Each shard gets its own optimizer instance with independent memory limits and monitoring. ## ๐Ÿ”ง Troubleshooting ### Bot Not Restarting **Problem**: Bot exits but doesn't restart **Solution**: Use a process manager like PM2 or Docker ```bash # Install PM2 npm install -g pm2 # Start your bot pm2 start bot.js --name "my-bot" # Bot will auto-restart when it exits ``` ## ๐Ÿ“ˆ Performance Impact Discord Optimizer has minimal performance impact: - **Memory overhead**: < 5MB - **CPU impact**: < 1% (during monitoring checks) - **Network impact**: Webhook alerts only (when configured) ## ๐Ÿค Contributing We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md). ### Development Setup ```bash git clone https://github.com/ajauish/discord-optimizer.git cd discord-optimizer npm install npm test ``` ### Running Tests ```bash npm test # Run all tests npm run test:watch # Watch mode npm run build # Build the package ``` ## ๐Ÿ“ License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. **Made with โค๏ธ by [Abdullah Jauish](https://jauish.com)** *Star โญ this repo if Discord Optimizer helped your bot!*