Rust SDK 基于 tokio + reqwest + serde 构建,异步、类型安全,38 个测试。所有协议类型派生 Serialize + Deserialize + Clone + Debug。已在 Linux、macOS、Windows 上测试通过。
安装
cargo add wechatbot tokio --features tokio/full
快速开始
use wechatbot::{WeChatBot, BotOptions}; #[tokio::main] async fn main() { let bot = WeChatBot::new(BotOptions::default()); let creds = bot.login(false).await.unwrap(); println!("已登录: {}", creds.account_id); bot.on_message(Box::new(|msg| { println!("{}: {}", msg.user_id, msg.text); })).await; bot.run().await.unwrap(); }
配置
let bot = WeChatBot::new(BotOptions { base_url: None, // 默认: ilinkai.weixin.qq.com cred_path: None, // 默认: ~/.wechatbot/credentials.json on_qr_url: Some(Box::new(|url| println!("扫码: {}", url))), on_error: Some(Box::new(|err| eprintln!("错误: {}", err))), });
消息处理
bot.on_message(Box::new(|msg| { match msg.content_type { ContentType::Text => println!("文本: {}", msg.text), ContentType::Image => println!("图片: {} 张", msg.images.len()), ContentType::Voice => { for v in &msg.voices { println!("语音: {:?} ({}ms)", v.text, v.duration_ms.unwrap_or(0)); } } ContentType::File => println!("文件: {:?}", msg.files[0].file_name), ContentType::Video => println!("视频"), } })).await;
发送消息
bot.reply(&msg, "Echo: 你好").await?; // 回复 bot.send(user_id, "你好").await?; // 主动发送 bot.send_typing(user_id).await?; // 显示输入中
错误处理
match result { Err(WeChatBotError::Api { errcode: -14, .. }) => { // 会话过期 —— 自动处理 } Err(WeChatBotError::NoContext(uid)) => { // 尚无 context_token } Err(WeChatBotError::Transport(e)) => { // 网络错误 } _ => {} }
AES-128-ECB 加密
let key = generate_aes_key(); let ct = encrypt_aes_ecb(b"Hello", &key); let pt = decrypt_aes_ecb(&ct, &key)?; // 解码协议密钥(支持 3 种格式) let k = decode_aes_key("ABEiM0RVZneImaq7zN3u/w==")?; // base64 let k = decode_aes_key("00112233445566778899aabbccddeeff")?; // hex