Expand description
§Vector SDK
Build a private-messaging bot in about a dozen lines.
Vector is a private, encrypted messenger. This SDK lets your bot send and receive messages, files, and reactions, join communities, and ride out network drops — without ever touching the protocol or encryption underneath.
use vector_sdk::VectorBot;
#[tokio::main]
async fn main() -> vector_sdk::Result<()> {
let bot = VectorBot::builder()
.nsec("nsec1...") // or .mnemonic("twelve words ...")
.build()
.await?;
println!("Online as {}", bot.npub());
// Reply to everything. The SAME handler serves DMs *and* Community channels.
bot.on_message(|_bot, msg| async move {
if msg.is_mine() { return; } // ignore our own messages
let _ = msg.reply(&format!("You said: {}", msg.text())).await;
}).await?;
Ok(())
}That bot already handles direct messages and communities, reconnects after a network drop, and catches up on what it missed.
§One API, everywhere
Your bot sends and receives through a Channel — a direct-message chat or a
community channel, handled identically. You never branch on which it is:
bot.channel(id) opens either by id, and
msg.reply(...) answers wherever the message came from.
let chat = bot.channel(id); // DM or Community channel — auto-detected
chat.send("hi").await?; //
chat.react(msg_id, "👍").await?; // identical surface either way
chat.send_file("./photo.png").await?; //
chat.typing().await?; // "typing…" indicator§What a bot can do
| You want to… | …you call |
|---|---|
| Send / reply / edit / delete | Channel::send · reply · edit · delete |
| React (emoji or custom image) | Channel::react · react_custom |
Write custom emoji in messages (:code:) | subscribe_emoji_pack · emojis |
| Send & receive files | Channel::send_file · VectorBot::download_attachment / save_attachment |
| Receive messages | VectorBot::on_message |
Answer typed slash commands (with a / picker) | VectorBot::command → CommandBuilder |
| Receive everything (joins, reactions, invites…) | VectorBot::on_event → match on BotEvent |
| Moderate a community | IncomingMessage::member → Member::kick · ban · timeout · Channel::hide |
| Roles and permissions | Community::create_role → Role · Member::add_role · Channel::set_overwrite · Member::can |
| Channels and Categories | Community::create_channel_with · create_category · Channel::set_topic · Channel::move_to |
| Pins, Nicknames, the Audit Log | Channel::pin · Member::set_nickname · Community::audit_log |
| Hear every change, and who made it | BotEvent::CommunityChange → ChangeKind |
| Create, join, preview | VectorBot::create_community · join · preview_link |
| Manage a community | IncomingMessage::community / VectorBot::community → Community |
| Be invitable safely | builder().public() / whitelist(..) |
| Manage profiles | fetch_profile · update_profile · block … |
| Join the Mini Apps (WebXDC games and tools) people share, on their realtime channel | bot.xdc(..).run(..), msg.xdc() (feature xdc; see the xdc module) |
| Make HTTP requests over the bot’s transport | net::build_http_client |
| Anything else | bot.core() → the full VectorCore facade |
§Receiving: on_message vs on_event
on_message is the fast path — one async handler per
inbound message, DMs and Community channels alike; a slow handler won’t hold up the others.
(For slash commands, reach for command rather than matching on
msg.text() here — see Commands below.)
For everything beyond messages, on_event delivers the
full stream as a BotEvent you match on: Message, Reaction, Edit, Delete
(saying who, and whether a moderator did it), MemberJoin, MemberLeave, Typing,
CommunityChange (one per change to Roles, Channels, bans, Timeouts…, with who made it),
Invite, Removed (the bot was kicked or banned) and Dissolved:
bot.on_event(|bot, event| async move {
match event {
BotEvent::Message(msg) if !msg.is_mine() => { let _ = msg.reply("hi").await; }
BotEvent::MemberJoin { channel_id, npub, .. } => {
let _ = bot.channel(channel_id).send(&format!("welcome {}!", &npub[..12])).await;
}
_ => {}
}
}).await?;§Commands
Don’t parse msg.text() by hand. Declare a command instead: give it a name, a
description, and typed arguments, and the SDK publishes a machine-readable manifest for
it. Every Vector client then renders a / picker listing your command, and offers a
typed field per argument — a dropdown for a choice, a member
picker for a user, a number field for an int
— and validates the input before the invocation is ever sent. Your handler receives the
arguments already parsed and type-checked.
bot.command("weather", "Current conditions for a city")
.string("city", "Which city", true) // required free text
.choice("units", "Temperature units", ["c", "f"], false) // optional dropdown
.run(|ctx| async move {
let city = ctx.str("city").unwrap_or_default();
let units = ctx.str("units").unwrap_or("c");
let _ = ctx.reply(format!("Weather in {city} in °{}…", units.to_uppercase())).await;
});Argument types: string, int,
number, flag (bool),
user (an npub), and choice. Read them
back off the CommandCtx with ctx.str/int/number/flag(name). A matched command runs its
handler and never reaches on_message, so commands and free-form
chat coexist; the manifest publishes automatically once the bot starts listening. See the
slash_command_bot
example for a full bot.
§Communities
When a message comes from a community, you get the sender as a member you can act on directly:
if let Some(member) = msg.member() { // the sender, as a Member of this community
if !member.is_admin() {
member.ban().await?; // or .kick() / .unban() / .grant_admin()
}
}§Public vs private bots
A bot must accept invites to be useful in communities, but a private bot mustn’t be spammable into random ones. Set the policy on the builder:
VectorBot::builder().nsec("nsec1...").public().build().await?; // accept from anyone
VectorBot::builder().nsec("nsec1...").whitelist(["npub1owner…"]).build().await?; // only these accountsAuto-accept fires for live invites and for ones received while the bot was
offline (swept on the next connect), so a restarted bot still joins what it
was invited to. The default is InvitePolicy::Manual — see
pending_invites / accept_invite.
§Staying connected
If the bot loses its connection, on_message /
on_event reconnect on their own and catch up on what was
missed. Your handler fires for messages that arrive while the
bot is running; to read older history, use Channel::history and
Channel::sync_before. VectorBotBuilder::catch_up chooses whether the bot
catches up before going live or pages the gap itself.
§Identity: bring your own, or let the bot make one
Supply a key with nsec / mnemonic —
or supply nothing, and build creates an identity on first run and
persists it (identity.nsec) in the bot’s data directory, reusing the same one every run after.
So a first bot needs zero setup:
let bot = VectorBot::builder().build().await?; // first run mints + stores an nsec; reused after
println!("online as {}", bot.npub());It never mints a fresh key per run — the identity is stable, so the bot keeps its DMs and
community memberships across restarts. Running several keyless bots? Give each its own
data_dir so they get distinct identities.
§Single identity per process
vector_core is built on process-global state, so one VectorBot owns
the process’s identity at a time. Build one bot per process. (Multiple
identities means multiple processes — or VectorCore::swap_session to
switch the active account in place.)
§Reaching deeper
VectorBot::core hands you the VectorCore engine underneath. A bot that needs it,
or one built by copying code out of Vector’s app, has found something the SDK is missing:
the guide Moving your bot onto the SDK
maps those internals onto SDK calls.
§Examples
Runnable bots live in examples/:
echo_bot: the minimal hello-world; replies to every message.slash_command_bot: a/commandrouter (/ping,/roll,/help…).ai_bot: an LLM chatbot with a typing indicator and threaded replies.community_admin_bot: Roles, a private category channel,/timeout,/role,/pin,/audit.moderation_bot: welcomes joiners and auto-bans on a word filter.whitelist_bot: a private bot that only joins communities it trusts.file_bot/save_files_bot: send a file / receive and decrypt one.xdc_tictactoe_bot/xdc_oracle_bot: play a shared Mini App live / be the server behind one (featurexdc).voice_whisper_bot: a voice assistant: writes down what’s said in a call and answers out loud (featurewhisper).voice_echo_bot/voice_radio_bot: says back what you say / plays a track in many calls (featurevoice).
VECTOR_NSEC=nsec1... cargo run -p vector-sdk --example echo_botRe-exports§
pub use voice::Speech;pub use voice::VoiceCall;pub use xdc::JoinWhen;pub use xdc::Xdc;pub use xdc::XdcAppBuilder;pub use xdc::XdcMatch;pub use xdc::XdcSender;pub use xdc::XdcSession;pub use vector_core;
Modules§
- net
- HTTP through the bot’s own transport: over Tor or I2P when the bot is, refused rather than sent direct when that network is down. Use it for any request a bot makes (an LLM, an API), or the request leaks the bot’s address around the network it chose.
- nostr
- Re-exported Nostr primitives, so downstreams can depend only on
vector_sdk. - policy
- Policies, for bots.
- voice
- Voice Channels: hear what members say and speak into the call. A bot may be in as many
calls at once as it likes, each its own
VoiceCall. - xdc
- Mini Apps (WebXDC): let a bot join the games and tools people share.
Structs§
- Attachment
- Attachment
File - Pre-upload file data.
- Audit
Entry - One act in a Community’s Audit Log.
- Audit
Log - A Community’s Audit Log, newest first.
- Category
- A handle to one Category. Obtained from
Community::categoryorCommunity::create_category. - Category
Info - A Category as a change reports it.
- Channel
- A unified handle for a chat or channel — a DM and a Community channel behave the same. Every
method routes to the right transport under the hood, so a bot author never branches on DM-vs-
channel. Obtained from
VectorBot::channel/dm/community, orIncomingMessage::channel. - Channel
Info - A Channel as a change reports it.
- Command
Builder - Builder returned by
VectorBot::command; finish withrun. - Command
Ctx - Everything a command handler needs: the triggering message, the typed arguments, and the bot.
- Community
- A handle to a Community for management — members, invites, roles, metadata. Obtained from
VectorBot::community,VectorBot::communities, orIncomingMessage::community. To message a channel within it, use aChannel(bot.channel(channel_id)). - Community
Change - One change to a Community, who made it and when.
- Community
Channel - One channel of a Community, as
Community::channelsreports it. - Containment
Report - What a
Community::contain_raidcall actually accomplished. What a containment actually accomplished. Every field is an honest count — a caller (Sentinel, a moderation console) reports these to a human, so a half-done containment must never read as a closed door. - Core
Config - Configuration for initializing VectorCore.
- Cursor
- A durable position in a channel’s history, for paging and for building your
own sync mechanism on top of
Channel::history_before/Channel::sync_before. - Delete
Outcome - Outcome of a delete-own-* operation.
- Edit
Entry - Emoji
Pack - Custom emoji packs (NIP-30 / NIP-51) and the emoji a send can tag.
- I2pOptions
- How a bot reaches I2P: the router it uses and what it may reach outside I2P. Requires the
i2pfeature. - Image
Metadata - Incoming
Message - An inbound message delivered to an
VectorBot::on_messagehandler. The same handler receives both DMs and Community channel messages — usereply/channelto respond uniformly without caring which it is. - Invite
Link - A minted public-invite link the owner retains (to list + revoke).
- Link
Preview - What a public invite link shows before joining.
- Login
Result - Manifest
- Member
- A handle to a member of a community — act on them directly. Obtained from
Community::memberorIncomingMessage::member. - Message
- NewChannel
- How a new Channel starts. The default is a public chat Channel at the top level.
- NewCommunity
- How a new Community starts. The default is one
#generalChannel on the active relays. - NoOp
Event Handler - No-op handler for CLI/tests.
- Overwrite
- Bits allowed and denied in one Channel or Category, for everyone, one Role or one member, on top of what they hold server-wide. No bits removes the overwrite.
- Pack
Emoji - Custom emoji packs (NIP-30 / NIP-51) and the emoji a send can tag.
- Permissions
- Management/moderation permission bits. Access (read/post a channel) is NOT here — that is key possession (the two-mechanism split). Bit positions are part of the wire format and are FROZEN: append a reserved bit, never renumber or reuse one.
- Pin
- A pinned message.
- Post
Options - How a post goes out. The default is a plain post, with pictures compressed.
- Reaction
- Relay
Check - One new relay, as the check before a move found it.
- Relay
Move - Role
- A handle to one Role of a Community. Obtained from
Community::roleorCommunity::create_role. - Role
Info - A role: its own addressable RoleMetadata event (vsk=1). Fully general; the MVP
auto-creates exactly one (
Role::admin). - Role
Spec - What a Role is made or edited to be. Fields left unset keep what the Role has.
- Send
Result - Result of sending a message.
- Sendable
Emoji - Custom emoji packs (NIP-30 / NIP-51) and the emoji a send can tag.
One custom emoji this account can send: type
:code:and the send tags it. - Serializable
Chat - Site
Metadata - Slim
Profile - Profile with npub string instead of interner handle. Used for:
- Status
- Vector
Bot - A logged-in Vector bot: an identity connected to relays, ready to send and
receive. Cheap to
Clone— clones share the same underlying session. - Vector
BotBuilder - Builder for a
VectorBot. Created viaVectorBot::builder. - Vector
Core - The main entry point for Vector Core.
- XdcFrame
- One frame an app (or another bot) sent on the channel.
- XdcPeer
- A peer on the mesh.
npubis the account whose advertisement first named this node in this chat;Noneuntil one has, or once two accounts have claimed the same node.
Enums§
- Audit
Action - What an Audit Log entry records.
- Audit
Target - What an act was done to.
- BotEvent
- Every kind of inbound event a bot can observe. Delivered to
VectorBot::on_event. DMs and Community channels are unified:chat_idis the sender’s npub for a DM, the channel id for a Community message. - CatchUp
- Who fetches what was published while a
listenclient was offline. - Change
Kind - What changed. Members are npubs, every other id is lowercase hex.
- Channel
Kind - Whether a
Channeltargets a direct message or a Community channel. - Error
- Alias for the SDK’s error type. Unified error type for all vector-core operations.
- Invite
Policy - How a bot handles inbound Community invites (gift-wrapped invite bundles). Set on the builder
with
public/whitelist/invite_policy. - Overwrite
Target - Who an overwrite applies to:
Everyone, aRole(id)or aMember(npub). Who an overwrite applies to. - Role
Scope - Discord’s “any channel” vs “this channel”. Server-scope acts everywhere; channel-scope is rejected against any other channel.
- Sync
Priority - Priority levels for profile syncing, most urgent first (
Critical < Low). - Vector
Error - Unified error type for all vector-core operations.
- XdcEvent
Constants§
- DISCOVERY_
RELAYS - Public relays that index addressable/replaceable events network-wide — the reliable discovery path for a bot’s manifest (and profile). One list shared with the reader side (clients query these beside a chat’s own relays), so publish reach and lookup reach can’t drift apart. Public relays that index replaceable events network-wide — the reliable discovery path for bot manifests. Read side: always queried ALONGSIDE a chat’s own relays, so a manifest resolves even when a community relay is unreachable or drops stranger events (Ditto does). Write side: the SDK publishes every bot’s manifest here for the same reason.
Traits§
- Event
Emitter - Emits events to the UI layer (Tauri frontend, CLI output, SDK callbacks).
- Inbound
Event Handler - Platform-specific callbacks for inbound event processing.
Type Aliases§
- Result
- Convenience alias used throughout vector-core (matches src-tauri’s
Result<T, String>pattern).