Skip to main content

Crate bsky_bot_sdk

Crate bsky_bot_sdk 

Source
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, or on_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() — a PostBuilder for 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() — a ThreadBuilder that chains posts into a reply thread and splits text over MAX_POST_GRAPHEMES at word boundaries, optionally numbering each part.
  • Direct messages via on_message and ctx.send_dm — react to private chat.bsky.convo conversations 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 RetryPolicy and retry_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 Schedule and BotBuilder::every/BotBuilder::cron).
  • A test harness (testkit) — unit-test your handler logic against a real Context served in-process, with no network and no credentials, then assert on exactly what the handler did.
  • Graceful shutdown on Ctrl-C or 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(&notif, format!("👋 hi @{who}!")).await?;
            Ok(())
        })
        .on_follow(|ctx, notif| async move {
            ctx.follow_back(&notif).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, then build to 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.
DirectMessage
An ergonomic wrapper over a single direct message.
DmConfig
Configuration for the direct-message poll loop.
JetstreamConfig
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.
PostBuilder
A fluent builder for a post with optional rich media and embeds.
RateLimitClient
An XRPC client that wraps the reqwest-backed ReqwestClient and records Bluesky’s RateLimit-* response headers as a side effect of every response, so a bot can honor — and inspect — the server’s real limits.
RateLimitConfig
Configuration describing Bluesky’s points-based write budget.
RateLimitStatus
A snapshot of Bluesky’s rate-limit state as it last told us, via the RateLimit-Limit / RateLimit-Remaining / RateLimit-Reset response headers.
RateLimiter
A token-bucket rate limiter shared across all writes performed by a bot.
RawCommit
The commit payload of a Jetstream commit event.
RawStreamEvent
The raw, deserialized Jetstream event.
RetryPolicy
How to retry an operation that fails transiently.
Schedule
When a scheduled job fires.
StreamEvent
An ergonomic wrapper over a single Jetstream event.
ThreadBuilder
A fluent builder that publishes a connected thread of posts.

Enums§

CommitOp
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 before middleware lets a notification reach the handlers, or drops it.
NotificationReason
Why a notification was delivered.
ReplyGate
Who may reply to a post, expressed as one allow-rule of a thread-gate.
StreamKind
The kind of a Jetstream event.
Tz
The timezone a cron Schedule is 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, Send future — the erased return type of a handler.
RawMessage
The chat.bsky.convo.defs#messageView returned inside conversation logs and from sendMessage, re-exported so callers can reach the full record via DirectMessage::raw without a separate atrium-api navigation.
RawNotification
The raw notification type returned by app.bsky.notification.listNotifications.
Result
Convenience Result alias used throughout the crate.