API requests
Send a typed request
Section titled “Send a typed request”All requests and models are imported directly from jingzhe. The following example reads bot information and sends an HTML message to a chat:
use jingzhe::{Bot, GetMe, ParseMode, SendMessage};
#[tokio::main]async fn main() -> anyhow::Result<()> { let token = std::env::var("TELEGRAM_BOT_TOKEN") .map_err(|_| anyhow::anyhow!("Set TELEGRAM_BOT_TOKEN to the bot token"))?; let bot = Bot::new(token)?; let me = bot.request(GetMe::new()).await?;
println!("Bot: {}, ID: {}", me.first_name, me.id);
let chat_id: i64 = std::env::var("TELEGRAM_CHAT_ID") .map_err(|_| anyhow::anyhow!("Set TELEGRAM_CHAT_ID to the target chat"))? .parse()?; bot.request(SendMessage::new(chat_id, "<b>Hello</b>").parse_mode(ParseMode::Html)).await?; Ok(())}Constructing a request does not access the network. Network work starts only when the request is explicitly awaited.
Consistent constructors
Section titled “Consistent constructors”Send requests use the chat target as the first constructor argument:
use jingzhe::{InputFile, LinkPreviewOptions, ParseMode, SendMessage, SendVideo};
async fn send(bot: &Bot, chat_id: i64) -> jingzhe::Result<()> { bot.request(SendMessage::new(chat_id, "<b>Jingzhe</b>") .parse_mode(ParseMode::Html) .link_preview_options(LinkPreviewOptions::new().is_disabled(true))).await?;
bot.request(SendVideo::new(chat_id, InputFile::path("video.mp4")) .thumbnail(InputFile::path("thumbnail.jpg")) .supports_streaming(true)).await?; Ok(())}SendMessage::new(chat_id, text)SendVideo::new(chat_id, video)SendRichMessage::new(chat_id, rich_message)
Set optional parameters with same-name builder methods. Formatting uses ParseMode, and successful responses share Message, File, User, and other models. Methods that return true use bool.
Request validation
Section titled “Request validation”Constructors preserve the API shape. Local validation rejects empty text, invalid URLs, oversized descriptions, duplicate commands, invalid keyboards, invalid albums, and similar requests. Telegram still validates account permissions, eligibility, and any other service-side constraints.
Bot::client() returns a cloneable, lightweight ApiClient without routing or application state. Context shares the same client.
Extending requests
Section titled “Extending requests”New methods can reuse JSON encoding, multi-file multipart, timeouts, error handling, and logging:
- Implement
Request. - Declare the
Responsetype andMethod::Custom("methodName"). - Bind local uploads to JSON pointers with
Attachment::atandRequest::attachments.
Built-in methods use the Method enum. Custom method names must be non-empty and contain only ASCII letters and digits.