API 请求
发送类型化请求
Section titled “发送类型化请求”所有请求和模型都直接从 jingzhe 导入。下面的代码读取机器人信息,并向指定聊天发送一条 HTML 消息:
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!("缺少 TELEGRAM_BOT_TOKEN,请设置 Bot Token"))?; let bot = Bot::new(token)?; let me = bot.request(GetMe::new()).await?;
println!("机器人:{},ID:{}", me.first_name, me.id);
let chat_id: i64 = std::env::var("TELEGRAM_CHAT_ID") .map_err(|_| anyhow::anyhow!("缺少 TELEGRAM_CHAT_ID,请设置目标聊天 ID"))? .parse()?; bot.request(SendMessage::new(chat_id, "<b>你好</b>").parse_mode(ParseMode::Html)).await?; Ok(())}构造请求不会联网。只有显式 .await 才会执行网络操作。
统一的构造方式
Section titled “统一的构造方式”发送消息统一使用聊天目标在前的构造方式:
use jingzhe::{InputFile, LinkPreviewOptions, ParseMode, SendMessage, SendVideo};
async fn send(bot: &Bot, chat_id: i64) -> jingzhe::Result<()> { bot.request(SendMessage::new(chat_id, "<b>惊蛰</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)
可选参数通过同名设置方法补充。格式统一使用 ParseMode,成功结果统一返回 Message、File、User 等模型;返回 true 的方法使用 bool。
构造器保证接口形状,本地校验会拒绝空文本、无效 URL、超限说明、重复命令、错误键盘或无效相册等请求。Telegram 仍会校验账户权限、资格及接口的其他业务约束。
Bot::client() 返回可克隆的轻量 ApiClient,不包含路由和应用状态。Context 也只共享同一个客户端。
未来新增方法可以复用现有的 JSON、多文件 multipart、超时、错误处理和日志:
- 实现
Request。 - 声明
Response和Method::Custom("方法名")。 - 本地上传文件通过
Attachment::at和Request::attachments绑定到 JSON pointer。
内置方法统一使用 Method 枚举。自定义方法名必须非空,并且只包含 ASCII 字母和数字。