REST and ratelimits
Every REST call funnels through one RequestHandler. The helpers on Client and on structures (createMessage, editChannel, member.ban, ...) all use it.
Every REST call funnels through one RequestHandler. The helpers on Client and on structures (createMessage, editChannel, member.ban, ...) all use it.
Issuing requests
You normally call the typed helpers, not the handler directly. To reach an endpoint Athena has not wrapped:
import { Routes } from 'discord-api-types/v10';
const channel = await client.requestHandler.request('GET', Routes.channel(channelID), true);Signature: request(method, url, auth?, body?, file?, route?, short?). For GET/DELETE, body keys become the query string. auth: true adds the Authorization header.
File uploads
await client.createMessage(channelID, { content: 'Look' }, { file: buffer, name: 'a.png' });
await client.createMessage(channelID, { content: 'Look' }, [
{ file: b1, name: 'a.png' },
{ file: b2, name: 'b.png' }
]);MIME type is sniffed from the filename. Multiple files become files[0], files[1], etc.
Discord's default upload limit is 10 MiB, enforced per attachment (boosted guilds and Nitro raise it). For interactions, interaction.attachmentSizeLimit carries the actual limit in bytes for the invoking context.
Alt text and spoilers
The attachments array on the message body carries metadata for each file. Its id is either an existing attachment's ID, or the index n matching your files[n], so id: 0 describes the first file you passed:
await client.createMessage(
channelID,
{
content: 'Ending spoilers below',
attachments: [{ id: 0, description: 'The final scene', is_spoiler: true }],
},
{ file: buffer, name: 'ending.png' },
);description is alt text (max 1024 characters), and is_spoiler: true blurs the file until a viewer clicks it. To check whether an attachment you received is a spoiler, test its flags against AttachmentFlags.IsSpoiler rather than looking for a SPOILER_ filename prefix. The prefix still works when uploading, but not every spoilered attachment has one.
Editing attachments
When you edit a message, send the id of every attachment you want to keep. Anything you leave out is removed from the message. You can also change description and is_spoiler on attachments that are already there:
// Keeps both files, spoilers the first one and relabels it
await client.editMessage(channelID, messageID, {
attachments: [
{ id: '1234567890', description: 'Spoiler: the final scene', is_spoiler: true },
{ id: '1234567891' },
],
});The shape is exported as AttachmentRequest, and every Athena method that creates or edits a message accepts it: client.createMessage / editMessage / executeWebhook / editWebhookMessage, channel.createMessage / editMessage, message.edit, and the interaction response, followup, and edit methods.
Ratelimit model
Discord limits per route bucket. Athena tracks each route with its own sequential bucket, so same-route requests run strictly in order, and updates buckets from the X-RateLimit-* headers.
Because routes keep their raw guild/channel/webhook IDs, one bucket exists per entity touched. Idle buckets (nothing queued, no request in flight, reset window elapsed) are swept every rest.bucketSweepInterval ms (default 5 minutes; 0 disables), so they do not accumulate for the lifetime of the process on large bots. A swept route simply relearns its limits from the next response's headers, identical to the first-ever request on that route.
On a 429: it reads Retry-After (or X-RateLimit-Reset-After), engages a global block if the limit was global, and re-queues the request in a priority slot so it keeps its place. Every 429 also emits a warn (429 on <route> (scope <scope>), retrying in <ms>ms), throttled to one per route per 10 seconds, so you can see a throttled route without logging debug.
Interaction acks and followups
Interaction responses do not wait behind your other REST traffic. Each interaction's callback (createInteractionResponse, which defer, createMessage, createModal, and friends all use) gets its own bucket, so acks for different interactions run in parallel. Acks are sent without the bot token (the interaction token in the URL authorizes them, and Discord exempts them from the global limit), so a global 429 earned by unrelated traffic never delays an ack.
Webhook calls, including interaction followups and followup edits, are bucketed per webhook token, matching Discord. One interaction's followups never share a bucket, or ratelimit headers, with another's.
Bounded 429 retries
By default a request keeps retrying 429s until it succeeds. Two limits stop that from turning into a misleading error later:
- Interaction routes stop at their own deadline. An ack is only accepted within 3 seconds of the interaction, and followups and edits only within the 15 minute token lifetime. If a 429's retry would land past that point, Athena rejects immediately with the 429 instead of retrying into a
10062 Unknown interactionor50027 Invalid Webhook Token. Ordinary webhooks and all other routes are unaffected. rest.maxRatelimitRetries(default0, unbounded) caps how many 429s any single request may absorb before it rejects with the 429.
Either way the rejection is a DiscordHTTPError whose code is 429, so you can catch it and fall back (for example, edit one summary message instead of sending a followup per click):
try {
await interaction.createFollowup({ content: 'Entered!', flags: MessageFlags.Ephemeral });
} catch (err) {
if (err instanceof DiscordHTTPError && err.code === 429) {
// the channel is saturated; skip or batch instead of retrying
} else throw err;
}The invalid-request limit
Separately from per-route ratelimits, Discord counts 401, 403, and 429 responses against a hard limit of 10,000 per 10 minutes; exceeding it triggers a temporary Cloudflare ban of your IP (shared-resource 429s are exempt). Athena tracks this window and emits a warn at 80%. If you see that warning, find the loop producing the errors instead of retrying blindly.
Latency compensation
By default Athena tracks a rolling average of request latency and folds it into reset timing to absorb clock skew. Disable with rest.disableLatencyCompensation: true. rest.latencyThreshold (default 30000 ms) is where it warns about excessive latency.
Connection reuse
Athena defaults to a shared keep-alive HTTP(S) agent, so requests reuse connections instead of doing a fresh TLS handshake each time. This matters a lot at volume. Supplying your own rest.agent overrides it.
Error stacks
By default every request captures a caller stack so a failing call's DiscordRESTError / DiscordHTTPError points at your code (rest.fullErrorStacks: true). On high-volume bots that per-request capture is measurable CPU; set rest.fullErrorStacks: false to skip it. Errors then capture a stack only when they are actually constructed (the failure path) and still carry the method, route, code, status, and message.
Force-queueing until ready
rest.forceQueueing: true holds authenticated requests until the first shardPreReady, avoiding a startup race against Discord's identify queue.
Retry behaviour
- 429: re-queued after the reset interval (with a clamp so a missing or malformed
Retry-Aftercannot cause a tight loop), up to the interaction deadline orrest.maxRatelimitRetriesdescribed above. - 502 and 408: up to 3 retries with random 100 to 2000 ms backoff. A 408 is the edge timing out (seen on large PUTs such as a global command overwrite) and says nothing about the request itself.
- other 5xx: thrown as
DiscordHTTPError. - 4xx: thrown as
DiscordRESTErrorwith Discord's code and message. See Errors.
Newer endpoints (2025-2026 API)
Paginated pins
const page = await client.getChannelPins(channelID, { before, limit });
// { items: [{ pinnedAt, message }], hasMore }Newest-pinned first; before is a timestamp, so pass the last item's pinnedAt to paginate. getPins, pinMessage, and unpinMessage use the new routes under the hood, and pinning requires the PIN_MESSAGES permission (enforced by Discord since 2026-02-23).
Bulk bans
bulkBanGuildMembers(guildID, userIDs, { deleteMessageSeconds, reason }) bans up to 200 users in one request and resolves { bannedUsers, failedUsers }. Requires both BAN_MEMBERS and MANAGE_GUILD.
Guild incidents and role counts
editGuildIncidentActions(guildID, { invitesDisabledUntil, dmsDisabledUntil })pauses invites and/or DMs for up to 24 hours (passnullto re-enable); the current state lives onguild.incidentsData.getGuildRoleMemberCounts(guildID)resolves a map of role ID to member count.
Message search
searchGuildMessages(guildID, query) takes a GuildMessagesSearchQuery filters object (content, channel_id, author_id, has, pinned, sorting, and more). Requires READ_MESSAGE_HISTORY plus the MESSAGE_CONTENT intent. While Discord is still indexing the guild it throws SearchIndexNotReadyError carrying a retryAfter; see Errors.
Voice channel status
setVoiceChannelStatus(channelID, status, reason?) sets or clears (pass null) a voice channel's status. Requires SET_VOICE_CHANNEL_STATUS, plus MANAGE_CHANNELS when the bot is not connected to that channel.
Invite target users
createChannelInvite (and channel.createInvite) accepts role_ids (roles granted when the invite is accepted) and the users allowed to accept it, either as target_user_ids (an array of up to 1000 IDs) or as targetUsersFile (a CSV). The two are mutually exclusive: passing both rejects before any request is sent.
const invite = await client.createChannelInvite(channelID, { target_user_ids: [userA, userB] });
await client.addInviteTargetUser(invite.code, userC);
await client.bulkAddInviteTargetUsers(invite.code, moreUserIDs); // up to 1000 per callTo edit the list on an existing invite: addInviteTargetUser / removeInviteTargetUser for one user, bulkAddInviteTargetUsers / bulkDeleteInviteTargetUsers for up to 1000, or the CSV route with updateInviteTargetUsers (processed asynchronously; poll getInviteTargetUsersJobStatus). getInviteTargetUsers reads the list. All of them require being the inviter or MANAGE_GUILD.
Member and role permissions
Discord can compute permissions for you, so you need no cached roles or overwrites. Each call resolves with a PermissionBitfield:
const perms = await client.getChannelMemberPermissions(channelID, userID);
if (perms.has(PermissionFlagsBits.SendMessages)) { /* ... */ }getGuildMemberPermissions(guildID, userID)andgetGuildRolePermissions(guildID, roleID)(alsoguild.getMemberPermissions/guild.getRolePermissions). The role variant is that role plus@everyoneonly.getChannelMemberPermissions(channelID, userID, { implicit? })andgetChannelRolePermissions(channelID, roleID, { implicit? })(alsochannel.getMemberPermissions/channel.getRolePermissions), applying channel overwrites.implicit(defaulttrue) masks permissions that depend on a missingVIEW_CHANNEL(orCONNECTon voice and stage).
These stay correct when cache.channelPermissionOverwrites is disabled, which makes permissionsOf unreliable. The channel variants require VIEW_CHANNEL (and CONNECT for voice and stage), so they cannot see into obfuscated channels.
Listing guilds on large bot sharding
getRESTGuilds({ after, before, limit, shard }) (REST mode) pages through the bot's guilds. Bots on large bot sharding must pass shard, a bucket from 0 to max_concurrency - 1 (see client.sessionStartLimit.max_concurrency): Discord answers 400 without it.
Tracing
client.on('rawREST', (e) => console.log(e.method, e.url, e.resp.statusCode, e.latency));Endpoints
Endpoints holds URL builders (for example Endpoints.CHANNEL_MESSAGES(channelID)) and CDN helpers. They return paths, not method-typed calls; response types come from discord-api-types.
Tips
- Always
awaitREST calls; forgetting it loses the ratelimit feedback path. - Prefer bulk endpoints (
bulkEditCommands) over loops. - Check the cache before REST:
channel.messages.get(id)is microseconds, the REST round trip is tens of milliseconds.