diff --git a/telegram/TelegramSender.php b/telegram/TelegramSender.php
index aae221a..e57c156 100755
--- a/telegram/TelegramSender.php
+++ b/telegram/TelegramSender.php
@@ -33,9 +33,12 @@ class TelegramSender
'chat_id' => $chatId,
'message_id' => $messageId,
'text' => $text,
- 'parse_mode' => $parseMode
];
+ if ($parseMode) {
+ $data['parse_mode'] = $parseMode;
+ }
+
if ($keyboard) {
$data['reply_markup'] = json_encode($keyboard);
}
diff --git a/telegram/webhook/telegram_bot_webhook.php b/telegram/webhook/telegram_bot_webhook.php
index 764d637..1ee1462 100755
--- a/telegram/webhook/telegram_bot_webhook.php
+++ b/telegram/webhook/telegram_bot_webhook.php
@@ -22,6 +22,13 @@ if (!$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 {
$pdo = getDbConnection();
$sender = new Telegram\TelegramSender();
@@ -55,6 +62,9 @@ try {
$callbackData = $callbackQuery['data'];
$chatId = $callbackQuery['message']['chat']['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);
}
@@ -163,10 +173,26 @@ function handleTelegramCommand(Telegram\TelegramSender $sender, PDO $pdo, int $c
$message .= "/setlang [código] - Establecer idioma\n";
$message .= "/bienvenida - Mensaje de bienvenida\n";
$message .= "/agente - Cambiar modo de chat\n";
- $message .= "#comando - Enviar plantilla\n";
- $message .= "Escribe cualquier texto para traducir automáticamente";
- $sender->sendMessage($chatId, $message);
+ $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📦 Plantillas:\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':
@@ -314,12 +340,15 @@ function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\T
$targetLang = $parts[1] ?? 'es';
$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
$stmt = $pdo->prepare("SELECT original_text FROM translation_cache WHERE text_hash = ?");
$stmt->execute([$textHash]);
$row = $stmt->fetch();
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");
return;
}
@@ -327,6 +356,7 @@ function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\T
$originalText = $row['original_text'];
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");
return;
}
@@ -334,21 +364,44 @@ function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\T
try {
// Obtener el idioma original
$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
$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) {
+ // 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, $targetLang);
- $sender->editMessageText($chatId, $messageId, "🌐 Traducción (" . strtoupper($targetLang) . "):\n\n" . $translated, $keyboard);
+ $result = $sender->editMessageText($chatId, $messageId, "🌐 Traducción (" . strtoupper($targetLang) . "):\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 {
+ 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);
}
} 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);
}
} elseif ($action === 'chat_mode') {