> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Laravel Notification for Discord(Webhook)

> Paquete para enviar notificaciones desde Laravel de forma sencilla mediante Discord Webhook. Sin bot ni WebSocket: configura la URL del Webhook y listo.

## Resumen

[revolution/laravel-notification-discord-webhook](https://github.com/invokable/laravel-notification-discord-webhook) es un paquete que envía notificaciones a Discord desde Laravel Notifications utilizando Discord Webhook.

La API oficial de bots de Discord requiere mantener una conexión WebSocket y su configuración es compleja. Con Webhook basta con obtener una URL para enviar notificaciones. Si solo quieres notificar los eventos de tu aplicación al canal de Discord de tu equipo, Webhook es la mejor opción.

<Info>
  Este paquete requiere PHP 8.3 o superior y Laravel 12.0 o superior.
</Info>

## Instalación

```shell theme={null}
composer require revolution/laravel-notification-discord-webhook
```

## Configuración

### Obtén la URL del Webhook de Discord

Puedes crear una URL de Webhook desde **Ajustes del servidor → Integraciones → Webhooks** de tu servidor de Discord. Para más detalles, consulta la [guía oficial de Discord](https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks).

### config/services.php

```php theme={null}
'discord' => [
    'webhook' => env('DISCORD_WEBHOOK'),
],
```

### .env

```dotenv theme={null}
DISCORD_WEBHOOK=https://discord.com/api/webhooks/...
```

## Uso básico

### Crea una clase Notification

Implementa el método `toDiscordWebhook()` y devuelve `DiscordChannel::class` desde `via()`.

```php theme={null}
<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Revolution\Laravel\Notification\DiscordWebhook\DiscordChannel;
use Revolution\Laravel\Notification\DiscordWebhook\DiscordMessage;

class DiscordNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(protected string $content)
    {
        //
    }

    public function via($notifiable): array
    {
        return [DiscordChannel::class];
    }

    public function toDiscordWebhook(object $notifiable): DiscordMessage
    {
        return DiscordMessage::create(content: $this->content);
    }
}
```

## Patrones de envío

### Notificaciones On-Demand

Para enviar notificaciones sin vincularlas a un modelo de usuario concreto, utiliza `Notification::route()`.

```php theme={null}
use Illuminate\Support\Facades\Notification;

Notification::route('discord-webhook', config('services.discord.webhook'))
            ->notify(new DiscordNotification('El despliegue se ha completado.'));
```

### Notificación desde el modelo User

Para usar una URL de Webhook distinta por usuario, define `routeNotificationForDiscordWebhook()`.

```php theme={null}
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    public function routeNotificationForDiscordWebhook($notification): string
    {
        return $this->discord_webhook;
    }
}
```

```php theme={null}
$user->notify(new DiscordNotification('Notificación de prueba'));
```

## Tipos de mensaje

### Mensaje de texto

Es la forma más sencilla de enviar.

```php theme={null}
public function toDiscordWebhook(object $notifiable): DiscordMessage
{
    return DiscordMessage::create(content: $this->content);
}
```

### Mensajes con embed

Con `DiscordEmbed` puedes mostrar contenido enriquecido, con título y URL.

```php theme={null}
use Revolution\Laravel\Notification\DiscordWebhook\DiscordMessage;
use Revolution\Laravel\Notification\DiscordWebhook\DiscordEmbed;

public function toDiscordWebhook(object $notifiable): DiscordMessage
{
    return DiscordMessage::create()
                          ->embed(
                              DiscordEmbed::make(
                                  title: 'INFO',
                                  description: $this->content,
                                  url: route('home'),
                              )
                          );
}
```

### Archivos adjuntos

Con `DiscordAttachment` puedes adjuntar archivos al mensaje. Son obligatorios `content` (el contenido del archivo) y `filename`.

```php theme={null}
use Revolution\Laravel\Notification\DiscordWebhook\DiscordMessage;
use Revolution\Laravel\Notification\DiscordWebhook\DiscordAttachment;
use Illuminate\Support\Facades\Storage;

public function toDiscordWebhook(object $notifiable): DiscordMessage
{
    return DiscordMessage::create()
        ->file(
            DiscordAttachment::make(
                content: Storage::get('test.png'),
                filename: 'test.png',
                description: 'test',
                filetype: 'image/png'
            )
        );
}
```

### Referencia a archivos dentro del embed

Puedes referenciar los archivos adjuntos en `image` o `thumbnail` del embed mediante `attachment://nombre-de-archivo`.

```php theme={null}
use Revolution\Laravel\Notification\DiscordWebhook\DiscordMessage;
use Revolution\Laravel\Notification\DiscordWebhook\DiscordAttachment;
use Revolution\Laravel\Notification\DiscordWebhook\DiscordEmbed;
use Illuminate\Support\Facades\Storage;

public function toDiscordWebhook(object $notifiable): DiscordMessage
{
    return DiscordMessage::create()
                          ->embed(
                              DiscordEmbed::make(
                                  title: 'test',
                                  description: $this->content,
                                  image: 'attachment://test.jpg',
                                  thumbnail: 'attachment://test2.jpg',
                              )
                          )
                          ->file(DiscordAttachment::make(
                              content: Storage::get('test.jpg'),
                              filename: 'test.jpg',
                              description: 'test',
                              filetype: 'image/jpg'
                          ))
                          ->file(new DiscordAttachment(
                              content: Storage::get('test2.jpg'),
                              filename: 'test2.jpg',
                              description: 'test2',
                              filetype: 'image/jpg'
                          ));
}
```

### Enviar un payload personalizado

Con `->with()` puedes especificar directamente cualquier parámetro del Webhook de Discord.

```php theme={null}
public function toDiscordWebhook(object $notifiable): DiscordMessage
{
    return DiscordMessage::create()
                          ->with([
                              'content' => $this->content,
                              'embeds' => [[]],
                          ]);
}
```

<Tip>
  Para más detalles sobre los parámetros que se pueden pasar a `->with()`, consulta la [documentación oficial de la API de Discord](https://discord.com/developers/docs/resources/webhook#execute-webhook).
</Tip>

## Resumen

Los bots de Discord son potentes, pero si solo quieres enviar notificaciones, Webhook es mucho más sencillo. Con este paquete puedes integrarte sin fricciones con el sistema de notificaciones de Laravel y notificar rápidamente los eventos de tu aplicación al canal de Discord del equipo.

<Info>
  Para la información más reciente, consulta el [repositorio de GitHub](https://github.com/invokable/laravel-notification-discord-webhook).
</Info>


## Related topics

- [Tutorial - Laravel Console Starter](/es/packages/laravel-console-starter/tutorial.md)
- [Socialite for Discord](/es/packages/socialite-discord.md)
- [Canal de notificaciones - LINE SDK for Laravel](/es/packages/laravel-line-sdk/notification.md)
- [LINE SDK for Laravel](/es/packages/laravel-line-sdk/index.md)
- [Webhook / Bot - LINE SDK for Laravel](/es/packages/laravel-line-sdk/bot.md)
