# Telegram Addon - Activation Guide

## ✅ Status: ACTIVATED

Telegram addon telah berhasil diaktifkan!

---

## 🔧 Perubahan yang Dilakukan

### 1. **env.js**
```javascript
const addON = ["AI_BOT", "QR", "TELEGRAM"]; // Added "TELEGRAM"
```

### 2. **tele.js** - Full Implementation
- ✅ Session management (create, verify, connect, disconnect, delete)
- ✅ OTP authentication via phone number
- ✅ Message sending/receiving
- ✅ Chat/dialogs retrieval
- ✅ Auto-reconnect on app start
- ✅ Database integration (`telegram_session` table)

### 3. **Database Table**
Table `telegram_session` sudah ada di database dengan kolom:
- `id`, `uid`, `status`, `session_id`, `title`
- `api_id`, `api_hash`, `data`, `session`, `createdAt`

---

## 📋 Cara Menggunakan

### Step 1: Setup Telegram API Credentials

1. Buka **Admin Panel** atau edit tabel `web_private`:

```sql
UPDATE web_private SET 
  teleAppId = 'YOUR_TELEGRAM_APP_ID',
  teleHash = 'YOUR_TELEGRAM_APP_HASH'
WHERE id = 1;
```

**Cara dapatkan API credentials:**
1. Kunjungi: https://my.telegram.org/apps
2. Login dengan nomor Telegram
3. Create new application
4. Copy **App api_id** dan **App api_hash**

---

### Step 2: Restart Server

```bash
# Stop server (Ctrl+C)
npm start
```

**Console harus show:**
```
📱 Initializing Telegram sessions...
   No active Telegram sessions found
```

---

### Step 3: Create Telegram Session via API

**Endpoint:** `POST /api/telegram/send_otp`

**Headers:**
```
Content-Type: application/json
Authorization: Bearer YOUR_JWT_TOKEN
```

**Body:**
```json
{
  "mobile": "6281234567890",
  "title": "My Telegram",
  "sessionId": "tg_001"
}
```

**Response:**
```json
{
  "success": true,
  "message": "OTP sent successfully. Please verify with the code.",
  "sessionId": "tg_001"
}
```

---

### Step 4: Verify OTP Code

**Endpoint:** `POST /api/telegram/verify_otp`

**Body:**
```json
{
  "sessionId": "tg_001",
  "code": "12345"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Session verified and connected successfully",
  "profile": {
    "id": "123456789",
    "firstName": "John",
    "lastName": "Doe",
    "username": "johndoe",
    "phone": "6281234567890"
  }
}
```

---

### Step 5: Send Message

**Endpoint:** `POST /api/telegram/send_message`

**Body:**
```json
{
  "sessionId": "tg_001",
  "chatId": "987654321",
  "message": "Hello from WhatsApp CRM!"
}
```

---

## 📡 API Endpoints

| Method | Endpoint | Function |
|--------|----------|----------|
| POST | `/api/telegram/send_otp` | Create session & send OTP |
| POST | `/api/telegram/verify_otp` | Verify OTP code |
| GET | `/api/telegram/sessions` | Get all user sessions |
| GET | `/api/telegram/session_status/:id` | Get session status |
| POST | `/api/telegram/reconnect` | Reconnect session |
| POST | `/api/telegram/disconnect` | Disconnect session |
| GET/DELETE | `/api/telegram/session/:id` | Delete session |
| POST | `/api/telegram/send_message` | Send message |
| GET | `/api/telegram/chats/:id` | Get chats/dialogs |
| GET | `/api/telegram/check_status/:id` | Check if connected |

---

## 🔄 Session Lifecycle

```
PENDING → ACTIVE → DISCONNECTED → INACTIVE
   ↓        ↓         ↓            ↓
OTP Sent  Verified  Disconnected  Deleted
```

---

## 🐛 Troubleshooting

### Error: "Telegram creds are required from admin"
**Solusi:** Set `teleAppId` dan `teleHash` di tabel `web_private`

### Error: "PHONE_NUMBER_INVALID"
**Solusi:** Gunakan format internasional dengan `+` (contoh: `+6281234567890`)

### Error: "PHONE_CODE_INVALID"
**Solusi:** OTP code salah atau expired. Kirim ulang OTP.

### Session tidak connect setelah restart
**Solusi:** 
```sql
-- Cek status session
SELECT * FROM telegram_session WHERE session_id = 'tg_001';

-- Jika status bukan ACTIVE, update manual
UPDATE telegram_session SET status = 'ACTIVE' WHERE session_id = 'tg_001';
```

---

## 📦 Dependencies

Package `telegram` sudah terinstall (`telegram@^2.26.22` dalam package.json).

Tidak perlu install tambahan!

---

**Last Updated:** April 9, 2026  
**WhatsApp CRM Version:** 5.9
