Running a Discord bot without monitoring is flying blind. You won't know it crashed until users complain - and by then, you have already lost engagement. Here is how to monitor properly.
What to Monitor
Uptime
Is your bot connected to Discord? Track connection status and reconnection events. Log every disconnect and how long recovery takes.
Response Time
How fast does your bot process commands? Track the time between receiving an interaction and sending a response. Anything over 3 seconds and Discord shows "interaction failed."
Error Rate
How many commands fail? Track exceptions per command and identify patterns. A sudden spike in errors usually means a broken API endpoint or a dependency issue.
Resource Usage
CPU and memory consumption over time. Memory leaks are common in long-running Node.js bots - track heap usage to catch them early.
Built-In Monitoring
Discord.js Events
client.on('ready', () => {
console.log(`[${new Date().toISOString()}] Bot online - ${client.guilds.cache.size} servers`);
});
client.on('shardDisconnect', (event, shardId) => {
console.error(`[${new Date().toISOString()}] Shard ${shardId} disconnected: ${event.code}`);
});
client.on('shardReconnecting', (shardId) => {
console.log(`[${new Date().toISOString()}] Shard ${shardId} reconnecting...`);
});
client.on('error', (error) => {
console.error(`[${new Date().toISOString()}] Client error:`, error);
});
Command Performance Tracking
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const start = performance.now();
try {
await handleCommand(interaction);
} catch (error) {
console.error(`Command ${interaction.commandName} failed:`, error);
} finally {
const duration = performance.now() - start;
console.log(`Command ${interaction.commandName}: ${duration.toFixed(0)}ms`);
}
});
Process Management with PM2
PM2 is the standard for Node.js process management on Linux servers:
# Start with PM2
pm2 start index.js --name "my-bot"
# Enable auto-restart on crash
pm2 startup
pm2 save
# Monitor in real-time
pm2 monit
# View logs
pm2 logs my-bot
PM2 automatically restarts your bot on crashes and provides basic CPU/memory monitoring.
External Uptime Monitoring
For critical bots, add external monitoring that checks from outside your server:
- Add a simple HTTP health endpoint to your bot
- Use a free uptime monitor (UptimeRobot, Better Stack) to ping it every 1-5 minutes
- Configure alerts via Discord webhook, email, or SMS
const http = require('http');
http.createServer((req, res) => {
if (req.url === '/health') {
const status = client.ws.status === 0 ? 200 : 503;
res.writeHead(status);
res.end(JSON.stringify({
status: client.ws.status === 0 ? 'healthy' : 'unhealthy',
uptime: process.uptime(),
guilds: client.guilds.cache.size,
ping: client.ws.ping
}));
}
}).listen(3000);
Alerting on Discord
Send monitoring alerts to a private Discord channel:
async function sendAlert(message) {
const webhook = new WebhookClient({ url: process.env.ALERT_WEBHOOK_URL });
await webhook.send({
content: `⚠️ **Bot Alert**: ${message}`,
username: 'Bot Monitor'
});
}
Memory Leak Detection
Node.js bots commonly develop memory leaks over time:
setInterval(() => {
const used = process.memoryUsage();
console.log(`Memory: RSS ${(used.rss / 1024 / 1024).toFixed(1)}MB, Heap ${(used.heapUsed / 1024 / 1024).toFixed(1)}MB`);
if (used.rss > 500 * 1024 * 1024) { // 500MB threshold
sendAlert('Memory usage exceeds 500MB - possible leak');
}
}, 60000); // Check every minute
Hosting Requirements
Monitoring adds minimal overhead to your bot, but reliable hosting is the foundation. Choose a provider with guaranteed uptime and NVMe SSDs for fast logging. The Netherlands is an excellent location for Discord bots - low latency to Discord's EU infrastructure.
Proper monitoring turns "the bot is down again" into proactive maintenance. Set it up once and you will catch issues before your users do.
