# 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!*