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

n8n-3571-node-improvement-discord-broken-rate #3311

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 24 additions & 8 deletions packages/nodes-base/nodes/Discord/Discord.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,6 @@ export class Discord implements INodeType {
],
};



async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const returnData: IDataObject[] = [];

Expand Down Expand Up @@ -204,6 +202,7 @@ export class Discord implements INodeType {

if(!body.payload_json){
requestOptions = {
resolveWithFullResponse: true,
method: 'POST',
body,
uri: webhookUri,
Expand All @@ -214,6 +213,7 @@ export class Discord implements INodeType {
};
}else {
requestOptions = {
resolveWithFullResponse: true,
method: 'POST',
body,
uri: webhookUri,
Expand All @@ -223,34 +223,50 @@ export class Discord implements INodeType {
};
}
let maxTries = 5;
let response;

do {
try {
await this.helpers.request(requestOptions);
response = await this.helpers.request(requestOptions);
const resetAfter = response.headers['x-ratelimit-reset-after'] * 1000;
const remainingRatelimit = response.headers['x-ratelimit-remaining'];

// remaining requests 0
// https://discord.com/developers/docs/topics/rate-limits
if (!+remainingRatelimit) {
await new Promise<void>((resolve) =>
setTimeout(resolve, resetAfter || 1000),
);
}

break;
} catch (error) {
// HTTP/1.1 429 TOO MANY REQUESTS
// Await when the current rate limit will reset
// https://discord.com/developers/docs/topics/rate-limits
if (error.statusCode === 429) {
//* Await ratelimit to be over
const retryAfter = error.response?.headers['retry-after'] || 1000;

await new Promise<void>((resolve) =>
setTimeout(resolve, error.response.body.retry_after || 150),
setTimeout(resolve, +retryAfter),
);

continue;
}

//* Different Discord error, throw it
throw error;
}
} while (--maxTries);

if (maxTries <= 0) {
throw new Error(
'Could not send Webhook message. Max. amount of rate-limit retries reached.',
'Could not send Webhook message. Max amount of rate-limit retries reached.',
);
}

returnData.push({ success: true });
}


return [this.helpers.returnJsonArray(returnData)];
}
}