Expand description
§ferobot
Telegram Bot API library for Rust.
All types and methods from Telegram Bot API.
§Quick Start
use ferobot::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 ferobot! 🦀").await.unwrap();
println!("Sent: #{}", msg.message_id);
}§Echo Bot with Long Polling
use ferobot::{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
use ferobot::{Bot, CommandHandler, Dispatcher, DispatcherOpts, Updater};
use ferobot::framework::{HandlerResult, Context};
async fn start(bot: ferobot::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:
ferobot = { version = "0.2", features = ["webhook"] }ⓘ
use ferobot::{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 ferobot::{Bot, client::{BotClient, FormPart}};
use ferobot::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 middleware::LoggingMiddleware;pub use middleware::Middleware;pub use middleware::RateLimiter;pub use raw::RawRequest;pub use retry::RetryPolicy;pub use bot_mapping::BotMapping;pub use client_sync::SyncBot;pub use framework::RedisStorage;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::ConversationStorage;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. - fluent
- Fluent builder API for every Telegram Bot API method.
- framework
- gen_
methods - middleware
- Middleware hooks that run before and after every update.
- raw
- Raw / escape-hatch API caller.
- retry
- Automatic retry with exponential back-off for Telegram API calls.
- storage
- Pluggable storage backends for
ConversationHandler. - types
- Telegram Bot API types.
Macros§
- p
- Build an optional Telegram params struct with named fields.
Structs§
- Bot
- The main Bot struct. Create one per bot token.
- Poller
- Long-polling update dispatcher with bounded concurrency and panic recovery.
- 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 ferobot.
- 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.