Fix: Botones de traducción - editar mensaje en Telegram y Discord

This commit is contained in:
2026-03-10 16:30:52 -06:00
parent 082e01b358
commit bf960f3fc3
11 changed files with 229 additions and 126 deletions

View File

@@ -140,32 +140,45 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sender = \Common\Helpers\SenderFactory::create($schedule['platform']);
// Obtener botones de traducción (convertir HTML a texto plano)
$plainText = html_entity_decode(strip_tags($schedule['content']), ENT_QUOTES | ENT_HTML5, 'UTF-8');
$plainText = preg_replace('/\s+/', ' ', $plainText); // Normalizar espacios
$plainText = $schedule['content'];
// Marcar donde hay imágenes
$plainText = preg_replace('/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', "\n[IMAGEN]\n", $plainText);
// Convertir saltos de párrafo y br a saltos de línea dobles
$plainText = preg_replace('/<\/p>/i', "\n\n", $plainText);
$plainText = preg_replace('/<p[^>]*>/i', '', $plainText);
$plainText = preg_replace('/<br\s*\/?>/i', "\n", $plainText);
// Eliminar HTML restante
$plainText = html_entity_decode(strip_tags($plainText), ENT_QUOTES | ENT_HTML5, 'UTF-8');
// Limpiar espacios múltiples pero preservar saltos de línea (máximo 2)
$plainText = preg_replace('/[ \t]+/', ' ', $plainText);
$plainText = preg_replace('/\n{3,}/', "\n\n", $plainText);
$plainText = trim($plainText);
$translationButtons = getTranslationButtons($pdo, $plainText);
// Parsear el contenido HTML en segmentos manteniendo el orden
$segments = $sender->parseContent($schedule['content']);
$messageCount = 0;
$totalSegments = count($segments);
$currentSegment = 0;
// Enviar cada segmento en el orden correcto
foreach ($segments as $segment) {
$currentSegment++;
$isLastSegment = ($currentSegment === $totalSegments);
if ($segment['type'] === 'text') {
// Convertir el texto al formato de la plataforma
$textContent = \Common\Helpers\ConverterFactory::convert($schedule['platform'], $segment['content']);
if (!empty(trim($textContent))) {
// Agregar botones de traducción al último segmento de texto
$buttons = null;
if ($segment === end($segments)) {
$buttons = $schedule['platform'] === 'telegram'
? $translationButtons['telegram']
: $translationButtons['discord'];
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
$buttons = $translationButtons['discord'];
}
if ($schedule['platform'] === 'telegram') {
$sender->sendMessage($schedule['platform_id'], $textContent, $buttons);
$sender->sendMessage($schedule['platform_id'], $textContent);
} else {
$sender->sendMessage($schedule['platform_id'], $textContent, null, $buttons);
}
@@ -174,22 +187,43 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
} elseif ($segment['type'] === 'image') {
$imagePath = $segment['src'];
// Quitar parámetros de URL si los hay
$imgPath = parse_url($imagePath, PHP_URL_PATH) ?: $imagePath;
$appUrl = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
$baseUrl = rtrim($appUrl, '/');
if (file_exists($imgPath)) {
// Es un archivo local
$sender->sendMessageWithAttachments($schedule['platform_id'], '', [$imgPath]);
$messageCount++;
} elseif (strpos($imagePath, 'http') === 0) {
// Es una URL remota
$embed = ['image' => ['url' => $imagePath]];
$sender->sendMessage($schedule['platform_id'], '', $embed);
$buttons = null;
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
$buttons = $translationButtons['discord'];
}
if ($schedule['platform'] === 'telegram') {
if (strpos($imagePath, 'http') !== 0) {
$imageUrl = $baseUrl . '/' . ltrim($imagePath, '/');
} else {
$imageUrl = $imagePath;
}
$sender->sendPhoto($schedule['platform_id'], $imageUrl);
$messageCount++;
} else {
$imgPath = parse_url($imagePath, PHP_URL_PATH) ?: $imagePath;
if (file_exists($imgPath)) {
$sender->sendMessageWithImages($schedule['platform_id'], '', [$imgPath], $buttons);
$messageCount++;
} elseif (strpos($imagePath, 'http') === 0) {
$embed = ['image' => ['url' => $imagePath]];
$sender->sendMessage($schedule['platform_id'], '', $embed, $buttons);
$messageCount++;
}
}
}
}
// Enviar botones de traducción en mensaje separado para Telegram
if ($schedule['platform'] === 'telegram' && !empty($translationButtons['telegram'])) {
$translationMessage = "🌐 <b>Traducciones disponibles:</b>\nHaz clic en una bandera para ver la traducción";
$sender->sendMessage($schedule['platform_id'], $translationMessage, $translationButtons['telegram']);
$messageCount++;
}
$stmt = $pdo->prepare("
INSERT INTO sent_messages (schedule_id, recipient_id, platform_message_id, message_count, sent_at)
VALUES (?, ?, '', ?, NOW())

View File

@@ -127,35 +127,39 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['
// Obtener botones de traducción (convertir HTML a texto plano)
$plainText = $schedule['content'];
// Convertir saltos de párrafo a saltos de línea
$plainText = preg_replace('/<\/p>/i', "\n", $plainText);
// Marcar donde hay imágenes
$plainText = preg_replace('/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', "\n[IMAGEN]\n", $plainText);
// Convertir saltos de párrafo y br a saltos de línea dobles
$plainText = preg_replace('/<\/p>/i', "\n\n", $plainText);
$plainText = preg_replace('/<p[^>]*>/i', '', $plainText);
$plainText = preg_replace('/<br\s*\/?>/i', "\n", $plainText);
// Eliminar HTML
// Eliminar HTML restante
$plainText = html_entity_decode(strip_tags($plainText), ENT_QUOTES | ENT_HTML5, 'UTF-8');
// Limpiar espacios múltiples pero preservar saltos de línea
// Limpiar espacios múltiples pero preservar saltos de línea (máximo 2)
$plainText = preg_replace('/[ \t]+/', ' ', $plainText);
$plainText = preg_replace('/\n\s*\n/', "\n", $plainText);
$plainText = preg_replace('/\n{3,}/', "\n\n", $plainText);
$plainText = trim($plainText);
$translationButtons = getTranslationButtons($pdo, $plainText);
$segments = $sender->parseContent($schedule['content']);
$messageCount = 0;
$totalSegments = count($segments);
$currentSegment = 0;
foreach ($segments as $segment) {
$currentSegment++;
$isLastSegment = ($currentSegment === $totalSegments);
if ($segment['type'] === 'text') {
$textContent = \Common\Helpers\ConverterFactory::convert($schedule['platform'], $segment['content']);
if (!empty(trim($textContent))) {
// Agregar botones de traducción al último segmento de texto
$buttons = null;
if ($segment === end($segments)) {
$buttons = $schedule['platform'] === 'telegram'
? $translationButtons['telegram']
: $translationButtons['discord'];
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
$buttons = $translationButtons['discord'];
}
if ($schedule['platform'] === 'telegram') {
$sender->sendMessage($schedule['platform_id'], $textContent, $buttons);
$sender->sendMessage($schedule['platform_id'], $textContent);
} else {
$sender->sendMessage($schedule['platform_id'], $textContent, null, $buttons);
}
@@ -163,19 +167,44 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['
}
} elseif ($segment['type'] === 'image') {
$imagePath = $segment['src'];
$imgPath = parse_url($imagePath, PHP_URL_PATH) ?: $imagePath;
if (file_exists($imgPath)) {
$sender->sendMessageWithAttachments($schedule['platform_id'], '', [$imgPath]);
$messageCount++;
} elseif (strpos($imagePath, 'http') === 0) {
$embed = ['image' => ['url' => $imagePath]];
$sender->sendMessage($schedule['platform_id'], '', $embed);
$appUrl = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
$baseUrl = rtrim($appUrl, '/');
$buttons = null;
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
$buttons = $translationButtons['discord'];
}
if ($schedule['platform'] === 'telegram') {
if (strpos($imagePath, 'http') !== 0) {
$imageUrl = $baseUrl . '/' . ltrim($imagePath, '/');
} else {
$imageUrl = $imagePath;
}
$sender->sendPhoto($schedule['platform_id'], $imageUrl);
$messageCount++;
} else {
$imgPath = parse_url($imagePath, PHP_URL_PATH) ?: $imagePath;
if (file_exists($imgPath)) {
$sender->sendMessageWithImages($schedule['platform_id'], '', [$imgPath], $buttons);
$messageCount++;
} elseif (strpos($imagePath, 'http') === 0) {
$embed = ['image' => ['url' => $imagePath]];
$sender->sendMessage($schedule['platform_id'], '', $embed, $buttons);
$messageCount++;
}
}
}
}
// Enviar botones de traducción en mensaje separado para Telegram
if ($schedule['platform'] === 'telegram' && !empty($translationButtons['telegram'])) {
$translationMessage = "🌐 <b>Traducciones disponibles:</b>\nHaz clic en una bandera para ver la traducción";
$sender->sendMessage($schedule['platform_id'], $translationMessage, $translationButtons['telegram']);
$messageCount++;
}
$stmt = $pdo->prepare("
INSERT INTO sent_messages (schedule_id, recipient_id, platform_message_id, message_count, sent_at)
VALUES (?, ?, '', ?, NOW())

View File

@@ -356,13 +356,11 @@ function handleAutoTranslationWithButtons(PDO $pdo, Message $message, string $te
// Preparar botones
$buttons = [];
foreach ($activeLanguages as $lang) {
if ($lang['language_code'] !== $detectedLang) {
$buttons[] = [
'label' => $lang['flag_emoji'] . ' ' . strtoupper($lang['language_code']),
'custom_id' => 'translate_' . $lang['language_code'] . ':' . $textHash,
'style' => 1
];
}
$buttons[] = [
'label' => $lang['flag_emoji'] . ' ' . strtoupper($lang['language_code']),
'custom_id' => 'translate_' . $lang['language_code'] . ':' . $textHash,
'style' => 1
];
}
// Enviar mensaje con botones usando MessageBuilder correctamente
@@ -508,13 +506,11 @@ function handleTranslateInteraction($interaction, string $customId): void
$targetLang = str_replace('translate_', '', $parts[0]);
$textHash = $parts[1] ?? '';
// Obtener texto de la base de datos primero
$stmt = $pdo->prepare("SELECT original_text FROM translation_cache WHERE text_hash = ?");
$stmt->execute([$textHash]);
$row = $stmt->fetch();
if (!$row || empty($row['original_text'])) {
// Enviar error efímero
$builder = \Discord\Builders\MessageBuilder::new()
->setContent('❌ Error: Texto no encontrado');
$interaction->respondWithMessage($builder, true);
@@ -523,34 +519,25 @@ function handleTranslateInteraction($interaction, string $customId): void
$originalText = $row['original_text'];
// Responder inmediatamente con "Traduciendo..."
$loadingBuilder = \Discord\Builders\MessageBuilder::new()
->setContent("⏳ Traduciendo a " . strtoupper($targetLang) . "...");
$interaction->respondWithMessage($loadingBuilder, true);
try {
$interaction->acknowledge();
} catch (\Exception $e) {
error_log("Acknowledge error: " . $e->getMessage());
}
// Ahora traducir (esto puede tardar)
// Usar texto sin emojis para detectar idioma y traducir con mayor precisión
$textForDetection = stripEmojisForDetection($originalText);
$sourceLang = $translator->detectLanguage($textForDetection) ?? 'es';
$translated = $translator->translate($textForDetection, $sourceLang, $targetLang);
if ($translated) {
// Limpiar todo el HTML
$translated = strip_tags($translated);
// Limpiar asteriscos duplicados
$translated = preg_replace('/\*+/', '', $translated);
// Limpiar comandos con espacios
$translated = preg_replace('/\/(\s+)(\w+)/', '/$2', $translated);
$translated = preg_replace('/#(\s+)(\w+)/', '#$2', $translated);
// Limpiar saltos de línea extras
$translated = preg_replace('/\n\s*\n/', "\n", $translated);
// Actualizar la respuesta con la traducción real
// Preservar emojis del original si los hay
$displayText = trim($translated);
if (strpos($originalText, '👍') !== false || preg_match('/[\x{1F300}-\x{1F9FF}]/u', $originalText)) {
// Si el original tenía emojis, intentar identificarlos
// Para mensajes simples, los emojis generalmente están al inicio o final
$emojiPrefix = '';
$emojiSuffix = '';
if (preg_match('/^([\x{1F300}-\x{1F9FF}]+)\s*/u', $originalText, $match)) {
@@ -562,25 +549,32 @@ function handleTranslateInteraction($interaction, string $customId): void
$displayText = $emojiPrefix . $displayText . $emojiSuffix;
}
$finalBuilder = \Discord\Builders\MessageBuilder::new()
->setContent("🌐 **Traducción (" . strtoupper($targetLang) . "):**\n\n" . $displayText);
$interaction->updateOriginalResponse($finalBuilder);
$messageText = "🌐 **Traducción (" . strtoupper($targetLang) . "):**\n\n" . $displayText;
$buttons = getDiscordTranslationButtons($pdo, $originalText);
$builder = \Discord\Builders\MessageBuilder::new()
->setContent($messageText);
if (!empty($buttons)) {
$actionRow = new \Discord\Builders\Components\ActionRow();
foreach ($buttons[0]['components'] as $btn) {
$button = \Discord\Builders\Components\Button::new(\Discord\Builders\Components\Button::STYLE_PRIMARY)
->setLabel($btn['label'])
->setCustomId($btn['custom_id']);
$actionRow->addComponent($button);
}
$builder->addComponent($actionRow);
}
$interaction->message->edit($builder);
} else {
// Actualizar con error
$errorBuilder = \Discord\Builders\MessageBuilder::new()
->setContent("❌ Error al traducir");
$interaction->updateOriginalResponse($errorBuilder);
$interaction->message->edit(\Discord\Builders\MessageBuilder::new()->setContent("❌ Error al traducir"));
}
} catch (Exception $e) {
error_log("Discord translate error: " . $e->getMessage());
try {
$builder = \Discord\Builders\MessageBuilder::new()
->setContent('❌ Error en el proceso de traducción');
$interaction->respondWithMessage($builder, true);
} catch (Exception $inner) {
error_log("Error responding to interaction: " . $inner->getMessage());
}
}
}

View File

@@ -1,3 +1,7 @@
[unix_http_server]
file=/var/run/supervisor.sock
chmod=0700
[supervisord]
nodaemon=true
logfile=/var/www/html/logs/supervisor.log
@@ -5,6 +9,12 @@ logfile_maxbytes=50MB
pidfile=/var/run/supervisord.pid
childlogdir=/var/www/html/logs
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
[supervisorctl]
serverurl=unix:///var/run/supervisor.sock
[program:apache]
process_name=%(program_name)s
command=/usr/sbin/apache2ctl -D FOREGROUND

View File

@@ -2,6 +2,7 @@
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/session_check.php';
require_once __DIR__ . '/includes/i18n.php';
require_once __DIR__ . '/includes/activity_logger.php';
checkSession();
$pageTitle = t('Galería de Imágenes');

View File

@@ -2,12 +2,9 @@
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/env_loader.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/i18n.php';
handleLanguageChange();
$domain = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
if ($domain) {
if ($domain && session_status() === PHP_SESSION_NONE) {
$parsed = parse_url($domain);
$host = $parsed['host'] ?? '';
if ($host) {
@@ -22,7 +19,9 @@ if ($domain) {
}
}
session_start();
require_once __DIR__ . '/includes/i18n.php';
handleLanguageChange();
if (isset($_SESSION['user_id'])) {
header('Location: index.php');

View File

@@ -104,15 +104,17 @@ function processScheduledMessages(): array
// Obtener botones de traducción (convertir HTML a texto plano)
$plainText = $schedule['content'];
// Convertir saltos de párrafo a saltos de línea
$plainText = preg_replace('/<\/p>/i', "\n", $plainText);
// Marcar donde hay imágenes
$plainText = preg_replace('/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', "\n[IMAGEN]\n", $plainText);
// Convertir saltos de párrafo y br a saltos de línea dobles
$plainText = preg_replace('/<\/p>/i', "\n\n", $plainText);
$plainText = preg_replace('/<p[^>]*>/i', '', $plainText);
$plainText = preg_replace('/<br\s*\/?>/i', "\n", $plainText);
// Eliminar HTML
// Eliminar HTML restante
$plainText = html_entity_decode(strip_tags($plainText), ENT_QUOTES | ENT_HTML5, 'UTF-8');
// Limpiar espacios múltiples pero preservar saltos de línea
// Limpiar espacios múltiples pero preservar saltos de línea (máximo 2)
$plainText = preg_replace('/[ \t]+/', ' ', $plainText);
$plainText = preg_replace('/\n\s*\n/', "\n", $plainText);
$plainText = preg_replace('/\n{3,}/', "\n\n", $plainText);
$plainText = trim($plainText);
$translationButtons = getTranslationButtons($pdo, $plainText);
@@ -120,24 +122,26 @@ function processScheduledMessages(): array
$segments = $sender->parseContent($schedule['content']);
$messageCount = 0;
$totalSegments = count($segments);
$currentSegment = 0;
// Enviar cada segmento en el orden correcto
foreach ($segments as $segment) {
$currentSegment++;
$isLastSegment = ($currentSegment === $totalSegments);
if ($segment['type'] === 'text') {
// Convertir el texto al formato de la plataforma
$textContent = ConverterFactory::convert($schedule['platform'], $segment['content']);
if (!empty(trim($textContent))) {
// Agregar botones de traducción al último segmento de texto
$buttons = null;
if ($segment === end($segments)) {
$buttons = $schedule['platform'] === 'telegram'
? $translationButtons['telegram']
: $translationButtons['discord'];
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
$buttons = $translationButtons['discord'];
}
if ($schedule['platform'] === 'telegram') {
$sender->sendMessage($schedule['platform_id'], $textContent, $buttons);
$sender->sendMessage($schedule['platform_id'], $textContent);
} else {
$sender->sendMessage($schedule['platform_id'], $textContent, null, $buttons);
}
@@ -146,22 +150,43 @@ function processScheduledMessages(): array
} elseif ($segment['type'] === 'image') {
$imagePath = $segment['src'];
// Quitar parámetros de URL si los hay
$imgPath = parse_url($imagePath, PHP_URL_PATH) ?: $imagePath;
$appUrl = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
$baseUrl = rtrim($appUrl, '/');
if (file_exists($imgPath)) {
// Es un archivo local
$sender->sendMessageWithAttachments($schedule['platform_id'], '', [$imgPath]);
$messageCount++;
} elseif (strpos($imagePath, 'http') === 0) {
// Es una URL remota
$embed = ['image' => ['url' => $imagePath]];
$sender->sendMessage($schedule['platform_id'], '', $embed);
$buttons = null;
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
$buttons = $translationButtons['discord'];
}
if ($schedule['platform'] === 'telegram') {
if (strpos($imagePath, 'http') !== 0) {
$imageUrl = $baseUrl . '/' . ltrim($imagePath, '/');
} else {
$imageUrl = $imagePath;
}
$sender->sendPhoto($schedule['platform_id'], $imageUrl);
$messageCount++;
} else {
$imgPath = parse_url($imagePath, PHP_URL_PATH) ?: $imagePath;
if (file_exists($imgPath)) {
$sender->sendMessageWithImages($schedule['platform_id'], '', [$imgPath], $buttons);
$messageCount++;
} elseif (strpos($imagePath, 'http') === 0) {
$embed = ['image' => ['url' => $imagePath]];
$sender->sendMessage($schedule['platform_id'], '', $embed, $buttons);
$messageCount++;
}
}
}
}
// Enviar botones de traducción en mensaje separado para Telegram
if ($schedule['platform'] === 'telegram' && !empty($translationButtons['telegram'])) {
$translationMessage = "🌐 <b>Traducciones disponibles:</b>\nHaz clic en una bandera para ver la traducción";
$sender->sendMessage($schedule['platform_id'], $translationMessage, $translationButtons['telegram']);
$messageCount++;
}
$stmt = $pdo->prepare("
INSERT INTO sent_messages (schedule_id, recipient_id, platform_message_id, message_count, sent_at)
VALUES (?, ?, ?, ?, NOW())

View File

@@ -34,7 +34,6 @@ class Translate
}
try {
// Primero intentar obtener del caché
$cacheKey = $this->generateCacheKey($text, $sourceLang, $targetLang);
$cached = $this->getFromCache($cacheKey);
@@ -46,25 +45,32 @@ class Translate
$lines = explode("\n", $text);
$translatedLines = [];
foreach ($lines as $line) {
if (trim($line) === '') {
error_log("Translate: " . count($lines) . " lines from $sourceLang to $targetLang");
foreach ($lines as $index => $line) {
$trimmed = trim($line);
if ($trimmed === '') {
$translatedLines[] = '';
error_log("Line $index: empty -> empty");
continue;
}
$response = $this->request('/translate', [
'q' => trim($line),
'q' => $trimmed,
'source' => $sourceLang,
'target' => $targetLang,
'format' => 'text'
]);
$translatedLines[] = $response['translatedText'] ?? trim($line);
$translated = $response['translatedText'] ?? $trimmed;
$translatedLines[] = $translated;
error_log("Line $index: '$trimmed' -> '$translated'");
}
$result = implode("\n", $translatedLines);
// Guardar en caché
error_log("Final result (length: " . strlen($result) . "): " . str_replace("\n", "\\n", substr($result, 0, 100)));
$this->saveToCache($cacheKey, $result);
return $result;

View File

@@ -27,7 +27,7 @@ class TelegramSender
return $this->request('sendMessage', $data);
}
public function editMessageText(int $chatId, int $messageId, string $text, ?array $keyboard = null, ?string $parseMode = 'HTML'): array
public function editMessageText(int $chatId, int $messageId, string $text, ?array $keyboard = null, ?string $parseMode = 'HTML', ?string $inlineMessageId = null): array
{
$data = [
'chat_id' => $chatId,
@@ -35,6 +35,12 @@ class TelegramSender
'text' => $text,
];
if ($inlineMessageId) {
unset($data['chat_id']);
unset($data['message_id']);
$data['inline_message_id'] = $inlineMessageId;
}
if ($parseMode) {
$data['parse_mode'] = $parseMode;
}

View File

@@ -23,11 +23,11 @@ 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);
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('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - Callback: $callbackData\n", FILE_APPEND);
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - Callback: $callbackData\n", FILE_APPEND);
}
try {
@@ -82,11 +82,12 @@ try {
$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, $callbackQuery['id'], $callbackData);
handleTelegramCallback($pdo, $sender, $translator, $chatId, $messageId, $inlineMessageId, $callbackQuery['id'], $callbackData);
}
} catch (Exception $e) {
@@ -119,7 +120,7 @@ function handleAutoTranslation(PDO $pdo, Telegram\TelegramSender $sender, src\Tr
}
}
function getTelegramTranslationButtons(PDO $pdo, string $text, ?string $excludeLang = null): ?array
function getTelegramTranslationButtons(PDO $pdo, string $text): ?array
{
try {
$stmt = $pdo->query("SELECT language_code, flag_emoji FROM supported_languages WHERE is_active = 1");
@@ -135,10 +136,6 @@ function getTelegramTranslationButtons(PDO $pdo, string $text, ?string $excludeL
$buttons = [];
foreach ($activeLanguages as $lang) {
if ($excludeLang && $lang['language_code'] === $excludeLang) {
continue;
}
$callbackData = "translate:" . $lang['language_code'] . ":" . $textHash;
$buttons[] = [
@@ -360,7 +357,7 @@ function sendTemplateByCommand(PDO $pdo, Telegram\TelegramSender $sender, int $c
}
}
function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\Translate $translator, int $chatId, int $messageId, string $callbackQueryId, string $callbackData): void
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] ?? '';
@@ -369,7 +366,7 @@ 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);
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 = ?");
@@ -377,7 +374,7 @@ function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\T
$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);
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;
}
@@ -385,7 +382,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);
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;
}
@@ -394,11 +391,11 @@ function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\T
// Obtener el idioma original (usar texto sin emojis para mayor precisión)
$textForDetection = stripEmojisForDetection($originalText);
$sourceLang = $translator->detectLanguage($textForDetection) ?? '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);
file_put_contents(__DIR__ . '/../../logs/telegram_debug.log', date('Y-m-d H:i:s') . " - sourceLang: $sourceLang, targetLang: $targetLang, originalText: " . substr($originalText, 0, 50) . "\n", FILE_APPEND);
// Traducir (usar texto sin emojis para evitar interferencias)
$translated = $translator->translate($textForDetection ?: $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);
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 >)
@@ -422,16 +419,16 @@ function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\T
$sender->answerCallbackQuery($callbackQueryId, "", false);
$keyboard = getTelegramTranslationButtons($pdo, $originalText, $targetLang);
$keyboard = getTelegramTranslationButtons($pdo, $originalText);
$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);
$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('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - ERROR: Translation failed\n", FILE_APPEND);
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('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - EXCEPTION: " . $e->getMessage() . "\n", FILE_APPEND);
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') {

View File

@@ -1,5 +1,7 @@
<?php
session_start();
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
require_once __DIR__ . '/../includes/session_check.php';
require_once __DIR__ . '/../includes/url_helper.php';
require_once __DIR__ . '/../includes/i18n.php';