Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retry sending a notification if you're being rate limited by Discord #61

Open
fakeheal opened this issue Aug 19, 2022 · 1 comment
Open

Comments

@fakeheal
Copy link

Hi, all,

First of all great package, thank you!

I'm trying to channel all notifications in my application to our staff discord's channel. Sometimes we send many notifications at once to various text channels we end up being rate limited.

I saw a pull request that returns the underlying GuzzleHttp exception inCouldNotSendNotification. Our notifications are queued and sent "asynchronously", so I was thinking of releasing the job again after the seconds spcified in the response by Discord.

This is my code in theory, because I don't know how to test it without making real requests to Discord (test it in ci/cd pipelines):

public function failed(Exception $exception)
{
    if ($exception instanceof CouldNotSendNotification) {
        if ($exception->getCode() === 429) {
            $json = json_decode($exception->getPrevious()->getResponse());
            $this->release($json->retry_after);
        }
    }
}

Could you please advise on how to proceed?

Thank you,
Ivanka

@Gummibeer
Copy link
Contributor

I have overridden the DiscordChannel class and added the Laravel retry() helper to retry the sending if it fails with a 429 status.
This works for me - am not sure if it's the bullet-proof solution, primary with the getHeader() logic - but in theory it should be correct.

return retry(
    times: 2,
    callback: fn () => $this->discord->send($channel, [
        'content' => $message->body,
        'embed' => $message->embed,
    ]),
    sleepMilliseconds: function (int $attempts, CouldNotSendNotification $exception): int {
        $previous = $exception->getPrevious();

        if ($previous instanceof ClientException && $previous->hasResponse()) {
            return ($previous->getResponse()->getHeader('x-ratelimit-reset-after') ?: 1) * 1000;
        }

        return 1000;
    },
    when: fn (Exception $exception) => $exception instanceof CouldNotSendNotification 
        && $exception->getCode() === Response::HTTP_TOO_MANY_REQUESTS
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants