Connecting and joining
-
Start a client. A client keeps its keys and state in a store sealed with a passphrase.
import fs from "node:fs";import { Client } from "zaun-client";const file = "bot.snapshot";const snapshot = fs.existsSync(file) ? fs.readFileSync(file) : undefined;const client = await Client.start({ name: "Ping bot", key: process.env.ZAUN_KEY, snapshot });client.on("change", () => fs.writeFileSync(file, client.save())); // keep the storeuse zaun_client::Client;// Keys and state live under ./bot/zaun/ (key files mode 0600).let client = Client::builder("./bot").name("Ping bot").key("store passphrase").start()?;Without relays named, the official SimpleX servers are used. Name your own with
.relay("smp://…")(Rust) orrelays: ["smp://…"](JavaScript). -
Join a community with an invite link, only the first time. Later runs reconnect from the saved state.
if (client.saved.size === 0) {await client.join(process.env.ZAUN_INVITE, "Ping bot"); // the link is a secret: never log it}let community = client.join("zaun://join/…", "Ping bot")?;println!("joined {community}");Joining opens a post-quantum SimpleX connection to the host, checks the host’s signed proof that it serves the community, makes your member key and registers it, then loads the community into the local cache.
-
Handle events.
client.on("ready", (community) => console.log(`ready in ${community.name}`));client.on("messageCreate", async (message) => {if (message.mine) return;if (message.content === "!ping") await message.reply("pong");});use zaun_client::Event;for event in client.events() {match event {Event::Ready(community) => println!("ready in {community}"),Event::MessageCreate(message) if !message.is_mine() => {if message.content() == "!ping" {message.reply("pong")?;}}_ => {}}}
Resulting code
Section titled “Resulting code”See the complete ping bot example, in Rust and JavaScript.
Creating a community instead
Section titled “Creating a community instead”An owner creates a community on a host that allows it (see First run):
client.create_community(address, host_key, name, display_name) in Rust,
client.createCommunity({ host, hostKey, name, displayName }) in JavaScript. The community’s root
key is saved in the client’s store: back it up.