# Your first bot

<!-- A working bot from an empty project: log in with a token, answer /start, add a second command. -->

A bot logs in with the token @BotFather gives you. This page builds one that answers `/start`, replies to it,
and has a second command.

## Example

```bash
cargo new my_bot && cd my_bot
cargo add vaegram --git https://github.com/rjriajul/vaegram --branch nightly
cargo add tokio --features macros,rt-multi-thread
```

Put this in `src/main.rs`, set the three variables, and run it:

```no_run
use vaegram::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    let api_id = std::env::var("VAEGRAM_API_ID").expect("set VAEGRAM_API_ID");
    let api_hash = std::env::var("VAEGRAM_API_HASH").expect("set VAEGRAM_API_HASH");
    let token = std::env::var("VAEGRAM_BOT_TOKEN").expect("set VAEGRAM_BOT_TOKEN");

    let app = Client::builder("my_bot", api_id.parse().expect("api_id is a number"), api_hash)
        .bot_token(token)
        .start()
        .await?;

    app.on_message(filters::command("start"), |msg| async move {
        let name = msg.from_user.as_ref().map_or("there", |u| u.first_name.as_str());
        msg.reply(format!("Hi {name}! Send /help for the commands.")).await?;
        Ok(())
    });

    app.run().await
}
```

Send `/start` to the bot and it answers. The first run writes `my_bot.session`; later runs log in from it.

## How it works

`Client::builder(name, api_id, api_hash)` holds the settings and connects nothing. `.bot_token(token)` says who
the client is. `.start()` opens the connection and logs in: with a token it never asks anything, and without a
saved login it signs in as the bot straight away.

`app.on_message(filter, handler)` registers a handler for new messages that pass `filter`. Filters are values you
combine with `&` (both), `|` (either) and `!` (not); `filters::command("start")` matches `/start` and
`/start@YourBot` in any chat. The handler receives the `Message`, returns a future, and ends with a `Result`:
`Ok(())` on success, or the error from a call that failed. A handler's `Err` goes to `Client::on_error`; with no
error handler registered, it arrives as `ClientEvent::HandlerFailed`.

`app.run()` is the loop. It takes updates from Telegram and runs the handlers until `Client::stop`, then returns:
no handler fires until it is awaited, so register handlers before it.

## Replying

Inside a handler, `msg.answer(text)` sends a text message to the same chat, and `msg.reply(text)` does the same
with a quote of the message being handled. Both return the sent `Message` when awaited, so you can edit or delete
it later:

```no_run
# use vaegram::prelude::*;
# async fn demo(msg: Message) -> Result<()> {
let sent = msg.reply("Got it").await?;
println!("sent message {}", sent.id);
# Ok(()) }
```

Both send plain text by default: the client's parse mode starts off, so `**bold**` arrives with the asterisks.
`.html()` and `.markdown()` on the returned request turn parsing on for that one message, and
`Text::from_html("..")` builds formatting without a parse mode.

## A second command

Handlers are independent; add another one for each command. This one answers `/help` with a bold first line:

```no_run
# use vaegram::prelude::*;
# fn register(app: &Client) {
app.on_message(filters::command("help"), |msg| async move {
    let list = Text::new().bold("Commands").plain("\n/start - say hello\n/help - this list");
    msg.answer(list).await?;
    Ok(())
});
# }
```

`filters::command` takes one name or a list: `filters::command(["start", "help"])`. Two handlers in the same
group do not both run: the first one whose filter matches handles the update. `.group(n)` puts a handler in a
later group, and every group gets its turn, so a group 1 handler still runs after a group 0 match.

## Common mistakes

- No updates arrive because the bot ran on the cloud Bot API before. Call `logOut` there once; until then
  Telegram keeps sending the bot's updates to the Bot API, and an MTProto login gets none.
- Two copies of the program on the same session file. The second one fails with `ResourceBusy`: give each its own
  name, or one process.
- Registering handlers after `run`, or never awaiting it. `.start()` alone only logs in, so no handler runs.
- Putting the token in the source. Read it from the environment, and keep the `.session` file out of git too.
- Assuming a parse mode. Formatting sent as a plain string stays literal; use `.html()`, `.markdown()` or `Text`.

## See also

- [API docs](https://docs.rs/vaegram/latest/vaegram/client/struct.Client.html) for `Client` and its methods.
- [Receiving updates](/docs/receiving-updates.md) for `run`, update state and catching up after a restart.
- [Filters](/docs/filters.md) and [Commands](/docs/commands.md) for picking updates.
- [Your first user account](/docs/first-user-account.md) when the login is a phone number instead.