Bot Telegram untuk Monitoring Server dengan Node.js dan Telegraf

Memantau kondisi server secara real-time adalah kebutuhan penting bagi setiap administrator sistem dan pengembang. Dengan bot Telegram, Anda bisa memantau CPU, RAM, disk, dan menerima notifikasi alert kapan saja dan di mana saja langsung dari ponsel. Tutorial ini membahas cara membuat bot Telegram monitoring server yang lengkap dan profesional menggunakan Node.js dan Telegraf.

Mengapa Menggunakan Bot Telegram untuk Monitoring?

Telegram menawarkan API yang sangat powerful dan gratis untuk membuat bot. Keunggulan menggunakan bot Telegram untuk monitoring server:

  • Real-time: Notifikasi langsung dikirim ke chat Telegram dalam hitungan detik
  • Akses Mudah: Telegram tersedia di semua platform — mobile, desktop, web
  • Gratis: Tidak ada biaya untuk mengirim pesan melalui bot
  • Format Kaya: Mendukung teks, gambar, dan tombol inline
  • Grup Monitoring: Bisa menambahkan bot ke grup untuk monitoring kolaboratif

Prasyarat

  1. Telegram Account — Untuk membuat bot dan menerima notifikasi
  2. Node.js 18+ — Untuk menjalankan bot
  3. VPS atau Server — Server yang ingin dipantau
  4. npm — Package manager Node.js

Langkah 1: Buat Bot BotFather

  1. Buka Telegram dan cari @BotFather
  2. Kirim perintah /newbot
  3. Ikuti instruksi:
  • Masukkan nama bot (contoh: Server Monitor Bot)
  • Masukkan username bot (contoh: MyServerMonitorBot)
  1. BotFather akan memberikan API Token. Simpan token ini dengan aman.

Contoh token:

kode
7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Langkah 2: Setup Project

Buat folder project dan instal dependensi:

bash
mkdir server-monitor-bot && cd server-monitor-bot
npm init -y
npm install telegraf node-fetch os-family

Tambahkan dependensi tambahan untuk monitoring sistem:

bash
npm install systeminformation express

Langkah 3: Struktur Project

kode
server-monitor-bot/
├── index.js           # File utama bot
├── commands/
│   ├── status.js      # Command /status
│   ├── cpu.js         # Command /cpu
│   ├── memory.js      # Command /memory
│   ├── disk.js        # Command /disk
│   └── alert.js       # Command /alert
├── config.js          # Konfigurasi
└── package.json

Langkah 4: File Konfigurasi

Buat config.js:

javascript
const CONFIG = {
  botToken: process.env.BOT_TOKEN || 'YOUR_BOT_TOKEN_HERE',
  chatId: process.env.CHAT_ID || 'YOUR_CHAT_ID',
  checkInterval: 5 * 60 * 1000, // 5 menit
  thresholds: {
    cpu: 80,        // Alert jika CPU > 80%
    memory: 85,     // Alert jika RAM > 85%
    disk: 90,       // Alert jika Disk > 90%
  },
};

module.exports = CONFIG;

Simpan variabel lingkungan di file .env:

env
BOT_TOKEN=7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
CHAT_ID=123456789

Langkah 5: Membuat Bot Utama

Buat file index.js:

javascript
import { Telegraf } from 'telegraf';
import { exec } from 'child_process';
import { stat } from 'fs/promises';
import CONFIG from './config.js';

const bot = new Telegraf(CONFIG.botToken);

// === HANDLER COMMAND ===

// /start - Sambutan dan menu
bot.start(async (ctx) => {
  const welcomeMessage = `
🤖 *Server Monitor Bot*

Halo! Saya adalah bot monitoring server Anda.

Berikut command yang tersedia:
/start  — Sambutan dan menu
/status — Status keseluruhan server
/cpu    — Penggunaan CPU
/memory — Penggunaan RAM
/disk   — Penggunaan Disk
/alert  — Atur threshold alert
/network — Status Jaringan
/uptime — Uptime server

Ketik /help untuk informasi lebih lanjut.
  `;
  await ctx.reply(welcomeMessage, { parse_mode: 'Markdown' });
});

// /status — Status lengkap server
bot.command('status', async (ctx) => {
  try {
    const status = await getServerStatus();
    const message = formatStatus(status);
    await ctx.reply(message, { parse_mode: 'Markdown' });
  } catch (error) {
    await ctx.reply('❌ Terjadi kesalahan saat mengambil data server.');
  }
});

// /cpu — Info CPU
bot.command('cpu', async (ctx) => {
  try {
    const cpuInfo = await getCPUInfo();
    await ctx.reply(cpuInfo, { parse_mode: 'Markdown' });
  } catch (error) {
    await ctx.reply('❌ Tidak bisa mengambil info CPU.');
  }
});

// /memory — Info RAM
bot.command('memory', async (ctx) => {
  try {
    const memInfo = await getMemoryInfo();
    await ctx.reply(memInfo, { parse_mode: 'Markdown' });
  } catch (error) {
    await ctx.reply('❌ Tidak bisa mengambil info memory.');
  }
});

// /disk — Info Disk
bot.command('disk', async (ctx) => {
  try {
    const diskInfo = await getDiskInfo();
    await ctx.reply(diskInfo, { parse_mode: 'Markdown' });
  } catch (error) {
    await ctx.reply('❌ Tidak bisa mengambil info disk.');
  }
});

// /uptime — Uptime server
bot.command('uptime', async (ctx) => {
  try {
    const uptime = await getUptime();
    await ctx.reply(`⏱️ *Uptime Server:*\n\n${uptime}`, { parse_mode: 'Markdown' });
  } catch (error) {
    await ctx.reply('❌ Tidak bisa mengambil uptime.');
  }
});

// /network — Status jaringan
bot.command('network', async (ctx) => {
  try {
    const netInfo = await getNetworkInfo();
    await ctx.reply(netInfo, { parse_mode: 'Markdown' });
  } catch (error) {
    await ctx.reply('❌ Tidak bisa mengambil info jaringan.');
  }
});

// /help — Bantuan
bot.command('help', async (ctx) => {
  await ctx.reply(`
📋 *Daftar Command:*

/status — Status keseluruhan server
/cpu — Detail penggunaan CPU
/memory — Detail penggunaan RAM
/disk — Detail penggunaan disk
/uptime — Lama server menyala
/network — Status koneksi jaringan
/alert — Atur sistem alert

*Format Alert:*
CPU > 80%, RAM > 85%, Disk > 90%

Ketik /start untuk kembali ke menu utama.
  `, { parse_mode: 'Markdown' });
});

Langkah 6: Fungsi Monitoring Sistem

Buat file monitor.js:

javascript
import { exec } from 'child_process';
import si from 'systeminformation';

// === FUNGSI UTAMA ===

export async function getServerStatus() {
  const [cpu, memory, disk, uptime, network] = await Promise.all([
    getCPUInfo(),
    getMemoryInfo(),
    getDiskInfo(),
    getUptime(),
    getNetworkInfo(),
  ]);

  return { cpu, memory, disk, uptime, network };
}

export async function getCPUInfo() {
  const currentLoad = await si.currentLoad();
  const cpuInfo = await si.cpu();
  const temperatures = await si.cpuTemperature ? await si.cpuTemperature() : null;

  const loadPercent = Math.round(currentLoad.currentLoad);
  const status = loadPercent > 80 ? '🔴 OVERLOAD' : loadPercent > 60 ? '🟡 HIGH' : '🟢 NORMAL';

  let tempInfo = '';
  if (temperatures && temperatures.main) {
    tempInfo = `\n🌡️ *Suhu CPU:* ${temperatures.main}°C`;
  }

  return `*💻 CPU Information*

*Penggunaan:* ${loadPercent}% ${status}
*Core:* ${cpuInfo.count} inti
*Model:* ${cpuInfo.brand}
*Kecepatan:* ${cpuInfo.speed} MHz${tempInfo}`;
}

export async function getMemoryInfo() {
  const mem = await si.mem();
  const usedPercent = Math.round((mem.used / mem.total) * 100);
  const status = usedPercent > 85 ? '🔴 CRITICAL' : usedPercent > 70 ? '🟡 WARNING' : '🟢 NORMAL';

  return `*🧠 Memory Information*

*Total:* ${formatBytes(mem.total)}
*Terpakai:* ${formatBytes(mem.used)}
*Free:* ${formatBytes(mem.free)}
*Penggunaan:* ${usedPercent}% ${status}

*Detail:*
• Active: ${formatBytes(mem.active)}
• Available: ${formatBytes(mem.available)}
• Buffer: ${formatBytes(mem.buffer)}
• Cached: ${formatBytes(mem.cached)}`;
}

export async function getDiskInfo() {
  const filesystem = await si.fsSize();
  const disk = filesystem[0] || {};
  const usedPercent = Math.round((disk.use / 100) * 100);
  const status = usedPercent > 90 ? '🔴 CRITICAL' : usedPercent > 75 ? '🟡 WARNING' : '🟢 NORMAL';

  let output = `*💾 Disk Information*

*Total:* ${formatBytes(disk.size)}
*Terpakai:* ${formatBytes(disk.used)}
*Free:* ${formatBytes(disk.available)}
*Penggunaan:* ${disk.use}% ${status}

*Filesystem:* ${disk.mount}`;

  // Detail semua partition
  if (filesystem.length > 1) {
    output += `\n\n*Partisi Lain:*`;
    for (let i = 1; i < filesystem.length; i++) {
      const p = filesystem[i];
      output += `\n• ${p.mount}: ${formatBytes(p.size)} (${p.use}% terpakai)`;
    }
  }

  return output;
}

export async function getUptime() {
  const uptimeSec = await si.system.time();
  const totalSeconds = uptimeSec;
  const days = Math.floor(totalSeconds / 86400);
  const hours = Math.floor((totalSeconds % 86400) / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;

  return `*⏱️ Uptime Server*

🕐 Sudah menyala selama:
• ${days} hari, ${hours} jam, ${minutes} menit, ${seconds} detik`;
}

export async function getNetworkInfo() {
  const network = await si.networkStats();
  const interfaces = await si.networkInterfaces();

  let output = '*🌐 Network Information*';

  for (const iface of interfaces) {
    if (iface.ip4 && !iface.ip4.includes('127.0.0.1')) {
      const stat = network.find(n => n.iface === iface.iface);
      output += `\n\n*${iface.iface}:*
• IP: ${iface.ip4}
• Netmask: ${iface.mac ? iface.mac : 'N/A'}
• MAC: ${iface.mac}`;
      if (stat) {
        output += `\n• RX: ${formatBytes(stat.rx_bytes)} / TX: ${formatBytes(stat.tx_bytes)}`;
      }
    }
  }

  return output;
}

// === FUNGSI BANTU ===

export function formatBytes(bytes) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// === FUNGSI ALERT ===

export async function checkAlerts() {
  const alerts = [];
  const cpuLoad = (await si.currentLoad()).currentLoad * 100;
  const mem = await si.mem();
  const memUsedPercent = (mem.used / mem.total) * 100;
  const disk = await si.fsSize();
  const diskUsedPercent = disk[0] ? disk[0].use : 0;

  if (cpuLoad > CONFIG.thresholds.cpu) {
    alerts.push(`🔴 *ALERT CPU:* ${Math.round(cpuLoad)}% (threshold: ${CONFIG.thresholds.cpu}%)`);
  }
  if (memUsedPercent > CONFIG.thresholds.memory) {
    alerts.push(`🔴 *ALERT MEMORY:* ${Math.round(memUsedPercent)}% (threshold: ${CONFIG.thresholds.memory}%)`);
  }
  if (diskUsedPercent > CONFIG.thresholds.disk) {
    alerts.push(`🔴 *ALERT DISK:* ${Math.round(diskUsedPercent)}% (threshold: ${CONFIG.thresholds.disk}%)`);
  }

  return alerts;
}

export function formatStatus(status) {
  const { cpu, memory, disk, uptime, network } = status;
  return `*📊 Server Status Summary*

${cpu}

${memory}

${disk}

${uptime}

${network}

*Status:* ${isAllNormal(cpu, memory, disk) ? '✅ Semua normal' : '⚠️ Perlu perhatian'}`;
}

function isAllNormal(cpu, memory, disk) {
  const cpuLoad = parseInt(cpu.match(/\d+/)?.[0] || '0');
  const memUsed = parseInt(memory.match(/\d+(?=%)/)?.[0] || '0');
  const diskUsed = parseInt(disk.match(/\d+(?=%)/)?.[0] || '0');
  return cpuLoad < 80 && memUsed < 85 && diskUsed < 90;
}

Langkah 7: Sistem Alert Otomatis

Tambahkan sistem monitoring berkala di index.js:

javascript
import { checkAlerts } from './monitor.js';

// Periodic alert check
setInterval(async () => {
  try {
    const alerts = await checkAlerts();
    if (alerts.length > 0 && CONFIG.chatId) {
      const alertMessage = alerts.join('\n\n');
      await bot.telegram.sendMessage(CONFIG.chatId, `🚨 *Server Alert!*\n\n${alertMessage}`, {
        parse_mode: 'Markdown',
      });
    }
  } catch (error) {
    console.error('Alert check failed:', error);
  }
}, CONFIG.checkInterval);

Langkah 8: Start Bot

Buat index.js lengkap untuk menjalankan bot:

javascript
import { Telegraf } from 'telegraf';
import CONFIG from './config.js';
import * as commands from './commands/index.js';

const bot = new Telegraf(CONFIG.botToken);

// Register all commands
bot.start(commands.start);
bot.command('status', commands.status);
bot.command('cpu', commands.cpu);
bot.command('memory', commands.memory);
bot.command('disk', commands.disk);
bot.command('uptime', commands.uptime);
bot.command('network', commands.network);
bot.command('alert', commands.alert);
bot.command('help', commands.help);

// Start bot
bot.launch();
console.log('🤖 Bot Monitoring Server sudah aktif!');

// Graceful shutdown
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));

Langkah 9: Deploy Bot dengan PM2

Agar bot berjalan 24/7, gunakan PM2:

bash
npm install -g pm2
pm2 start index.js --name "server-monitor-bot" --env production
pm2 save
pm2 startup

Untuk melihat log:

bash
pm2 logs server-monitor-bot

Untuk restart:

bash
pm2 restart server-monitor-bot

Langkah 10: Buat Script Setup Lengkap

Buat setup.sh untuk instalasi mudah:

bash
#!/bin/bash
echo "=== Server Monitor Bot Setup ==="

# Update system
apt update && apt upgrade -y

# Install Node.js
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs

# Clone repository
git clone https://github.com/username/server-monitor-bot.git
cd server-monitor-bot

# Install dependencies
npm install

# Copy env file
cp .env.example .env
echo "Edit .env file dengan token Anda!"

# Install PM2
npm install -g pm2

# Start bot
pm2 start index.js --name "server-monitor-bot"
pm2 save
pm2 startup

echo "✅ Setup selesai! Bot sudah berjalan."

Kesimpulan

Bot Telegram monitoring server menggunakan Node.js dan Telegraf memberikan solusi yang praktis dan efektif untuk memantau kesehatan server. Dengan fitur status lengkap, alert otomatis, dan dukungan command yang kaya, Anda selalu mendapatkan informasi terkini tentang kondisi server langsung dari ponsel.

Langkah kunci yang perlu diingat:

  • Simpan bot token dengan aman dan jangan dipublikasikan
  • Atur threshold alert sesuai kapasitas server Anda
  • Deploy bot dengan PM2 agar selalu berjalan 24/7
  • Periksa log secara berkala untuk memastikan bot berfungsi optimal
  • Tambahkan fitur monitoring baru sesuai kebutuhan seperti uptime check, response time, atau monitoring layanan tertentu

Dengan tutorial ini, Anda dapat membangun sistem monitoring server yang profesional dan andal menggunakan teknologi yang gratis dan mudah diakses.

---

Bot ini dapat dikembangkan lebih lanjut untuk monitoring database, aplikasi web, dan layanan lainnya.

Artikel Terkait