Bot Telegram - Perfex AI
Inicio Documentación Módulo AI Documento

Bot Telegram - Perfex AI

MD 8 secciones
Resumen

Documentación interna del módulo Perfex AI [hash:f42cecfea7d97418226121f2cab74516]

# Bot Telegram - Perfex AI

Sección 1
**Controladores:** `Telegram.php`, `Telegram_webhook.php` | **Vista:** `telegram/settings.php`

---

## Arquitectura

Sección 2
El bot Telegram se conecta al CRM via webhook. Cuando un usuario envía un mensaje al bot, Telegram hace POST al webhook del CRM, que procesa el mensaje con la IA y responde.

## Componentes

Sección 3
| Componente | Archivo | Función |
|------------|---------|---------|
| Settings UI | `controllers/Telegram.php` | Configuración del bot en admin |
| Webhook Handler | `controllers/Telegram_webhook.php` | Recibe y procesa mensajes |
| Settings View | `views/telegram/settings.php` | Interfaz de configuración |
| Logs | `tblperfex_ai_webhook_logs` | Registro de webhooks recibidos |

## Configuración (Settings)

Sección 4
| Setting | Descripción | Default |
|---------|-------------|---------|
| `telegram_enabled` | Bot activo/inactivo | 0 |
| `telegram_bot_token` | Token del bot (@BotFather) | - |
| `telegram_bot_username` | Username del bot | - |
| `telegram_ai_provider` | Proveedor IA (gemini/claude) | gemini |
| `telegram_model` | Modelo Gemini para Telegram | - |
| `telegram_claude_model` | Modelo Claude para Telegram | - |
| `telegram_system_prompt` | System prompt personalizado | - |
| `telegram_tools_enabled` | Herramientas CRM activas | 0 |
| `telegram_welcome_message` | Mensaje de bienvenida | - |
| `telegram_rate_limit` | Límite de mensajes/minuto | - |
| `telegram_group_respond_all` | Responder a todos en grupos | 0 |
| `telegram_staff_user` | Staff ID para operaciones CRM | - |

## Flujo del Webhook

Sección 5
1. **Telegram** envía POST con el update al webhook URL
2. **Telegram_webhook** verifica el token y parsea el mensaje
3. Si es comando (`/start`, `/help`) → respuesta predefinida
4. Si es mensaje de texto:
a. Verifica rate limit
b. Carga contexto (KB si está habilitada)
c. Envía a la IA (Gemini o Claude según config)
d. Si `telegram_tools_enabled` → la IA puede ejecutar herramientas CRM
e. Envía respuesta al usuario via Telegram API
5. Log en `tblperfex_ai_webhook_logs`

## Health Check

Sección 6
El cron `perfex_ai_health_check_cron` verifica cada 30 minutos:
- Que el webhook esté configurado (`getWebhookInfo`)
- Que no haya errores de webhook (`last_error_message`)
- Si detecta problemas → notificación al admin (staff_id=1)

## Seguridad

Sección 7
- Webhook URL contiene el token como verificación
- CSRF excluido para el endpoint del webhook
- Rate limiting por usuario
- Solo staff autorizado puede configurar

## Documentos Relacionados

Sección 8
- [Arquitectura](modulo_arquitectura.md) - Estructura general
- [Configuración](modulo_configuracion.md) - Todos los settings
- [Cron Jobs](modulo_cron_jobs.md) - Health check del bot