Primer commit del sistema separado falta mejorar mucho
This commit is contained in:
35
discord/api/commands/create.php
Executable file
35
discord/api/commands/create.php
Executable file
@@ -0,0 +1,35 @@
|
||||
<?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';
|
||||
|
||||
$userData = JWTAuth::authenticate();
|
||||
if (!$userData) {
|
||||
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$comando = trim($input['comando'] ?? '');
|
||||
$descripcion = trim($input['descripcion'] ?? '');
|
||||
$plantilla_id = $input['plantilla_id'] ?? null;
|
||||
|
||||
if (empty($comando) || empty($plantilla_id)) {
|
||||
jsonResponse(['success' => false, 'error' => 'Faltan datos requeridos'], 400);
|
||||
}
|
||||
|
||||
try {
|
||||
$db = getDB();
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO comandos_discord (comando, descripcion, plantilla_id)
|
||||
VALUES (?, ?, ?)
|
||||
");
|
||||
$stmt->execute([$comando, $descripcion, $plantilla_id]);
|
||||
|
||||
jsonResponse(['success' => true]);
|
||||
} catch (PDOException $e) {
|
||||
if ($e->getCode() == 23000) {
|
||||
jsonResponse(['success' => false, 'error' => 'Este comando ya existe'], 409);
|
||||
}
|
||||
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
|
||||
}
|
||||
27
discord/api/commands/delete.php
Executable file
27
discord/api/commands/delete.php
Executable file
@@ -0,0 +1,27 @@
|
||||
<?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';
|
||||
|
||||
$userData = JWTAuth::authenticate();
|
||||
if (!$userData) {
|
||||
jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
|
||||
}
|
||||
|
||||
$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 comandos_discord WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
|
||||
jsonResponse(['success' => true]);
|
||||
} catch (PDOException $e) {
|
||||
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
|
||||
}
|
||||
104
discord/api/messages/delete.php
Executable file
104
discord/api/messages/delete.php
Executable file
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Eliminar/Deshabilitar Mensaje Discord
|
||||
* Cambia el estado del mensaje a 'deshabilitado' y opcionalmente lo elimina de Discord.
|
||||
*/
|
||||
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 Discord ID
|
||||
$stmt = $db->prepare("SELECT usuario_id, canal_id, mensaje_discord_id, tipo_envio FROM mensajes_discord 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 Discord si existe un mensaje_discord_id y fue un envío inmediato
|
||||
$discordDeletionSuccess = true;
|
||||
$discordDeletionError = null;
|
||||
|
||||
if (!empty($message['mensaje_discord_id']) && $message['tipo_envio'] === 'inmediato') {
|
||||
$botToken = $_ENV['DISCORD_BOT_TOKEN'] ?? getenv('DISCORD_BOT_TOKEN');
|
||||
if (!$botToken) {
|
||||
logToFile('discord/errors.log', "Error eliminando mensaje de Discord: Token de bot no configurado.", 'ERROR');
|
||||
$discordDeletionError = "Token de bot no configurado, no se pudo eliminar de Discord.";
|
||||
$discordDeletionSuccess = false;
|
||||
} else {
|
||||
$url = "https://discord.com/api/v10/channels/{$message['canal_id']}/messages/{$message['mensaje_discord_id']}";
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||||
'Authorization: Bot ' . $botToken,
|
||||
]);
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
|
||||
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) {
|
||||
$discordDeletionError = "Error cURL al eliminar de Discord: " . $curlError;
|
||||
$discordDeletionSuccess = false;
|
||||
} elseif ($httpCode !== 204) { // 204 No Content es la respuesta esperada para DELETE exitoso
|
||||
$responseJson = json_decode($response, true);
|
||||
$discordDeletionError = $responseJson['message'] ?? 'Error desconocido de Discord al eliminar';
|
||||
$discordDeletionSuccess = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Deshabilitar el mensaje en la base de datos
|
||||
// Si es un mensaje programado/recurrente pendiente, simplemente lo deshabilitamos sin intentar borrar de Discord
|
||||
$updateStmt = $db->prepare("UPDATE mensajes_discord SET estado = 'deshabilitado' WHERE id = ?");
|
||||
$updateStmt->execute([$messageId]);
|
||||
|
||||
logToFile('discord/messages.log', "Mensaje deshabilitado (ID: {$messageId}) por Usuario: {$userData->username}. Discord deletion: " . ($discordDeletionSuccess ? 'OK' : 'Fallido/' . $discordDeletionError));
|
||||
|
||||
jsonResponse([
|
||||
'success' => true,
|
||||
'message' => 'Mensaje deshabilitado correctamente.',
|
||||
'discord_deletion_attempted' => !empty($message['mensaje_discord_id']) && $message['tipo_envio'] === 'inmediato',
|
||||
'discord_deletion_success' => $discordDeletionSuccess,
|
||||
'discord_deletion_error' => $discordDeletionError
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
logToFile('discord/errors.log', "Error deshabilitando mensaje: " . $e->getMessage(), 'ERROR');
|
||||
jsonResponse(['success' => false, 'error' => 'Ocurrió un error en el servidor.'], 500);
|
||||
}
|
||||
7
discord/api/messages/php_errors.log
Executable file
7
discord/api/messages/php_errors.log
Executable file
@@ -0,0 +1,7 @@
|
||||
[30-Nov-2025 16:17:06 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/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 16:20:55 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/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 16:22:33 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/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 16:34:09 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/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 16:34:29 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/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:02:10 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[03-Dec-2025 20:51:19 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/messages.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
49
discord/api/messages/retry.php
Executable file
49
discord/api/messages/retry.php
Executable file
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Reintentar Mensaje Discord
|
||||
* 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', 'discord')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para gestionar mensajes de Discord.'], 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_discord 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);
|
||||
}
|
||||
221
discord/api/messages/send.php
Executable file
221
discord/api/messages/send.php
Executable file
@@ -0,0 +1,221 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Enviar Mensaje Discord
|
||||
*/
|
||||
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', 'discord')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para enviar mensajes de Discord.'], 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 {
|
||||
// 1. Procesar contenido HTML para extraer imágenes y limpiar texto (una vez para todos)
|
||||
$dom = new DOMDocument();
|
||||
// Suprimir errores de HTML mal formado y usar UTF-8
|
||||
libxml_use_internal_errors(true);
|
||||
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $contenido, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
|
||||
libxml_clear_errors();
|
||||
|
||||
$embeds = [];
|
||||
$images = $dom->getElementsByTagName('img');
|
||||
|
||||
// Extraer hasta 10 imágenes (límite de Discord)
|
||||
$count = 0;
|
||||
foreach ($images as $img) {
|
||||
if ($count >= 10) break;
|
||||
$src = $img->getAttribute('src');
|
||||
if ($src) {
|
||||
$embeds[] = [
|
||||
'image' => ['url' => $src]
|
||||
];
|
||||
$count++;
|
||||
}
|
||||
}
|
||||
|
||||
// Limpiar texto: convertir saltos de línea y eliminar tags
|
||||
$cleanContent = str_replace(['<br>', '<br/>', '<p>'], ["\n", "\n", "\n"], $contenido);
|
||||
$cleanContent = strip_tags($cleanContent);
|
||||
$cleanContent = html_entity_decode($cleanContent);
|
||||
$cleanContent = trim($cleanContent);
|
||||
|
||||
$db = getDB();
|
||||
$botToken = $_ENV['DISCORD_BOT_TOKEN'] ?? getenv('DISCORD_BOT_TOKEN');
|
||||
|
||||
if (!$botToken) {
|
||||
throw new Exception("Token de bot no configurado");
|
||||
}
|
||||
|
||||
$allResults = [];
|
||||
|
||||
foreach ($destinatarios as $destinatarioId) {
|
||||
$messageStatus = 'pendiente'; // Estado por defecto para programados/recurrentes
|
||||
$discordMessageId = null;
|
||||
$errorMessage = null;
|
||||
|
||||
if ($tipoEnvio === 'inmediato') {
|
||||
$url = "https://discord.com/api/v10/channels/{$destinatarioId}/messages";
|
||||
|
||||
$data = [
|
||||
'content' => $cleanContent
|
||||
];
|
||||
|
||||
if (!empty($embeds)) {
|
||||
$data['embeds'] = $embeds;
|
||||
}
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||||
'Authorization: Bot ' . $botToken,
|
||||
'Content-Type: application/json'
|
||||
]);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
|
||||
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 >= 400) {
|
||||
$errorMessage = $responseJson['message'] ?? 'Error desconocido de Discord';
|
||||
if (isset($responseJson['errors'])) {
|
||||
$errorMessage .= ' - ' . json_encode($responseJson['errors']);
|
||||
}
|
||||
} else {
|
||||
$messageStatus = 'enviado';
|
||||
$discordMessageId = $responseJson['id'] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Guardar en base de datos (Historial) para CADA destinatario
|
||||
// Inmediato: estado 'enviado' o 'fallido'
|
||||
// Programado/Recurrente: estado 'pendiente'
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO mensajes_discord (usuario_id, canal_id, contenido, estado, mensaje_discord_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'); // La fecha de envío es ahora
|
||||
}
|
||||
|
||||
$stmt->execute([
|
||||
$userData->userId,
|
||||
$destinatarioId,
|
||||
$contenido,
|
||||
($tipoEnvio === 'inmediato' && $messageStatus === 'fallido') ? 'fallido' : $messageStatus, // Estado correcto para inmediato/fallido
|
||||
$discordMessageId,
|
||||
$scheduledSendTime,
|
||||
$tipoEnvio
|
||||
]);
|
||||
|
||||
$messageDbId = $db->lastInsertId();
|
||||
|
||||
// Si es recurrente, guardar también en la tabla recurrentes_discord
|
||||
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_discord (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' => ($tipoEnvio === 'inmediato' && $messageStatus === 'fallido') ? 'fallido' : $messageStatus,
|
||||
'error' => $errorMessage,
|
||||
'discord_message_id' => $discordMessageId,
|
||||
'tipo_envio' => $tipoEnvio
|
||||
];
|
||||
|
||||
if ($messageStatus === 'enviado') {
|
||||
logToFile('discord/messages.log', "Mensaje enviado a {$destinatarioId} por {$userData->username}");
|
||||
} elseif ($messageStatus === 'pendiente') {
|
||||
logToFile('discord/messages.log', "Mensaje {$tipoEnvio} guardado para {$destinatarioId} por {$userData->username}");
|
||||
} else {
|
||||
logToFile('discord/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('discord/errors.log', "Error general en el envío de mensajes: " . $e->getMessage(), 'ERROR');
|
||||
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
|
||||
}
|
||||
41
discord/api/recipients/create.php
Executable file
41
discord/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', 'discord')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para crear destinatarios de Discord.'], 403);
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$nombre = trim($input['nombre'] ?? '');
|
||||
$discord_id = trim($input['discord_id'] ?? '');
|
||||
$tipo = trim($input['tipo'] ?? 'canal');
|
||||
|
||||
if (empty($nombre) || empty($discord_id)) {
|
||||
jsonResponse(['success' => false, 'error' => 'Faltan datos'], 400);
|
||||
}
|
||||
|
||||
try {
|
||||
$db = getDB();
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO destinatarios_discord (nombre, discord_id, tipo, activo)
|
||||
VALUES (?, ?, ?, 1)
|
||||
");
|
||||
$stmt->execute([$nombre, $discord_id, $tipo]);
|
||||
|
||||
jsonResponse(['success' => true]);
|
||||
} catch (PDOException $e) {
|
||||
if ($e->getCode() == 23000) {
|
||||
jsonResponse(['success' => false, 'error' => 'Este ID de Discord ya está registrado'], 409);
|
||||
}
|
||||
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
|
||||
}
|
||||
33
discord/api/recipients/delete.php
Executable file
33
discord/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', 'discord')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para eliminar destinatarios de Discord.'], 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_discord WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
|
||||
jsonResponse(['success' => true]);
|
||||
} catch (PDOException $e) {
|
||||
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
|
||||
}
|
||||
85
discord/api/recipients/edit.php
Executable file
85
discord/api/recipients/edit.php
Executable file
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Editar Destinatario Discord
|
||||
*/
|
||||
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', 'discord')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para editar destinatarios de Discord.'], 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'] ?? '');
|
||||
$discord_id = trim($input['discord_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($discord_id) || empty($tipo)) {
|
||||
jsonResponse(['success' => false, 'error' => 'Faltan datos requeridos (nombre, ID de Discord, 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_discord 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 discord_id (excluyendo el propio destinatario)
|
||||
$stmt = $db->prepare("SELECT id FROM destinatarios_discord WHERE discord_id = ? AND id != ?");
|
||||
$stmt->execute([$discord_id, $id]);
|
||||
if ($stmt->fetch()) {
|
||||
jsonResponse(['success' => false, 'error' => 'Ya existe un destinatario con este ID de Discord'], 409);
|
||||
}
|
||||
|
||||
// 3. Actualizar el destinatario
|
||||
$stmt = $db->prepare("
|
||||
UPDATE destinatarios_discord
|
||||
SET nombre = ?, discord_id = ?, tipo = ?
|
||||
WHERE id = ?
|
||||
");
|
||||
$stmt->execute([$nombre, $discord_id, $tipo, $id]);
|
||||
|
||||
logToFile('discord/recipients.log', "Destinatario editado: ID={$id}, Nombre={$nombre}, Usuario={$userData->username}");
|
||||
jsonResponse(['success' => true, 'message' => 'Destinatario actualizado correctamente']);
|
||||
|
||||
} catch (Exception $e) {
|
||||
logToFile('discord/errors.log', "Error editando destinatario: " . $e->getMessage(), 'ERROR');
|
||||
jsonResponse(['success' => false, 'error' => 'Ocurrió un error en el servidor.'], 500);
|
||||
}
|
||||
125
discord/api/recipients/kick.php
Executable file
125
discord/api/recipients/kick.php
Executable file
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Expulsar/Remover Destinatario Discord
|
||||
* Expulsa a un usuario de un guild o remueve el bot de un 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', 'discord')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para expulsar destinatarios de Discord.'], 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['DISCORD_BOT_TOKEN'] ?? getenv('DISCORD_BOT_TOKEN');
|
||||
$guildId = $_ENV['DISCORD_GUILD_ID'] ?? getenv('DISCORD_GUILD_ID');
|
||||
|
||||
if (!$botToken) {
|
||||
throw new Exception("Token de bot de Discord no configurado.");
|
||||
}
|
||||
if (!$guildId) {
|
||||
throw new Exception("ID de Guild de Discord no configurado.");
|
||||
}
|
||||
|
||||
// 1. Obtener detalles del destinatario de nuestra DB
|
||||
$stmt = $db->prepare("SELECT discord_id, tipo FROM destinatarios_discord WHERE id = ?");
|
||||
$stmt->execute([$recipientDbId]);
|
||||
$recipient = $stmt->fetch();
|
||||
|
||||
if (!$recipient) {
|
||||
jsonResponse(['success' => false, 'error' => 'Destinatario no encontrado en la base de datos local.'], 404);
|
||||
}
|
||||
|
||||
$discordId = $recipient['discord_id'];
|
||||
$tipo = $recipient['tipo'];
|
||||
|
||||
$actionSuccess = false;
|
||||
$actionMessage = '';
|
||||
|
||||
// Lógica para expulsar/remover según el tipo
|
||||
switch ($tipo) {
|
||||
case 'usuario':
|
||||
// Expulsar usuario de un guild (servidor)
|
||||
// Endpoint: DELETE /guilds/{guild.id}/members/{user.id}
|
||||
$url = "https://discord.com/api/v10/guilds/{$guildId}/members/{$discordId}";
|
||||
$ch = curl_init($url);
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||||
'Authorization: Bot ' . $botToken,
|
||||
'Content-Type: application/json'
|
||||
]);
|
||||
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 expulsar al usuario de Discord: " . $curlError);
|
||||
}
|
||||
if ($httpCode === 204) { // 204 No Content es éxito para DELETE
|
||||
$actionSuccess = true;
|
||||
$actionMessage = "Usuario {$discordId} expulsado del guild {$guildId} en Discord.";
|
||||
} else {
|
||||
$responseJson = json_decode($response, true);
|
||||
$actionMessage = "Error de Discord al expulsar usuario ({$httpCode}): " . ($responseJson['message'] ?? 'Desconocido');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'canal':
|
||||
case 'grupo':
|
||||
// Para canales/grupos, "expulsar" podría significar que el bot abandone el canal/grupo
|
||||
// Esto es más complejo y no hay un endpoint directo "abandonar canal" para un bot en v10 sin conocer el webhook.
|
||||
// Para simplificar, por ahora solo marcaremos como removido en nuestra DB.
|
||||
// Una implementación real necesitaría una lógica para que el bot salga del canal/thread.
|
||||
$actionSuccess = true; // Por ahora, se asume éxito en la acción "local"
|
||||
$actionMessage = "No hay una API directa para que el bot 'expulse' de un canal/grupo Discord. Eliminado de la base de datos local.";
|
||||
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_discord WHERE id = ?");
|
||||
$deleteStmt->execute([$recipientDbId]);
|
||||
|
||||
logToFile('discord/recipients.log', "Destinatario '{$recipient['discord_id']}' ({$tipo}) expulsado/eliminado de Discord y de la DB local por Usuario: {$userData->username}.");
|
||||
jsonResponse(['success' => true, 'message' => 'Destinatario expulsado/eliminado correctamente.', 'discord_action' => $actionMessage]);
|
||||
} else {
|
||||
logToFile('discord/errors.log', "Fallo al expulsar/eliminar destinatario '{$recipient['discord_id']}' ({$tipo}): {$actionMessage}", 'ERROR');
|
||||
jsonResponse(['success' => false, 'error' => 'Fallo al realizar la acción en Discord: ' . $actionMessage], 500);
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
logToFile('discord/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);
|
||||
}
|
||||
100
discord/api/templates/create.php
Executable file
100
discord/api/templates/create.php
Executable file
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
/**
|
||||
* API de Plantillas de Discord - Crear
|
||||
* REFRACTORIZADO para usar la tabla `comandos_discord`
|
||||
*/
|
||||
|
||||
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';
|
||||
|
||||
ini_set('display_errors', 0);
|
||||
error_reporting(E_ALL);
|
||||
|
||||
try {
|
||||
$userData = JWTAuth::requireAuth();
|
||||
} catch (Exception $e) {
|
||||
http_response_code(401);
|
||||
echo json_encode(['success' => false, 'error' => 'No autenticado: ' . $e->getMessage()]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!hasPermission('manage_templates', 'discord')) {
|
||||
http_response_code(403);
|
||||
echo json_encode(['success' => false, 'error' => 'No tienes permiso para crear plantillas de Discord.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
http_response_code(405);
|
||||
echo json_encode(['success' => false, 'error' => 'Método no permitido.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$data = json_decode(file_get_contents('php://input'), true);
|
||||
$nombre = trim($data['nombre'] ?? '');
|
||||
$comando = ltrim(trim($data['comando'] ?? ''), '#/');
|
||||
$contenido = $data['contenido'] ?? '';
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
$db = getDB();
|
||||
try {
|
||||
$db->beginTransaction();
|
||||
|
||||
// 1. Verificar si el comando ya existe en la tabla `comandos_discord`
|
||||
if (!empty($comando)) {
|
||||
$stmt = $db->prepare("SELECT id FROM comandos_discord WHERE comando = ?");
|
||||
$stmt->execute([$comando]);
|
||||
if ($stmt->fetch()) {
|
||||
$db->rollBack();
|
||||
http_response_code(409); // Conflict
|
||||
echo json_encode(['success' => false, 'error' => 'Ya existe un comando con ese nombre.']);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Insertar la plantilla (sin la columna `comando`)
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO plantillas_discord (nombre, contenido, usuario_id, fecha_creacion, fecha_modificacion)
|
||||
VALUES (?, ?, ?, NOW(), NOW())
|
||||
");
|
||||
$stmt->execute([$nombre, $contenido, $userData->userId]);
|
||||
$newTemplateId = $db->lastInsertId();
|
||||
|
||||
// 3. Si hay un comando, insertarlo en la tabla `comandos_discord`
|
||||
if (!empty($comando)) {
|
||||
logToFile('discord/templates.log', "Intentando insertar comando en comandos_discord. Comando: {$comando}, Plantilla ID: {$newTemplateId}", 'INFO');
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO comandos_discord (comando, descripcion, plantilla_id)
|
||||
VALUES (?, ?, ?)
|
||||
");
|
||||
// Usamos el nombre de la plantilla como descripción por defecto
|
||||
$stmt->execute([$comando, $nombre, $newTemplateId]);
|
||||
logToFile('discord/templates.log', "Comando insertado en comandos_discord. Comando: {$comando}, Plantilla ID: {$newTemplateId}", 'INFO');
|
||||
}
|
||||
|
||||
$db->commit();
|
||||
|
||||
logToFile('discord/templates.log', "Plantilla creada: {$nombre} (ID: {$newTemplateId}), por Usuario: {$userData->username}");
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Plantilla creada correctamente.',
|
||||
'templateId' => $newTemplateId
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
if ($db->inTransaction()) {
|
||||
$db->rollBack();
|
||||
}
|
||||
http_response_code(500);
|
||||
logToFile('discord/errors.log', 'Error creando plantilla: ' . $e->getMessage(), 'ERROR');
|
||||
echo json_encode(['success' => false, 'error' => 'Ocurrió un error en el servidor al crear la plantilla.']);
|
||||
}
|
||||
139
discord/api/templates/delete.php
Executable file
139
discord/api/templates/delete.php
Executable file
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
/**
|
||||
* API de Plantillas de Discord - Eliminar
|
||||
* Este script es llamado por la función deleteTemplate() en list.php
|
||||
*/
|
||||
|
||||
// Habilitar logging de errores
|
||||
ini_set('display_errors', 0);
|
||||
error_reporting(E_ALL);
|
||||
|
||||
// Función de logging mejorada
|
||||
function logError($message, $data = null) {
|
||||
$logDir = '/var/www/html/bot/logs/discord/';
|
||||
if (!is_dir($logDir)) {
|
||||
@mkdir($logDir, 0777, true);
|
||||
}
|
||||
$logFile = $logDir . 'error.log';
|
||||
$timestamp = date('Y-m-d H:i:s');
|
||||
$logMessage = "[$timestamp] [ERROR] $message";
|
||||
if ($data) {
|
||||
$logMessage .= "\n" . (is_string($data) ? $data : json_encode($data, JSON_PRETTY_PRINT));
|
||||
}
|
||||
error_log($logMessage . "\n", 3, $logFile);
|
||||
}
|
||||
|
||||
// Iniciar buffer para capturar cualquier salida no deseada
|
||||
ob_start();
|
||||
|
||||
try {
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Registrar inicio
|
||||
logError("Inicio de eliminación de plantilla");
|
||||
|
||||
// Incluir dependencias
|
||||
require_once __DIR__ . '/../../../shared/utils/helpers.php';
|
||||
require_once __DIR__ . '/../../../shared/auth/jwt.php';
|
||||
require_once __DIR__ . '/../../../shared/database/connection.php';
|
||||
|
||||
// Limpiar buffer por si hay salida no deseada
|
||||
ob_clean();
|
||||
|
||||
// Autenticación JWT para API (no redirigir)
|
||||
$userData = JWTAuth::authenticate();
|
||||
if (!$userData) {
|
||||
http_response_code(401);
|
||||
echo json_encode(['success' => false, 'error' => 'Acceso no autorizado.']);
|
||||
logError("Error de autenticación");
|
||||
exit;
|
||||
}
|
||||
|
||||
logError("Usuario autenticado: " . json_encode(['id' => $userData->userId, 'username' => $userData->username]));
|
||||
|
||||
// Verificar método
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
http_response_code(405);
|
||||
echo json_encode(['success' => false, 'error' => 'Método no permitido.']);
|
||||
logError("Método no permitido: " . $_SERVER['REQUEST_METHOD']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Obtener datos del cuerpo de la petición
|
||||
$input = file_get_contents('php://input');
|
||||
$data = json_decode($input, true);
|
||||
$template_id = $data['id'] ?? null;
|
||||
|
||||
logError("Datos recibidos", ['input' => $input, 'data' => $data, 'template_id' => $template_id]);
|
||||
|
||||
// Validar ID
|
||||
if (!$template_id || !is_numeric($template_id)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'ID de plantilla inválido o no proporcionado.']);
|
||||
logError("ID de plantilla inválido", ['template_id' => $template_id]);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Conectar a la base de datos
|
||||
try {
|
||||
$db = getDB();
|
||||
logError("Conexión a BD exitosa");
|
||||
} catch (Exception $e) {
|
||||
logError("Error al conectar a la base de datos", $e->getMessage());
|
||||
throw $e;
|
||||
}
|
||||
|
||||
// Iniciar transacción
|
||||
$db->beginTransaction();
|
||||
logError("Transacción iniciada");
|
||||
|
||||
try {
|
||||
// 1. Eliminar comandos asociados (si existen)
|
||||
$stmt = $db->prepare("DELETE FROM comandos_discord WHERE plantilla_id = ?");
|
||||
$stmt->execute([$template_id]);
|
||||
$deletedCommands = $stmt->rowCount();
|
||||
logError("Comandos eliminados", ['count' => $deletedCommands]);
|
||||
|
||||
// 2. Intentar eliminar la plantilla
|
||||
$stmt = $db->prepare("DELETE FROM plantillas_discord WHERE id = ?");
|
||||
$stmt->execute([$template_id]);
|
||||
$deleted = $stmt->rowCount();
|
||||
|
||||
if ($deleted > 0) {
|
||||
$db->commit();
|
||||
logError("Plantilla eliminada exitosamente", ['id' => $template_id]);
|
||||
echo json_encode(['success' => true]);
|
||||
} else {
|
||||
$db->rollBack();
|
||||
http_response_code(404);
|
||||
logError("No se encontró la plantilla para eliminar", ['id' => $template_id]);
|
||||
echo json_encode(['success' => false, 'error' => 'No se encontró la plantilla para eliminar.']);
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
$db->rollBack();
|
||||
logError("Error en la transacción", [
|
||||
'error' => $e->getMessage(),
|
||||
'trace' => $e->getTraceAsString()
|
||||
]);
|
||||
http_response_code(500);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => 'Ocurrió un error en el servidor.',
|
||||
'detail' => $e->getMessage()
|
||||
]);
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
logError("Error no manejado", [
|
||||
'error' => $e->getMessage(),
|
||||
'trace' => $e->getTraceAsString()
|
||||
]);
|
||||
http_response_code(500);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => 'Error interno del servidor.',
|
||||
'detail' => $e->getMessage()
|
||||
]);
|
||||
}
|
||||
|
||||
// Limpiar cualquier salida no deseada
|
||||
ob_end_flush();
|
||||
138
discord/api/templates/edit.php
Executable file
138
discord/api/templates/edit.php
Executable file
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
/**
|
||||
* API de Plantillas de Discord - Editar
|
||||
* REFRACTORIZADO para usar la tabla `comandos_discord`
|
||||
*/
|
||||
|
||||
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';
|
||||
|
||||
ini_set('display_errors', 0);
|
||||
error_reporting(E_ALL);
|
||||
|
||||
try {
|
||||
$userData = JWTAuth::requireAuth();
|
||||
} catch (Exception $e) {
|
||||
http_response_code(401);
|
||||
echo json_encode(['success' => false, 'error' => 'Acceso no autorizado.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!hasPermission('manage_templates', 'discord')) {
|
||||
http_response_code(403);
|
||||
echo json_encode(['success' => false, 'error' => 'No tienes permiso para editar plantillas de Discord.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
http_response_code(405);
|
||||
echo json_encode(['success' => false, 'error' => 'Método no permitido.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$data = json_decode(file_get_contents('php://input'), true);
|
||||
$plantilla_id = $data['id'] ?? null;
|
||||
$nombre = trim($data['nombre'] ?? '');
|
||||
$comando = ltrim(trim($data['comando'] ?? ''), '#/');
|
||||
$contenido = $data['contenido'] ?? '';
|
||||
|
||||
if (!$plantilla_id || !is_numeric($plantilla_id)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'ID de plantilla inválido.']);
|
||||
exit;
|
||||
}
|
||||
if (empty($nombre) || empty($contenido)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'El nombre y el contenido son obligatorios.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$db = getDB();
|
||||
try {
|
||||
logToFile('discord/templates.log', "Iniciando edición de plantilla (ID: {$plantilla_id}). Comando recibido: {$comando}", 'INFO');
|
||||
$db->beginTransaction();
|
||||
|
||||
// 1. Verificar que la plantilla existe y el usuario tiene permiso
|
||||
$stmt = $db->prepare("SELECT usuario_id FROM plantillas_discord WHERE id = ?");
|
||||
$stmt->execute([$plantilla_id]);
|
||||
$plantillaExistente = $stmt->fetch();
|
||||
|
||||
if (!$plantillaExistente) {
|
||||
throw new Exception('Plantilla no encontrada.', 404);
|
||||
}
|
||||
if ($userData->rol !== 'Admin' && $plantillaExistente['usuario_id'] != $userData->userId) {
|
||||
throw new Exception('No tiene permisos para editar esta plantilla.', 403);
|
||||
}
|
||||
|
||||
// 2. Actualizar la plantilla en sí (nombre y contenido)
|
||||
$stmt = $db->prepare("
|
||||
UPDATE plantillas_discord
|
||||
SET nombre = ?, contenido = ?, fecha_modificacion = NOW()
|
||||
WHERE id = ?
|
||||
");
|
||||
$stmt->execute([$nombre, $contenido, $plantilla_id]);
|
||||
|
||||
// 3. Gestionar el comando en la tabla `comandos_discord`
|
||||
// Primero, obtener el comando actual si existe
|
||||
$stmt = $db->prepare("SELECT id, comando FROM comandos_discord WHERE plantilla_id = ?");
|
||||
$stmt->execute([$plantilla_id]);
|
||||
$comandoExistente = $stmt->fetch();
|
||||
|
||||
logToFile('discord/templates.log', "Comando existente para plantilla {$plantilla_id}: " . ($comandoExistente ? json_encode($comandoExistente) : 'Ninguno'), 'INFO');
|
||||
|
||||
|
||||
// Antes de insertar/actualizar, verificar si el nuevo nombre de comando ya está en uso por OTRA plantilla
|
||||
if (!empty($comando)) {
|
||||
$stmt = $db->prepare("SELECT id FROM comandos_discord WHERE comando = ? AND plantilla_id != ?");
|
||||
$stmt->execute([$comando, $plantilla_id]);
|
||||
if ($stmt->fetch()) {
|
||||
throw new Exception('Ya existe otro comando con ese nombre.', 409);
|
||||
}
|
||||
}
|
||||
|
||||
// Lógica de casos
|
||||
if (!empty($comando) && $comandoExistente) {
|
||||
// Caso: El comando se está modificando
|
||||
if ($comando !== $comandoExistente['comando']) {
|
||||
logToFile('discord/templates.log', "Modificando comando existente para plantilla {$plantilla_id}. De: {$comandoExistente['comando']} a: {$comando}", 'INFO');
|
||||
$stmt = $db->prepare("UPDATE comandos_discord SET comando = ?, descripcion = ? WHERE id = ?");
|
||||
$stmt->execute([$comando, $nombre, $comandoExistente['id']]);
|
||||
} else {
|
||||
logToFile('discord/templates.log', "Comando existente no modificado para plantilla {$plantilla_id}. Valor: {$comando}", 'INFO');
|
||||
}
|
||||
} elseif (!empty($comando) && !$comandoExistente) {
|
||||
// Caso: Se está añadiendo un comando nuevo
|
||||
logToFile('discord/templates.log', "Añadiendo nuevo comando para plantilla {$plantilla_id}. Comando: {$comando}", 'INFO');
|
||||
$stmt = $db->prepare("INSERT INTO comandos_discord (comando, descripcion, plantilla_id) VALUES (?, ?, ?)");
|
||||
$stmt->execute([$comando, $nombre, $plantilla_id]);
|
||||
} elseif (empty($comando) && $comandoExistente) {
|
||||
// Caso: Se está eliminando el comando
|
||||
logToFile('discord/templates.log', "Eliminando comando existente para plantilla {$plantilla_id}. Comando: {$comandoExistente['comando']}", 'INFO');
|
||||
$stmt = $db->prepare("DELETE FROM comandos_discord WHERE id = ?");
|
||||
$stmt->execute([$comandoExistente['id']]);
|
||||
} else {
|
||||
logToFile('discord/templates.log', "No se gestionó comando para plantilla {$plantilla_id}. Comando recibido: {$comando}, Existente: " . ($comandoExistente ? $comandoExistente['comando'] : 'Ninguno'), 'INFO');
|
||||
}
|
||||
// Si no hay comando nuevo y no había uno existente, no se hace nada.
|
||||
|
||||
$db->commit();
|
||||
|
||||
logToFile('discord/templates.log', "Edición de plantilla completada (ID: {$plantilla_id}).", 'INFO');
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Plantilla actualizada correctamente.'
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
if ($db->inTransaction()) {
|
||||
$db->rollBack();
|
||||
}
|
||||
$code = $e->getCode() >= 400 ? $e->getCode() : 500;
|
||||
http_response_code($code);
|
||||
logToFile('discord/templates.log', 'ERROR: Error editando plantilla (ID: ' . ($plantilla_id ?? 'N/A') . '): ' . $e->getMessage(), 'ERROR');
|
||||
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
|
||||
}
|
||||
64
discord/api/templates/list.php
Executable file
64
discord/api/templates/list.php
Executable file
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
/**
|
||||
* API de Plantillas de Discord - 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', 'discord')) {
|
||||
http_response_code(403);
|
||||
echo json_encode(['success' => false, 'error' => 'No tienes permiso para ver las plantillas de Discord.']);
|
||||
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_discord 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 /discord/api/templates/list.php: ' . $e->getMessage());
|
||||
echo json_encode(['success' => false, 'error' => 'Error del servidor al obtener las plantillas.']);
|
||||
}
|
||||
36
discord/api/templates/php_errors.log
Executable file
36
discord/api/templates/php_errors.log
Executable file
@@ -0,0 +1,36 @@
|
||||
[04-Dec-2025 14:59:12 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 14:59:12 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 14:59:13 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:57:13 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:57:13 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:57:13 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:57:13 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:58:35 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:58:35 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:58:35 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:58:35 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:58:49 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:58:49 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:58:49 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:58:49 America/Mexico_City] PHP Warning: file_put_contents(/var/www/html/bot/shared/utils/../logs/discord/templates.log): Failed to open stream: No such file or directory in /var/www/html/bot/shared/utils/helpers.php on line 40
|
||||
[04-Dec-2025 15:59:17 America/Mexico_City] PHP Fatal error: Uncaught Error: Call to undefined function isAuthenticated() in /var/www/html/bot/discord/api/templates/delete.php:19
|
||||
Stack trace:
|
||||
#0 {main}
|
||||
thrown in /var/www/html/bot/discord/api/templates/delete.php on line 19
|
||||
[04-Dec-2025 15:59:57 America/Mexico_City] PHP Fatal error: Uncaught Error: Call to undefined function isAuthenticated() in /var/www/html/bot/discord/api/templates/delete.php:19
|
||||
Stack trace:
|
||||
#0 {main}
|
||||
thrown in /var/www/html/bot/discord/api/templates/delete.php on line 19
|
||||
[04-Dec-2025 22:04:20 UTC] PHP Parse error: syntax error, unexpected token "=" in /var/www/html/bot/discord/api/templates/delete.php on line 20
|
||||
[04-Dec-2025 22:05:28 UTC] PHP Parse error: syntax error, unexpected token "exit", expecting "]" in /var/www/html/bot/discord/api/templates/delete.php on line 24
|
||||
[04-Dec-2025 22:05:56 UTC] PHP Parse error: syntax error, unexpected token "exit", expecting "]" in /var/www/html/bot/discord/api/templates/delete.php on line 24
|
||||
[04-Dec-2025 22:06:02 UTC] PHP Parse error: syntax error, unexpected token "exit", expecting "]" in /var/www/html/bot/discord/api/templates/delete.php on line 24
|
||||
[04-Dec-2025 22:08:10 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 26
|
||||
[04-Dec-2025 22:11:10 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 26
|
||||
[04-Dec-2025 22:13:26 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
|
||||
[04-Dec-2025 22:28:45 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
|
||||
[04-Dec-2025 22:31:33 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
|
||||
[04-Dec-2025 22:32:17 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
|
||||
[04-Dec-2025 22:32:21 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
|
||||
[04-Dec-2025 22:32:47 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 18
|
||||
[04-Dec-2025 22:34:50 UTC] PHP Parse error: syntax error, unexpected token "\" in /var/www/html/bot/discord/api/templates/delete.php on line 19
|
||||
143
discord/api/welcome/send_test.php
Executable file
143
discord/api/welcome/send_test.php
Executable file
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Enviar Mensaje de Prueba de Bienvenida
|
||||
*/
|
||||
header('Content-Type: application/json');
|
||||
|
||||
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', 'discord')) {
|
||||
jsonResponse(['success' => false, 'error' => 'No tienes permiso para gestionar el mensaje de bienvenida de Discord.'], 403);
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
|
||||
}
|
||||
|
||||
try {
|
||||
$db = getDB();
|
||||
|
||||
// 1. Obtener configuración de bienvenida
|
||||
$stmt = $db->query("
|
||||
SELECT b.*, g.ruta as imagen_ruta
|
||||
FROM bienvenida_discord b
|
||||
LEFT JOIN gallery g ON b.imagen_id = g.id
|
||||
LIMIT 1
|
||||
");
|
||||
$config = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$config) {
|
||||
throw new Exception("No hay configuración de bienvenida guardada");
|
||||
}
|
||||
|
||||
if (empty($config['canal_id'])) {
|
||||
throw new Exception("No se ha configurado un canal de bienvenida");
|
||||
}
|
||||
|
||||
// 2. Obtener idiomas activos para los botones
|
||||
$stmt = $db->query("SELECT codigo, nombre, nombre_nativo, bandera FROM idiomas WHERE activo = 1 ORDER BY nombre ASC");
|
||||
$idiomas = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// 3. Preparar contenido del mensaje
|
||||
$contenido = $config['texto'] ?? "Bienvenido al servidor!";
|
||||
|
||||
// Reemplazar variables
|
||||
$dummyUser = "<@{$userData->id}> (Usuario de Prueba)";
|
||||
$contenido = str_replace('{usuario}', $dummyUser, $contenido);
|
||||
|
||||
// Limpiar HTML a texto plano (similar a send.php)
|
||||
$cleanContent = str_replace(['<br>', '<br/>', '<p>'], ["\n", "\n", "\n"], $contenido);
|
||||
$cleanContent = strip_tags($cleanContent);
|
||||
$cleanContent = html_entity_decode($cleanContent);
|
||||
$cleanContent = trim($cleanContent);
|
||||
|
||||
$data = [
|
||||
'content' => $cleanContent
|
||||
];
|
||||
|
||||
// 4. (Imagen eliminada por solicitud)
|
||||
// if (!empty($config['imagen_ruta'])) { ... }
|
||||
|
||||
// 5. Agregar botones de idioma (Components)
|
||||
if (!empty($idiomas)) {
|
||||
$components = [];
|
||||
$currentRow = ['type' => 1, 'components' => []];
|
||||
|
||||
foreach ($idiomas as $index => $lang) {
|
||||
// Discord permite max 5 botones por fila, max 5 filas
|
||||
if (count($currentRow['components']) >= 5) {
|
||||
$components[] = $currentRow;
|
||||
$currentRow = ['type' => 1, 'components' => []];
|
||||
}
|
||||
|
||||
// Usar bandera si existe, sino nombre nativo, sino nombre
|
||||
$label = $lang['bandera'] ?: ($lang['nombre_nativo'] ?: $lang['nombre']);
|
||||
|
||||
$currentRow['components'][] = [
|
||||
'type' => 2, // Button
|
||||
'style' => 1, // Primary (Blurple)
|
||||
'label' => $label,
|
||||
'custom_id' => "lang_select_" . $lang['codigo']
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($currentRow['components'])) {
|
||||
$components[] = $currentRow;
|
||||
}
|
||||
|
||||
$data['components'] = $components;
|
||||
}
|
||||
|
||||
// 6. Enviar a Discord
|
||||
$botToken = $_ENV['DISCORD_BOT_TOKEN'] ?? getenv('DISCORD_BOT_TOKEN');
|
||||
$url = "https://discord.com/api/v10/channels/{$config['canal_id']}/messages";
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||||
'Authorization: Bot ' . $botToken,
|
||||
'Content-Type: application/json'
|
||||
]);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
|
||||
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 >= 400) {
|
||||
$errorMsg = $responseJson['message'] ?? 'Error desconocido de Discord';
|
||||
if (isset($responseJson['errors'])) {
|
||||
$errorMsg .= ' - ' . json_encode($responseJson['errors']);
|
||||
}
|
||||
throw new Exception("Discord API Error ({$httpCode}): {$errorMsg}");
|
||||
}
|
||||
|
||||
jsonResponse([
|
||||
'success' => true,
|
||||
'message' => 'Mensaje de prueba enviado correctamente',
|
||||
'debug_url' => $imageUrl ?? 'No image'
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
|
||||
}
|
||||
Reference in New Issue
Block a user