Primer commit del sistema separado falta mejorar mucho

This commit is contained in:
nickpons666
2025-12-30 01:18:46 -06:00
commit 1679c73e52
2384 changed files with 472342 additions and 0 deletions

110
telegram/api/messages/delete.php Executable file
View File

@@ -0,0 +1,110 @@
<?php
/**
* API - Eliminar/Deshabilitar Mensaje Telegram
* Cambia el estado del mensaje a 'deshabilitado' y opcionalmente lo elimina de Telegram.
*/
header('Content-Type: application/json');
// Habilitar errores para debug (quitar en producción estricta)
ini_set('display_errors', 0);
error_reporting(E_ALL);
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
$input = json_decode(file_get_contents('php://input'), true);
$messageId = $input['id'] ?? null;
if (empty($messageId) || !is_numeric($messageId)) {
jsonResponse(['success' => false, 'error' => 'ID de mensaje inválido o no proporcionado'], 400);
}
try {
$db = getDB();
// 1. Obtener detalles del mensaje para verificar permisos y Telegram ID
$stmt = $db->prepare("SELECT usuario_id, chat_id, mensaje_telegram_id, tipo_envio FROM mensajes_telegram WHERE id = ?");
$stmt->execute([$messageId]);
$message = $stmt->fetch();
if (!$message) {
jsonResponse(['success' => false, 'error' => 'Mensaje no encontrado'], 404);
}
// Verificar permisos: solo Admin o el propietario pueden eliminar/deshabilitar
if ($userData->rol !== 'Admin' && $message['usuario_id'] != $userData->userId) {
jsonResponse(['success' => false, 'error' => 'No tiene permisos para eliminar este mensaje'], 403);
}
// 2. Intentar eliminar de Telegram si existe un mensaje_telegram_id y fue un envío inmediato
$telegramDeletionSuccess = true;
$telegramDeletionError = null;
if (!empty($message['mensaje_telegram_id']) && $message['tipo_envio'] === 'inmediato') {
$botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
if (!$botToken) {
logToFile('telegram/errors.log', "Error eliminando mensaje de Telegram: Token de bot no configurado.", 'ERROR');
$telegramDeletionError = "Token de bot no configurado, no se pudo eliminar de Telegram.";
$telegramDeletionSuccess = false;
} else {
$telegramApiUrl = "https://api.telegram.org/bot{$botToken}/deleteMessage";
$postFields = [
'chat_id' => $message['chat_id'],
'message_id' => $message['mensaje_telegram_id']
];
$ch = curl_init($telegramApiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
$telegramDeletionError = "Error cURL al eliminar de Telegram: " . $curlError;
$telegramDeletionSuccess = false;
} elseif ($httpCode !== 200) { // 200 OK es la respuesta esperada para DELETE exitoso en Telegram (con 'ok': true)
$responseJson = json_decode($response, true);
if (!($responseJson['ok'] ?? false)) {
$telegramDeletionError = $responseJson['description'] ?? 'Error desconocido de Telegram al eliminar';
$telegramDeletionSuccess = false;
}
}
}
}
// 3. Deshabilitar el mensaje en la base de datos
// Si es un mensaje programado/recurrente pendiente, simplemente lo deshabilitamos sin intentar borrar de Telegram
$updateStmt = $db->prepare("UPDATE mensajes_telegram SET estado = 'deshabilitado' WHERE id = ?");
$updateStmt->execute([$messageId]);
logToFile('telegram/messages.log', "Mensaje deshabilitado (ID: {$messageId}) por Usuario: {$userData->username}. Telegram deletion: " . ($telegramDeletionSuccess ? 'OK' : 'Fallido/' . $telegramDeletionError));
jsonResponse([
'success' => true,
'message' => 'Mensaje deshabilitado correctamente.',
'telegram_deletion_attempted' => !empty($message['mensaje_telegram_id']) && $message['tipo_envio'] === 'inmediato',
'telegram_deletion_success' => $telegramDeletionSuccess,
'telegram_deletion_error' => $telegramDeletionError
]);
} catch (Exception $e) {
logToFile('telegram/errors.log', "Error deshabilitando mensaje: " . $e->getMessage(), 'ERROR');
jsonResponse(['success' => false, 'error' => 'Ocurrió un error en el servidor.'], 500);
}

View File

@@ -0,0 +1,4 @@
[30-Nov-2025 16:36:15 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/telegram/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[30-Nov-2025 17:01:44 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/telegram/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[30-Nov-2025 17:07:42 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/telegram/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[30-Nov-2025 17:12:03 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/telegram/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40

49
telegram/api/messages/retry.php Executable file
View File

@@ -0,0 +1,49 @@
<?php
/**
* API - Reintentar Mensaje Telegram
* Cambia el estado de un mensaje a 'pendiente'.
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
// Verificar permiso (reutilizamos 'send_messages' ya que es una acción relacionada)
if (!hasPermission('send_messages', 'telegram')) {
jsonResponse(['success' => false, 'error' => 'No tienes permiso para gestionar mensajes de Telegram.'], 403);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
$input = json_decode(file_get_contents('php://input'), true);
$messageId = $input['id'] ?? null;
if (empty($messageId)) {
jsonResponse(['success' => false, 'error' => 'Falta el ID del mensaje.'], 400);
}
try {
$db = getDB();
// Cambiar el estado del mensaje a 'pendiente'
$stmt = $db->prepare("UPDATE mensajes_telegram SET estado = 'pendiente' WHERE id = ?");
$stmt->execute([$messageId]);
if ($stmt->rowCount() > 0) {
jsonResponse(['success' => true, 'message' => 'Mensaje marcado como pendiente.']);
} else {
jsonResponse(['success' => false, 'error' => 'No se encontró el mensaje o no se pudo actualizar.']);
}
} catch (Exception $e) {
jsonResponse(['success' => false, 'error' => 'Error en la base de datos: ' . $e->getMessage()], 500);
}

213
telegram/api/messages/send.php Executable file
View File

@@ -0,0 +1,213 @@
<?php
/**
* API - Enviar Mensaje Telegram (Adaptado para múltiples destinatarios y tipos de envío)
*/
header('Content-Type: application/json');
// Habilitar errores para debug (quitar en producción estricta)
ini_set('display_errors', 0);
error_reporting(E_ALL);
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
// Verificar permiso
if (!hasPermission('send_messages', 'telegram')) {
jsonResponse(['success' => false, 'error' => 'No tienes permiso para enviar mensajes de Telegram.'], 403);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
$input = json_decode(file_get_contents('php://input'), true);
$destinatariosInput = $input['destinatario_id'] ?? []; // Puede ser un string o un array
$contenido = $input['contenido'] ?? '';
$tipoEnvio = $input['tipo_envio'] ?? 'inmediato'; // 'inmediato', 'programado', 'recurrente'
// Asegurarse de que $destinatariosInput sea siempre un array
if (!is_array($destinatariosInput)) {
$destinatariosInput = [$destinatariosInput];
}
$destinatarios = array_filter(array_map('trim', $destinatariosInput)); // Limpiar y filtrar vacíos
if (empty($destinatarios) || empty($contenido)) {
jsonResponse(['success' => false, 'error' => 'Faltan datos requeridos: destinatario(s) y contenido'], 400);
}
try {
$db = getDB();
$botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
if (!$botToken) {
throw new Exception("Token de bot de Telegram no configurado.");
}
// Procesar contenido HTML para extraer imágenes y texto
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $contenido, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$imageUrl = null;
$images = $dom->getElementsByTagName('img');
if ($images->length > 0) {
// Telegram Bot API generalmente solo permite una imagen por mensaje (en sendPhoto)
// Tomamos la primera imagen encontrada
$imageUrl = $images->item(0)->getAttribute('src');
}
// Limpiar texto para Telegram (puede usar Markdown, pero primero quitamos HTML tags)
$cleanContent = strip_tags($contenido); // Quitar tags HTML
$cleanContent = html_entity_decode($cleanContent, ENT_QUOTES, 'UTF-8'); // Decodificar entidades HTML
$cleanContent = trim($cleanContent);
$allResults = [];
foreach ($destinatarios as $destinatarioId) {
$messageStatus = 'pendiente'; // Estado por defecto para programados/recurrentes si no es inmediato
$telegramMessageId = null;
$errorMessage = null;
if ($tipoEnvio === 'inmediato') {
$telegramApiUrl = "https://api.telegram.org/bot{$botToken}/";
$postFields = [
'chat_id' => $destinatarioId,
];
if ($imageUrl) {
// Si hay imagen, usar sendPhoto
$postFields['photo'] = $imageUrl;
// El caption del sendPhoto soporta HTML/Markdown, por simplicidad usamos el texto limpio
$postFields['caption'] = $cleanContent;
$method = 'sendPhoto';
} else {
// Si no hay imagen, usar sendMessage
$postFields['text'] = $cleanContent;
$method = 'sendMessage';
}
$ch = curl_init($telegramApiUrl . $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
$responseJson = json_decode($response, true);
if ($curlError) {
$errorMessage = "Error cURL: " . $curlError;
} elseif ($httpCode !== 200 || !($responseJson['ok'] ?? false)) {
$errorMessage = $responseJson['description'] ?? 'Error desconocido de Telegram API';
} else {
$messageStatus = 'enviado';
$telegramMessageId = $responseJson['result']['message_id'] ?? null;
}
}
// 3. Guardar en base de datos (Historial) para CADA destinatario
$stmt = $db->prepare("
INSERT INTO mensajes_telegram (usuario_id, chat_id, contenido, estado, mensaje_telegram_id, fecha_envio, tipo_envio)
VALUES (?, ?, ?, ?, ?, ?, ?)
");
$scheduledSendTime = null;
if ($tipoEnvio === 'programado' && isset($input['fecha_envio'])) {
// Convertir la fecha local a UTC para guardar en DB
$datetime = new DateTime($input['fecha_envio'], new DateTimeZone($_ENV['TIME_ZONE_ENVIOS'] ?? 'UTC'));
$datetime->setTimezone(new DateTimeZone('UTC'));
$scheduledSendTime = $datetime->format('Y-m-d H:i:s');
} elseif ($tipoEnvio === 'inmediato') {
$scheduledSendTime = date('Y-m-d H:i:s');
}
$finalMessageStatus = ($tipoEnvio === 'inmediato' && $messageStatus === 'fallido') ? 'fallido' : $messageStatus;
$stmt->execute([
$userData->userId,
$destinatarioId,
$contenido, // Guardamos el original con HTML/formato para referencia
$finalMessageStatus,
$telegramMessageId,
$scheduledSendTime,
$tipoEnvio
]);
$messageDbId = $db->lastInsertId();
// Si es recurrente, guardar también en la tabla recurrentes_telegram
if ($tipoEnvio === 'recurrente') {
// Validar y obtener hora de envío
$horaEnvio = $input['hora_envio'] ?? '09:00:00';
if (!preg_match('/^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/', $horaEnvio) && !preg_match('/^([01]\d|2[0-3]):([0-5]\d)$/', $horaEnvio)) {
$horaEnvio = '09:00:00'; // Valor por defecto si es inválido
}
if (strlen($horaEnvio) === 5) { // Si viene sin segundos, añadir
$horaEnvio .= ':00';
}
$nextSendTime = null; // Esto debería ser calculado por un demonio de scheduling
$stmtRecur = $db->prepare("
INSERT INTO recurrentes_telegram (mensaje_id, frecuencia, hora_envio, dia_semana, dia_mes, activo, proximo_envio)
VALUES (?, ?, ?, ?, ?, 1, ?)
");
$stmtRecur->execute([
$messageDbId,
$input['frecuencia'] ?? 'diario',
$horaEnvio,
$input['dia_semana'] ?? null,
$input['dia_mes'] ?? null,
$nextSendTime // Será calculado por el demonio
]);
}
$allResults[] = [
'destinatario_id' => $destinatarioId,
'message_db_id' => $messageDbId,
'status' => $finalMessageStatus,
'error' => $errorMessage,
'telegram_message_id' => $telegramMessageId,
'tipo_envio' => $tipoEnvio
];
if ($finalMessageStatus === 'enviado') {
logToFile('telegram/messages.log', "Mensaje enviado a {$destinatarioId} por {$userData->username}");
} elseif ($finalMessageStatus === 'pendiente') {
logToFile('telegram/messages.log', "Mensaje {$tipoEnvio} guardado para {$destinatarioId} por {$userData->username}");
} else {
logToFile('telegram/errors.log', "Error enviando mensaje a {$destinatarioId}: {$errorMessage}", 'ERROR');
}
}
// Determinar el éxito general de la operación
$overallSuccess = array_reduce($allResults, function($carry, $item) {
// Considerar éxito si al menos un mensaje fue enviado o está pendiente
return $carry || ($item['status'] === 'enviado' || $item['status'] === 'pendiente');
}, false);
jsonResponse([
'success' => $overallSuccess,
'message' => 'Procesamiento de mensajes completado.',
'details' => $allResults,
'overall_status' => $overallSuccess ? 'partial_success_or_pending' : 'all_failed'
]);
} catch (Exception $e) {
logToFile('telegram/errors.log', "Error general en el envío de mensajes: " . $e->getMessage(), 'ERROR');
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}

View File

@@ -0,0 +1,41 @@
<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
// Verificar permiso
if (!hasPermission('manage_recipients', 'telegram')) {
jsonResponse(['success' => false, 'error' => 'No tienes permiso para crear destinatarios de Telegram.'], 403);
}
$input = json_decode(file_get_contents('php://input'), true);
$nombre = trim($input['nombre'] ?? '');
$telegram_id = trim($input['telegram_id'] ?? '');
$tipo = trim($input['tipo'] ?? 'canal');
if (empty($nombre) || empty($telegram_id)) {
jsonResponse(['success' => false, 'error' => 'Faltan datos'], 400);
}
try {
$db = getDB();
$stmt = $db->prepare("
INSERT INTO destinatarios_telegram (nombre, telegram_id, tipo, activo)
VALUES (?, ?, ?, 1)
");
$stmt->execute([$nombre, $telegram_id, $tipo]);
jsonResponse(['success' => true]);
} catch (PDOException $e) {
if ($e->getCode() == 23000) {
jsonResponse(['success' => false, 'error' => 'Este ID de Telegram ya está registrado'], 409);
}
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}

View File

@@ -0,0 +1,33 @@
<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
// Verificar permiso
if (!hasPermission('manage_recipients', 'telegram')) {
jsonResponse(['success' => false, 'error' => 'No tienes permiso para eliminar destinatarios de Telegram.'], 403);
}
$input = json_decode(file_get_contents('php://input'), true);
$id = $input['id'] ?? null;
if (!$id) {
jsonResponse(['success' => false, 'error' => 'ID requerido'], 400);
}
try {
$db = getDB();
$stmt = $db->prepare("DELETE FROM destinatarios_telegram WHERE id = ?");
$stmt->execute([$id]);
jsonResponse(['success' => true]);
} catch (PDOException $e) {
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}

View File

@@ -0,0 +1,85 @@
<?php
/**
* API - Editar Destinatario Telegram
*/
header('Content-Type: application/json');
// Habilitar errores para debug (quitar en producción estricta)
ini_set('display_errors', 0);
error_reporting(E_ALL);
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
// Verificar permiso
if (!hasPermission('manage_recipients', 'telegram')) {
jsonResponse(['success' => false, 'error' => 'No tienes permiso para editar destinatarios de Telegram.'], 403);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
$input = json_decode(file_get_contents('php://input'), true);
$id = $input['id'] ?? null;
$nombre = trim($input['nombre'] ?? '');
$telegram_id = trim($input['telegram_id'] ?? '');
$tipo = trim($input['tipo'] ?? '');
// Validaciones
if (empty($id) || !is_numeric($id)) {
jsonResponse(['success' => false, 'error' => 'ID de destinatario inválido'], 400);
}
if (empty($nombre) || empty($telegram_id) || empty($tipo)) {
jsonResponse(['success' => false, 'error' => 'Faltan datos requeridos (nombre, ID de Telegram, tipo)'], 400);
}
if (!in_array($tipo, ['canal', 'usuario', 'grupo'])) { // Permitir 'grupo' aunque no esté en UI aún
jsonResponse(['success' => false, 'error' => 'Tipo de destinatario inválido'], 400);
}
try {
$db = getDB();
// 1. Verificar si el destinatario existe y si el usuario tiene permisos
$stmt = $db->prepare("SELECT usuario_id FROM destinatarios_telegram WHERE id = ?");
$stmt->execute([$id]);
$recipient = $stmt->fetch();
if (!$recipient) {
jsonResponse(['success' => false, 'error' => 'Destinatario no encontrado'], 404);
}
// Opcional: Si se implementara la propiedad del destinatario, se verificaría aquí
// if ($userData->rol !== 'Admin' && $recipient['usuario_id'] != $userData->userId) {
// jsonResponse(['success' => false, 'error' => 'No tiene permisos para editar este destinatario'], 403);
// }
// 2. Verificar duplicidad de telegram_id (excluyendo el propio destinatario)
$stmt = $db->prepare("SELECT id FROM destinatarios_telegram WHERE telegram_id = ? AND id != ?");
$stmt->execute([$telegram_id, $id]);
if ($stmt->fetch()) {
jsonResponse(['success' => false, 'error' => 'Ya existe un destinatario con este ID de Telegram'], 409);
}
// 3. Actualizar el destinatario
$stmt = $db->prepare("
UPDATE destinatarios_telegram
SET nombre = ?, telegram_id = ?, tipo = ?
WHERE id = ?
");
$stmt->execute([$nombre, $telegram_id, $tipo, $id]);
logToFile('telegram/recipients.log', "Destinatario editado: ID={$id}, Nombre={$nombre}, Usuario={$userData->username}");
jsonResponse(['success' => true, 'message' => 'Destinatario actualizado correctamente']);
} catch (Exception $e) {
logToFile('telegram/errors.log', "Error editando destinatario: " . $e->getMessage(), 'ERROR');
jsonResponse(['success' => false, 'error' => 'Ocurrió un error en el servidor.'], 500);
}

130
telegram/api/recipients/kick.php Executable file
View File

@@ -0,0 +1,130 @@
<?php
/**
* API - Expulsar/Remover Destinatario Telegram
* Expulsa a un usuario de un chat de Telegram o remueve el bot de un chat/canal/grupo (según el tipo)
*/
header('Content-Type: application/json');
// Habilitar errores para debug (quitar en producción estricta)
ini_set('display_errors', 0);
error_reporting(E_ALL);
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
// Verificar permiso
if (!hasPermission('manage_recipients', 'telegram')) {
jsonResponse(['success' => false, 'error' => 'No tienes permiso para expulsar/remover destinatarios de Telegram.'], 403);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
$input = json_decode(file_get_contents('php://input'), true);
$recipientDbId = $input['id'] ?? null; // ID de nuestra base de datos
if (empty($recipientDbId) || !is_numeric($recipientDbId)) {
jsonResponse(['success' => false, 'error' => 'ID de destinatario inválido o no proporcionado'], 400);
}
try {
$db = getDB();
$botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
if (!$botToken) {
throw new Exception("Token de bot de Telegram no configurado.");
}
// 1. Obtener detalles del destinatario de nuestra DB
$stmt = $db->prepare("SELECT telegram_id, tipo FROM destinatarios_telegram WHERE id = ?");
$stmt->execute([$recipientDbId]);
$recipient = $stmt->fetch();
if (!$recipient) {
jsonResponse(['success' => false, 'error' => 'Destinatario no encontrado en la base de datos local.'], 404);
}
$telegramId = $recipient['telegram_id']; // Puede ser ID de usuario o de chat/canal
$tipo = $recipient['tipo'];
$actionSuccess = false;
$actionMessage = '';
// Lógica para expulsar/remover según el tipo en Telegram
// NOTA: Para expulsar a un usuario, se necesita el chat_id (grupo/canal) y el user_id.
// Nuestra tabla 'destinatarios_telegram' guarda el 'telegram_id' que puede ser chat_id o user_id.
// Esto hace que la lógica de expulsión sea más compleja si no tenemos el chat_id contextual.
// Por simplicidad, implementaremos la remoción local. Si el plan requiere expulsar de un chat específico,
// se necesitaría un input adicional para el chat_id.
switch ($tipo) {
case 'usuario':
// Para expulsar un usuario, necesitamos el `chat_id` del grupo/canal donde está.
// Actualmente `destinatarios_telegram` solo guarda el ID del usuario.
// Si el plan es "expulsar" al usuario de un chat donde el bot es admin,
// necesitaríamos el chat_id del input.
// Para mantener la consistencia con el Discord "expulsar" (que elimina de la DB y del Guild),
// aquí solo eliminaremos de la DB local y daremos un mensaje que la acción en Telegram es limitada.
$actionSuccess = true;
$actionMessage = "Acción de 'expulsar' un usuario de Telegram es compleja sin un chat_id. Se eliminó de la base de datos local.";
break;
case 'canal':
case 'grupo':
// Para canales/grupos, "expulsar" podría significar que el bot abandone el chat/canal/grupo.
// Endpoint: leaveChat
// 'kickChatMember' es para usuarios, no para bots abandonando chats.
$url = "https://api.telegram.org/bot{$botToken}/leaveChat";
$postFields = ['chat_id' => $telegramId];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
throw new Exception("Error cURL al intentar que el bot abandone el chat/canal de Telegram: " . $curlError);
}
$responseJson = json_decode($response, true);
if ($httpCode === 200 && ($responseJson['ok'] ?? false)) {
$actionSuccess = true;
$actionMessage = "Bot abandonó el chat/canal {$telegramId} en Telegram.";
} else {
$actionMessage = "Error de Telegram al abandonar chat/canal ({$httpCode}): " . ($responseJson['description'] ?? 'Desconocido');
}
break;
default:
jsonResponse(['success' => false, 'error' => 'Tipo de destinatario no soportado para expulsión.'], 400);
break;
}
if ($actionSuccess) {
// Eliminar el destinatario de nuestra base de datos
$deleteStmt = $db->prepare("DELETE FROM destinatarios_telegram WHERE id = ?");
$deleteStmt->execute([$recipientDbId]);
logToFile('telegram/recipients.log', "Destinatario '{$recipient['telegram_id']}' ({$tipo}) expulsado/eliminado de Telegram y de la DB local por Usuario: {$userData->username}.");
jsonResponse(['success' => true, 'message' => 'Destinatario expulsado/eliminado correctamente.', 'telegram_action' => $actionMessage]);
} else {
logToFile('telegram/errors.log', "Fallo al expulsar/eliminar destinatario '{$recipient['telegram_id']}' ({$tipo}): {$actionMessage}", 'ERROR');
jsonResponse(['success' => false, 'error' => 'Fallo al realizar la acción en Telegram: ' . $actionMessage], 500);
}
} catch (Exception $e) {
logToFile('telegram/errors.log', "Error general en la API de expulsión de destinatarios: " . $e->getMessage(), 'ERROR');
jsonResponse(['success' => false, 'error' => 'Ocurrió un error en el servidor: ' . $e->getMessage()], 500);
}

View File

@@ -0,0 +1,3 @@
[30-Nov-2025 17:14:57 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/telegram/errors.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[30-Nov-2025 17:15:03 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/telegram/errors.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
[30-Nov-2025 17:15:07 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/telegram/errors.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40

View File

@@ -0,0 +1,93 @@
<?php
/**
* API de Plantillas de Telegram - Crear
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Para depuración
ini_set('display_errors', 0);
error_reporting(E_ALL);
// Autenticación
try {
$userData = JWTAuth::requireAuth();
} catch (Exception $e) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'No autenticado: ' . $e->getMessage()]);
exit;
}
// Verificar permiso
if (!hasPermission('manage_templates', 'telegram')) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No tienes permiso para crear plantillas de Telegram.']);
exit;
}
// Solo permitir método POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
exit;
}
// Obtener datos
$data = json_decode(file_get_contents('php://input'), true);
$nombre = trim($data['nombre'] ?? '');
$comando = trim($data['comando'] ?? '');
$contenido = $data['contenido'] ?? '';
// Validación
if (empty($nombre) || empty($contenido)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'El nombre y el contenido de la plantilla son obligatorios.']);
exit;
}
try {
$db = getDB();
// Verificar si el comando ya existe (si se proporcionó)
if ($comando) {
$stmt = $db->prepare("SELECT id FROM plantillas_telegram WHERE comando = ?");
$stmt->execute([$comando]);
if ($stmt->fetch()) {
http_response_code(409); // 409 Conflict
echo json_encode(['success' => false, 'error' => 'Ya existe una plantilla con ese comando.']);
exit;
}
}
// Insertar en la base de datos
$stmt = $db->prepare("
INSERT INTO plantillas_telegram (nombre, comando, contenido, usuario_id, fecha_creacion, fecha_modificacion)
VALUES (?, ?, ?, ?, NOW(), NOW())
");
$stmt->execute([
$nombre,
empty($comando) ? null : $comando,
$contenido,
$userData->userId
]);
$newTemplateId = $db->lastInsertId();
logToFile('telegram/templates.log', "Plantilla creada: {$nombre} (ID: {$newTemplateId}), Usuario: {$userData->username}");
echo json_encode([
'success' => true,
'message' => 'Plantilla creada correctamente.',
'templateId' => $newTemplateId
]);
} catch (Exception $e) {
http_response_code(500);
error_log('Error en /telegram/api/templates/create.php: ' . $e->getMessage());
echo json_encode(['success' => false, 'error' => 'Error del servidor al guardar la plantilla.']);
}

View File

@@ -0,0 +1,64 @@
<?php
/**
* API - Eliminar plantilla Telegram
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
if (!isAuthenticated()) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'No autenticado']);
exit;
}
// Verificar permiso
if (!hasPermission('manage_templates', 'telegram')) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No tienes permiso para eliminar plantillas de Telegram.']);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['id'])) {
jsonResponse(['success' => false, 'error' => 'ID no proporcionado'], 400);
}
try {
$db = getDB();
// Verificar que la plantilla existe
$stmt = $db->prepare("SELECT * FROM plantillas_telegram WHERE id = ?");
$stmt->execute([$input['id']]);
$plantilla = $stmt->fetch();
if (!$plantilla) {
jsonResponse(['success' => false, 'error' => 'Plantilla no encontrada'], 404);
}
// Verificar permisos (admin o creador)
if ($userData->rol !== 'Admin' && $plantilla['usuario_id'] != $userData->userId) {
jsonResponse(['success' => false, 'error' => 'No tiene permisos para eliminar esta plantilla'], 403);
}
// Eliminar plantilla
$stmt = $db->prepare("DELETE FROM plantillas_telegram WHERE id = ?");
$stmt->execute([$input['id']]);
logToFile('telegram/templates.log', "Plantilla eliminada: ID={$input['id']}, Usuario={$userData->username}");
jsonResponse(['success' => true, 'message' => 'Plantilla eliminada correctamente']);
} catch (Exception $e) {
logToFile('telegram/errors.log', "Error eliminando plantilla: " . $e->getMessage(), 'ERROR');
jsonResponse(['success' => false, 'error' => 'Error del servidor'], 500);
}

115
telegram/api/templates/edit.php Executable file
View File

@@ -0,0 +1,115 @@
<?php
/**
* API de Plantillas de Telegram - Editar
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Para depuración
ini_set('display_errors', 0);
error_reporting(E_ALL);
// Autenticación
try {
$userData = JWTAuth::requireAuth();
} catch (Exception $e) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'No autenticado: ' . $e->getMessage()]);
exit;
}
// Verificar permiso
if (!hasPermission('manage_templates', 'telegram')) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No tienes permiso para editar plantillas de Telegram.']);
exit;
}
// Solo permitir método POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
exit;
}
// Obtener datos
$data = json_decode(file_get_contents('php://input'), true);
$id = $data['id'] ?? null;
$nombre = trim($data['nombre'] ?? '');
$comando = trim($data['comando'] ?? '');
$contenido = $data['contenido'] ?? '';
// Validación
if (!$id || !is_numeric($id)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'ID de plantilla inválido o no proporcionado.']);
exit;
}
if (empty($nombre) || empty($contenido)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'El nombre y el contenido de la plantilla son obligatorios.']);
exit;
}
try {
$db = getDB();
// Obtener la plantilla actual para verificar permisos
$stmt = $db->prepare("SELECT usuario_id FROM plantillas_telegram WHERE id = ?");
$stmt->execute([$id]);
$plantillaExistente = $stmt->fetch();
if (!$plantillaExistente) {
http_response_code(404);
echo json_encode(['success' => false, 'error' => 'Plantilla no encontrada.']);
exit;
}
// Verificar permisos: solo Admin o el propietario pueden editar
if ($userData->rol !== 'Admin' && $plantillaExistente['usuario_id'] != $userData->userId) {
http_response_code(403); // Forbidden
echo json_encode(['success' => false, 'error' => 'No tiene permisos para editar esta plantilla.']);
exit;
}
// Verificar si el comando ya existe (excepto para la plantilla actual)
if (!empty($comando)) {
$stmt = $db->prepare("SELECT id FROM plantillas_telegram WHERE comando = ? AND id != ?");
$stmt->execute([$comando, $id]);
if ($stmt->fetch()) {
http_response_code(409); // Conflict
echo json_encode(['success' => false, 'error' => 'Ya existe otra plantilla con ese comando.']);
exit;
}
}
// Actualizar en la base de datos
$stmt = $db->prepare("
UPDATE plantillas_telegram
SET nombre = ?, comando = ?, contenido = ?, fecha_modificacion = NOW()
WHERE id = ?
");
$stmt->execute([
$nombre,
empty($comando) ? null : $comando,
$contenido,
$id
]);
logToFile('telegram/templates.log', "Plantilla editada: ID={$id}, por Usuario: {$userData->username}");
echo json_encode([
'success' => true,
'message' => 'Plantilla actualizada correctamente.'
]);
} catch (Exception $e) {
http_response_code(500);
logToFile('telegram/errors.log', 'Error editando plantilla: ' . $e->getMessage(), 'ERROR');
echo json_encode(['success' => false, 'error' => 'Ocurrió un error en el servidor al actualizar la plantilla.']);
}

64
telegram/api/templates/list.php Executable file
View File

@@ -0,0 +1,64 @@
<?php
/**
* API de Plantillas de Telegram - Listar
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Para depuración
ini_set('display_errors', 0);
error_reporting(E_ALL);
// Verificar autenticación
if (!isAuthenticated()) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'No autenticado']);
exit;
}
// Verificar permiso
if (!hasPermission('view_templates', 'telegram')) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No tienes permiso para ver las plantillas de Telegram.']);
exit;
}
try {
$db = getDB();
// Búsqueda (opcional, para futuras mejoras)
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$sql = "
SELECT p.id, p.nombre, p.comando, p.fecha_modificacion, u.username
FROM plantillas_telegram p
LEFT JOIN usuarios u ON p.usuario_id = u.id
";
$params = [];
if (!empty($search)) {
$sql .= " WHERE p.nombre LIKE ? OR p.comando LIKE ?";
$params[] = "%{$search}%";
$params[] = "%{$search}%";
}
$sql .= " ORDER BY p.fecha_modificacion DESC";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$templates = $stmt->fetchAll();
echo json_encode([
'success' => true,
'templates' => $templates
]);
} catch (Exception $e) {
http_response_code(500);
error_log('Error en /telegram/api/templates/list.php: ' . $e->getMessage());
echo json_encode(['success' => false, 'error' => 'Error del servidor al obtener las plantillas.']);
}

119
telegram/api/webhook/manage.php Executable file
View File

@@ -0,0 +1,119 @@
<?php
/**
* API - Gestión de Webhook de Telegram
*/
header('Content-Type: application/json');
// Habilitar errores para debug (quitar en producción estricta)
ini_set('display_errors', 0);
error_reporting(E_ALL);
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
// Verificar permiso
if (!hasPermission('manage_webhooks', 'telegram')) {
jsonResponse(['success' => false, 'error' => 'No tienes permiso para gestionar webhooks de Telegram.'], 403);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';
try {
$botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
$webhookSecretToken = $_ENV['TELEGRAM_WEBHOOK_TOKEN'] ?? getenv('TELEGRAM_WEBHOOK_TOKEN');
if (empty($botToken)) {
throw new Exception("TELEGRAM_BOT_TOKEN no configurado en .env");
}
$telegramApiUrl = "https://api.telegram.org/bot{$botToken}/";
$result = null;
switch ($action) {
case 'set':
$url = $input['url'] ?? '';
if (empty($url)) {
jsonResponse(['success' => false, 'error' => 'URL del webhook no proporcionada'], 400);
}
$postFields = ['url' => $url];
if (!empty($webhookSecretToken)) {
$postFields['secret_token'] = $webhookSecretToken;
}
$response = sendTelegramApiRequest($telegramApiUrl . 'setWebhook', $postFields);
$result = $response['response'];
$success = $response['ok'];
if (!$success) {
logToFile('telegram/errors.log', "Error configurando webhook: " . json_encode($result), 'ERROR');
} else {
logToFile('telegram/webhooks.log', "Webhook configurado a: {$url} por Usuario: {$userData->username}");
}
jsonResponse(['success' => $success, 'message' => $result['description'] ?? 'OK', 'data' => $result]);
break;
case 'delete':
$response = sendTelegramApiRequest($telegramApiUrl . 'deleteWebhook');
$result = $response['response'];
$success = $response['ok'];
if (!$success) {
logToFile('telegram/errors.log', "Error eliminando webhook: " . json_encode($result), 'ERROR');
} else {
logToFile('telegram/webhooks.log', "Webhook eliminado por Usuario: {$userData->username}");
}
jsonResponse(['success' => $success, 'message' => $result['description'] ?? 'OK', 'data' => $result]);
break;
case 'info':
$response = sendTelegramApiRequest($telegramApiUrl . 'getWebhookInfo');
$result = $response['response'];
$success = $response['ok'];
jsonResponse(['success' => $success, 'message' => $result['description'] ?? 'OK', 'data' => $result]);
break;
default:
jsonResponse(['success' => false, 'error' => 'Acción de webhook no reconocida'], 400);
break;
}
} catch (Exception $e) {
logToFile('telegram/errors.log', "Error general en la gestión de webhook: " . $e->getMessage(), 'ERROR');
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}
/**
* Función auxiliar para enviar solicitudes a la API de Telegram
*/
function sendTelegramApiRequest($url, $params = []) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (!empty($params)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
$responseJson = json_decode($response, true);
return [
'ok' => ($httpCode === 200 && ($responseJson['ok'] ?? false)),
'response' => $responseJson,
'http_code' => $httpCode,
'curl_error' => $curlError
];
}

View File

@@ -0,0 +1,144 @@
<?php
/**
* API - Enviar Mensaje de Bienvenida de Prueba a Telegram
*/
header('Content-Type: application/json');
// Habilitar errores para debug (quitar en producción estricta)
ini_set('display_errors', 0);
error_reporting(E_ALL);
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}
// Verificar permiso
if (!hasPermission('manage_welcome', 'telegram')) {
jsonResponse(['success' => false, 'error' => 'No tienes permiso para gestionar el mensaje de bienvenida de Telegram.'], 403);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
try {
$db = getDB();
$botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
if (!$botToken) {
throw new Exception("Token de bot de Telegram no configurado.");
}
// 1. Obtener la configuración de bienvenida
$stmt = $db->query("
SELECT b.*, g.ruta as imagen_ruta
FROM bienvenida_telegram b
LEFT JOIN gallery g ON b.imagen_id = g.id
LIMIT 1
");
$config = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$config || empty($config['activo'])) {
throw new Exception("El mensaje de bienvenida no está activo o configurado.");
}
if (empty($config['chat_id'])) {
throw new Exception("No hay un canal de bienvenida configurado.");
}
$chat_id = $config['chat_id'];
$texto = $config['texto'] ?? "¡Bienvenido {usuario}!";
$imagen_url = !empty($config['imagen_id']) && !empty($config['imagen_ruta']) ?
($_ENV['APP_URL'] ?? 'http://localhost') . '/gallery/uploads/' . basename($config['imagen_ruta']) : null;
// Simular un nuevo usuario para el mensaje de prueba
$testUser = $userData->username ?? 'Tester'; // Usar el username del usuario logueado como test
$messageText = str_replace('{usuario}', $testUser, $texto);
// Preparar opciones de teclado (botones de idioma y botón "Únete al grupo")
$keyboard = [];
$inline_keyboard = [];
// Botones de Idioma
$idiomasHabilitados = json_decode($config['idiomas_habilitados'], true) ?? [];
if (!empty($idiomasHabilitados)) {
$row = [];
foreach ($idiomasHabilitados as $langCode) {
// Suponemos que tienes una forma de obtener el nombre del idioma por su código
$langName = strtoupper($langCode); // Simplificado: usa el código como nombre
$row[] = ['text' => $langName, 'callback_data' => "lang_select_{$langCode}"];
if (count($row) == 2) { // 2 botones por fila
$inline_keyboard[] = $row;
$row = [];
}
}
if (!empty($row)) {
$inline_keyboard[] = $row;
}
}
// Botón "Únete al grupo"
if (!empty($config['boton_unirse_texto']) && !empty($config['boton_unirse_url'])) {
$inline_keyboard[] = [['text' => $config['boton_unirse_texto'], 'url' => $config['boton_unirse_url']]];
}
if (!empty($inline_keyboard)) {
$keyboard = ['inline_keyboard' => $inline_keyboard];
}
$telegramApiUrl = "https://api.telegram.org/bot{$botToken}/";
$method = 'sendMessage';
$postFields = [
'chat_id' => $chat_id,
'parse_mode' => 'HTML', // o 'MarkdownV2', dependiendo del formato de Summernote
];
if ($imagen_url) {
$method = 'sendPhoto';
$postFields['photo'] = $imagen_url;
$postFields['caption'] = $messageText;
unset($postFields['text']); // sendPhoto usa 'caption' en lugar de 'text'
} else {
$postFields['text'] = $messageText;
}
if (!empty($keyboard)) {
$postFields['reply_markup'] = json_encode($keyboard);
}
$ch = curl_init($telegramApiUrl . $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
throw new Exception("Error cURL: " . $curlError);
}
$responseJson = json_decode($response, true);
if ($httpCode !== 200 || !($responseJson['ok'] ?? false)) {
$errorMsg = $responseJson['description'] ?? 'Error desconocido de Telegram API';
throw new Exception("Telegram API Error ({$httpCode}): {$errorMsg}");
}
logToFile('telegram/messages.log', "Mensaje de bienvenida de prueba enviado a {$chat_id} por {$userData->username}");
jsonResponse(['success' => true, 'message' => 'Mensaje de prueba enviado con éxito a Telegram!', 'telegram_response' => $responseJson]);
} catch (Exception $e) {
logToFile('telegram/errors.log', "Error enviando mensaje de bienvenida de prueba: " . $e->getMessage(), 'ERROR');
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}