teloxide/README.md
2020-07-26 04:24:38 +06:00

13 KiB

teloxide

A full-featured framework that empowers you to easily build Telegram bots using the async/.await syntax in Rust. It handles all the difficult stuff so you can focus only on your business logic.

Table of contents

Features

  • Functioal reactive design. teloxide has functional reactive design, allowing you to declaratively manipulate streams of updates from Telegram using filters, maps, folds, zips, and a lot of other adaptors.
  • Persistence. Dialogues management is independent of how/where dialogues are stored: you can just replace one line and make them persistent. Out-of-the-box storages include Redis.
  • Strongly typed bot commands. You can describe bot commands as enumerations, and then they'll be automatically constructed from strings. Just like you describe JSON structures in serde-json and command-line arguments in structopt.

Setting up your environment

  1. Download Rust.
  2. Create a new bot using @Botfather to get a token in the format 123456789:blablabla.
  3. Initialise the TELOXIDE_TOKEN environmental variable to your token:
# Unix-like
$ export TELOXIDE_TOKEN=<Your token here>

# Windows
$ set TELOXIDE_TOKEN=<Your token here>
  1. Be sure that you are up to date:
# If you're using stable
$ rustup update stable
$ rustup override set stable

# If you're using nightly
$ rustup update nightly
$ rustup override set nightly
  1. Execute cargo new my_bot, enter the directory and put these lines into your Cargo.toml:
[dependencies]
teloxide = "0.2.0"
log = "0.4.8"
tokio = "0.2.11"
pretty_env_logger = "0.4.0"

API overview

The ping-pong bot

This bot has a single message handler, which answers "pong" to each incoming message:

(Full)

use teloxide::prelude::*;

#[tokio::main]
async fn main() {
    teloxide::enable_logging!();
    log::info!("Starting ping_pong_bot...");

    let bot = Bot::from_env();

    Dispatcher::new(bot)
        .messages_handler(|rx: DispatcherHandlerRx<Message>| {
            rx.for_each(|message| async move {
                message.answer("pong").send().await.log_on_error().await;
            })
        })
        .dispatch()
        .await;
}

Commands

Commands are strongly typed and defined declaratively, similar to how we define CLI using structopt and JSON structures in serde-json. The following bot accepts these commands:

  • /username <your username>
  • /usernameandage <your username> <your age>
  • /help

(Full)

// Imports are omitted...

#[derive(BotCommand)]
#[command(rename = "lowercase", description = "These commands are supported:")]
enum Command {
    #[command(description = "display this text.")]
    Help,
    #[command(description = "handle a username.")]
    Username(String),
    #[command(
        description = "handle a username and an age.",
        parse_with = "split"
    )]
    UsernameAndAge { username: String, age: u8 },
}

async fn answer(
    cx: UpdateWithCx<Message>,
    command: Command,
) -> ResponseResult<()> {
    match command {
        Command::Help => cx.answer(Command::descriptions()).send().await?,
        Command::Username(username) => {
            cx.answer_str(format!("Your username is @{}.", username)).await?
        }
        Command::UsernameAndAge { username, age } => {
            cx.answer_str(format!(
                "Your username is @{} and age is {}.",
                username, age
            ))
            .await?
        }
    };

    Ok(())
}

async fn handle_commands(rx: DispatcherHandlerRx<Message>) {
    rx.commands::<Command, &str>(panic!("Insert here your bot's name"))
        .for_each_concurrent(None, |(cx, command)| async move {
            answer(cx, command).await.log_on_error().await;
        })
        .await;
}

#[tokio::main]
async fn main() {
    // Setup is omitted...
}

Dialogues

A dialogue is described by an enumeration, where each variant is one of possible dialogue's states. There are also transition functions, which turn a dialogue from one state to another, thereby forming an FSM.

Below is a bot, which asks you three questions and then sends the answers back to you. Here's possible states for a dialogue:

(dialogue_bot/src/states.rs)

// Imports are omitted...

#[derive(Transition, SmartDefault, From)]
pub enum Dialogue {
    #[default]
    Start(StartState),
    ReceiveFullName(ReceiveFullNameState),
    ReceiveAge(ReceiveAgeState),
    ReceiveLocation(ReceiveLocationState),
}

#[derive(Default)]
pub struct StartState;

#[derive(Generic)]
pub struct ReceiveFullNameState;

#[derive(Generic)]
pub struct ReceiveAgeState {
    pub full_name: String,
}

#[derive(Generic)]
pub struct ReceiveLocationState {
    pub full_name: String,
    pub age: u8,
}

... and here are the transition functions, which turn one state into another:

(dialogue_bot/src/transitions.rs)

// Imports are omitted...

pub type Out = TransitionOut<Dialogue>;

#[teloxide(transition)]
async fn start(_state: StartState, cx: TransitionIn) -> Out {
    cx.answer_str("Let's start! What's your full name?").await?;
    next(ReceiveFullNameState)
}

#[teloxide(transition)]
async fn receive_full_name(
    state: ReceiveFullNameState,
    cx: TransitionIn,
) -> Out {
    match cx.update.text_owned() {
        Some(ans) => {
            cx.answer_str("How old are you?").await?;
            next(ReceiveAgeState::up(state, ans))
        }
        _ => {
            cx.answer_str("Send me a text message.").await?;
            next(state)
        }
    }
}

#[teloxide(transition)]
async fn receive_age_state(state: ReceiveAgeState, cx: TransitionIn) -> Out {
    match cx.update.text().map(str::parse::<u8>) {
        Some(Ok(ans)) => {
            cx.answer_str("What's your location?").await?;
            next(ReceiveLocationState::up(state, ans))
        }
        _ => {
            cx.answer_str("Send me a number.").await?;
            next(state)
        }
    }
}

#[teloxide(transition)]
async fn receive_location(
    state: ReceiveLocationState,
    cx: TransitionIn,
) -> Out {
    match cx.update.text() {
        Some(ans) => {
            cx.answer_str(format!(
                "Full name: {}\nAge: {}\nLocation: {}",
                state.full_name, state.age, ans
            ))
            .await?;
            exit()
        }
        _ => {
            cx.answer_str("Send me a text message.").await?;
            next(state)
        }
    }
}

Finally, the main function looks like this:

(dialogue_bot/src/main.rs)

// Imports are omitted...

#[tokio::main]
async fn main() {
    teloxide::enable_logging!();
    log::info!("Starting dialogue_bot...");

    let bot = Bot::from_env();

    Dispatcher::new(bot)
        .messages_handler(DialogueDispatcher::new(
            |input: DialogueWithCx<Message, Dialogue, Infallible>| async move {
                // Unwrap without panic because of std::convert::Infallible.
                input
                    .dialogue
                    .unwrap()
                    .react(input.cx)
                    .await
                    .expect("Something wrong with the bot!")
            },
        ))
        .dispatch()
        .await;
}

More examples!

Recommendations

  • Use this pattern:
#[tokio::main]
async fn main() {
    run().await;
}

async fn run() {
    // Your logic here...
}

Instead of this:

#[tokio::main]
async fn main() {
    // Your logic here...
}

The second one produces very strange compiler messages because of the #[tokio::main] macro. However, the examples in this README use the second variant for brevity.

FAQ

Q: Where I can ask questions?

A: Issues is a good place for well-formed questions, for example, about the library design, enhancements, bug reports. But if you can't compile your bot due to compilation errors and need quick help, feel free to ask in our official group.

Q: Why Rust?

A: Most programming languages have their own implementations of Telegram bots frameworks, so why not Rust? We think Rust provides enough good ecosystem and the language itself to be suitable for writing bots.

Q: Can I use webhooks?

A: teloxide doesn't provide special API for working with webhooks due to their nature with lots of subtle settings. Instead, you setup your webhook by yourself, as shown in examples/ngrok_ping_pong_bot and examples/heroku_ping_pong_bot.

Associated links:

Q: Can I use different loggers?

A: Yes. The enable_logging! and enable_logging_with_filter! macros are just convenient utilities, not necessary to use them. You can setup a different logger, for example, fern, as usual, e.g. teloxide has no specific requirements as it depends only on log.

Community bots

Feel free to push your own bot into our collection!

Contributing

See CONRIBUTING.md.