# Connecting and joining

> Start a client, join a community with an invite, keep its state between runs, and handle your first events.

1. **Start a client.** A client keeps its keys and state in a store sealed with a passphrase.

   **JavaScript:**

   ```js
   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 store
   ```

   **Rust:**

   ```rust
   use 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) or `relays: ["smp://…"]` (JavaScript).

2. **Join a community** with an invite link, **only the first time**. Later runs reconnect from
   the saved state.

   **JavaScript:**

   ```js
   if (client.saved.size === 0) {
     await client.join(process.env.ZAUN_INVITE, "Ping bot"); // the link is a secret: never log it
   }
   ```

   **Rust:**

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

3. **Handle events.**

   **JavaScript:**

   ```js
   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");
   });
   ```

   **Rust:**

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

See the complete [ping bot example](/docs/examples/client-ping-bot/), in Rust and JavaScript.

## Creating a community instead

An owner creates a community on a host that allows it (see [First run](/docs/guide/host/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.
