Primer commit del sistema separado falta mejorar mucho
This commit is contained in:
41
telegram/api/recipients/create.php
Executable file
41
telegram/api/recipients/create.php
Executable 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);
|
||||
}
|
||||
33
telegram/api/recipients/delete.php
Executable file
33
telegram/api/recipients/delete.php
Executable 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);
|
||||
}
|
||||
85
telegram/api/recipients/edit.php
Executable file
85
telegram/api/recipients/edit.php
Executable 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
130
telegram/api/recipients/kick.php
Executable 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);
|
||||
}
|
||||
3
telegram/api/recipients/php_errors.log
Executable file
3
telegram/api/recipients/php_errors.log
Executable 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
|
||||
Reference in New Issue
Block a user