Expand description
§bsky-bot-sdk
An ergonomic, event-driven SDK for building Bluesky
(AT Protocol) bots in Rust. It sits on top of atrium’s
bsky-sdk, adding the pieces a bot needs
that the low-level client leaves to you:
- A notification event loop that polls
listNotifications, de-duplicates across restarts, and dispatches each event to your handlers. - Real-time network ingestion via the
Jetstream firehose — react to the
whole network with
on_keyword,on_hashtag, oron_firehose, not just your own notifications. - Typed events — match on
NotificationReason::Mention,NotificationReason::Follow, … instead of stringly-typed reasons. - Action helpers on
Context—reply_to,like,repost,follow_back,post— with automatic rich-text facet detection (mentions, links, hashtags). - Media & embeds via
ctx.compose()— aPostBuilderfor images (with required alt text), video, external link cards (auto-fetched OpenGraph), and quote posts, all uploaded to the bot’s own PDS so they work on any server. - Threads with auto-split via
ctx.thread()— aThreadBuilderthat chains posts into a reply thread and splits text overMAX_POST_GRAPHEMESat word boundaries, optionally numbering each part. - Direct messages via
on_messageandctx.send_dm— react to privatechat.bsky.convoconversations and reply, the bot’s own messages filtered out so an echo cannot loop. - Automated self-label via
automated_label— declare the account a bot on its profile (BOT_SELF_LABEL), the guideline-recommended, cheap signal that it’s automated. - Resilience — transient failures (network blips, 5xx, throttling) on the
poll loops and idempotent reads are retried with jittered backoff (see
RetryPolicyandretry_policy); the Jetstream stream auto-reconnects. Record writes are never blindly retried. - Session persistence so restarts resume instead of re-authenticating.
- Rate limiting — a client-side token bucket models Bluesky’s points-based
write budget, and the SDK records the server’s
RateLimit-*response headers (Context::server_rate_limit) and waits when the server reports the window exhausted, so writes pre-empt a 429 instead of absorbing one. - Scheduling — run actions on an interval or a cron schedule (see
ScheduleandBotBuilder::every/BotBuilder::cron). - A test harness (
testkit) — unit-test your handler logic against a realContextserved in-process, with no network and no credentials, then assert on exactly what the handler did. - Graceful shutdown on
Ctrl-Cor any future you provide.
§Quick start
use bsky_bot_sdk::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
Bot::builder()
.credentials("mybot.bsky.social", "xxxx-xxxx-xxxx-xxxx")
.session_file("session.json")
.on_mention(|ctx, notif| async move {
let who = notif.author_handle().to_string();
ctx.reply_to(¬if, format!("👋 hi @{who}!")).await?;
Ok(())
})
.on_follow(|ctx, notif| async move {
ctx.follow_back(¬if).await?;
Ok(())
})
.build()
.await?
.run()
.await
}Handlers are async closures of the form
Fn(Context, Notification) -> impl Future<Output = Result<()>>. Register as
many as you like; a handler returning Err is routed to your
on_error handler (or logged) and never aborts the
loop.
§Re-exports
The underlying bsky_sdk and atrium_api crates are re-exported so you
can reach for lower-level types (custom records, embeds, XRPC calls) without a
separate dependency or a version-mismatch risk.
Re-exports§
pub use store::FileStore;pub use store::MemoryStore;pub use store::Store;pub use atrium_api;pub use bsky_sdk;
Modules§
- prelude
- Convenient glob-import of the crate’s most-used types.
- store
- A pluggable key/value store for the pieces a bot needs to remember across restarts.
- testkit
- An in-process test harness for unit-testing bot logic without a network.
Structs§
- Backoff
- Exponential-backoff-with-jitter parameters for stream reconnection.
- Bot
- A configured, authenticated bot ready to poll for notifications and dispatch them to handlers, plus any scheduled jobs.
- BotBuilder
- Builder for a
Bot: configure credentials, polling behaviour, and handlers, thenbuildto authenticate and obtain a runnable bot. - BotConfig
- Configuration controlling how a bot authenticates and polls for work.
- BotIdentity
- The bot’s own account identity, resolved at login.
- Command
- A parsed command: the command word plus its arguments.
- Context
- Everything a handler needs to react to a notification.
- Dedup
- Tracks which notifications have already been handled across poll cycles.
- Direct
Message - An ergonomic wrapper over a single direct message.
- DmConfig
- Configuration for the direct-message poll loop.
- Jetstream
Config - Configuration for the Jetstream real-time ingestion connection.
- Notification
- An ergonomic wrapper around a single Bluesky notification.
- Paginated
- An async stream over a Bluesky list or feed that pages transparently.
- Post
Builder - A fluent builder for a post with optional rich media and embeds.
- Rate
Limit Client - An XRPC client that wraps the reqwest-backed
ReqwestClientand records Bluesky’sRateLimit-*response headers as a side effect of every response, so a bot can honor — and inspect — the server’s real limits. - Rate
Limit Config - Configuration describing Bluesky’s points-based write budget.
- Rate
Limit Status - A snapshot of Bluesky’s rate-limit state as it last told us, via the
RateLimit-Limit/RateLimit-Remaining/RateLimit-Resetresponse headers. - Rate
Limiter - A token-bucket rate limiter shared across all writes performed by a bot.
- RawCommit
- The
commitpayload of a Jetstream commit event. - RawStream
Event - The raw, deserialized Jetstream event.
- Retry
Policy - How to retry an operation that fails transiently.
- Schedule
- When a scheduled job fires.
- Stream
Event - An ergonomic wrapper over a single Jetstream event.
- Thread
Builder - A fluent builder that publishes a connected thread of posts.
Enums§
- Commit
Op - The operation carried by a commit event.
- DmAccess
- Who may start a direct-message conversation with the bot.
- Error
- The error type returned by all fallible operations in this crate.
- Flow
- Whether a
beforemiddleware lets a notification reach the handlers, or drops it. - Notification
Reason - Why a notification was delivered.
- Reply
Gate - Who may reply to a post, expressed as one allow-rule of a thread-gate.
- Stream
Kind - The kind of a Jetstream event.
- Tz
- The timezone a cron
Scheduleis evaluated in.
Constants§
- BOT_
SELF_ LABEL - The self-label value that marks an account as an automated bot.
- DEFAULT_
JETSTREAM_ ENDPOINT - The default public Jetstream instance (US-East).
- DEFAULT_
SERVICE - The default Bluesky PDS entryway.
- MAX_
IMAGES - Maximum number of images Bluesky allows in a single post.
- MAX_
POST_ GRAPHEMES - Bluesky’s maximum post length, in Unicode extended grapheme clusters.
Type Aliases§
- BoxFuture
- A boxed,
Sendfuture — the erased return type of a handler. - RawMessage
- The
chat.bsky.convo.defs#messageViewreturned inside conversation logs and fromsendMessage, re-exported so callers can reach the full record viaDirectMessage::rawwithout a separateatrium-apinavigation. - RawNotification
- The raw notification type returned by
app.bsky.notification.listNotifications. - Result
- Convenience
Resultalias used throughout the crate.