Skip to content

Commit

Permalink
add: in user notify event update with new field in notification discord
Browse files Browse the repository at this point in the history
  • Loading branch information
alejandro-velasquez committed Nov 25, 2024
1 parent c1195ee commit a0c37e0
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 49 deletions.
76 changes: 39 additions & 37 deletions app/Helpers/DiscordNotifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,60 +6,62 @@

class DiscordNotifier
{
public static function send($message)
public static function send($message, $embed = [])
{
$webhookUrl = env('DISCORD_WEBHOOK_URL');

if ($webhookUrl) {
Http::post($webhookUrl, [
$payload = [
'content' => $message,
]);
];

if (!empty($embed)) {
$payload['embeds'] = [$embed];
}

Http::post($webhookUrl, $payload);
}
}

public static function notifyException(\Throwable $exception)
{
$trace = substr($exception->getTraceAsString(), 0, 1800); // Límite ajustado para Discord
$message = "**Exception Alert**\n"
. "**Message:** {$exception->getMessage()}\n"
. "**File:** {$exception->getFile()}:{$exception->getLine()}\n"
$trace = substr($exception->getTraceAsString(), 0, 1800); // Discord tiene límites.
$message = "**🚨 Exception Alert**\n"
. "**Mensaje:** {$exception->getMessage()}\n"
. "**Archivo:** {$exception->getFile()}:{$exception->getLine()}\n"
. "**Trace:** ```{$trace}```";

self::send($message);
}

public static function notifyEvent($eventType, $details = [])
{
$webhookUrl = env('DISCORD_WEBHOOK_URL');

if ($webhookUrl) {
$logoUrl = 'https://755e-186-113-97-221.ngrok-free.app/gananza-logov1.png';
$embed = [
'title' => '🔔 Gananza Alerts',
'description' => "Se ha detectado un evento: **{$eventType}**.",
'color' => 7506394, // Color (ejemplo: azul)
'fields' => [],
'footer' => [
'text' => 'Notificaciones del Sistema',
'icon_url' => $logoUrl, // Cambiar al logo de tu sitio
],
'timestamp' => now()->toIso8601String(),
];
public static function notifyEvent($eventType, $details = [], $imageUrl = null)
{
$webhookUrl = env('DISCORD_WEBHOOK_URL');

// Añadir los detalles al mensaje si están disponibles
foreach ($details as $key => $value) {
$embed['fields'][] = [
'name' => ucfirst($key),
'value' => $value,
'inline' => true,
if ($webhookUrl) {
$logoUrl = $imageUrl ?? asset('logo.png'); // Imagen por defecto
$embed = [
'title' => '🔔 Notificación del Sistema',
'description' => "Se ha detectado un evento: **{$eventType}**.",
'color' => 7506394, // Color (hex: #72A0C1)
'fields' => [],
'footer' => [
'text' => 'Notificaciones del Sistema',
'icon_url' => $logoUrl,
],
'timestamp' => now()->toIso8601String(),
];
}

Http::post($webhookUrl, [
'embeds' => [$embed],
'username' => 'Sistema de Notificaciones', // Nombre personalizado
'avatar_url' => $logoUrl, // Cambiar al logo de tu sitio
]);
// Agregar detalles al mensaje.
foreach ($details as $key => $value) {
$embed['fields'][] = [
'name' => ucfirst($key),
'value' => $value,
'inline' => true,
];
}

self::send('', $embed);
}
}
}
}
42 changes: 30 additions & 12 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,26 +58,44 @@ protected static function boot()

// Evento cuando el modelo es creado
static::created(function ($model) {
DiscordNotifier::notifyEvent('User Created', [
'id' => $model->id,
'attributes' => $model->getAttributes(),
]);
$createdBy = auth()->user();
DiscordNotifier::notifyEvent('Usuario Creado', [
'ID Usuario Creado' => $model->id,
'Nombre Usuario Creado' => $model->name,
'ID Quien Creó' => $createdBy->id ?? 'Desconocido',
'Nombre Quien Creó' => $createdBy->name ?? 'Desconocido',
],
asset('images/logo.png')
);
});

// Evento cuando el modelo es actualizado
static::updated(function ($model) {
DiscordNotifier::notifyEvent('User Updated', [
'id' => $model->id,
'changes' => $model->getChanges(),
]);
DiscordNotifier::notifyEvent('Usuario actualizado', [
'ID Usuario Actualizado' => $model->id,
'Nombre Usuario Actualizado' => $model->name,
'Cambios Realizados' => json_encode($model->getChanges()), // Cambios realizados en formato JSON
'ID Quien Actualizó' => $updatedBy->id ?? 'Desconocido',
'Nombre Quien Actualizó' => $updatedBy->name ?? 'Desconocido',
],
asset('images/logo.png')
);
});

// Evento cuando el modelo es eliminado
static::deleted(function ($model) {
DiscordNotifier::notifyEvent('User Deleted', [
'id' => $model->id,
]);
});
$deletedBy = auth()->user(); // Usuario autenticado
DiscordNotifier::notifyEvent(
'Usuario Borrado',
[
'ID Usuario Eliminado' => $model->id,
'Nombre Usuario Eliminado' => $model->name,
'ID Quien Eliminó' => $deletedBy->id ?? 'Desconocido',
'Nombre Quien Eliminó' => $deletedBy->name ?? 'Desconocido',
],
asset('images/logo.png') // Ruta de imagen pública
);
});
}

}
File renamed without changes

0 comments on commit a0c37e0

Please sign in to comment.