feat(index.js): enhance sendWebhook function to handle rate limits with retries for improved reliability when sending requests to Discord

This commit is contained in:
SethCohen
2025-06-17 00:46:40 -04:00
parent 9fe781fdc7
commit feb5a40237
+33 -12
View File
@@ -202,21 +202,42 @@ const buildEmbedMessage = (name, html_url, description) => {
}; };
/** /**
* Sends the webhook request to Discord. * Sends the webhook request to Discord, handling rate limits (429) with retries.
* @param {string} webhookUrl The URL of the Discord webhook. * @param {string} webhookUrl The URL of the Discord webhook.
* @param {object} requestBody The payload to send in the webhook. * @param {object} requestBody The payload to send in the webhook.
* @param {number} [maxRetries=3] Maximum number of retries on rate limit.
*/ */
const sendWebhook = async (webhookUrl, requestBody) => { const sendWebhook = async (webhookUrl, requestBody, maxRetries = 3) => {
try { let attempt = 0;
const response = await fetch(`${webhookUrl}?wait=true`, { while (attempt <= maxRetries) {
method: 'POST', try {
body: JSON.stringify(requestBody), const response = await fetch(`${webhookUrl}?wait=true`, {
headers: { 'Content-Type': 'application/json' } method: 'POST',
}); body: JSON.stringify(requestBody),
const data = await response.json(); headers: { 'Content-Type': 'application/json' }
core.info(JSON.stringify(data)); });
} catch (err) { if (response.status === 429) {
core.setFailed(err.message); // Rate limited, get retry-after
const retryAfter = parseInt(response.headers.get('retry-after') || '1', 10);
core.warning(`Rate limited by Discord. Retrying after ${retryAfter} seconds (attempt ${attempt + 1}/${maxRetries})`);
await new Promise(res => setTimeout(res, retryAfter * 1000));
attempt++;
continue;
}
const data = await response.json();
if (!response.ok) {
core.setFailed(`Discord webhook error: ${JSON.stringify(data)}`);
} else {
core.info(JSON.stringify(data));
}
break;
} catch (err) {
core.setFailed(err.message);
break;
}
}
if (attempt > maxRetries) {
core.setFailed('Exceeded maximum Discord webhook retry attempts due to rate limiting.');
} }
}; };