# Ping bot with zaun-client

> An external bot in Rust and JavaScript that joins with an invite and answers text commands.

A bot that joins a community like any member and answers text commands. It runs anywhere, not in the
host; see [External bots](/docs/guide/bots/external-bots/) for when to choose this over a hosted bot.

Source: [`zaun/examples`](https://github.com/zaunchat/zaun-client/tree/main/zaun/examples) in zaun-client.

**JavaScript:**

```js title="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

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
}
```

```sh
ZAUN_KEY='store passphrase' ZAUN_INVITE='zaun://join/…' node examples/ping_bot.mjs
```

**Rust:**

```rust title="ping_bot.rs"
//! A bot that joins a Zaun community and answers `!ping`, `!members`, `!can` and `!kick`.
//!
//! ```sh
//! ZAUN_BOT_KEY='store passphrase' cargo run -p zaun-client --example ping_bot -- ./bot 'zaun://join/…'
//! ```
//!
//! The invitation is needed only the first time; later runs reconnect from `./bot`.

use zaun_client::protocol::bits::Permissions;
use zaun_client::{Client, Event, Message};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut args = std::env::args().skip(1);
    let dir = args.next().ok_or("usage: ping_bot DIR [INVITE_LINK]")?;
    let key = std::env::var("ZAUN_BOT_KEY").map_err(|_| "set ZAUN_BOT_KEY")?;
    let client = Client::builder(&dir).name("Ping bot").key(key).start()?;
    if let Some(link) = args.next() {
        let community = client.join(&link, "Ping bot")?;
        println!("joined {community}");
    }
    for event in client.events() {
        match event {
            Event::Ready(community) => {
                println!(
                    "ready in {community} ({} channels)",
                    community.channels().len()
                );
            }
            Event::MessageCreate(message) if !message.is_mine() => {
                if let Err(e) = answer(&message) {
                    eprintln!("could not answer: {e}");
                }
            }
            Event::MemberAdd(member) => {
                println!("{member} joined {}", member.community());
            }
            Event::CommunityDelete { community, reason } => {
                println!("removed from {}: {reason:?}", community.id().to_b64());
            }
            _ => {}
        }
    }
    Ok(())
}

fn answer(message: &Message) -> zaun_client::Result<()> {
    let author = message.author();
    match message.content().trim() {
        "!ping" => {
            message.reply("pong")?;
        }
        "!members" => {
            let members = message.community().fetch_members()?;
            message
                .channel()
                .send(format!("{} members", members.len()))?;
        }
        "!can" => {
            let ok = author.can(Permissions::SEND_MESSAGES, Some(message.channel()));
            message.reply(format!(
                "you {} post here",
                if ok { "can" } else { "cannot" }
            ))?;
        }
        text if text.starts_with("!kick ") => {
            let name = text.trim_start_matches("!kick ").trim();
            if !author.can(Permissions::KICK_MEMBERS, None) {
                message.reply("you cannot kick")?;
            } else if let Some(target) =
                (message.community().members().into_iter()).find(|m| m.display_name() == name)
            {
                target.kick(Some("asked to"))?;
                message.react("👋")?;
            }
        }
        _ => {}
    }
    Ok(())
}
```

```sh
ZAUN_BOT_KEY='store passphrase' cargo run -p zaun-client --example ping_bot -- ./bot 'zaun://join/…'
```

## How it works

- 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`).
