Primer commit del sistema separado falta mejorar mucho
This commit is contained in:
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