Fix: Botones de traducción para /comandos y limpieza de HTML en Telegram
This commit is contained in:
@@ -33,9 +33,12 @@ class TelegramSender
|
|||||||
'chat_id' => $chatId,
|
'chat_id' => $chatId,
|
||||||
'message_id' => $messageId,
|
'message_id' => $messageId,
|
||||||
'text' => $text,
|
'text' => $text,
|
||||||
'parse_mode' => $parseMode
|
|
||||||
];
|
];
|
||||||
|
|
||||||
|
if ($parseMode) {
|
||||||
|
$data['parse_mode'] = $parseMode;
|
||||||
|
}
|
||||||
|
|
||||||
if ($keyboard) {
|
if ($keyboard) {
|
||||||
$data['reply_markup'] = json_encode($keyboard);
|
$data['reply_markup'] = json_encode($keyboard);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,13 @@ if (!$update) {
|
|||||||
exit('No update');
|
exit('No update');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " -收到更新\n", FILE_APPEND);
|
||||||
|
|
||||||
|
if (isset($update['callback_query'])) {
|
||||||
|
$callbackData = $update['callback_query']['data'] ?? 'no data';
|
||||||
|
file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - Callback: $callbackData\n", FILE_APPEND);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$pdo = getDbConnection();
|
$pdo = getDbConnection();
|
||||||
$sender = new Telegram\TelegramSender();
|
$sender = new Telegram\TelegramSender();
|
||||||
@@ -55,6 +62,9 @@ try {
|
|||||||
$callbackData = $callbackQuery['data'];
|
$callbackData = $callbackQuery['data'];
|
||||||
$chatId = $callbackQuery['message']['chat']['id'];
|
$chatId = $callbackQuery['message']['chat']['id'];
|
||||||
$messageId = $callbackQuery['message']['message_id'];
|
$messageId = $callbackQuery['message']['message_id'];
|
||||||
|
$userId = $callbackQuery['from']['id'] ?? '';
|
||||||
|
|
||||||
|
error_log("Telegram callback - chatId: $chatId, messageId: $messageId, userId: $userId, callbackData: $callbackData");
|
||||||
|
|
||||||
handleTelegramCallback($pdo, $sender, $translator, $chatId, $messageId, $callbackQuery['id'], $callbackData);
|
handleTelegramCallback($pdo, $sender, $translator, $chatId, $messageId, $callbackQuery['id'], $callbackData);
|
||||||
}
|
}
|
||||||
@@ -163,10 +173,26 @@ function handleTelegramCommand(Telegram\TelegramSender $sender, PDO $pdo, int $c
|
|||||||
$message .= "/setlang [código] - Establecer idioma\n";
|
$message .= "/setlang [código] - Establecer idioma\n";
|
||||||
$message .= "/bienvenida - Mensaje de bienvenida\n";
|
$message .= "/bienvenida - Mensaje de bienvenida\n";
|
||||||
$message .= "/agente - Cambiar modo de chat\n";
|
$message .= "/agente - Cambiar modo de chat\n";
|
||||||
$message .= "#comando - Enviar plantilla\n";
|
|
||||||
$message .= "Escribe cualquier texto para traducir automáticamente";
|
|
||||||
|
|
||||||
|
$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);
|
$sender->sendMessage($chatId, $message);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'setlang':
|
case 'setlang':
|
||||||
@@ -314,12 +340,15 @@ function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\T
|
|||||||
$targetLang = $parts[1] ?? 'es';
|
$targetLang = $parts[1] ?? 'es';
|
||||||
$textHash = $parts[2] ?? '';
|
$textHash = $parts[2] ?? '';
|
||||||
|
|
||||||
|
file_put_contents('/var/www/html/lastwar/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
|
// Recuperar texto de la base de datos
|
||||||
$stmt = $pdo->prepare("SELECT original_text FROM translation_cache WHERE text_hash = ?");
|
$stmt = $pdo->prepare("SELECT original_text FROM translation_cache WHERE text_hash = ?");
|
||||||
$stmt->execute([$textHash]);
|
$stmt->execute([$textHash]);
|
||||||
$row = $stmt->fetch();
|
$row = $stmt->fetch();
|
||||||
|
|
||||||
if (!$row) {
|
if (!$row) {
|
||||||
|
file_put_contents('/var/www/html/lastwar/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");
|
$sender->answerCallbackQuery($callbackQueryId, "❌ Error: Texto no encontrado");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -327,6 +356,7 @@ function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\T
|
|||||||
$originalText = $row['original_text'];
|
$originalText = $row['original_text'];
|
||||||
|
|
||||||
if (empty($originalText)) {
|
if (empty($originalText)) {
|
||||||
|
file_put_contents('/var/www/html/lastwar/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");
|
$sender->answerCallbackQuery($callbackQueryId, "❌ Error: No se pudo recuperar el texto");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -334,21 +364,44 @@ function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\T
|
|||||||
try {
|
try {
|
||||||
// Obtener el idioma original
|
// Obtener el idioma original
|
||||||
$sourceLang = $translator->detectLanguage($originalText) ?? 'es';
|
$sourceLang = $translator->detectLanguage($originalText) ?? 'es';
|
||||||
|
file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - sourceLang: $sourceLang, targetLang: $targetLang, originalText: " . substr($originalText, 0, 50) . "\n", FILE_APPEND);
|
||||||
|
|
||||||
// Traducir
|
// Traducir
|
||||||
$translated = $translator->translate($originalText, $sourceLang, $targetLang);
|
$translated = $translator->translate($originalText, $sourceLang, $targetLang);
|
||||||
|
file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - translated: $translated\n", FILE_APPEND);
|
||||||
|
|
||||||
if ($translated) {
|
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);
|
$sender->answerCallbackQuery($callbackQueryId, "", false);
|
||||||
|
|
||||||
$keyboard = getTelegramTranslationButtons($pdo, $originalText, $targetLang);
|
$keyboard = getTelegramTranslationButtons($pdo, $originalText, $targetLang);
|
||||||
|
|
||||||
$sender->editMessageText($chatId, $messageId, "🌐 <b>Traducción (" . strtoupper($targetLang) . "):</b>\n\n" . $translated, $keyboard);
|
$result = $sender->editMessageText($chatId, $messageId, "🌐 <b>Traducción (" . strtoupper($targetLang) . "):</b>\n\n" . $translated, $keyboard);
|
||||||
|
file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - editMessageText result: " . json_encode($result) . "\n", FILE_APPEND);
|
||||||
} else {
|
} else {
|
||||||
|
file_put_contents('/var/www/html/lastwar/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);
|
$sender->answerCallbackQuery($callbackQueryId, "❌ Error al traducir el mensaje", false);
|
||||||
}
|
}
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
error_log("Callback translation error: " . $e->getMessage());
|
file_put_contents('/var/www/html/lastwar/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);
|
$sender->answerCallbackQuery($callbackQueryId, "❌ Error en la traducción", false);
|
||||||
}
|
}
|
||||||
} elseif ($action === 'chat_mode') {
|
} elseif ($action === 'chat_mode') {
|
||||||
|
|||||||
Reference in New Issue
Block a user