astrae

Commands in Python.
Gateway in Rust.

Astrae is a Discord framework for bots that have to stay up. You write commands, events, cache policy, and SQL in Python. The websocket, HTTP client, and rate limiter run in a Rust extension in the same process. One process is enough to start. Redis only if you split the gateway from the workers, or share cache across clusters.

maturin develop Quickstart Public exports

bot.py
from typing import Annotated
from astrae import Client, CommandContext, Intents, StringOption

bot = Client(
    command_prefix="!",
    intents=Intents.DEFAULT | Intents.MESSAGE_CONTENT,
)

@bot.command(name="echo", description="Echo a message")
async def echo(
    ctx: CommandContext,
    message: Annotated[str, StringOption(description="What to say")],
) -> None:
    await ctx.reply(message)

bot.run()
Python

Commands, events, cache policy, SQL, views, and loops. This is the bot you write.

Rust

Websocket, HTTP, and rate limits in the same process. You do not start a second runtime.

Redis, if you split

Shared cache, worker events, and cluster telemetry. A small bot never needs it.

What ships

The Python package is the surface. The Rust extension owns Discord's socket. Everything below is on from astrae import ….

Commands

Prefix, slash, hybrid, user and message menus. One callback. Annotated options. Author and Current* are injected, not options.

Context

reply, defer, followup, update. Styled success / error / deny / neutral. prompt and confirm wait on Approve / Decline.

Pagination

ctx.paginate over strings, embeds, fields, or files. Only the invoker can press the buttons. Times out after 60 seconds.

Components

View, button, ActionRow, SelectMenu, Modal, TextInput. Components V2: Container, Section, TextDisplay, Thumbnail, MediaGallery, Separator.

Cogs

Group commands and listeners. cog_check, cog_command_error. Extensions are modules with setup(client). The cluster console can reload them.

Events

@bot.listen("message_create"). Names are lowercase. EventContext has shard, delivery id, and the previous snapshot on updates.

Loops

@loop(minutes=1) starts and cancels with the client. Scheduler.cron is wall-clock. Redis locks stop two workers from running the same job.

Cache

Memory, or Redis if you share. Users stored once. Member records are nick, roles, guild assets, and a pointer. Opcode 8 still chunks.

Dashboard

127.0.0.1:9100 after run(). Command logs, REST, components, loop stalls. Prometheus at /metrics.

Cluster

astrae cluster assigns shard ranges and restarts a dead child. Gateway processes keep sockets. Workers take Redis events. A bad token exits 78.

SQL

client.db. SQLite, Postgres, or MySQL. Your rows, not Discord's cache. Migration / Migrator for schema.

Observe

LoopMonitor is on. setup_sentry() / setup_tracelet() / setup_posthog(). Jishaku for owners. GcFreezer pins long-lived cache.

Prefix, slash, and hybrid share the callback.

@bot.command can sync as slash too. @bot.slash_command is slash only. @bot.hybrid_command is both. @bot.context_menu is a user or message menu. Guild prefix needs Message Content. Slash does not.

Annotated is what Discord shows. Author, CurrentUser, CurrentMember, CurrentGuild, CurrentChannel, and CurrentRole are taken from the invoke. They are not options. Guild ones are None in a DM.

Converters and error handlers are the same door either way. Raise a CommandError subclass for an expected rejection; Astrae maps those to ctx.error or help.

Command guide

from typing import Annotated
from astrae import (
    Author, CommandContext, CurrentGuild, StringOption, User, UserOption,
)

@bot.hybrid_command(name="who", description="Show who ran this")
async def who(
    ctx: CommandContext,
    author: Author,
    guild: CurrentGuild,
    target: Annotated[User | None, UserOption(description="Someone else")] = None,
    note: Annotated[str, StringOption(description="Optional note")] = "",
) -> None:
    person = target or author
    place = guild.name if guild else "DM"
    await ctx.reply(f"{person.username} in {place} {note}".strip())

The context already knows how to talk.

ctx.reply is the first response. defer if the work is slow. followup after that. Component handlers use update or defer_update. Styled helpers mention the invoker and use Client.context_theme — or ASTRAE_COLOR_APPROVED / _WARNED / _DENIED / _NEUTRAL from the environment.

from astrae import CommandContext, Embed

async def warn(ctx: CommandContext) -> None:
    await ctx.prompt("Send the warning?")
    await ctx.success("Warned")

async def members(ctx: CommandContext) -> None:
    if ctx.guild is None:
        await ctx.error("Guild only")
        return
    await ctx.paginate(
        [m.username for m in ctx.guild.humans],
        embed=Embed(title=ctx.guild.name),
        per_page=15,
    )

Buttons, selects, and modals are ordinary Python.

A View holds the callbacks. view.rows() is what you attach. Persistent views need timeout=None, stable custom_ids, and bot.add_view(...) on every start. Callbacks get CommandContext, same as a command. Do not put secrets in custom_id.

from astrae import ButtonStyle, CommandContext, View, button

class ConfirmView(View):
    @button(label="Confirm", custom_id="confirm", style=ButtonStyle.SUCCESS)
    async def confirm(self, ctx: CommandContext) -> None:
        await ctx.update(content="Confirmed", components=[])

    @button(label="Cancel", custom_id="cancel", style=ButtonStyle.SECONDARY)
    async def cancel(self, ctx: CommandContext) -> None:
        await ctx.update(content="Cancelled", components=[])

bot.add_view(ConfirmView(timeout=None))

@bot.command(name="confirm")
async def confirm(ctx: CommandContext) -> None:
    await ctx.reply("Continue?", components=ConfirmView(timeout=None).rows())

Components V2 layouts use Container, Section, TextDisplay, Thumbnail, MediaGallery, Separator, and the COMPONENTS_V2_FLAG message flag.

Components and interactions

Cogs group commands. Extensions load them.

A cog is a class. Decorate methods with @command. Override cog_check to gate the whole group. Override cog_command_error if the default reply is wrong. Plugin is a lighter bundle of the same idea.

An extension is a module with setup(client), sync or async. Reload tears the old one down first, then loads the replacement, including already-imported submodules. Keep setup safe to run twice.

from typing import Annotated
from astrae import Client, Cog, CommandContext, IntegerOption, command, listener

class Moderation(Cog):
    name = "moderation"

    @command(name="slowmode", description="Set channel slowmode")
    async def slowmode(
        self, ctx: CommandContext,
        seconds: Annotated[int, IntegerOption(description="Delay")],
    ) -> None:
        await self.client.http.channels.modify(
            ctx.channel_id, rate_limit_per_user=seconds
        )
        await ctx.success(f"Slowmode {seconds}s")

class Bot(Client):
    async def setup_hook(self) -> None:
        await self.add_cog(Moderation(self))
        await self.load_extension("cogs.tags")

Rust receives the event. Python listeners run.

@bot.event for the named hook. @bot.listen("message_create") when you want the Discord name. Ask for EventContext when you need shard, delivery id, receive time, or the previous snapshot on an update. That snapshot is this process's last look, not a database.

Listeners sit on the dispatch path. time.sleep stalls the loop. Queue the heavy work. Workers can see the same Redis delivery twice after a crash.

Events

from astrae import EventContext, Message

@bot.listen("message_create")
async def audit_message(message: Message, context: EventContext) -> None:
    if message.author and message.author.bot:
        return
    print(context.shard, message.id, message.content[:80])

Loops follow the client. Cron is separate.

The decorator alone does not start anything. client.add_loop does. They wait one interval before the first run. A raised error is logged; the loop keeps going. One iteration at a time.

from astrae import ActivityType, Client, loop

@loop(minutes=5)
async def refresh_status() -> None:
    bot.set_presence(name="the gateway", activity_type=ActivityType.WATCHING)

class Bot(Client):
    async def setup_hook(self) -> None:
        self.add_loop(refresh_status)

Scheduler.cron is five fields: minute, hour, day, month, weekday. *, an integer, or a comma list. No ranges, no steps. Scheduler.lock / hold are best-effort Redis leases. Jobs still need to be idempotent.

Background tasks

Opcode 8 still runs. The member blob does not stay huge.

Astrae requests the full member list, then drops fields a bot cannot use before the payload is queued. Users are stored once. A member record is nick, roles, joined_at, guild avatar, guild banner, and a pointer. A cache miss is not “Discord does not have this.”

Kept

  • id, username, global_name
  • avatar, banner, bot
  • nick, roles, joined_at
  • primary_guild

Not stored

  • bio — Discord does not send it
  • collectibles
  • avatar_decoration_data
  • clan, unless it is primary_guild
from astrae import CacheConfig, CachePolicy, Client, Intents

bot = Client(
    cache_redis="redis://127.0.0.1:6379/2",
    intents=Intents.DEFAULT | Intents.GUILD_MEMBERS,
    cache=CacheConfig(
        users=CachePolicy(size=None, ttl=None),
        members=CachePolicy(size=None, ttl=None),
    ),
    cache_all_members_after_boot=True,
    member_warmup_memory_limit_mb=1024,
    primary_guilds=False,
)

Defaults are mixed on purpose: 250k users, 500k members, 10k messages for 120 seconds, invites 600 seconds, presences off. Full member warmup is opt-in and needs Redis, the Guild Members intent, and unbounded user/member size.

Cache

The dashboard binds loopback.

After bot.run(), open 127.0.0.1:9100. Cluster 0 serves the page. Other clusters publish expiring Redis telemetry; they do not open extra listeners. Command logs strip bodies. Loop stalls from LoopMonitor show up in activity and the error feed.

127.0.0.1:9100
  • / live dashboard
  • /dashboard/commands every cluster
  • /dashboard/operations commands, REST, components, errors
  • /dashboard/guilds top guilds and shard state
  • /api/health fleet JSON
  • /metrics Prometheus

Metrics and dashboard

One Client, then as many processes as you need.

A small bot holds every shard in one process. Split when one process is the wrong failure domain. Gateway processes keep the sockets. Workers take shard-affine events over Redis. The supervisor assigns contiguous ranges, restarts a child that dies, and does not restart exit 78 (InvalidToken).

cluster 0
astrae cluster mybot --clusters 2 --shards 8

--shards auto calls /gateway/bot. Children get ASTRAE_CLUSTER_ID, ASTRAE_SHARD_IDS, and friends; ClusterContext.from_env() reads them. The interactive console can restart a child, reshard, and reload extensions.

Sharding and clusters CLI

SQL is for your rows.

Gateway events and the Discord cache do not go here. Database is on client.db. URLs: sqlite:///bot.db, postgres://..., mysql://.... Pass dsn= on the client, or set DATABASE_URL.

from astrae import Database

db = Database.shared("sqlite:///bot.db")

row = await db.fetchrow(
    "SELECT value FROM settings WHERE name = :name",
    {"name": "greeting"},
)

async with db.transaction() as connection:
    await connection.execute(
        "UPDATE settings SET value = :value WHERE name = :name",
        {"value": "Hello", "name": "greeting"},
    )

Database

Owner debug, then telemetry.

Load Jishaku only where owners are people you trust. Eval runs as the bot. Non-owners are dropped silently. With Redis telemetry, jsk reports the whole fleet: guilds, users, channels, shard readiness, RSS.

setup_sentry() and setup_tracelet() read SENTRY_DSN / TRACELET_DSN. setup_posthog() sends command_used. Put this in setup_hook(), not on_ready — shards can ready more than once.

Jishaku

from astrae import Client, Jishaku

class Bot(Client):
    async def setup_hook(self) -> None:
        await self.add_cog(Jishaku(self))
        self.setup_sentry()
        self.setup_posthog()

More names on the root import

from astrae import … is the public contract. UNSET means omit the key. None means JSON null. Voice names exist; they are not a working music stack.

Embed File Upload AllowedMentions Poll User Member Guild Channel Message Interaction Intents Permission MessageFlags ButtonStyle Forbidden NotFound RateLimited InvalidToken

Every public export API reference Examples

Coming from discord.py: names will look familiar. It is not a fork. Do not rename the import and expect the bot to boot. Put async setup in setup_hook(). Global slash sync is on; turn it off with sync_commands=False while you iterate.

Install from source Migration notes API map