Skip to main content

Crate teloxide

Crate teloxide 

Source
Expand description

A full-featured framework that empowers you to easily build Telegram bots using Rust. It handles all the difficult stuff so you can focus only on your business logic. Currently, version 10.5 of Telegram Bot API is supported.

For a high-level overview, see our GitHub repository. Requires Rust 1.94 or newer.

[examples/throw_dice.rs]

use teloxide::prelude::*;

pretty_env_logger::init();
log::info!("Starting throw dice bot...");

let bot = Bot::from_env();

teloxide::repl(bot, |bot: Bot, msg: Message| async move {
    bot.send_dice(msg.chat.id).await?;
    Ok(())
})
.await;

§Working with Updates and Messages

There is a great number of update kinds and message kinds to work with! Usually it’s essential to filter specific ones and process them in handler functions. Teloxide provides some filter methods for Update and Message types in UpdateFilterExt and MessageFilterExt traits respectively. In addition to filtering, these methods will inject the appropriate type into your handler functions. For instance, if you use Update::filter_message, the instance of the Message will be available as a parameter for your handler functions. Similarly the use of Message::filter_text will inject a String into the context.

Moreover, filter_map function can inject some dependencies according to the schema flow. More in the example below!

Here is a quick example (filter text message and inject it’s text into the handler function):

use teloxide::{prelude::*, types::User};

pub type Error = Box<dyn std::error::Error + Send + Sync>;

#[tokio::main]
async fn main() -> Result<(), Error> {
    let bot = Bot::from_env();
    let schema = Update::filter_message()
        /*
           Inject the `User` object representing the author of an incoming
           message into every successive handler function (1)
        */
        .filter_map(|update: Update| update.from().cloned())
        .branch(
            /*
               Use filter_text method of MessageFilterExt to accept
               only textual messages. Others will be ignored by this handler (2)
            */
            Message::filter_text().endpoint(process_text_message),
        );

    Dispatcher::builder(bot, schema).build().dispatch().await;
    Ok(())
}

/// Replies to the user's text messages
async fn process_text_message(bot: Bot, user: User, message_text: String) -> Result<(), Error> {
    /*
       The id of a chat with a user is the same as his telegram_id
       from the bot's perspective.

       Injected dependencies:
       - Bot is provided by the Dispatcher::dispatch
       - User is provided by the (1)
       - String is provided by the (2)
    */
    let _ = bot.send_message(format!("Hi! You sent: {message_text}")).chat_id(user.id).await?;
    Ok(())
}

For more info about dptree, please check out this guide on it!

To consume updates directly without a dispatcher, see update_stream.

§Cargo features

FeatureDescription
webhooksEnables general webhook utilities (almost useless on its own).
webhooks-axumEnables webhook implementation based on axum framework.
macrosRe-exports macros from teloxide-macros.
ctrlc_handlerEnables the DispatcherBuilder::enable_ctrlc_handler function (enabled by default).
throttleEnables the Throttle bot adaptor.
cache-meEnables the CacheMe bot adaptor.
trace-adaptorEnables the Trace bot adaptor.
erasedEnables the ErasedRequester bot adaptor.
fullEnables webhooks, webhooks-axum, sqlite-storage-nativetls, redis-storage, postgres-storage-nativetls, cbor-serializer, bincode-serializer, macros, ctrlc_handler, teloxide-core/full, native-tls, rustls, throttle, cache-me, trace-adaptor, erased, and tracing. It does not enable the SQL storage -rustls variants, rustls-native-roots, or nightly.
nightlyEnables nightly-only features (see the teloxide-core features).
native-tlsEnables the native-tls TLS implementation (enabled by default).
rustlsEnables the rustls TLS implementation.
rustls-native-rootsEnables rustls with native certificate roots for the bot HTTP client.
tracingEnables tracing support for update handlers.
redis-storageEnables the Redis storage support for dialogues.
sqlite-storage-nativetlsEnables the Sqlite storage support for dialogues (depends on native-tls).
sqlite-storage-rustlsEnables the Sqlite storage support for dialogues (depends on rustls).
postgres-storage-nativetlsEnables PostgreSQL storage for dialogues (depends on native-tls).
postgres-storage-rustlsEnables PostgreSQL storage for dialogues (depends on rustls).
cbor-serializerEnables the CBOR serializer for dialogues.
bincode-serializerEnables the Bincode serializer for dialogues.

Re-exports§

pub use repls::repl;ctrlc_handler
pub use repls::repl_with_listener;ctrlc_handler
pub use dispatching::filter_command;
pub use dispatching::filter_mention_command;
pub use teloxide_macros as macros;macros
pub use dptree;

Modules§

adaptors
Wrappers altering functionality of a bot.
backoff
dispatching
An update dispatching model based on dptree.
error_handlers
Convenient error handling.
errors
Possible error types.
net
Network-specific API.
payloads
Request data sent to Telegram.
prelude
Commonly used items.
replsctrlc_handler
REPLs for dispatching updates.
requests
Telegram API requests.
stop
Stopping asynchronous tasks, e.g., listeners.
sugar
Some syntax sugar support for TBA functionality.
types
Telegram API types.
update_listeners
Receiving updates from Telegram.
update_stream
Receive Telegram updates as a futures::Stream without a dispatcher.
utils
Some useful utilities.

Macros§

handler
Filters by a pattern, passing its payload forwards.

Structs§

Bot
A requests sender.

Enums§

ApiError
A kind of an API error.
DownloadError
An error caused by downloading a file.
RequestError
An error caused by sending a request to Telegram.

Functions§

respond
A shortcut for ResponseResult::Ok(val).