Files
lastwar/telegram/webhook/telegram_bot_webhook.php
nickpons666 223c44f1d8 Feature: Agregar selección de idiomas por plataforma (Telegram/Discord)
- Agregar columnas telegram_enabled y discord_enabled a supported_languages
- Nueva interfaz en admin/languages.php con checkboxes para Telegram y Discord
- Los bots ahora solo muestran botones de traducción para los idiomas seleccionados por plataforma
2026-03-10 18:52:30 -06:00

486 lines
21 KiB
PHP
Executable File

<?php
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/env_loader.php';
require_once __DIR__ . '/../../includes/emoji_helper.php';
require_once __DIR__ . '/../TelegramSender.php';
require_once __DIR__ . '/../actions/TelegramActions.php';
require_once __DIR__ . '/../converters/HtmlToTelegramHtmlConverter.php';
require_once __DIR__ . '/../../src/Translate.php';
$botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
$webhookSecret = $_ENV['TELEGRAM_WEBHOOK_TOKEN'] ?? getenv('TELEGRAM_WEBHOOK_TOKEN');
$receivedToken = $_GET['auth_token'] ?? '';
if ($webhookSecret !== $receivedToken) {
http_response_code(403);
exit('Unauthorized');
}
$update = json_decode(file_get_contents('php://input'), true);
if (!$update) {
exit('No update');
}
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - Received update\n", FILE_APPEND);
if (isset($update['callback_query'])) {
$callbackData = $update['callback_query']['data'] ?? 'no data';
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - Callback: $callbackData\n", FILE_APPEND);
}
try {
$pdo = getDbConnection();
$sender = new Telegram\TelegramSender();
$actions = new Telegram\Actions\TelegramActions();
$translator = new src\Translate();
if (isset($update['message'])) {
$message = $update['message'];
$chatId = $message['chat']['id'];
$userId = $message['from']['id'] ?? null;
$text = $message['text'] ?? '';
$caption = $message['caption'] ?? ''; // Caption de foto/video
$username = $message['from']['first_name'] ?? 'Usuario';
registerTelegramUser($pdo, $message['from']);
if (!isExistingTelegramUser($pdo, $userId)) {
sendWelcomeMessage($pdo, $sender, $chatId, $username);
}
// Ignorar stickers puros (sin caption)
if (isset($message['sticker']) && empty($caption)) {
exit('Sticker ignorado');
}
// Ignorar GIFs/animaciones puras (sin caption)
if (isset($message['animation']) && empty($caption)) {
exit('GIF ignorado');
}
// Procesar texto de mensajes regulares (solo si tiene contenido real)
if (!empty($text) && hasRealContent($text)) {
if (str_starts_with($text, '/')) {
handleTelegramCommand($sender, $pdo, $chatId, $userId, $text, $username);
} elseif (str_starts_with($text, '#')) {
$command = ltrim($text, '#');
sendTemplateByCommand($pdo, $sender, $chatId, $command);
} else {
handleTelegramMessage($pdo, $sender, $chatId, $userId, $text);
}
}
// Procesar caption de fotos o videos (solo si tiene contenido real)
elseif (!empty($caption) && hasRealContent($caption)) {
handleTelegramMessage($pdo, $sender, $chatId, $userId, $caption);
}
// Si no hay contenido real (solo emojis, stickers, GIFs), ignorar
} elseif (isset($update['callback_query'])) {
$callbackQuery = $update['callback_query'];
$callbackData = $callbackQuery['data'];
$chatId = $callbackQuery['message']['chat']['id'];
$messageId = $callbackQuery['message']['message_id'];
$inlineMessageId = $callbackQuery['inline_message_id'] ?? null;
$userId = $callbackQuery['from']['id'] ?? '';
error_log("Telegram callback - chatId: $chatId, messageId: $messageId, userId: $userId, callbackData: $callbackData");
handleTelegramCallback($pdo, $sender, $translator, $chatId, $messageId, $inlineMessageId, $callbackQuery['id'], $callbackData);
}
} catch (Exception $e) {
error_log("Telegram Webhook Error: " . $e->getMessage());
}
function registerTelegramUser(PDO $pdo, array $user): void
{
// Obtener idioma por defecto de la base de datos (el primero activo)
$stmtDefault = $pdo->query("SELECT language_code FROM supported_languages WHERE is_active = 1 LIMIT 1");
$defaultLang = $stmtDefault->fetchColumn() ?: 'es';
$stmt = $pdo->prepare("
INSERT INTO recipients (platform_id, name, type, platform, language_code, chat_mode)
VALUES (?, ?, 'user', 'telegram', ?, 'bot')
ON DUPLICATE KEY UPDATE name = VALUES(name)
");
$name = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
$languageCode = $user['language_code'] ?? $defaultLang;
$stmt->execute([$user['id'], $name, $languageCode]);
}
function handleAutoTranslation(PDO $pdo, Telegram\TelegramSender $sender, src\Translate $translator, int $chatId, string $text): void
{
// Usar el texto original completo para generar los botones y guardar en caché
$keyboard = getTelegramTranslationButtons($pdo, $text);
if (!empty($keyboard)) {
$message = "🌐 <b>Traducciones disponibles:</b>\nHaz clic en una bandera para ver la traducción";
$sender->sendMessage($chatId, $message, $keyboard);
}
}
function getTelegramTranslationButtons(PDO $pdo, string $text): ?array
{
try {
$stmt = $pdo->query("SELECT language_code, flag_emoji FROM supported_languages WHERE is_active = 1 AND telegram_enabled = 1");
$activeLanguages = $stmt->fetchAll();
if (count($activeLanguages) <= 1) {
return null;
}
$textHash = md5($text);
$stmt = $pdo->prepare("INSERT INTO translation_cache (text_hash, original_text) VALUES (?, ?) ON DUPLICATE KEY UPDATE original_text = VALUES(original_text)");
$stmt->execute([$textHash, $text]);
$buttons = [];
foreach ($activeLanguages as $lang) {
$callbackData = "translate:" . $lang['language_code'] . ":" . $textHash;
$buttons[] = [
'text' => $lang['flag_emoji'] . ' ' . strtoupper($lang['language_code']),
'callback_data' => $callbackData
];
}
if (empty($buttons)) {
return null;
}
return ['inline_keyboard' => array_chunk($buttons, 3)];
} catch (Exception $e) {
error_log("getTelegramTranslationButtons error: " . $e->getMessage());
return null;
}
}
function handleTelegramCommand(Telegram\TelegramSender $sender, PDO $pdo, int $chatId, int $userId, string $command, string $username): void
{
$command = str_replace(['/', '@botname'], '', $command);
$parts = explode(' ', $command);
$cmd = strtolower($parts[0]);
$args = array_slice($parts, 1);
switch ($cmd) {
case 'start':
$stmt = $pdo->query("SELECT * FROM telegram_bot_messages WHERE id = 1");
$config = $stmt->fetch();
if ($config && $config['is_active']) {
$text = str_replace('{user_name}', $username, $config['message_text']);
$buttons = [];
if ($config['button_text'] && $config['group_invite_link']) {
$buttons[] = [
'text' => $config['button_text'],
'url' => $config['group_invite_link']
];
}
$keyboard = !empty($buttons) ? $sender->createInlineKeyboard($buttons) : null;
$sender->sendMessage($chatId, $text, $keyboard);
} else {
$sender->sendMessage($chatId, "¡Hola {$username}! 👋\n\nUsa /comandos para ver los comandos disponibles.");
}
break;
case 'comandos':
$message = "📋 <b>Comandos disponibles:</b>\n\n";
$message .= "/start - Iniciar bot\n";
$message .= "/comandos - Ver comandos\n";
$message .= "/setlang [código] - Establecer idioma\n";
$message .= "/bienvenida - Mensaje de bienvenida\n";
$message .= "/agente - Cambiar modo de chat\n";
$stmt = $pdo->query("SELECT name, telegram_command FROM recurrent_messages WHERE telegram_command IS NOT NULL AND telegram_command != '' ORDER BY name");
$customCommands = $stmt->fetchAll();
if (!empty($customCommands)) {
$message .= "\n📦 <b>Plantillas:</b>\n";
foreach ($customCommands as $cmd) {
$message .= "#" . htmlspecialchars($cmd['telegram_command']) . " - " . htmlspecialchars($cmd['name']) . "\n";
}
}
$message .= "\n✍️ Escribe cualquier texto para traducir automáticamente";
$translationButtons = getTelegramTranslationButtons($pdo, $message);
if ($translationButtons) {
$sender->sendMessage($chatId, $message, $translationButtons);
} else {
$sender->sendMessage($chatId, $message);
}
break;
case 'setlang':
$langCode = $args[0] ?? 'es';
$stmt = $pdo->prepare("UPDATE recipients SET language_code = ? WHERE platform_id = ? AND platform = 'telegram'");
$stmt->execute([$langCode, $chatId]);
$sender->sendMessage($chatId, "✅ Idioma actualizado a: " . strtoupper($langCode));
break;
case 'bienvenida':
$stmt = $pdo->query("SELECT * FROM telegram_bot_messages WHERE id = 1");
$config = $stmt->fetch();
if ($config && $config['is_active']) {
$text = str_replace('{user_name}', $username, $config['message_text']);
// Agregar botones de traducción (convertir HTML a texto plano)
$plainText = html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8');
$plainText = preg_replace('/\s+/', ' ', $plainText);
$translationButtons = getTelegramTranslationButtons($pdo, $plainText);
if (!empty($translationButtons)) {
$keyboard = $sender->createInlineKeyboard(array_map(function($btn) {
return ['text' => $btn['flag'], 'callback_data' => $btn['callback_data']];
}, $translationButtons));
$sender->sendMessage($chatId, $text, $keyboard);
} else {
$sender->sendMessage($chatId, $text);
}
}
break;
case 'agente':
$buttons = [
[
'text' => '🤖 Seguir con Bot',
'callback_data' => 'chat_mode:bot:' . $userId
],
[
'text' => '💬 Platicar con IA',
'callback_data' => 'chat_mode:ia:' . $userId
]
];
$keyboard = $sender->createInlineKeyboard($buttons);
$sender->sendMessage($chatId, "🤖 <b>Selecciona un modo de chat:</b>", $keyboard);
break;
}
}
function handleTelegramMessage(PDO $pdo, Telegram\TelegramSender $sender, int $chatId, int $userId, string $text): void
{
// Si no hay contenido real (solo emojis, espacios), ignorar
if (!hasRealContent($text)) {
return;
}
$stmt = $pdo->prepare("SELECT chat_mode FROM recipients WHERE platform_id = ? AND platform = 'telegram'");
$stmt->execute([$userId]);
$recipient = $stmt->fetch();
if ($recipient && $recipient['chat_mode'] === 'ia') {
sendToN8NIA($sender, $chatId, $userId, $text);
} else {
require_once __DIR__ . '/../../src/Translate.php';
$translator = new src\Translate();
handleAutoTranslation($pdo, $sender, $translator, $chatId, $text);
}
}
function sendToN8NIA(Telegram\TelegramSender $sender, int $chatId, int $userId, string $userMessage): void
{
$useN8n = $_ENV['N8N_IA_WEBHOOK_URL'] ?? getenv('N8N_IA_WEBHOOK_URL') ?? '';
$useN8n = trim($useN8n, '"');
if (!empty($useN8n)) {
$data = [
'user_id' => (string)$userId,
'message' => $userMessage
];
$ch = curl_init($useN8n);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($httpCode < 200 || $httpCode >= 300) {
$sender->sendMessage($chatId, "❌ Error HTTP: $httpCode");
error_log("N8N IA Telegram Error: HTTP $httpCode - $error");
}
return;
}
require_once __DIR__ . '/../../src/IA/Agent.php';
$agent = new \IA\Agent();
try {
$response = $agent->generateResponse($userMessage);
$sender->sendMessage($chatId, $response);
} catch (\Exception $e) {
$sender->sendMessage($chatId, "❌ Error: " . $e->getMessage());
error_log("IA Agent Error: " . $e->getMessage());
}
}
function sendTemplateByCommand(PDO $pdo, Telegram\TelegramSender $sender, int $chatId, string $command): void
{
$stmt = $pdo->prepare("SELECT * FROM recurrent_messages WHERE telegram_command = ?");
$stmt->execute([$command]);
$template = $stmt->fetch();
if ($template) {
// Parsear el contenido manteniendo el orden texto-imagen
$segments = $sender->parseContent($template['message_content']);
if (!empty($segments)) {
// Obtener texto completo para botones de traducción
$plainText = $template['message_content'];
$plainText = preg_replace('/<br\s*\/?>/i', "\n", $plainText);
$plainText = preg_replace('/<\/p>/i', "\n", $plainText);
$plainText = preg_replace('/<p[^>]*>/i', '', $plainText);
$plainText = strip_tags($plainText);
$plainText = html_entity_decode($plainText, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$plainText = preg_replace('/[ \t]+/', ' ', $plainText);
$plainText = preg_replace('/\n\s*\n/', "\n", $plainText);
$plainText = trim($plainText);
$translationButtons = getTelegramTranslationButtons($pdo, $plainText);
// Enviar contenido ordenado con botones
$sender->sendContentWithOrderedImagesAndButtons($chatId, $segments, $translationButtons);
}
} else {
$sender->sendMessage($chatId, "❌ Plantilla no encontrada: #{$command}");
}
}
function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\Translate $translator, int $chatId, int $messageId, ?string $inlineMessageId, string $callbackQueryId, string $callbackData): void
{
$parts = explode(':', $callbackData, 3);
$action = $parts[0] ?? '';
if ($action === 'translate') {
$targetLang = $parts[1] ?? 'es';
$textHash = $parts[2] ?? '';
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - targetLang: $targetLang, textHash: $textHash\n", FILE_APPEND);
// Recuperar texto de la base de datos
$stmt = $pdo->prepare("SELECT original_text FROM translation_cache WHERE text_hash = ?");
$stmt->execute([$textHash]);
$row = $stmt->fetch();
if (!$row) {
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - ERROR: No text found\n", FILE_APPEND);
$sender->answerCallbackQuery($callbackQueryId, "❌ Error: Texto no encontrado");
return;
}
$originalText = $row['original_text'];
if (empty($originalText)) {
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - ERROR: Empty text\n", FILE_APPEND);
$sender->answerCallbackQuery($callbackQueryId, "❌ Error: No se pudo recuperar el texto");
return;
}
try {
// Traducción parcial - detecta el idioma de cada segmento y traduce solo lo necesario
$textForTranslation = stripEmojisForDetection($originalText);
$translated = $translator->translatePartial($textForTranslation ?: $originalText, $targetLang);
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - targetLang: $targetLang, originalText: " . substr($originalText, 0, 50) . "\n", FILE_APPEND);
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - translated: $translated\n", FILE_APPEND);
if ($translated) {
// Limpiar TODAS las etiquetas HTML problemáticas (con espacios como < b > o </ b >)
$translated = preg_replace('/<\s*(\/?)\s*([a-z]+)\s*>?/i', '<$1$2>', $translated);
// Eliminar espacios extra en comandos de Telegram
$translated = preg_replace('/\/(\s+)(\w+)/', '/$2', $translated);
$translated = preg_replace('/#(\s+)(\w+)/', '#$2', $translated);
// Verificar si hay etiquetas HTML inválidas después de la limpieza
if (preg_match('/<[a-z][^>]*\s+[^>]*>/i', $translated)) {
// Si hay más problemas, convertir a texto plano pero mantener estructura
$translated = strip_tags($translated);
// Agregar emoji para mejor visualización
$translated = str_replace('/start', '✅ /start', $translated);
$translated = str_replace('/comandos', '📋 /comandos', $translated);
$translated = str_replace('/setlang', '🌐 /setlang', $translated);
$translated = str_replace('/bienvenida', '👋 /bienvenida', $translated);
$translated = str_replace('/agente', '🤖 /agente', $translated);
}
$sender->answerCallbackQuery($callbackQueryId, "", false);
$keyboard = getTelegramTranslationButtons($pdo, $originalText);
$result = $sender->editMessageText($chatId, $messageId, "🌐 <b>Traducción (" . strtoupper($targetLang) . "):</b>\n\n" . $translated, $keyboard, 'HTML', $inlineMessageId);
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - editMessageText result: " . json_encode($result) . "\n", FILE_APPEND);
} else {
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - ERROR: Translation failed\n", FILE_APPEND);
$sender->answerCallbackQuery($callbackQueryId, "❌ Error al traducir el mensaje", false);
}
} catch (Exception $e) {
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - EXCEPTION: " . $e->getMessage() . "\n", FILE_APPEND);
$sender->answerCallbackQuery($callbackQueryId, "❌ Error en la traducción", false);
}
} elseif ($action === 'chat_mode') {
$mode = $parts[1] ?? 'bot';
$userId = $parts[2] ?? '';
if (empty($userId)) {
$sender->answerCallbackQuery($callbackQueryId, "❌ Error: Usuario no identificado");
return;
}
$chatMode = ($mode === 'ia') ? 'ia' : 'bot';
$stmt = $pdo->prepare("UPDATE recipients SET chat_mode = ? WHERE platform_id = ? AND platform = 'telegram'");
$stmt->execute([$chatMode, $userId]);
if ($chatMode === 'ia') {
$sender->answerCallbackQuery($callbackQueryId, "✅ Modo IA activado. Ahora puedes platicar con la IA.", false);
$sender->sendMessage($chatId, "✅ <b>Modo IA activado.</b>\n\nAhora puedes platicar conmigo. Escribe cualquier cosa y la enviaré a la IA.");
} else {
$sender->answerCallbackQuery($callbackQueryId, "✅ Modo Bot activado.", false);
$sender->sendMessage($chatId, "✅ <b>Modo Bot activado.</b>\n\nAhora puedes usar comandos como #comando y traducción.");
}
}
}
function isExistingTelegramUser(PDO $pdo, int $userId): bool
{
$stmt = $pdo->prepare("SELECT id FROM recipients WHERE platform_id = ? AND platform = 'telegram'");
$stmt->execute([$userId]);
return $stmt->fetch() !== false;
}
function sendWelcomeMessage(PDO $pdo, Telegram\TelegramSender $sender, int $chatId, string $username): void
{
$stmt = $pdo->query("SELECT * FROM telegram_bot_messages WHERE id = 1");
$config = $stmt->fetch();
if ($config && $config['is_active']) {
$text = str_replace('{user_name}', $username, $config['message_text']);
$buttons = [];
if ($config['button_text'] && $config['group_invite_link']) {
$buttons[] = [
'text' => $config['button_text'],
'url' => $config['group_invite_link']
];
}
$keyboard = !empty($buttons) ? $sender->createInlineKeyboard($buttons) : null;
$sender->sendMessage($chatId, $text, $keyboard);
} else {
$sender->sendMessage($chatId, "¡Hola {$username}! 👋\n\nUsa /comandos para ver los comandos disponibles.");
}
}