6.8 KiB
🤖 Telegram Bot Webhook Integration
Dokumentasi untuk integrasi Telegram Bot webhook dengan API.
📋 Overview
Webhook Telegram Bot terintegrasi dengan Fast API untuk mengecek tagihan PDAM melalui bot Telegram.
🚀 Setup
1. Konfigurasi Environment
Pastikan konfigurasi di .env sudah benar:
# Telegram API Configuration
TELEGRAM_BOT_TOKEN=8325211525:AAGPN-Ko2UZr-OIshu54jvi_7wzaMClR8SA
# Fast API Configuration (for Telegram Bot)
FAST_API_CLIENT_ID=FAS_1753810437_4ff75b
FAST_API_CLIENT_SECRET=d286ae4f60902d63b72854a38cdaeb9436c6e011f99ad4cf57e512fd6573f711
# Base URL (untuk memanggil Fast API)
BASE_URL=https://api.wipay.id
2. Set Webhook di Telegram
Set webhook URL ke endpoint API:
Windows (CMD/PowerShell):
curl -X POST "https://api.telegram.org/bot8325211525:AAGPN-Ko2UZr-OIshu54jvi_7wzaMClR8SA/setWebhook" -d "url=https://api.wipay.id/telegram/webhook"
Linux/Mac:
curl -X POST "https://api.telegram.org/bot<BOT_TOKEN>/setWebhook" \
-d "url=https://api.wipay.id/telegram/webhook"
Atau gunakan browser (Paling Mudah):
https://api.telegram.org/bot8325211525:AAGPN-Ko2UZr-OIshu54jvi_7wzaMClR8SA/setWebhook?url=https://api.wipay.id/telegram/webhook
PowerShell (Alternatif):
Invoke-WebRequest -Uri "https://api.telegram.org/bot8325211525:AAGPN-Ko2UZr-OIshu54jvi_7wzaMClR8SA/setWebhook?url=https://api.wipay.id/telegram/webhook" -Method POST
3. Verifikasi Webhook
Cek status webhook:
curl "https://api.telegram.org/bot<BOT_TOKEN>/getWebhookInfo"
📍 Endpoint
POST /telegram/webhook
Endpoint untuk menerima update dari Telegram.
Request:
- Method:
POST - Content-Type:
application/json - Body: Telegram Update JSON (dikirim otomatis oleh Telegram)
Response:
{
"status": "ok"
}
🎯 Fitur Bot
Commands
- /start - Memulai bot dan menampilkan menu utama
- /cekid - Menampilkan ID Telegram user
- /tagihan - Memulai proses cek tagihan
Menu Inline
- Cek Tagihan - Memulai proses cek tagihan
- Cek ID Telegram - Menampilkan ID Telegram user
- Bantuan - Menampilkan daftar perintah
Flow Cek Tagihan
- User klik "Cek Tagihan" atau ketik
/tagihan - Bot meminta nomor pelanggan
- User memasukkan nomor pelanggan (contoh:
059912) - Bot memanggil Fast API
/fast/check_bill - Bot menampilkan hasil tagihan
📁 File Structure
tim-backend/timo.wipay.id_api/
├── src/
│ ├── Controllers/
│ │ └── TelegramBotController.php # Controller untuk webhook
│ └── Helpers/
│ ├── TelegramHelper.php # Helper untuk Telegram API
│ └── SessionHelper.php # Helper untuk session management
├── storage/
│ └── telegram_sessions.json # File session (auto-generated)
└── logs/
└── telegram_bot.log # Log bot (auto-generated)
🔧 Komponen
TelegramBotController
Controller utama yang menangani webhook:
webhook()- Entry point untuk webhookhandleCallbackQuery()- Handle inline button clickshandleMessage()- Handle text messageshandlePelangganInput()- Handle nomor pelanggan input
TelegramHelper
Helper untuk interaksi dengan Telegram API:
sendText()- Kirim pesan tekssendMenu()- Kirim pesan dengan inline keyboardanswerCallback()- Jawab callback querycleanUtf8()- Clean UTF-8 textsafe()- Escape HTMLlog()- Logging
SessionHelper
Helper untuk session management (file-based):
getSession()- Ambil sessionsetSession()- Set sessionclearSession()- Hapus sessionloadSessions()- Load semua sessionssaveSessions()- Save semua sessions
📊 Response Format
Fast API Response
Bot memanggil /fast/check_bill dan memproses response:
{
"status": "success",
"data": {
"errno": 0,
"error": "",
"recordsTotal": 1,
"data": [
{
"pel_nama": "EKSAN HADI",
"pel_alamat": "PERUM AGNIA D1 NO.17",
"rek_bln": 12,
"rek_thn": 2025,
"pemakaian": 11,
"rek_total": 82740,
"rek_ket": "Tagihan Air"
}
]
}
}
Error Cases
- errno = 5: Wajib bayar di loket
- recordsTotal = 0: Tidak ada tagihan
- recordsTotal = 1: Satu tagihan (tampilkan detail)
- recordsTotal > 1: Multiple tagihan (tampilkan list)
🔍 Logging
Semua aktivitas bot di-log ke file:
logs/telegram_bot.log
Format log:
[2026-01-26 10:30:45] RAW UPDATE: {...}
[2026-01-26 10:30:45] SEND TEXT - Chat ID: 123456, HTTP: 200, Response: {...}
🛡️ Security
- No Authentication Required: Webhook endpoint tidak memerlukan autentikasi (Telegram akan mengirim request langsung)
- Fast API Authentication: Bot menggunakan API Key untuk memanggil Fast API
- Session Management: Session disimpan di file system (bisa diubah ke database jika diperlukan)
🧪 Testing
Test Webhook Lokal
- Install ngrok:
ngrok http 8000
- Set webhook ke ngrok URL:
curl -X POST "https://api.telegram.org/bot<BOT_TOKEN>/setWebhook" \
-d "url=https://your-ngrok-url.ngrok.io/telegram/webhook"
- Test dengan mengirim pesan ke bot
Test dengan cURL
curl -X POST "http://localhost:8000/telegram/webhook" \
-H "Content-Type: application/json" \
-d '{
"update_id": 123456789,
"message": {
"message_id": 1,
"from": {
"id": 123456789,
"first_name": "Test",
"username": "testuser"
},
"chat": {
"id": 123456789,
"type": "private"
},
"date": 1234567890,
"text": "/start"
}
}'
📝 Notes
-
Session Storage: Saat ini menggunakan file-based storage. Untuk production, pertimbangkan menggunakan database atau Redis.
-
Error Handling: Bot akan menampilkan pesan error yang user-friendly jika terjadi masalah.
-
Rate Limiting: Telegram memiliki rate limiting sendiri. Tidak perlu implement rate limiting tambahan.
-
Webhook Security: Untuk production, pertimbangkan untuk memverifikasi signature dari Telegram (belum diimplementasikan).
🔄 Migration dari Script PHP Lama
Script PHP lama sudah di-migrate ke struktur Slim Framework:
- ✅ Semua fungsi sudah di-convert ke class methods
- ✅ Session management menggunakan helper class
- ✅ Telegram API calls menggunakan helper class
- ✅ Logging terintegrasi dengan sistem logging
- ✅ Error handling lebih robust
🎯 Next Steps
- Database Session: Migrate session dari file ke database
- Webhook Verification: Implement signature verification
- More Commands: Tambahkan command lain sesuai kebutuhan
- Payment Integration: Integrate dengan payment flow jika diperlukan
Last Updated: 2026-01-26 Status: ✅ Ready for Production