Webhook
Webhook 由可选 webhook feature 提供,使用 Axum 0.8,默认不会引入 HTTP 服务端:
jingzhe = { version = "0.1.0", features = ["webhook"] }use jingzhe::{Bot, Context, WebhookConfig, command};
#[command(description = "开始使用")]async fn start(context: Context) -> anyhow::Result<()> { context.reply("惊蛰 Webhook 已收到命令。").await?; Ok(())}
#[tokio::main]async fn main() -> anyhow::Result<()> { let token = std::env::var("TELEGRAM_BOT_TOKEN")?; let public_url = std::env::var("WEBHOOK_URL")?; let secret = std::env::var("WEBHOOK_SECRET")?;
Bot::new(token)? .command(start) .run_webhook( WebhookConfig::new(public_url) .listen("127.0.0.1:3000") .secret_token(secret), ) .await?;
Ok(())}连接 Telegram 云端 API 时,公开地址必须是 HTTPS。本地监听默认是 127.0.0.1:3000,TLS 通常由反向代理提供。使用本地 Bot API 服务器时,可通过 WebhookConfig 的 .allow_http() 显式允许 HTTP。
run_webhook 会先校验、绑定监听,再显式请求 setWebhook。默认保留待处理事件,不自动发布命令菜单。退出时等待在途请求完成,不自动删除 Telegram Webhook。
仓库示例:
cargo run -p jingzhe --features webhook --example webhook需要设置 WEBHOOK_URL 和 WEBHOOK_SECRET。
已有 Axum 服务
Section titled “已有 Axum 服务”使用 bot.webhook_router(&config)? 可以把路由合并到已有 Axum 服务:
let router = bot.webhook_router(&config)?.with_state(shared_state);这个方法不会启动第二个服务,也不会调用 setWebhook。应用负责发布 Webhook、监听、反向代理和生命周期。
完整示例见 examples/axum_integration.rs。
服务在读取请求体前校验 X-Telegram-Bot-Api-Secret-Token,并取得处理容量:
| 情况 | 响应 |
|---|---|
| 认证缺失或错误 | 401 |
| 服务已满载 | 503 |
| 请求体超限 | 413 |
| JSON 非法 | 400 |
| 处理器失败 | 500 |
| 处理器成功完成 | 200 |
WebhookConfig 默认处理并发 1、请求体上限 1 MiB;并发可配置为 1–1024,请求体上限可提高到 16 MiB。提高并发后,处理完成顺序不保证与 update_id 一致。