discord-optimizer
Version:
Reduce Discord.js bot RAM usage with automatic optimization and restart capabilities
253 lines (186 loc) โข 6.65 kB
Markdown
# Discord Optimizer
[](https://badge.fury.io/js/discord-optimizer)
[](https://opensource.org/licenses/MIT)
[](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!*