Skip to content

Ping bot with zaun-client

A bot that joins a community like any member and answers text commands. It runs anywhere, not in the host; see External bots for when to choose this over a hosted bot.

Source: zaun/examples in zaun-client.

ping_bot.mjs
// A ping bot over the JS build: joins with an invitation once, answers `!ping`, and keeps
// its state in one sealed file between runs. Build the package first
// (scripts/build-zaun-js.sh).
//
// ZAUN_KEY='store passphrase' ZAUN_INVITE='zaun://join/…' node examples/ping_bot.mjs
import fs from "node:fs";
import { Client } from "zaun-client";
const file = "ping-bot.snapshot";
const key = process.env.ZAUN_KEY;
if (!key) throw new Error("set ZAUN_KEY to the store passphrase");
const snapshot = fs.existsSync(file) ? fs.readFileSync(file) : undefined;
// `relays: ["smp://…"]` picks the SimpleX servers; without it the official ones are used.
const client = await Client.start({ name: "Ping bot", key, snapshot });
client.on("change", () => fs.writeFileSync(file, client.save())); // keep the store
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");
if (message.content === "!who") {
await message.channel.send(`${message.author.displayName}, you are in ${message.community.name}`);
}
});
if (client.saved.size === 0 && process.env.ZAUN_INVITE) {
await client.join(process.env.ZAUN_INVITE, "Ping bot"); // the link is a secret: never log it
}
Terminal window
ZAUN_KEY='store passphrase' ZAUN_INVITE='zaun://join/…' node examples/ping_bot.mjs
  • The invite is needed only the first time; later runs reconnect from the saved store (./bot in Rust, the snapshot file in JavaScript).
  • !ping replies, !members fetches the member list, !can checks a permission locally, and !kick (Rust) kicks by display name if the author may.
  • It ignores its own messages (is_mine() / message.mine).