LLM and agent context

A compact, accurate summary of Athena to paste into an AI coding assistant (Claude Code, Copilot, Cursor) working in an Athena project. Keep it in your...

A compact, accurate summary of Athena to paste into an AI coding assistant (Claude Code, Copilot, Cursor) working in an Athena project. Keep it in your project's agent instructions.

What Athena is

A TypeScript Discord library for Node 22.15+, forked from Eris, targeting discord-api-types/v10 (re-exported as Constants). Zero required runtime dependencies beyond discord-api-types and eventemitter3: WebSocket and compression use the runtime's built-ins, and the ws package is optional (proxy agents/custom headers only). Published as athena-prime, installed under the alias athena (npm install athena@npm:athena-prime), so imports stay from 'athena'. athena/webhooks is a subpath export receiving Discord Webhook Events over HTTP (verifyWebhookSignature, handleWebhookEventRequest, createWebhookEventsListener). Synchronous in-memory cache by default; optional pluggable and Redis-backed caches.

Discord's official API docs live at docs.discord.com, with an MCP server at https://docs.discord.com/mcp.

Top-level exports

import {
  Client, CommandClient, VERSION,
  // structures
  Base, BaseChannel, CategoryChannel, ForumChannel, MediaChannel, Guild, GuildChannel,
  GuildTextChannel, GuildVoiceChannel, GuildPreview, GuildAuditLogEntry, GuildIntegration,
  GuildTemplate, NewsChannel, NewsThreadChannel, PartialChannel, PrivateChannel, StageChannel,
  StageInstance, ThreadChannel, ThreadMember, UnavailableGuild, VoiceTextChannel, Member,
  Message, Role, User, VoiceState, Invite, PermissionOverwrite, Entitlement, SKU, Subscription,
  AutoModerationRule, GuildScheduledEvent,
  // interactions
  Interaction, CommandInteraction, ComponentInteraction, AutocompleteInteraction,
  ModalSubmitInteraction, PingInteraction, UnknownInteraction,
  // util
  Bitfield, Bucket, ChannelFlagBitfield, Collection, LRUCollection, NullCollection,
  RemoteBackedCollection, RedisCacheStore, GatewayIntentsBitfield, MessageFlagBitfield,
  MultipartData, PermissionBitfield, SequentialBucket, SKUFlagBitfield,
  // rest / gateway / errors
  Endpoints, RequestHandler, Shard, ShardManager,
  DiscordHTTPError, DiscordRESTError, CommandError, SearchIndexNotReadyError,
  // builders / commands
  CommandBuilder, ComponentBuilder, NewComponentBuilder, ModalBuilder, Command, Event, CooldownHandler, SlashCommand
} from 'athena';

Type-only exports include GatewayRateLimitedData, GatewayChannelInfoData / GatewayChannelInfoEntry, GatewayVoiceChannelStatusUpdateData, GatewayVoiceChannelStartTimeUpdateData, and GuildMessagesSearchQuery.

Construction

new Client(`Bot ${token}`, options?)        // token MUST start with "Bot "
new CommandClient({ token, options, commandContext?, commandMiddleware?, cooldownLogic?, deployGlobally? })

Default intents 3243773 (all non-privileged). Privileged: GuildPresences, GuildMembers, MessageContent.

Transport defaults: compress: true (boolean | 'zlib' | 'zstd') picks the best available stream via the built-in node

(zstd-stream on Node >= 22.15, zlib-stream otherwise; explicit 'zstd' warns and falls back to zlib when unsupported). gateway: { transport: 'auto' } runs on the runtime's built-in WebSocket unless options.ws is set; 'ws' selects the optional ws package (npm install ws), 'native' forces the built-in.

Key conventions

  • Snowflake IDs are always string.
  • update(data) mutates a structure from a new dispatch payload (internal).
  • Base-derived objects have id, createdAt, toJSON().
  • Type guards narrow unions: interaction.isCommand(), channel.isTextBased(), etc.
  • Cache reads are synchronous: client.users.get(id), guild.members.get(id). For possibly-uncached, use async client.fetchUser(id) / guild.fetchMember(id).

Commands

@SlashCommand(new CommandBuilder('ping', 'Replies pong'))
class PingCommand extends Command {
  async handleCommand(context, interaction: CommandInteraction) {
    await interaction.createMessage({ content: 'Pong!' });
  }
}
client.registerCommand(new PingCommand());
client.on('ready', () => client.deployCommands());

Read options with getString / getRequiredInteger / getUser / getChannel / etc. Route modals and components by custom_id prefix matching the command name.

Components

ComponentBuilder = V1 (.toJSON(), max 5 rows). NewComponentBuilder = V2 (.toMessageData(), up to 40 components; cannot carry content/embeds/poll). Buttons: addNormalButton, addURLButton, addPremiumButton. Selects: addStringSelect, addChannelSelect, addRoleSelect, addUserSelect, addMentionableSelect.

Errors

DiscordRESTError (Discord JSON error, has numeric code; HTTP status on status), DiscordHTTPError (non-JSON/transport), SearchIndexNotReadyError (searchGuildMessages while Discord indexes; retryAfter, documentsIndexed), CommandError enum emitted via the commandError event (NotDeveloperGuild, DeniedUser, DeniedGuild, MissingPermission, OnCooldown, MiddlewareError, UncaughtError).

Caching at scale

  • Retention knobs on options.cache (all default to historical behaviour): guildEmojis / guildStickers: false skip retaining raw emoji/sticker arrays per guild; transientMembers: false stops caching members/users seen only via reactions, typing, messages, and interactions (resolve later reads with fetchMember); userSweepIntervalMs > 0 periodically evicts users referenced by nothing (also callable manually via client.sweepUsers()).
  • Per-cache overrides via options.cache (factories for users, members, messages, ...). LRUCollection(Class, max), NullCollection(Class).
  • Cross-cluster dedup: RemoteBackedCollection + RedisCacheStore (over an injected Redis client) implementing RemoteCacheStore (getEntity/getEntities/getAllEntities/setEntity/removeEntity), resolved via client.fetchUser / guild.fetchMember.
  • One-flag preset: largeBotOptimizations: true (or env ATHENA_LARGE_BOT=1) = rest.fullErrorStacks: false + cache.guildEmojis/guildStickers: false + cache.userSweepIntervalMs: 3_600_000. Explicit options win; never sets transientMembers.
  • Member and Message allocate container fields (roles, clientStatus, activities; mentions, embeds, reactions, ...) lazily on first access - automatic, identity-stable, safe to mutate in place.

Performance options (REST)

rest.fullErrorStacks: false skips the per-request caller-stack capture (errors still carry method, route, code, status, message). rest.bucketSweepInterval (default 300000 ms, 0 disables) sweeps idle ratelimit buckets so they don't accumulate. rest.maxRatelimitRetries (default 0, unbounded) caps the 429s one request may absorb before rejecting with the 429.

New in 2.10 / 3.0 (June 2026)

  • REST helpers: getChannelPins (paginated pins: { items: [{ pinnedAt, message }], hasMore }), bulkBanGuildMembers, searchGuildMessages(guildID, GuildMessagesSearchQuery) (throws SearchIndexNotReadyError while indexing), setVoiceChannelStatus, editGuildIncidentActions, getGuildRoleMemberCounts.
  • Events: rateLimited (gateway RATE_LIMITED, member chunk requests), voiceChannelStatusUpdate, voiceChannelStartTimeUpdate, channelInfo (opcode 43 response via client.requestChannelInfo).
  • interaction.createMessage(...) and interaction.editParent(...) resolve with the created/updated Message (no getOriginalMessage round trip). interaction.launchActivity() for Activities apps.

New in the August 2026 Discord API wave

  • file_types upload filtering. addAttachmentOption(name, description, required?, fileTypes?) and addFileUpload({ ..., file_types }) accept up to 10 entries, each a media category (image, video, audio) or a dot-prefixed extension (.pdf). Matches on extension only, so it is not validation. MIME types and lists over 10 throw at build time.
  • attachments[].is_spoiler blurs an attachment until clicked (sets AttachmentFlags.IsSpoiler); read the flag, not a SPOILER_ filename prefix. On edit, send the id of every attachment to keep; description and is_spoiler are editable on existing ones. Shape exported as AttachmentRequest.
  • interaction.channelAppPermissions - Map<channelID, PermissionBitfield> on CommandInteraction, ComponentInteraction, and ModalSubmitInteraction. Your bot's permissions in each resolved channel, straight off the payload, so no cached overwrites are needed. Empty when the bot user is not in the guild: treat a miss as "unknown", not "denied".
  • GuildAuditLogEntry.status for voice channel status entries (192/193), whose target is the voice channel. target returns null instead of throwing for action types Athena caches nothing for.
  • client.application.flagsNew (bigint) holds flag bits above bit 30, which the 32-bit flags cannot represent.

New in 4.4 to 4.7 (August to November 2026)

  • Interaction acks are isolated. Each interaction's callback has its own bucket and is sent without auth, so acks run in parallel and ignore the global block. Webhook routes (including interaction followups) are bucketed per token.
  • Bounded 429 retries. Interaction callbacks never retry past the 3 second ack window, interaction-token webhook routes never past the 15 minute token lifetime: they reject with the 429 (DiscordHTTPError, code 429) instead of a later 10062 / 50027. rest.maxRatelimitRetries caps 429 retries for any request. Every 429 emits a throttled warn.
  • 408 is retried like 502 (up to 3 retries, random 100 to 2000 ms backoff).
  • Gateway backlog safety. shard.compression.pending counts messages awaiting decompression; heartbeats get one extra interval while it is above zero, and a disconnect discards the backlog instead of emitting Unexpected end of JSON input errors.
  • Channel obfuscation (mandatory from 2026-11-16). Channels the bot cannot view arrive with name ___hidden___ and placeholder data. Check channel.obfuscated, never the name. Only id, type, position, parentID are real; permissionsOf is only meaningful for the bot itself; getRESTGuildChannels omits them; interaction.channel uses the real payload; channelUpdate handlers that diff should skip when channel.obfuscated || oldChannel?.obfuscated (the old snapshot carries obfuscated). capabilities: Constants.GatewayCapabilityBits.ChannelObfuscation opts in early (temporary).
  • Permission endpoints resolving a PermissionBitfield: getGuildMemberPermissions(guildID, userID), getGuildRolePermissions(guildID, roleID), getChannelMemberPermissions(channelID, userID, { implicit? }), getChannelRolePermissions(channelID, roleID, { implicit? }), plus guild. / channel.getMemberPermissions / getRolePermissions. No cache needed; channel variants need VIEW_CHANNEL.
  • Invite target users: addInviteTargetUser, removeInviteTargetUser, bulkAddInviteTargetUsers, bulkDeleteInviteTargetUsers (max 1000), and target_user_ids on createChannelInvite (mutually exclusive with targetUsersFile).
  • getRESTGuilds({ shard }) is required on large bot sharding (0 to max_concurrency - 1), else 400.
  • Audit log: CHANNEL_POSITION_UPDATE (16) / ROLE_POSITION_UPDATE (33) entries resolve the channel or role when targeted, null when not; entry.count holds the number of updates.

New in 4.8.0 (November 2026)

  • presenceUpdate works. Through 4.7.0 every PRESENCE_UPDATE threw Missing object id, so the event never fired; require 4.8.0+ for presence.
  • ThreadChannel.appliedTags: tag IDs on forum and media posts (empty array on other threads).
  • Every MessageType Discord defines (poll results, AutoMod alerts, purchases, stage and incident messages) is handled without a warn.
  • editGuildWidget targets /guilds/{id}/widget; loadSKUs / getEntitlements use the application ID.

When generating code, prefer

  • interaction.getRequiredString('name') over digging into interaction.data.options.
  • MessageFlags.Ephemeral over the literal 64.
  • PermissionFlagsBits.X over hex values.
  • CommandBuilder over hand-written command JSON.
  • await-ing all REST calls.
  • Imports from 'athena'; from 'discord-api-types/v10' only for types Athena does not re-export.

Common pitfalls

  • Missing the Bot token prefix.
  • getAllUsers: true without the GuildMembers intent (throws on construct).
  • Responding to an interaction after 3 seconds (code 10062) or twice (40060).
  • Not handling the error event.
  • Mixing V1 and V2 components on one message.
  • Detecting hidden channels by name === '___hidden___' instead of channel.obfuscated, or logging obfuscation flips in channelUpdate as renames.
  • Installing plain athena from the registry (frozen legacy 2.8.0) instead of the athena@npm:athena-prime alias.