bsky_bot_sdk/lib.rs
1//! # bsky-bot-sdk
2//!
3//! An ergonomic, event-driven SDK for building [Bluesky](https://bsky.app)
4//! (AT Protocol) bots in Rust. It sits on top of atrium's
5//! [`bsky-sdk`](https://crates.io/crates/bsky-sdk), adding the pieces a bot needs
6//! that the low-level client leaves to you:
7//!
8//! - **A notification event loop** that polls `listNotifications`, de-duplicates
9//! across restarts, and dispatches each event to your handlers.
10//! - **Real-time network ingestion** via the
11//! [Jetstream](https://docs.bsky.app/blog/jetstream) firehose — react to the
12//! *whole network* with [`on_keyword`](BotBuilder::on_keyword),
13//! [`on_hashtag`](BotBuilder::on_hashtag), or
14//! [`on_firehose`](BotBuilder::on_firehose), not just your own notifications.
15//! - **Typed events** — match on [`NotificationReason::Mention`],
16//! [`NotificationReason::Follow`], … instead of stringly-typed reasons.
17//! - **Action helpers** on [`Context`] — [`reply_to`](Context::reply_to),
18//! [`like`](Context::like), [`repost`](Context::repost),
19//! [`follow_back`](Context::follow_back), [`post`](Context::post) — with
20//! automatic rich-text facet detection (mentions, links, hashtags).
21//! - **Media & embeds** via [`ctx.compose()`](Context::compose) — a
22//! [`PostBuilder`] for images (with **required** alt text), video, external
23//! link cards (auto-fetched OpenGraph), and quote posts, all uploaded to the
24//! bot's own PDS so they work on any server.
25//! - **Threads with auto-split** via [`ctx.thread()`](Context::thread) — a
26//! [`ThreadBuilder`] that chains posts into a reply thread and splits text over
27//! [`MAX_POST_GRAPHEMES`] at word boundaries, optionally numbering each part.
28//! - **Direct messages** via [`on_message`](BotBuilder::on_message) and
29//! [`ctx.send_dm`](Context::send_dm) — react to private
30//! [`chat.bsky.convo`](https://docs.bsky.app/docs/category/chat) conversations
31//! and reply, the bot's own messages filtered out so an echo cannot loop.
32//! - **Automated self-label** via
33//! [`automated_label`](BotBuilder::automated_label) — declare the account a bot
34//! on its profile ([`BOT_SELF_LABEL`]), the guideline-recommended, cheap signal
35//! that it's automated.
36//! - **Resilience** — transient failures (network blips, 5xx, throttling) on the
37//! poll loops and idempotent reads are retried with jittered backoff (see
38//! [`RetryPolicy`] and [`retry_policy`](BotBuilder::retry_policy)); the
39//! Jetstream stream auto-reconnects. Record writes are never blindly retried.
40//! - **Session persistence** so restarts resume instead of re-authenticating.
41//! - **Rate limiting** — a client-side token bucket models Bluesky's points-based
42//! write budget, *and* the SDK records the server's `RateLimit-*` response
43//! headers ([`Context::server_rate_limit`]) and waits when the server reports
44//! the window exhausted, so writes pre-empt a 429 instead of absorbing one.
45//! - **Scheduling** — run actions on an interval or a cron schedule (see
46//! [`Schedule`] and [`BotBuilder::every`]/[`BotBuilder::cron`]).
47//! - **A test harness** ([`testkit`]) — unit-test your handler logic against a
48//! real [`Context`] served in-process, with no network and no credentials, then
49//! assert on exactly what the handler did.
50//! - **Graceful shutdown** on `Ctrl-C` or any future you provide.
51//!
52//! ## Quick start
53//!
54//! ```no_run
55//! use bsky_bot_sdk::prelude::*;
56//!
57//! #[tokio::main]
58//! async fn main() -> Result<()> {
59//! Bot::builder()
60//! .credentials("mybot.bsky.social", "xxxx-xxxx-xxxx-xxxx")
61//! .session_file("session.json")
62//! .on_mention(|ctx, notif| async move {
63//! let who = notif.author_handle().to_string();
64//! ctx.reply_to(¬if, format!("👋 hi @{who}!")).await?;
65//! Ok(())
66//! })
67//! .on_follow(|ctx, notif| async move {
68//! ctx.follow_back(¬if).await?;
69//! Ok(())
70//! })
71//! .build()
72//! .await?
73//! .run()
74//! .await
75//! }
76//! ```
77//!
78//! Handlers are async closures of the form
79//! `Fn(Context, Notification) -> impl Future<Output = Result<()>>`. Register as
80//! many as you like; a handler returning `Err` is routed to your
81//! [`on_error`](BotBuilder::on_error) handler (or logged) and never aborts the
82//! loop.
83//!
84//! ## Re-exports
85//!
86//! The underlying [`bsky_sdk`] and [`atrium_api`] crates are re-exported so you
87//! can reach for lower-level types (custom records, embeds, XRPC calls) without a
88//! separate dependency or a version-mismatch risk.
89
90#![deny(unsafe_code)]
91#![warn(missing_docs)]
92
93mod bot;
94mod command;
95mod config;
96mod context;
97mod dedup;
98mod dm;
99mod embed;
100mod error;
101mod event;
102mod handler;
103mod ratelimit;
104mod read;
105mod retry;
106mod schedule;
107mod self_label;
108mod stream;
109mod thread;
110
111pub mod prelude;
112pub mod store;
113pub mod testkit;
114
115pub use bot::{Bot, BotBuilder};
116pub use command::Command;
117pub use config::{BotConfig, DEFAULT_SERVICE};
118pub use context::{BotIdentity, Context, ReplyGate};
119pub use dedup::Dedup;
120pub use dm::{DirectMessage, DmAccess, DmConfig, RawMessage};
121pub use embed::{MAX_IMAGES, PostBuilder};
122pub use error::{Error, Result};
123pub use event::{Notification, NotificationReason, RawNotification};
124pub use handler::{BoxFuture, Flow};
125pub use ratelimit::{RateLimitClient, RateLimitConfig, RateLimitStatus, RateLimiter};
126pub use read::Paginated;
127pub use retry::RetryPolicy;
128pub use schedule::{Schedule, Tz};
129pub use self_label::BOT_SELF_LABEL;
130pub use store::{FileStore, MemoryStore, Store};
131pub use stream::{
132 Backoff, CommitOp, DEFAULT_JETSTREAM_ENDPOINT, JetstreamConfig, RawCommit, RawStreamEvent,
133 StreamEvent, StreamKind,
134};
135pub use thread::{MAX_POST_GRAPHEMES, ThreadBuilder};
136
137// Re-export the underlying crates for advanced use and to guarantee a single,
138// consistent version of the AT Protocol types across your app.
139pub use atrium_api;
140pub use bsky_sdk;