406 lines
16 KiB
PHP
Executable File
406 lines
16 KiB
PHP
Executable File
<?php
|
|
|
|
require_once __DIR__ . '/../../includes/db.php';
|
|
require_once __DIR__ . '/../../includes/env_loader.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');
|
|
}
|
|
|
|
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'] ?? '';
|
|
$username = $message['from']['first_name'] ?? 'Usuario';
|
|
|
|
registerTelegramUser($pdo, $message['from']);
|
|
|
|
if (!isExistingTelegramUser($pdo, $userId)) {
|
|
sendWelcomeMessage($pdo, $sender, $chatId, $username);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
} elseif (isset($update['callback_query'])) {
|
|
$callbackQuery = $update['callback_query'];
|
|
$callbackData = $callbackQuery['data'];
|
|
$chatId = $callbackQuery['message']['chat']['id'];
|
|
$messageId = $callbackQuery['message']['message_id'];
|
|
|
|
handleTelegramCallback($pdo, $sender, $translator, $chatId, $messageId, $callbackQuery['id'], $callbackData);
|
|
}
|
|
|
|
} catch (Exception $e) {
|
|
error_log("Telegram Webhook Error: " . $e->getMessage());
|
|
}
|
|
|
|
function registerTelegramUser(PDO $pdo, array $user): void
|
|
{
|
|
$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'] ?? 'es';
|
|
|
|
$stmt->execute([$user['id'], $name, $languageCode]);
|
|
}
|
|
|
|
function handleAutoTranslation(PDO $pdo, Telegram\TelegramSender $sender, src\Translate $translator, int $chatId, string $text): void
|
|
{
|
|
$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, ?string $excludeLang = null): ?array
|
|
{
|
|
try {
|
|
$stmt = $pdo->query("SELECT language_code, flag_emoji FROM supported_languages WHERE is_active = 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) {
|
|
if ($excludeLang && $lang['language_code'] === $excludeLang) {
|
|
continue;
|
|
}
|
|
|
|
$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";
|
|
$message .= "#comando - Enviar plantilla\n";
|
|
$message .= "Escribe cualquier texto para traducir automáticamente";
|
|
|
|
$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
|
|
{
|
|
$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) {
|
|
$converter = new Telegram\Converters\HtmlToTelegramHtmlConverter();
|
|
$content = $converter->convert($template['message_content']);
|
|
|
|
$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 = trim($plainText);
|
|
|
|
$translationButtons = getTelegramTranslationButtons($pdo, $plainText);
|
|
|
|
if ($translationButtons) {
|
|
$sender->sendMessage($chatId, $content, $translationButtons);
|
|
} else {
|
|
$sender->sendMessage($chatId, $content);
|
|
}
|
|
} else {
|
|
$sender->sendMessage($chatId, "❌ Plantilla no encontrada: #{$command}");
|
|
}
|
|
}
|
|
|
|
function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\Translate $translator, int $chatId, int $messageId, string $callbackQueryId, string $callbackData): void
|
|
{
|
|
$parts = explode(':', $callbackData, 3);
|
|
$action = $parts[0] ?? '';
|
|
|
|
if ($action === 'translate') {
|
|
$targetLang = $parts[1] ?? 'es';
|
|
$textHash = $parts[2] ?? '';
|
|
|
|
// 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) {
|
|
$sender->answerCallbackQuery($callbackQueryId, "❌ Error: Texto no encontrado");
|
|
return;
|
|
}
|
|
|
|
$originalText = $row['original_text'];
|
|
|
|
if (empty($originalText)) {
|
|
$sender->answerCallbackQuery($callbackQueryId, "❌ Error: No se pudo recuperar el texto");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// Obtener el idioma original
|
|
$sourceLang = $translator->detectLanguage($originalText) ?? 'es';
|
|
|
|
// Traducir
|
|
$translated = $translator->translate($originalText, $sourceLang, $targetLang);
|
|
|
|
if ($translated) {
|
|
$sender->answerCallbackQuery($callbackQueryId, "", false);
|
|
|
|
$keyboard = getTelegramTranslationButtons($pdo, $originalText, $targetLang);
|
|
|
|
$sender->editMessageText($chatId, $messageId, "🌐 <b>Traducción (" . strtoupper($targetLang) . "):</b>\n\n" . $translated, $keyboard);
|
|
} else {
|
|
$sender->answerCallbackQuery($callbackQueryId, "❌ Error al traducir el mensaje", false);
|
|
}
|
|
} catch (Exception $e) {
|
|
error_log("Callback translation error: " . $e->getMessage());
|
|
$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.");
|
|
}
|
|
}
|