spatie / laravel-backup

A package to backup your Laravel app
https://spatie.be/docs/laravel-backup
MIT License
5.61k stars 758 forks source link

Discord embed limits #1819

Open mho22 opened 2 months ago

mho22 commented 2 months ago

In my journey to make Laravel backup Notifications work, I found some difficulties making a BackupHasFailedNotification display on Discord. Always returning 400 - Bad request.

I finally found out Discord Embed Limits :

- Embed titles are limited to 256 characters
- Embed descriptions are limited to 4096 characters
- There can be up to 25 fields
- A field's name is limited to 256 characters and its value to 1024 characters
- The footer text is limited to 2048 characters
- The author name is limited to 256 characters
- The sum of all characters from all embed structures in a message must not exceed 6000 characters
- 10 embeds can be sent per message

And that's right, when a BackupHasFailedNotification is called, the fields name parameter is way larger than 1024 causing it to return Bad Request like indicated in the docs.

After some tweaks in DiscordMessage class it runs as expected.

This is what I did :

Notifications/Channels/Discord/DiscordMessage.php


...
use Illuminate\Support\Str;
...

public function fields(array $fields, bool $inline = true): self
{
    foreach ($fields as $label => $value) {
        $this->fields[] = [
-          'name' => $label,
+         'name' => Str::limit( $label, 250 ),
-          'value => $value,
+         'value' => Str::limit( $value, 1000 ),
            'inline' => $inline,
        ];
    }

    return $this;
}

public function toArray(): array
{
    return [
        'username' => $this->username ?? 'Laravel Backup',
        'avatar_url' => $this->avatarUrl,
        'embeds' => [
            [
-              'title => $this->title,
+             'title' => Str::limit( $this->title, 250 ),
                'url' => $this->url,
                'type' => 'rich',
-             'description' => $this->description,
+             'description' => Str::limit( $this->description, 4000 ),
-            'fields' => $this->fields,
+             'fields' => array_slice( $this->fields, 0, 25 ),
                'color' => hexdec($this->color),
                'footer' => [
-                 'text' => $this->footer ?? '',
+                 'text' => $this->footer ? Str::limit( $this->footer, 2000 ) : '',
                ],
                'timestamp' => $this->timestamp ?? now(),
            ],
        ],
    ];
}

I first added the correct limit numbers but it didn't work. I then decided to round the values and it worked.

Should I suggest a PR for this ?

Nielsvanpach commented 1 week ago

Yes, feel free to send a PR to fix this!

mho22 commented 1 week ago

@Nielsvanpach, this will be completed today.