Expand description
§tgbotrs
A fully-featured, auto-generated Telegram Bot API library for Rust.
All 285 types and 165 methods from Telegram Bot API Strongly typed, fully async, automatically kept in sync with every official release.
§Quick Start
use tgbotrs::Bot;
#[tokio::main]
async fn main() {
let bot = Bot::new("YOUR_BOT_TOKEN").await.unwrap();
println!("Running as @{}", bot.me.username.as_deref().unwrap_or("unknown"));
let msg = bot.send_message(123456789i64, "Hello from tgbotrs! 🦀", None).await.unwrap();
println!("Sent: #{}", msg.message_id);
}§Echo Bot with Long Polling
use tgbotrs::{Bot, Poller, UpdateHandler};
#[tokio::main]
async fn main() {
let bot = Bot::new("YOUR_TOKEN").await.unwrap();
let handler: UpdateHandler = Box::new(|bot, update| {
Box::pin(async move {
let Some(msg) = update.message else { return };
let Some(text) = msg.get_text().map(str::to_owned) else { return };
let _ = msg.reply(&bot, text, None).await;
})
});
Poller::new(bot, handler).timeout(30).start().await.unwrap();
}§Dispatcher + Updater (recommended for non-trivial bots)
use tgbotrs::{Bot, CommandHandler, Dispatcher, DispatcherOpts, Updater};
use tgbotrs::framework::{HandlerResult, Context};
async fn start(bot: tgbotrs::Bot, ctx: Context) -> HandlerResult {
if let Some(msg) = ctx.effective_message() {
msg.reply(&bot, "Hello! 👋", None).await?;
}
Ok(())
}
#[tokio::main]
async fn main() {
let bot = Bot::new("YOUR_TOKEN").await.unwrap();
let mut dp = Dispatcher::new(DispatcherOpts::default());
dp.add_handler(CommandHandler::new("start", start));
Updater::new(bot, dp).start_polling().await.unwrap();
}§Webhook Server
Enable the webhook feature in Cargo.toml:
tgbotrs = { version = "0.2", features = ["webhook"] }ⓘ
use tgbotrs::{Bot, Dispatcher, DispatcherOpts, Updater};
#[tokio::main]
async fn main() {
let bot = Bot::new("YOUR_TOKEN").await.unwrap();
let dp = Dispatcher::new(DispatcherOpts::default());
Updater::new(bot, dp)
.webhook_port(8443)
.webhook_secret("my_secret")
.start_webhook("https://yourdomain.com/bot")
.await.unwrap();
}§Custom HTTP Client (for testing)
use tgbotrs::{Bot, client::{BotClient, FormPart}};
use tgbotrs::BotError;
use async_trait::async_trait;
#[derive(Debug)]
struct MockClient;
#[async_trait]
impl BotClient for MockClient {
async fn post_json(&self, _url: &str, _body: serde_json::Value)
-> Result<bytes::Bytes, BotError>
{
Ok(bytes::Bytes::from(r#"{"ok":true,"result":{"id":42,"is_bot":true,"first_name":"Test","username":"testbot"}}"#))
}
async fn post_form(&self, _url: &str, _parts: Vec<FormPart>)
-> Result<bytes::Bytes, BotError>
{
Ok(bytes::Bytes::from(r#"{"ok":true,"result":true}"#))
}
}
let bot = Bot::with_client("1234:TOKEN", "https://api.telegram.org", MockClient).unwrap();§License
MIT License - Copyright (c) 2024-present Ankit Chaubey
Re-exports§
pub use client::BotClient;pub use client::FormBody;pub use client::FormPart;pub use client::ReqwestClient;pub use entities::parse_entities;pub use entities::parse_entity;pub use entities::MessageEntityExt;pub use entities::ParsedEntity;pub use bot_mapping::BotMapping;pub use client_sync::SyncBot;pub use framework::CallbackQueryHandler;pub use framework::CommandHandler;pub use framework::Context;pub use framework::ContinueGroups;pub use framework::ConversationHandler;pub use framework::ConversationOpts;pub use framework::Dispatcher;pub use framework::DispatcherAction;pub use framework::DispatcherOpts;pub use framework::EndConversation;pub use framework::EndGroups;pub use framework::FilterExt;pub use framework::Handler;pub use framework::HandlerResult;pub use framework::InMemoryStorage;pub use framework::KeyStrategy;pub use framework::MessageHandler;pub use framework::NextState;pub use types::*;
Modules§
- bot_
mapping - Multi-bot webhook routing (item 22).
- client
- Pluggable HTTP back-end for [
Bot]. - client_
sync - Synchronous
ureq-backed HTTP client (item 23). - entities
- Helpers for parsing
MessageEntityoffsets correctly. - framework
- gen_
methods - types
- All Telegram Bot API types, auto-generated from the official spec.
Structs§
- Bot
- The main Bot struct. Create one per bot token.
- Poller
- Long-polling update dispatcher.
- Updater
- Combines a
Botand aDispatcherinto a single, self-contained runner. - Webhook
Server - A built-in HTTP server that receives Telegram webhook updates.
Enums§
- BotError
- The main error type for tgbotrs.
- ChatId
- A chat identifier - either a numeric ID or a
@usernamestring. - Input
File - A file to be sent via the Telegram Bot API.
- Input
File OrString - A field that accepts either an
InputFileor a plain string (file_id / URL). - Input
Media - Typed enum for
sendMediaGroupand related methods. - Reply
Markup - Unified
reply_markuptype covering all four keyboard variants.
Type Aliases§
- Update
Handler - A function that handles an incoming update.