Fix: Botones de traducción - editar mensaje en Telegram y Discord
This commit is contained in:
@@ -140,32 +140,45 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|||||||
$sender = \Common\Helpers\SenderFactory::create($schedule['platform']);
|
$sender = \Common\Helpers\SenderFactory::create($schedule['platform']);
|
||||||
|
|
||||||
// Obtener botones de traducción (convertir HTML a texto plano)
|
// 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 = $schedule['content'];
|
||||||
$plainText = preg_replace('/\s+/', ' ', $plainText); // Normalizar espacios
|
// 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);
|
$translationButtons = getTranslationButtons($pdo, $plainText);
|
||||||
|
|
||||||
// Parsear el contenido HTML en segmentos manteniendo el orden
|
// Parsear el contenido HTML en segmentos manteniendo el orden
|
||||||
$segments = $sender->parseContent($schedule['content']);
|
$segments = $sender->parseContent($schedule['content']);
|
||||||
|
|
||||||
$messageCount = 0;
|
$messageCount = 0;
|
||||||
|
$totalSegments = count($segments);
|
||||||
|
$currentSegment = 0;
|
||||||
|
|
||||||
// Enviar cada segmento en el orden correcto
|
// Enviar cada segmento en el orden correcto
|
||||||
foreach ($segments as $segment) {
|
foreach ($segments as $segment) {
|
||||||
|
$currentSegment++;
|
||||||
|
$isLastSegment = ($currentSegment === $totalSegments);
|
||||||
|
|
||||||
if ($segment['type'] === 'text') {
|
if ($segment['type'] === 'text') {
|
||||||
// Convertir el texto al formato de la plataforma
|
// Convertir el texto al formato de la plataforma
|
||||||
$textContent = \Common\Helpers\ConverterFactory::convert($schedule['platform'], $segment['content']);
|
$textContent = \Common\Helpers\ConverterFactory::convert($schedule['platform'], $segment['content']);
|
||||||
|
|
||||||
if (!empty(trim($textContent))) {
|
if (!empty(trim($textContent))) {
|
||||||
// Agregar botones de traducción al último segmento de texto
|
|
||||||
$buttons = null;
|
$buttons = null;
|
||||||
if ($segment === end($segments)) {
|
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
|
||||||
$buttons = $schedule['platform'] === 'telegram'
|
$buttons = $translationButtons['discord'];
|
||||||
? $translationButtons['telegram']
|
|
||||||
: $translationButtons['discord'];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($schedule['platform'] === 'telegram') {
|
if ($schedule['platform'] === 'telegram') {
|
||||||
$sender->sendMessage($schedule['platform_id'], $textContent, $buttons);
|
$sender->sendMessage($schedule['platform_id'], $textContent);
|
||||||
} else {
|
} else {
|
||||||
$sender->sendMessage($schedule['platform_id'], $textContent, null, $buttons);
|
$sender->sendMessage($schedule['platform_id'], $textContent, null, $buttons);
|
||||||
}
|
}
|
||||||
@@ -174,22 +187,43 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|||||||
} elseif ($segment['type'] === 'image') {
|
} elseif ($segment['type'] === 'image') {
|
||||||
$imagePath = $segment['src'];
|
$imagePath = $segment['src'];
|
||||||
|
|
||||||
// Quitar parámetros de URL si los hay
|
$appUrl = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
|
||||||
$imgPath = parse_url($imagePath, PHP_URL_PATH) ?: $imagePath;
|
$baseUrl = rtrim($appUrl, '/');
|
||||||
|
|
||||||
if (file_exists($imgPath)) {
|
$buttons = null;
|
||||||
// Es un archivo local
|
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
|
||||||
$sender->sendMessageWithAttachments($schedule['platform_id'], '', [$imgPath]);
|
$buttons = $translationButtons['discord'];
|
||||||
$messageCount++;
|
}
|
||||||
} elseif (strpos($imagePath, 'http') === 0) {
|
|
||||||
// Es una URL remota
|
if ($schedule['platform'] === 'telegram') {
|
||||||
$embed = ['image' => ['url' => $imagePath]];
|
if (strpos($imagePath, 'http') !== 0) {
|
||||||
$sender->sendMessage($schedule['platform_id'], '', $embed);
|
$imageUrl = $baseUrl . '/' . ltrim($imagePath, '/');
|
||||||
|
} else {
|
||||||
|
$imageUrl = $imagePath;
|
||||||
|
}
|
||||||
|
$sender->sendPhoto($schedule['platform_id'], $imageUrl);
|
||||||
$messageCount++;
|
$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("
|
$stmt = $pdo->prepare("
|
||||||
INSERT INTO sent_messages (schedule_id, recipient_id, platform_message_id, message_count, sent_at)
|
INSERT INTO sent_messages (schedule_id, recipient_id, platform_message_id, message_count, sent_at)
|
||||||
VALUES (?, ?, '', ?, NOW())
|
VALUES (?, ?, '', ?, NOW())
|
||||||
|
|||||||
@@ -127,35 +127,39 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['
|
|||||||
|
|
||||||
// Obtener botones de traducción (convertir HTML a texto plano)
|
// Obtener botones de traducción (convertir HTML a texto plano)
|
||||||
$plainText = $schedule['content'];
|
$plainText = $schedule['content'];
|
||||||
// Convertir saltos de párrafo a saltos de línea
|
// Marcar donde hay imágenes
|
||||||
$plainText = preg_replace('/<\/p>/i', "\n", $plainText);
|
$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('/<p[^>]*>/i', '', $plainText);
|
||||||
$plainText = preg_replace('/<br\s*\/?>/i', "\n", $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');
|
$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('/[ \t]+/', ' ', $plainText);
|
||||||
$plainText = preg_replace('/\n\s*\n/', "\n", $plainText);
|
$plainText = preg_replace('/\n{3,}/', "\n\n", $plainText);
|
||||||
$plainText = trim($plainText);
|
$plainText = trim($plainText);
|
||||||
$translationButtons = getTranslationButtons($pdo, $plainText);
|
$translationButtons = getTranslationButtons($pdo, $plainText);
|
||||||
|
|
||||||
$segments = $sender->parseContent($schedule['content']);
|
$segments = $sender->parseContent($schedule['content']);
|
||||||
$messageCount = 0;
|
$messageCount = 0;
|
||||||
|
$totalSegments = count($segments);
|
||||||
|
$currentSegment = 0;
|
||||||
|
|
||||||
foreach ($segments as $segment) {
|
foreach ($segments as $segment) {
|
||||||
|
$currentSegment++;
|
||||||
|
$isLastSegment = ($currentSegment === $totalSegments);
|
||||||
|
|
||||||
if ($segment['type'] === 'text') {
|
if ($segment['type'] === 'text') {
|
||||||
$textContent = \Common\Helpers\ConverterFactory::convert($schedule['platform'], $segment['content']);
|
$textContent = \Common\Helpers\ConverterFactory::convert($schedule['platform'], $segment['content']);
|
||||||
if (!empty(trim($textContent))) {
|
if (!empty(trim($textContent))) {
|
||||||
// Agregar botones de traducción al último segmento de texto
|
|
||||||
$buttons = null;
|
$buttons = null;
|
||||||
if ($segment === end($segments)) {
|
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
|
||||||
$buttons = $schedule['platform'] === 'telegram'
|
$buttons = $translationButtons['discord'];
|
||||||
? $translationButtons['telegram']
|
|
||||||
: $translationButtons['discord'];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($schedule['platform'] === 'telegram') {
|
if ($schedule['platform'] === 'telegram') {
|
||||||
$sender->sendMessage($schedule['platform_id'], $textContent, $buttons);
|
$sender->sendMessage($schedule['platform_id'], $textContent);
|
||||||
} else {
|
} else {
|
||||||
$sender->sendMessage($schedule['platform_id'], $textContent, null, $buttons);
|
$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') {
|
} elseif ($segment['type'] === 'image') {
|
||||||
$imagePath = $segment['src'];
|
$imagePath = $segment['src'];
|
||||||
$imgPath = parse_url($imagePath, PHP_URL_PATH) ?: $imagePath;
|
|
||||||
|
|
||||||
if (file_exists($imgPath)) {
|
$appUrl = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
|
||||||
$sender->sendMessageWithAttachments($schedule['platform_id'], '', [$imgPath]);
|
$baseUrl = rtrim($appUrl, '/');
|
||||||
$messageCount++;
|
|
||||||
} elseif (strpos($imagePath, 'http') === 0) {
|
$buttons = null;
|
||||||
$embed = ['image' => ['url' => $imagePath]];
|
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
|
||||||
$sender->sendMessage($schedule['platform_id'], '', $embed);
|
$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++;
|
$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("
|
$stmt = $pdo->prepare("
|
||||||
INSERT INTO sent_messages (schedule_id, recipient_id, platform_message_id, message_count, sent_at)
|
INSERT INTO sent_messages (schedule_id, recipient_id, platform_message_id, message_count, sent_at)
|
||||||
VALUES (?, ?, '', ?, NOW())
|
VALUES (?, ?, '', ?, NOW())
|
||||||
|
|||||||
@@ -356,13 +356,11 @@ function handleAutoTranslationWithButtons(PDO $pdo, Message $message, string $te
|
|||||||
// Preparar botones
|
// Preparar botones
|
||||||
$buttons = [];
|
$buttons = [];
|
||||||
foreach ($activeLanguages as $lang) {
|
foreach ($activeLanguages as $lang) {
|
||||||
if ($lang['language_code'] !== $detectedLang) {
|
$buttons[] = [
|
||||||
$buttons[] = [
|
'label' => $lang['flag_emoji'] . ' ' . strtoupper($lang['language_code']),
|
||||||
'label' => $lang['flag_emoji'] . ' ' . strtoupper($lang['language_code']),
|
'custom_id' => 'translate_' . $lang['language_code'] . ':' . $textHash,
|
||||||
'custom_id' => 'translate_' . $lang['language_code'] . ':' . $textHash,
|
'style' => 1
|
||||||
'style' => 1
|
];
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enviar mensaje con botones usando MessageBuilder correctamente
|
// Enviar mensaje con botones usando MessageBuilder correctamente
|
||||||
@@ -508,13 +506,11 @@ function handleTranslateInteraction($interaction, string $customId): void
|
|||||||
$targetLang = str_replace('translate_', '', $parts[0]);
|
$targetLang = str_replace('translate_', '', $parts[0]);
|
||||||
$textHash = $parts[1] ?? '';
|
$textHash = $parts[1] ?? '';
|
||||||
|
|
||||||
// Obtener texto de la base de datos primero
|
|
||||||
$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 || empty($row['original_text'])) {
|
if (!$row || empty($row['original_text'])) {
|
||||||
// Enviar error efímero
|
|
||||||
$builder = \Discord\Builders\MessageBuilder::new()
|
$builder = \Discord\Builders\MessageBuilder::new()
|
||||||
->setContent('❌ Error: Texto no encontrado');
|
->setContent('❌ Error: Texto no encontrado');
|
||||||
$interaction->respondWithMessage($builder, true);
|
$interaction->respondWithMessage($builder, true);
|
||||||
@@ -523,34 +519,25 @@ function handleTranslateInteraction($interaction, string $customId): void
|
|||||||
|
|
||||||
$originalText = $row['original_text'];
|
$originalText = $row['original_text'];
|
||||||
|
|
||||||
// Responder inmediatamente con "Traduciendo..."
|
try {
|
||||||
$loadingBuilder = \Discord\Builders\MessageBuilder::new()
|
$interaction->acknowledge();
|
||||||
->setContent("⏳ Traduciendo a " . strtoupper($targetLang) . "...");
|
} catch (\Exception $e) {
|
||||||
$interaction->respondWithMessage($loadingBuilder, true);
|
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);
|
$textForDetection = stripEmojisForDetection($originalText);
|
||||||
$sourceLang = $translator->detectLanguage($textForDetection) ?? 'es';
|
$sourceLang = $translator->detectLanguage($textForDetection) ?? 'es';
|
||||||
$translated = $translator->translate($textForDetection, $sourceLang, $targetLang);
|
$translated = $translator->translate($textForDetection, $sourceLang, $targetLang);
|
||||||
|
|
||||||
if ($translated) {
|
if ($translated) {
|
||||||
// Limpiar todo el HTML
|
|
||||||
$translated = strip_tags($translated);
|
$translated = strip_tags($translated);
|
||||||
// Limpiar asteriscos duplicados
|
|
||||||
$translated = preg_replace('/\*+/', '', $translated);
|
$translated = preg_replace('/\*+/', '', $translated);
|
||||||
// Limpiar comandos con espacios
|
|
||||||
$translated = preg_replace('/\/(\s+)(\w+)/', '/$2', $translated);
|
$translated = preg_replace('/\/(\s+)(\w+)/', '/$2', $translated);
|
||||||
$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);
|
$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);
|
$displayText = trim($translated);
|
||||||
if (strpos($originalText, '👍') !== false || preg_match('/[\x{1F300}-\x{1F9FF}]/u', $originalText)) {
|
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 = '';
|
$emojiPrefix = '';
|
||||||
$emojiSuffix = '';
|
$emojiSuffix = '';
|
||||||
if (preg_match('/^([\x{1F300}-\x{1F9FF}]+)\s*/u', $originalText, $match)) {
|
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;
|
$displayText = $emojiPrefix . $displayText . $emojiSuffix;
|
||||||
}
|
}
|
||||||
|
|
||||||
$finalBuilder = \Discord\Builders\MessageBuilder::new()
|
$messageText = "🌐 **Traducción (" . strtoupper($targetLang) . "):**\n\n" . $displayText;
|
||||||
->setContent("🌐 **Traducción (" . strtoupper($targetLang) . "):**\n\n" . $displayText);
|
|
||||||
$interaction->updateOriginalResponse($finalBuilder);
|
$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 {
|
} else {
|
||||||
// Actualizar con error
|
$interaction->message->edit(\Discord\Builders\MessageBuilder::new()->setContent("❌ Error al traducir"));
|
||||||
$errorBuilder = \Discord\Builders\MessageBuilder::new()
|
|
||||||
->setContent("❌ Error al traducir");
|
|
||||||
$interaction->updateOriginalResponse($errorBuilder);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
error_log("Discord translate error: " . $e->getMessage());
|
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());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
[unix_http_server]
|
||||||
|
file=/var/run/supervisor.sock
|
||||||
|
chmod=0700
|
||||||
|
|
||||||
[supervisord]
|
[supervisord]
|
||||||
nodaemon=true
|
nodaemon=true
|
||||||
logfile=/var/www/html/logs/supervisor.log
|
logfile=/var/www/html/logs/supervisor.log
|
||||||
@@ -5,6 +9,12 @@ logfile_maxbytes=50MB
|
|||||||
pidfile=/var/run/supervisord.pid
|
pidfile=/var/run/supervisord.pid
|
||||||
childlogdir=/var/www/html/logs
|
childlogdir=/var/www/html/logs
|
||||||
|
|
||||||
|
[rpcinterface:supervisor]
|
||||||
|
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
|
||||||
|
|
||||||
|
[supervisorctl]
|
||||||
|
serverurl=unix:///var/run/supervisor.sock
|
||||||
|
|
||||||
[program:apache]
|
[program:apache]
|
||||||
process_name=%(program_name)s
|
process_name=%(program_name)s
|
||||||
command=/usr/sbin/apache2ctl -D FOREGROUND
|
command=/usr/sbin/apache2ctl -D FOREGROUND
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
require_once __DIR__ . '/includes/db.php';
|
require_once __DIR__ . '/includes/db.php';
|
||||||
require_once __DIR__ . '/includes/session_check.php';
|
require_once __DIR__ . '/includes/session_check.php';
|
||||||
require_once __DIR__ . '/includes/i18n.php';
|
require_once __DIR__ . '/includes/i18n.php';
|
||||||
|
require_once __DIR__ . '/includes/activity_logger.php';
|
||||||
checkSession();
|
checkSession();
|
||||||
|
|
||||||
$pageTitle = t('Galería de Imágenes');
|
$pageTitle = t('Galería de Imágenes');
|
||||||
|
|||||||
@@ -2,12 +2,9 @@
|
|||||||
require_once __DIR__ . '/includes/db.php';
|
require_once __DIR__ . '/includes/db.php';
|
||||||
require_once __DIR__ . '/includes/env_loader.php';
|
require_once __DIR__ . '/includes/env_loader.php';
|
||||||
require_once __DIR__ . '/includes/auth.php';
|
require_once __DIR__ . '/includes/auth.php';
|
||||||
require_once __DIR__ . '/includes/i18n.php';
|
|
||||||
|
|
||||||
handleLanguageChange();
|
|
||||||
|
|
||||||
$domain = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
|
$domain = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
|
||||||
if ($domain) {
|
if ($domain && session_status() === PHP_SESSION_NONE) {
|
||||||
$parsed = parse_url($domain);
|
$parsed = parse_url($domain);
|
||||||
$host = $parsed['host'] ?? '';
|
$host = $parsed['host'] ?? '';
|
||||||
if ($host) {
|
if ($host) {
|
||||||
@@ -22,7 +19,9 @@ if ($domain) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
session_start();
|
require_once __DIR__ . '/includes/i18n.php';
|
||||||
|
|
||||||
|
handleLanguageChange();
|
||||||
|
|
||||||
if (isset($_SESSION['user_id'])) {
|
if (isset($_SESSION['user_id'])) {
|
||||||
header('Location: index.php');
|
header('Location: index.php');
|
||||||
|
|||||||
@@ -104,15 +104,17 @@ function processScheduledMessages(): array
|
|||||||
|
|
||||||
// Obtener botones de traducción (convertir HTML a texto plano)
|
// Obtener botones de traducción (convertir HTML a texto plano)
|
||||||
$plainText = $schedule['content'];
|
$plainText = $schedule['content'];
|
||||||
// Convertir saltos de párrafo a saltos de línea
|
// Marcar donde hay imágenes
|
||||||
$plainText = preg_replace('/<\/p>/i', "\n", $plainText);
|
$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('/<p[^>]*>/i', '', $plainText);
|
||||||
$plainText = preg_replace('/<br\s*\/?>/i', "\n", $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');
|
$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('/[ \t]+/', ' ', $plainText);
|
||||||
$plainText = preg_replace('/\n\s*\n/', "\n", $plainText);
|
$plainText = preg_replace('/\n{3,}/', "\n\n", $plainText);
|
||||||
$plainText = trim($plainText);
|
$plainText = trim($plainText);
|
||||||
$translationButtons = getTranslationButtons($pdo, $plainText);
|
$translationButtons = getTranslationButtons($pdo, $plainText);
|
||||||
|
|
||||||
@@ -120,24 +122,26 @@ function processScheduledMessages(): array
|
|||||||
$segments = $sender->parseContent($schedule['content']);
|
$segments = $sender->parseContent($schedule['content']);
|
||||||
|
|
||||||
$messageCount = 0;
|
$messageCount = 0;
|
||||||
|
$totalSegments = count($segments);
|
||||||
|
$currentSegment = 0;
|
||||||
|
|
||||||
// Enviar cada segmento en el orden correcto
|
// Enviar cada segmento en el orden correcto
|
||||||
foreach ($segments as $segment) {
|
foreach ($segments as $segment) {
|
||||||
|
$currentSegment++;
|
||||||
|
$isLastSegment = ($currentSegment === $totalSegments);
|
||||||
|
|
||||||
if ($segment['type'] === 'text') {
|
if ($segment['type'] === 'text') {
|
||||||
// Convertir el texto al formato de la plataforma
|
// Convertir el texto al formato de la plataforma
|
||||||
$textContent = ConverterFactory::convert($schedule['platform'], $segment['content']);
|
$textContent = ConverterFactory::convert($schedule['platform'], $segment['content']);
|
||||||
|
|
||||||
if (!empty(trim($textContent))) {
|
if (!empty(trim($textContent))) {
|
||||||
// Agregar botones de traducción al último segmento de texto
|
|
||||||
$buttons = null;
|
$buttons = null;
|
||||||
if ($segment === end($segments)) {
|
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
|
||||||
$buttons = $schedule['platform'] === 'telegram'
|
$buttons = $translationButtons['discord'];
|
||||||
? $translationButtons['telegram']
|
|
||||||
: $translationButtons['discord'];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($schedule['platform'] === 'telegram') {
|
if ($schedule['platform'] === 'telegram') {
|
||||||
$sender->sendMessage($schedule['platform_id'], $textContent, $buttons);
|
$sender->sendMessage($schedule['platform_id'], $textContent);
|
||||||
} else {
|
} else {
|
||||||
$sender->sendMessage($schedule['platform_id'], $textContent, null, $buttons);
|
$sender->sendMessage($schedule['platform_id'], $textContent, null, $buttons);
|
||||||
}
|
}
|
||||||
@@ -146,22 +150,43 @@ function processScheduledMessages(): array
|
|||||||
} elseif ($segment['type'] === 'image') {
|
} elseif ($segment['type'] === 'image') {
|
||||||
$imagePath = $segment['src'];
|
$imagePath = $segment['src'];
|
||||||
|
|
||||||
// Quitar parámetros de URL si los hay
|
$appUrl = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
|
||||||
$imgPath = parse_url($imagePath, PHP_URL_PATH) ?: $imagePath;
|
$baseUrl = rtrim($appUrl, '/');
|
||||||
|
|
||||||
if (file_exists($imgPath)) {
|
$buttons = null;
|
||||||
// Es un archivo local
|
if ($isLastSegment && $schedule['platform'] !== 'telegram') {
|
||||||
$sender->sendMessageWithAttachments($schedule['platform_id'], '', [$imgPath]);
|
$buttons = $translationButtons['discord'];
|
||||||
$messageCount++;
|
}
|
||||||
} elseif (strpos($imagePath, 'http') === 0) {
|
|
||||||
// Es una URL remota
|
if ($schedule['platform'] === 'telegram') {
|
||||||
$embed = ['image' => ['url' => $imagePath]];
|
if (strpos($imagePath, 'http') !== 0) {
|
||||||
$sender->sendMessage($schedule['platform_id'], '', $embed);
|
$imageUrl = $baseUrl . '/' . ltrim($imagePath, '/');
|
||||||
|
} else {
|
||||||
|
$imageUrl = $imagePath;
|
||||||
|
}
|
||||||
|
$sender->sendPhoto($schedule['platform_id'], $imageUrl);
|
||||||
$messageCount++;
|
$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("
|
$stmt = $pdo->prepare("
|
||||||
INSERT INTO sent_messages (schedule_id, recipient_id, platform_message_id, message_count, sent_at)
|
INSERT INTO sent_messages (schedule_id, recipient_id, platform_message_id, message_count, sent_at)
|
||||||
VALUES (?, ?, ?, ?, NOW())
|
VALUES (?, ?, ?, ?, NOW())
|
||||||
|
|||||||
@@ -34,7 +34,6 @@ class Translate
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Primero intentar obtener del caché
|
|
||||||
$cacheKey = $this->generateCacheKey($text, $sourceLang, $targetLang);
|
$cacheKey = $this->generateCacheKey($text, $sourceLang, $targetLang);
|
||||||
$cached = $this->getFromCache($cacheKey);
|
$cached = $this->getFromCache($cacheKey);
|
||||||
|
|
||||||
@@ -46,25 +45,32 @@ class Translate
|
|||||||
$lines = explode("\n", $text);
|
$lines = explode("\n", $text);
|
||||||
$translatedLines = [];
|
$translatedLines = [];
|
||||||
|
|
||||||
foreach ($lines as $line) {
|
error_log("Translate: " . count($lines) . " lines from $sourceLang to $targetLang");
|
||||||
if (trim($line) === '') {
|
|
||||||
|
foreach ($lines as $index => $line) {
|
||||||
|
$trimmed = trim($line);
|
||||||
|
if ($trimmed === '') {
|
||||||
$translatedLines[] = '';
|
$translatedLines[] = '';
|
||||||
|
error_log("Line $index: empty -> empty");
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
$response = $this->request('/translate', [
|
$response = $this->request('/translate', [
|
||||||
'q' => trim($line),
|
'q' => $trimmed,
|
||||||
'source' => $sourceLang,
|
'source' => $sourceLang,
|
||||||
'target' => $targetLang,
|
'target' => $targetLang,
|
||||||
'format' => 'text'
|
'format' => 'text'
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$translatedLines[] = $response['translatedText'] ?? trim($line);
|
$translated = $response['translatedText'] ?? $trimmed;
|
||||||
|
$translatedLines[] = $translated;
|
||||||
|
error_log("Line $index: '$trimmed' -> '$translated'");
|
||||||
}
|
}
|
||||||
|
|
||||||
$result = implode("\n", $translatedLines);
|
$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);
|
$this->saveToCache($cacheKey, $result);
|
||||||
|
|
||||||
return $result;
|
return $result;
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ class TelegramSender
|
|||||||
return $this->request('sendMessage', $data);
|
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 = [
|
$data = [
|
||||||
'chat_id' => $chatId,
|
'chat_id' => $chatId,
|
||||||
@@ -35,6 +35,12 @@ class TelegramSender
|
|||||||
'text' => $text,
|
'text' => $text,
|
||||||
];
|
];
|
||||||
|
|
||||||
|
if ($inlineMessageId) {
|
||||||
|
unset($data['chat_id']);
|
||||||
|
unset($data['message_id']);
|
||||||
|
$data['inline_message_id'] = $inlineMessageId;
|
||||||
|
}
|
||||||
|
|
||||||
if ($parseMode) {
|
if ($parseMode) {
|
||||||
$data['parse_mode'] = $parseMode;
|
$data['parse_mode'] = $parseMode;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,11 +23,11 @@ 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);
|
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'])) {
|
if (isset($update['callback_query'])) {
|
||||||
$callbackData = $update['callback_query']['data'] ?? 'no data';
|
$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 {
|
try {
|
||||||
@@ -82,11 +82,12 @@ 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'];
|
||||||
|
$inlineMessageId = $callbackQuery['inline_message_id'] ?? null;
|
||||||
$userId = $callbackQuery['from']['id'] ?? '';
|
$userId = $callbackQuery['from']['id'] ?? '';
|
||||||
|
|
||||||
error_log("Telegram callback - chatId: $chatId, messageId: $messageId, userId: $userId, callbackData: $callbackData");
|
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) {
|
} 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 {
|
try {
|
||||||
$stmt = $pdo->query("SELECT language_code, flag_emoji FROM supported_languages WHERE is_active = 1");
|
$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 = [];
|
$buttons = [];
|
||||||
foreach ($activeLanguages as $lang) {
|
foreach ($activeLanguages as $lang) {
|
||||||
if ($excludeLang && $lang['language_code'] === $excludeLang) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$callbackData = "translate:" . $lang['language_code'] . ":" . $textHash;
|
$callbackData = "translate:" . $lang['language_code'] . ":" . $textHash;
|
||||||
|
|
||||||
$buttons[] = [
|
$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);
|
$parts = explode(':', $callbackData, 3);
|
||||||
$action = $parts[0] ?? '';
|
$action = $parts[0] ?? '';
|
||||||
@@ -369,7 +366,7 @@ 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);
|
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
|
// 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 = ?");
|
||||||
@@ -377,7 +374,7 @@ function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\T
|
|||||||
$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);
|
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");
|
$sender->answerCallbackQuery($callbackQueryId, "❌ Error: Texto no encontrado");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -385,7 +382,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);
|
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");
|
$sender->answerCallbackQuery($callbackQueryId, "❌ Error: No se pudo recuperar el texto");
|
||||||
return;
|
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)
|
// Obtener el idioma original (usar texto sin emojis para mayor precisión)
|
||||||
$textForDetection = stripEmojisForDetection($originalText);
|
$textForDetection = stripEmojisForDetection($originalText);
|
||||||
$sourceLang = $translator->detectLanguage($textForDetection) ?? 'es';
|
$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)
|
// Traducir (usar texto sin emojis para evitar interferencias)
|
||||||
$translated = $translator->translate($textForDetection ?: $originalText, $sourceLang, $targetLang);
|
$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) {
|
if ($translated) {
|
||||||
// Limpiar TODAS las etiquetas HTML problemáticas (con espacios como < b > o </ b >)
|
// 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);
|
$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);
|
$result = $sender->editMessageText($chatId, $messageId, "🌐 <b>Traducción (" . strtoupper($targetLang) . "):</b>\n\n" . $translated, $keyboard, 'HTML', $inlineMessageId);
|
||||||
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);
|
file_put_contents(__DIR__ . '/../../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);
|
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);
|
$sender->answerCallbackQuery($callbackQueryId, "❌ Error al traducir el mensaje", false);
|
||||||
}
|
}
|
||||||
} catch (Exception $e) {
|
} 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);
|
$sender->answerCallbackQuery($callbackQueryId, "❌ Error en la traducción", false);
|
||||||
}
|
}
|
||||||
} elseif ($action === 'chat_mode') {
|
} elseif ($action === 'chat_mode') {
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
session_start();
|
if (session_status() === PHP_SESSION_NONE) {
|
||||||
|
session_start();
|
||||||
|
}
|
||||||
require_once __DIR__ . '/../includes/session_check.php';
|
require_once __DIR__ . '/../includes/session_check.php';
|
||||||
require_once __DIR__ . '/../includes/url_helper.php';
|
require_once __DIR__ . '/../includes/url_helper.php';
|
||||||
require_once __DIR__ . '/../includes/i18n.php';
|
require_once __DIR__ . '/../includes/i18n.php';
|
||||||
|
|||||||
Reference in New Issue
Block a user