Setup Telegram Bot dari Nol: Dari Daftar Hingga Auto-Reply

Telegram bot adalah tools powerful untuk automasi. Dari customer service otomatis sampai jualan produk digital — semuanya bisa di-handle bot. Tutorial ini ajarkan cara membuat Telegram bot dari nol menggunakan JavaScript.

Step 1: Daftar Bot di BotFather

  1. Buka Telegram, cari @BotFather
  2. Kirim /newbot
  3. Berikan nama bot (contoh: "LYID Support Bot")
  4. Berikan username (harus berakhir dengan "bot", contoh: "lyid_support_bot")
  5. Simpan token yang diberikan (contoh: 123456789:ABCdefGHIjklMNOpqrsTUVwxyz)
💡 Tips: Token ini adalah "password" bot kamu. Jangan pernah share atau commit ke git. Simpan di file .env.

Step 2: Setup Project

# Buat folder project
mkdir my-telegram-bot
cd my-telegram-bot

# Init Node.js project
npm init -y

# Install dependency
npm install node-telegram-bot-api dotenv

# Buat file .env
echo "BOT_TOKEN=your_token_here" > .env

Step 3: Bot Dasar dengan Auto-Reply

// bot.js
require('dotenv').config();
const TelegramBot = require('node-telegram-bot-api');

const bot = new TelegramBot(process.env.BOT_TOKEN, { polling: true });

// Handle /start command
bot.onText(/\/start/, (msg) => {
  const chatId = msg.chat.id;
  const name = msg.from.first_name;
  
  bot.sendMessage(chatId, 
    `Halo ${name}! 👋\n\n` +
    `Selamat datang di bot kami.\n\n` +
    `Perintah yang tersedia:\n` +
    `/help - Bantuan\n` +
    `/produk - Lihat produk\n` +
    `/status - Cek status`
  );
});

// Handle /help command
bot.onText(/\/help/, (msg) => {
  bot.sendMessage(msg.chat.id, 
    'Ini adalah bot bantuan kami.\n\n' +
    'Hubungi admin: @username'
  );
});

// Handle semua pesan teks (auto-reply)
bot.on('message', (msg) => {
  if (msg.text && !msg.text.startsWith('/')) {
    bot.sendMessage(msg.chat.id, 
      'Terima kasih atas pesannya! Tim kami akan segera merespons.'
    );
  }
});

console.log('Bot berjalan...');

Step 4: Inline Keyboard (Tombol Interaktif)

Inline keyboard membuat bot lebih interaktif. User bisa klik tombol tanpa mengetik:

// Handle /produk command dengan inline keyboard
bot.onText(/\/produk/, (msg) => {
  const chatId = msg.chat.id;
  
  bot.sendMessage(chatId, 'Pilih produk yang kamu minati:', {
    reply_markup: {
      inline_keyboard: [
        [
          { text: '🤖 Bot Airdrop', callback_data: 'product_airdrop' },
          { text: '🌐 Jasa Website', callback_data: 'product_web' }
        ],
        [
          { text: '📚 Paket Hemat', callback_data: 'product_bundle' }
        ]
      ]
    }
  });
});

// Handle callback dari inline keyboard
bot.on('callback_query', (query) => {
  const chatId = query.message.chat.id;
  const data = query.data;
  
  if (data === 'product_airdrop') {
    bot.sendMessage(chatId, 
      '🤖 Bot Airdrop LYID\n\n' +
      'Harga: Rp 100.000 - 150.000\n' +
      'Fitur: Auto-claim, multi-wallet, proxy support\n\n' +
      'Klik /buy untuk membeli'
    );
  }
  
  // Answer callback query (hilangkan loading icon)
  bot.answerCallbackQuery(query.id);
});

Step 5: Database untuk Menyimpan Data

Untuk bot yang serius, kamu butuh database. SQLite adalah pilihan terbaik untuk bot kecil-menengah:

const Database = require('better-sqlite3');
const db = new Database('bot.db');

// Buat tabel users
db.exec(`
  CREATE TABLE IF NOT EXISTS users (
    chat_id INTEGER PRIMARY KEY,
    username TEXT,
    first_name TEXT,
    joined_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    is_premium INTEGER DEFAULT 0
  )
`);

// Simpan user baru
function saveUser(msg) {
  db.prepare(`
    INSERT OR IGNORE INTO users (chat_id, username, first_name)
    VALUES (?, ?, ?)
  `).run(msg.chat.id, msg.from.username, msg.from.first_name);
}

// Cek apakah user premium
function isPremium(chatId) {
  const user = db.prepare('SELECT is_premium FROM users WHERE chat_id = ?')
    .get(chatId);
  return user?.is_premium === 1;
}

Step 6: Deploy ke Server

Bot harus berjalan 24/7. Ada beberapa opsi:

# Deploy dengan PM2 (di PC sendiri)
npm install -g pm2
pm2 start bot.js --name my-bot
pm2 save
pm2 startup  # auto-start saat boot
✅ Selesai! Bot kamu sekarang berjalan 24/7 dan bisa menerima pesan dari siapa saja.

Best Practices

  1. Simpan token di .env — jangan hardcode di source
  2. Handle error — wrap setiap handler dengan try/catch
  3. Rate limiting — jangan spam API Telegram (max 30 msg/detik)
  4. Logging — catat semua interaksi untuk debugging
  5. Graceful shutdown — handle SIGTERM untuk cleanup

Mau Bot Telegram yang Sudah Jadi?

LYID punya bot Telegram untuk berbagai kebutuhan — dari airdrop automation sampai license management.

Lihat Bot di @OG_LYID_bot Lihat Semua Script →
Manday
Manday

Founder LYID — Layer Airdrop ID. Membangun bot automasi crypto sejak 2024.