Files
api-wipay/TELEGRAM_BOT_WEBHOOK.md

267 lines
6.8 KiB
Markdown
Raw Permalink Normal View History

2026-01-26 09:27:28 +07:00
# 🤖 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:
```env
# 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):**
```cmd
curl -X POST "https://api.telegram.org/bot8325211525:AAGPN-Ko2UZr-OIshu54jvi_7wzaMClR8SA/setWebhook" -d "url=https://api.wipay.id/telegram/webhook"
```
**Linux/Mac:**
```bash
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):**
```powershell
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:
```bash
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:**
```json
{
"status": "ok"
}
```
## 🎯 Fitur Bot
### Commands
1. **/start** - Memulai bot dan menampilkan menu utama
2. **/cekid** - Menampilkan ID Telegram user
3. **/tagihan** - Memulai proses cek tagihan
### Menu Inline
1. **Cek Tagihan** - Memulai proses cek tagihan
2. **Cek ID Telegram** - Menampilkan ID Telegram user
3. **Bantuan** - Menampilkan daftar perintah
### Flow Cek Tagihan
1. User klik "Cek Tagihan" atau ketik `/tagihan`
2. Bot meminta nomor pelanggan
3. User memasukkan nomor pelanggan (contoh: `059912`)
4. Bot memanggil Fast API `/fast/check_bill`
5. 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 webhook
- `handleCallbackQuery()` - Handle inline button clicks
- `handleMessage()` - Handle text messages
- `handlePelangganInput()` - Handle nomor pelanggan input
### TelegramHelper
Helper untuk interaksi dengan Telegram API:
- `sendText()` - Kirim pesan teks
- `sendMenu()` - Kirim pesan dengan inline keyboard
- `answerCallback()` - Jawab callback query
- `cleanUtf8()` - Clean UTF-8 text
- `safe()` - Escape HTML
- `log()` - Logging
### SessionHelper
Helper untuk session management (file-based):
- `getSession()` - Ambil session
- `setSession()` - Set session
- `clearSession()` - Hapus session
- `loadSessions()` - Load semua sessions
- `saveSessions()` - Save semua sessions
## 📊 Response Format
### Fast API Response
Bot memanggil `/fast/check_bill` dan memproses response:
```json
{
"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
1. **errno = 5**: Wajib bayar di loket
2. **recordsTotal = 0**: Tidak ada tagihan
3. **recordsTotal = 1**: Satu tagihan (tampilkan detail)
4. **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
1. **No Authentication Required**: Webhook endpoint tidak memerlukan autentikasi (Telegram akan mengirim request langsung)
2. **Fast API Authentication**: Bot menggunakan API Key untuk memanggil Fast API
3. **Session Management**: Session disimpan di file system (bisa diubah ke database jika diperlukan)
## 🧪 Testing
### Test Webhook Lokal
1. Install ngrok:
```bash
ngrok http 8000
```
2. Set webhook ke ngrok URL:
```bash
curl -X POST "https://api.telegram.org/bot<BOT_TOKEN>/setWebhook" \
-d "url=https://your-ngrok-url.ngrok.io/telegram/webhook"
```
3. Test dengan mengirim pesan ke bot
### Test dengan cURL
```bash
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
1. **Session Storage**: Saat ini menggunakan file-based storage. Untuk production, pertimbangkan menggunakan database atau Redis.
2. **Error Handling**: Bot akan menampilkan pesan error yang user-friendly jika terjadi masalah.
3. **Rate Limiting**: Telegram memiliki rate limiting sendiri. Tidak perlu implement rate limiting tambahan.
4. **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
1. **Database Session**: Migrate session dari file ke database
2. **Webhook Verification**: Implement signature verification
3. **More Commands**: Tambahkan command lain sesuai kebutuhan
4. **Payment Integration**: Integrate dengan payment flow jika diperlukan
---
**Last Updated**: 2026-01-26
**Status**: ✅ Ready for Production