重构并拆分项目
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "wechat"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
# ── 加密与签名 ──
|
||||
base64 = "0.22" # Base64 编码
|
||||
sha2 = "0.11.0" # SHA-256 哈希(审批码)
|
||||
rand = "0.10.1" # 随机数
|
||||
# ── 异步运行时 ──
|
||||
tokio = { version = "1.0", features = ["rt-multi-thread", "macros", "sync", "time", "process", "signal", "io-util"] } # 异步运行时核心
|
||||
# ── HTTP 客户端 ──
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] } # HTTP 请求(微信 API + DeepSeek API + 工具调用)
|
||||
# ── 序列化 ──
|
||||
serde = { version = "1.0", features = ["derive"] } # 序列化/反序列化
|
||||
serde_json = "1.0" # JSON 处理
|
||||
serde_yaml = "0.9" # YAML 解析(工具规范文件)
|
||||
# ── 日志 ──
|
||||
tracing = "0.1" # 结构化日志
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] } # 日志输出
|
||||
tracing-appender = "0.2.5" # 文件日志(日滚)
|
||||
# ── 二维码 ──
|
||||
qrcode = { version = "0.14", default-features = false }
|
||||
# ── UUID ──
|
||||
uuid = { version = "1", features = ["v4", "serde"] } # 唯一标识符 # 二维码生成(仅 Unicode 终端渲染)
|
||||
@@ -0,0 +1,492 @@
|
||||
# wechat 模块使用文档
|
||||
|
||||
`wechat` 是一个封装微信 iLink Bot API 的 Rust crate,负责微信 Bot 的扫码登录、监听器生命周期管理、长轮询收消息和文本消息发送。
|
||||
|
||||
当前模块只提供库能力,不会自动启动后台任务,也不会自动持久化登录态。业务服务需要主动创建 `WeChatClient`、完成登录或恢复登录态,然后调用收发消息接口。
|
||||
|
||||
## 模块结构
|
||||
|
||||
```text
|
||||
wechat/
|
||||
src/
|
||||
lib.rs # 模块导出
|
||||
client.rs # WeChatClient,封装所有 HTTP API 调用
|
||||
types.rs # iLink Bot API 请求、响应和消息结构
|
||||
```
|
||||
|
||||
公开模块:
|
||||
|
||||
```rust
|
||||
pub mod client;
|
||||
pub mod types;
|
||||
```
|
||||
|
||||
常用类型:
|
||||
|
||||
```rust
|
||||
use wechat::client::WeChatClient;
|
||||
use wechat::types::{GetUpdatesResp, LoginResult, MessageItem, WeixinMessage};
|
||||
```
|
||||
|
||||
## Cargo 引用
|
||||
|
||||
本仓库根目录已经把 `wechat` 加入 workspace:
|
||||
|
||||
```toml
|
||||
[workspace]
|
||||
members = ["service", "ai", "common", "wechat"]
|
||||
```
|
||||
|
||||
如果其他 workspace crate 需要使用它,在对应 `Cargo.toml` 里加入:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
wechat = { path = "../wechat" }
|
||||
```
|
||||
|
||||
## 环境变量
|
||||
|
||||
| 变量 | 必填 | 默认值 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `WEIXIN_BASE_URL` | 否 | `https://ilinkai.weixin.qq.com` | iLink Bot API 地址。测试、代理或私有部署时可覆盖。 |
|
||||
|
||||
示例:
|
||||
|
||||
```bash
|
||||
export WEIXIN_BASE_URL="https://ilinkai.weixin.qq.com"
|
||||
```
|
||||
|
||||
## 基本生命周期
|
||||
|
||||
推荐调用顺序:
|
||||
|
||||
1. 创建客户端:`WeChatClient::new(None)`
|
||||
2. 扫码登录:`login(...)`
|
||||
3. 持久化登录结果:保存 `token`、`account_id`、`base_url`
|
||||
4. 注册监听器:`notify_start()`
|
||||
5. 循环拉取消息:`receive_messages()`
|
||||
6. 处理用户消息并回复:`send_text(...)`
|
||||
7. 服务退出前注销监听器:`notify_stop()`
|
||||
|
||||
## 快速开始
|
||||
|
||||
下面示例会扫码登录,注册监听器,然后持续接收用户文本消息并原样回复。
|
||||
|
||||
```rust
|
||||
use std::time::Duration;
|
||||
|
||||
use wechat::client::WeChatClient;
|
||||
use wechat::types::WeixinMessage;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), String> {
|
||||
let client = WeChatClient::new(None);
|
||||
|
||||
let login = client
|
||||
.login(
|
||||
|qrcode_url| {
|
||||
println!("二维码地址: {qrcode_url}");
|
||||
},
|
||||
120,
|
||||
)
|
||||
.await?;
|
||||
|
||||
println!("登录成功: account_id={}", login.account_id);
|
||||
|
||||
client.notify_start().await?;
|
||||
|
||||
loop {
|
||||
let updates = client.receive_messages().await?;
|
||||
|
||||
for msg in updates.msgs {
|
||||
if msg.msg_type != Some(WeixinMessage::TYPE_USER) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(from_user_id) = msg.from_user_id.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let Some(text) = msg.text_content() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
client
|
||||
.send_text(from_user_id, &format!("收到: {text}"), msg.context_token.as_deref())
|
||||
.await?;
|
||||
}
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 登录
|
||||
|
||||
完整登录接口:
|
||||
|
||||
```rust
|
||||
pub async fn login(
|
||||
&self,
|
||||
on_qrcode: impl Fn(&str),
|
||||
timeout_secs: u64,
|
||||
) -> Result<LoginResult, String>
|
||||
```
|
||||
|
||||
参数说明:
|
||||
|
||||
| 参数 | 说明 |
|
||||
| --- | --- |
|
||||
| `on_qrcode` | 获取二维码内容后的回调。当前实现会传入 `qrcode_img_content`,通常是可打开或可展示为二维码的内容。 |
|
||||
| `timeout_secs` | 扫码确认总超时时间,单位秒。 |
|
||||
|
||||
返回值:
|
||||
|
||||
```rust
|
||||
pub struct LoginResult {
|
||||
pub token: String,
|
||||
pub account_id: String,
|
||||
pub base_url: String,
|
||||
pub user_id: String,
|
||||
}
|
||||
```
|
||||
|
||||
登录内部流程:
|
||||
|
||||
1. `get_qrcode()` 调用 `/ilink/bot/get_bot_qrcode` 获取二维码。
|
||||
2. 终端渲染二维码,同时打印二维码链接。
|
||||
3. `poll_qr_status()` 轮询 `/ilink/bot/get_qrcode_status`。
|
||||
4. 用户扫码并确认后,把 `bot_token` 和 `ilink_bot_id` 写入客户端内存。
|
||||
5. 返回 `LoginResult`,供业务层持久化。
|
||||
|
||||
扫码状态值:
|
||||
|
||||
| 状态 | 含义 | 当前处理 |
|
||||
| --- | --- | --- |
|
||||
| `wait` | 等待扫码 | 继续轮询 |
|
||||
| `scaned` | 已扫码,等待微信确认 | 提示用户确认 |
|
||||
| `scaned_but_redirect` | 需要切换 IDC | 使用 `redirect_host` 更新轮询地址 |
|
||||
| `confirmed` | 登录成功 | 保存 token/account_id 并返回 |
|
||||
| `expired` | 二维码过期 | 返回错误 |
|
||||
|
||||
## 恢复登录态
|
||||
|
||||
`wechat` 模块不负责把登录态写入数据库或文件。业务层应在登录成功后保存:
|
||||
|
||||
- `LoginResult.token`
|
||||
- `LoginResult.account_id`
|
||||
- `LoginResult.base_url`
|
||||
- `get_updates_buf()` 返回值,建议在每次 `receive_messages()` 成功后保存
|
||||
|
||||
下次启动时恢复:
|
||||
|
||||
```rust
|
||||
let mut client = WeChatClient::new(None);
|
||||
|
||||
client
|
||||
.set_auth(
|
||||
"持久化保存的 token",
|
||||
"持久化保存的 account_id",
|
||||
"持久化保存的 base_url",
|
||||
)
|
||||
.await;
|
||||
|
||||
client
|
||||
.set_updates_buf("持久化保存的 get_updates_buf")
|
||||
.await;
|
||||
|
||||
client.notify_start().await?;
|
||||
```
|
||||
|
||||
注意:`set_auth` 需要 `&mut self`,因此恢复登录态时变量要声明为 `mut`。
|
||||
|
||||
## 注册和注销监听器
|
||||
|
||||
注册监听器:
|
||||
|
||||
```rust
|
||||
client.notify_start().await?;
|
||||
```
|
||||
|
||||
注销监听器:
|
||||
|
||||
```rust
|
||||
client.notify_stop().await?;
|
||||
```
|
||||
|
||||
这两个接口分别调用:
|
||||
|
||||
- `POST /ilink/bot/msg/notifystart`
|
||||
- `POST /ilink/bot/msg/notifystop`
|
||||
|
||||
建议:
|
||||
|
||||
- 登录或恢复登录态后先调用 `notify_start()`,再开始拉消息。
|
||||
- 进程收到退出信号时调用 `notify_stop()`。
|
||||
- 如果进程异常退出,下一次启动后仍应重新调用 `notify_start()`。
|
||||
|
||||
## 接收消息
|
||||
|
||||
接口:
|
||||
|
||||
```rust
|
||||
pub async fn receive_messages(&self) -> Result<GetUpdatesResp, String>
|
||||
```
|
||||
|
||||
响应结构:
|
||||
|
||||
```rust
|
||||
pub struct GetUpdatesResp {
|
||||
pub ret: i32,
|
||||
pub errcode: Option<i32>,
|
||||
pub errmsg: Option<String>,
|
||||
pub msgs: Vec<WeixinMessage>,
|
||||
pub get_updates_buf: String,
|
||||
pub longpolling_timeout_ms: Option<i64>,
|
||||
}
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- 该接口调用 `/ilink/bot/getupdates`。
|
||||
- 客户端内部维护 `updates_buf`,并在响应里的 `get_updates_buf` 非空时自动更新。
|
||||
- 如果请求超时,当前实现返回一个空消息列表,不视为致命错误。
|
||||
- 如果 `ret != 0` 或 `errcode != 0`,当前实现会写 warn 日志,但仍把响应返回给调用方。
|
||||
|
||||
文本消息提取:
|
||||
|
||||
```rust
|
||||
for msg in updates.msgs {
|
||||
if msg.msg_type == Some(WeixinMessage::TYPE_USER) {
|
||||
if let Some(text) = msg.text_content() {
|
||||
println!("收到文本: {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
消息关键字段:
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| `msg_type` | `1` 表示用户消息,`2` 表示 Bot 消息。 |
|
||||
| `from_user_id` | 发送者 ID。回复私聊消息时通常作为 `send_text` 的 `to`。 |
|
||||
| `to_user_id` | 接收者 ID。 |
|
||||
| `group_id` | 群消息 ID,群聊场景可能非空。 |
|
||||
| `item_list` | 消息内容列表,可包含文本、图片、语音、文件、视频。 |
|
||||
| `context_token` | 微信上下文令牌。回复时透传可保持多轮上下文。 |
|
||||
|
||||
## 发送文本消息
|
||||
|
||||
接口:
|
||||
|
||||
```rust
|
||||
pub async fn send_text(
|
||||
&self,
|
||||
to: &str,
|
||||
text: &str,
|
||||
context_token: Option<&str>,
|
||||
) -> Result<String, String>
|
||||
```
|
||||
|
||||
参数说明:
|
||||
|
||||
| 参数 | 说明 |
|
||||
| --- | --- |
|
||||
| `to` | 接收者用户 ID。通常来自收到消息的 `from_user_id`。 |
|
||||
| `text` | 要发送的文本内容。 |
|
||||
| `context_token` | 可选上下文令牌,建议透传收到消息里的 `context_token`。 |
|
||||
|
||||
返回值是本地生成的 `client_id`,可用于日志追踪。
|
||||
|
||||
示例:
|
||||
|
||||
```rust
|
||||
let client_id = client
|
||||
.send_text(
|
||||
from_user_id,
|
||||
"你好,我是 Bot",
|
||||
msg.context_token.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
println!("消息已提交: client_id={client_id}");
|
||||
```
|
||||
|
||||
当前发送实现固定构造:
|
||||
|
||||
- `message_type = 2`,表示 Bot 消息
|
||||
- `message_state = 2`,表示完成态
|
||||
- `item_list = [MessageItem::text(text)]`
|
||||
|
||||
## 非文本消息
|
||||
|
||||
协议类型已经定义了以下消息 item:
|
||||
|
||||
- `TextItem`
|
||||
- `ImageItem`
|
||||
- `VoiceItem`
|
||||
- `FileItem`
|
||||
- `VideoItem`
|
||||
|
||||
当前便捷发送接口只实现了 `send_text()`。如果需要发送图片、文件或视频,需要新增对应的发送方法,构造 `WeixinMessage.item_list` 中的 `MessageItem`。
|
||||
|
||||
接收侧可以通过 `MessageItem.item_type` 判断类型:
|
||||
|
||||
```rust
|
||||
for item in msg.item_list.unwrap_or_default() {
|
||||
match item.item_type {
|
||||
Some(MessageItem::TYPE_TEXT) => {
|
||||
let text = item.text_item.and_then(|v| v.text);
|
||||
println!("文本: {:?}", text);
|
||||
}
|
||||
Some(MessageItem::TYPE_IMAGE) => {
|
||||
println!("图片: {:?}", item.image_item);
|
||||
}
|
||||
Some(MessageItem::TYPE_VOICE) => {
|
||||
println!("语音: {:?}", item.voice_item);
|
||||
}
|
||||
Some(MessageItem::TYPE_FILE) => {
|
||||
println!("文件: {:?}", item.file_item);
|
||||
}
|
||||
Some(MessageItem::TYPE_VIDEO) => {
|
||||
println!("视频: {:?}", item.video_item);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 长轮询循环建议
|
||||
|
||||
推荐业务层把接收循环放到独立 tokio task:
|
||||
|
||||
```rust
|
||||
let client_for_loop = client.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
match client_for_loop.receive_messages().await {
|
||||
Ok(updates) => {
|
||||
for msg in updates.msgs {
|
||||
// 处理消息
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::warn!("接收微信消息失败: {err}");
|
||||
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
注意:
|
||||
|
||||
- `WeChatClient` 实现了 `Clone`,内部 token、account_id 和 updates_buf 使用 `Arc<Mutex<_>>` 共享。
|
||||
- `receive_messages()` 已经处理普通超时,业务层不需要把空消息视为错误。
|
||||
- 处理消息时建议过滤 `WeixinMessage::TYPE_BOT`,避免重复处理 Bot 自己发出的消息。
|
||||
- 每次成功拉取后可以调用 `get_updates_buf()` 并持久化,降低重启后重复收消息的概率。
|
||||
|
||||
## 与 AI 回复集成示例
|
||||
|
||||
示例逻辑:收到用户文本后调用业务自己的 AI 函数,再把结果发回微信。
|
||||
|
||||
```rust
|
||||
async fn handle_wechat_message(client: &WeChatClient, msg: WeixinMessage) -> Result<(), String> {
|
||||
if msg.msg_type != Some(WeixinMessage::TYPE_USER) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let Some(from_user_id) = msg.from_user_id.as_deref() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let Some(user_text) = msg.text_content() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let answer = call_ai(user_text).await?;
|
||||
|
||||
client
|
||||
.send_text(from_user_id, &answer, msg.context_token.as_deref())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn call_ai(input: &str) -> Result<String, String> {
|
||||
Ok(format!("AI 回复: {input}"))
|
||||
}
|
||||
```
|
||||
|
||||
## API 端点
|
||||
|
||||
`WeChatClient` 当前使用以下 iLink Bot API:
|
||||
|
||||
| 方法 | 路径 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `GET` | `/ilink/bot/get_bot_qrcode` | 获取扫码登录二维码 |
|
||||
| `GET` | `/ilink/bot/get_qrcode_status` | 查询扫码状态 |
|
||||
| `POST` | `/ilink/bot/msg/notifystart` | 注册监听器 |
|
||||
| `POST` | `/ilink/bot/msg/notifystop` | 注销监听器 |
|
||||
| `POST` | `/ilink/bot/getupdates` | 长轮询拉取消息 |
|
||||
| `POST` | `/ilink/bot/sendmessage` | 发送消息 |
|
||||
|
||||
请求头由模块内部生成:
|
||||
|
||||
- `Content-Type: application/json`
|
||||
- `Content-Length`
|
||||
- `iLink-App-ClientVersion`
|
||||
- `X-WECHAT-UIN`
|
||||
- 登录后请求额外带:
|
||||
- `Authorization: Bearer <token>`
|
||||
- `AuthorizationType: ilink_bot_token`
|
||||
|
||||
## 日志
|
||||
|
||||
模块使用 `tracing` 输出日志,主要 target 为:
|
||||
|
||||
```text
|
||||
ias::auth
|
||||
```
|
||||
|
||||
业务程序可初始化日志:
|
||||
|
||||
```rust
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter("info,ias::auth=debug")
|
||||
.init();
|
||||
```
|
||||
|
||||
## 错误处理
|
||||
|
||||
所有公开异步方法当前返回 `Result<_, String>`。
|
||||
|
||||
常见错误:
|
||||
|
||||
| 场景 | 典型错误 | 处理建议 |
|
||||
| --- | --- | --- |
|
||||
| 二维码过期 | `二维码已过期` | 重新调用 `login()`。 |
|
||||
| 登录超时 | `登录超时` | 增大 `timeout_secs` 或重新登录。 |
|
||||
| token 无效 | HTTP 401/403 或接口返回错误 | 清理持久化登录态,重新扫码登录。 |
|
||||
| 长轮询超时 | 返回空 `msgs` | 正常情况,继续下一轮。 |
|
||||
| 网络错误 | `请求失败` | 延迟重试,必要时检查 `WEIXIN_BASE_URL`。 |
|
||||
|
||||
## 当前限制
|
||||
|
||||
- `ILINK_APP_ID` 当前是空字符串。如接入方要求 app id,需要在 `client.rs` 中配置或改造成环境变量。
|
||||
- 登录态只保存在内存中,重启恢复需要业务层调用 `set_auth()` 和 `set_updates_buf()`。
|
||||
- 只提供文本发送便捷方法 `send_text()`。
|
||||
- 群聊回复策略需要业务层结合 `group_id` 和实际 iLink 协议进一步确认。
|
||||
- `send_text()` 当前不解析服务端响应体,只在 HTTP 层确认请求成功后返回本地 `client_id`。
|
||||
|
||||
## 排障清单
|
||||
|
||||
1. 确认能访问 `WEIXIN_BASE_URL`。
|
||||
2. 确认扫码后在微信侧完成确认。
|
||||
3. 登录后先调用 `notify_start()`,再调用 `receive_messages()`。
|
||||
4. 如果收不到消息,检查 `get_updates_buf` 是否恢复了过旧状态;必要时清空后重试。
|
||||
5. 如果发送失败,检查 token 是否过期,以及 `to` 是否使用了正确的 `from_user_id`。
|
||||
6. 打开 `ias::auth=debug` 日志观察 API 请求和状态变化。
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
//! ## 微信 iLink Bot API 客户端
|
||||
//!
|
||||
//! 封装了与微信 iLink Bot API 的所有通信:
|
||||
//!
|
||||
//! ### 核心功能
|
||||
//! - **扫码登录** — `get_qrcode()` → `poll_qr_status()` → `login()`
|
||||
//! - **消息接收** — `receive_messages()`(长轮询)
|
||||
//! - **消息发送** — `send_text()`
|
||||
//! - **生命周期** — `notify_start()` / `notify_stop()`
|
||||
//!
|
||||
//! ### 线程安全
|
||||
//! `#[derive(Clone)]` + 内部 `Arc<Mutex<>>` 保证所有方法可以在 tokio task 间共享。
|
||||
//!
|
||||
//! ### 环境变量
|
||||
//! - `WEIXIN_BASE_URL` — API 地址(默认 `https://ilinkai.weixin.qq.com`)
|
||||
|
||||
use crate::types::*;
|
||||
use base64::Engine;
|
||||
use reqwest::Client as HttpClient;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
/// ## 微信 iLink Bot API 客户端
|
||||
///
|
||||
/// ### 职责
|
||||
/// 封装了与微信 iLink Bot API 的所有通信,包括:
|
||||
/// * 扫码登录流程(获取二维码、轮询状态)
|
||||
/// * 消息接收(长轮询 getUpdates)
|
||||
/// * 消息发送(sendMessage)
|
||||
/// * 生命周期管理(notifyStart/notifyStop)
|
||||
///
|
||||
/// ### 线程安全
|
||||
/// `#[derive(Clone)]` + 内部 `Arc<Mutex<>>` 保证所有方法可以在 tokio task 间共享。
|
||||
///
|
||||
/// ### API 端点
|
||||
/// * 二维码: `{base_url}/ilink/bot/get_bot_qrcode`
|
||||
/// * 登录状态: `{base_url}/ilink/bot/get_qrcode_status`
|
||||
/// * 收消息: `{base_url}/ilink/bot/getupdates`
|
||||
/// * 发消息: `{base_url}/ilink/bot/sendmessage`
|
||||
/// * 注册监听: `{base_url}/ilink/bot/msg/notifystart`
|
||||
#[derive(Clone)]
|
||||
pub struct WeChatClient {
|
||||
http: HttpClient,
|
||||
base_url: String,
|
||||
token: Arc<Mutex<String>>,
|
||||
account_id: Arc<Mutex<String>>,
|
||||
/// get_updates_buf,用于长轮询的上下文缓冲
|
||||
updates_buf: Arc<Mutex<String>>,
|
||||
}
|
||||
|
||||
impl WeChatClient {
|
||||
/// iLink App ID(从 package.json 的 ilink_appid 字段,硬编码或环境变量)
|
||||
const ILINK_APP_ID: &'static str = "";
|
||||
/// 默认 bot_type
|
||||
const DEFAULT_BOT_TYPE: &'static str = "3";
|
||||
/// 默认 API 地址(可通过 WEIXIN_BASE_URL 环境变量覆盖)
|
||||
const DEFAULT_BASE_URL: &'static str = "https://ilinkai.weixin.qq.com";
|
||||
/// 二维码固定 API 地址(可通过 WEIXIN_BASE_URL 环境变量覆盖)
|
||||
fn fixed_base_url() -> String {
|
||||
std::env::var("WEIXIN_BASE_URL")
|
||||
.unwrap_or_else(|_| "https://ilinkai.weixin.qq.com".to_string())
|
||||
}
|
||||
/// 版本号编码:0x00MMNNPP
|
||||
const CLIENT_VERSION: u32 = 0x000100_00; // 1.0.0
|
||||
|
||||
pub fn new(base_url: Option<String>) -> Self {
|
||||
// 优先级: 显式参数 > WEIXIN_BASE_URL 环境变量 > 默认值
|
||||
let base = base_url
|
||||
.or_else(|| std::env::var("WEIXIN_BASE_URL").ok())
|
||||
.unwrap_or_else(|| Self::DEFAULT_BASE_URL.to_string());
|
||||
|
||||
Self {
|
||||
http: HttpClient::builder()
|
||||
.timeout(Duration::from_secs(60))
|
||||
.build()
|
||||
.expect("创建 HTTP client 失败"),
|
||||
base_url: base,
|
||||
token: Arc::new(Mutex::new(String::new())),
|
||||
account_id: Arc::new(Mutex::new(String::new())),
|
||||
updates_buf: Arc::new(Mutex::new(String::new())),
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 公共方法 ───
|
||||
|
||||
/// ## 获取登录二维码链接
|
||||
///
|
||||
/// 调用 iLink API `/ilink/bot/get_bot_qrcode` 获取二维码。
|
||||
/// 二维码内容是一个 URL,浏览器打开后显示二维码图片。
|
||||
pub async fn get_qrcode(&self) -> Result<(String, String), String> {
|
||||
let url = format!(
|
||||
"{}/ilink/bot/get_bot_qrcode?bot_type={}",
|
||||
&Self::fixed_base_url(),
|
||||
Self::DEFAULT_BOT_TYPE
|
||||
);
|
||||
|
||||
let resp: QRCodeResponse = self
|
||||
.http
|
||||
.get(&url)
|
||||
.headers(Self::common_headers())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("请求二维码失败: {}", e))?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("解析二维码响应失败: {}", e))?;
|
||||
|
||||
Ok((resp.qrcode, resp.qrcode_img_content))
|
||||
}
|
||||
|
||||
/// ## 轮询扫码状态(带 35 秒超时的长轮询)
|
||||
///
|
||||
/// 调用 iLink API 检查用户是否已扫码。
|
||||
/// * `wait` — 继续等待
|
||||
/// * `scaned` — 已扫码,等待确认
|
||||
/// * `scaned_but_redirect` — IDC 重定向(切换到 redirect_host)
|
||||
/// * `confirmed` — 登录成功
|
||||
/// * `expired` — 二维码过期
|
||||
///
|
||||
/// 网络错误不会导致退出,而是返回 `wait` 让调用者继续轮询。
|
||||
pub async fn poll_qr_status(
|
||||
&self,
|
||||
qrcode: &str,
|
||||
base_url: &str,
|
||||
) -> Result<StatusResponse, String> {
|
||||
let url = format!("{}/ilink/bot/get_qrcode_status?qrcode={}", base_url, qrcode);
|
||||
|
||||
let resp_result = self
|
||||
.http
|
||||
.get(&url)
|
||||
.headers(Self::common_headers())
|
||||
.timeout(Duration::from_secs(35))
|
||||
.send()
|
||||
.await;
|
||||
|
||||
match resp_result {
|
||||
Ok(response) => {
|
||||
let text = response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| format!("读取响应体失败: {}", e))?;
|
||||
serde_json::from_str::<StatusResponse>(&text)
|
||||
.map_err(|e| format!("解析状态响应失败: {}", e))
|
||||
}
|
||||
Err(e) if e.is_timeout() => {
|
||||
// 超时是正常的,返回 wait 让调用者继续轮询
|
||||
Ok(StatusResponse {
|
||||
status: "wait".to_string(),
|
||||
bot_token: None,
|
||||
ilink_bot_id: None,
|
||||
baseurl: None,
|
||||
ilink_user_id: None,
|
||||
redirect_host: None,
|
||||
})
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(target: "ias::auth", "轮询二维码状态网络错误: {},继续等待", e);
|
||||
Ok(StatusResponse {
|
||||
status: "wait".to_string(),
|
||||
bot_token: None,
|
||||
ilink_bot_id: None,
|
||||
baseurl: None,
|
||||
ilink_user_id: None,
|
||||
redirect_host: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行完整扫码登录流程
|
||||
pub async fn login(
|
||||
&self,
|
||||
on_qrcode: impl Fn(&str),
|
||||
timeout_secs: u64,
|
||||
) -> Result<LoginResult, String> {
|
||||
info!(target: "ias::auth", "开始微信扫码登录...");
|
||||
|
||||
let (qrcode, qrcode_img_content) = self.get_qrcode().await?;
|
||||
|
||||
// 显示二维码链接
|
||||
on_qrcode(&qrcode_img_content);
|
||||
|
||||
// 生成二维码终端显示
|
||||
if let Ok(code) = qrcode::QrCode::new(qrcode_img_content.as_bytes()) {
|
||||
let svg = code
|
||||
.render::<qrcode::render::unicode::Dense1x2>()
|
||||
.dark_color(qrcode::render::unicode::Dense1x2::Dark)
|
||||
.light_color(qrcode::render::unicode::Dense1x2::Light)
|
||||
.build();
|
||||
println!("\n{}", svg);
|
||||
}
|
||||
|
||||
println!("请使用微信扫描上方二维码登录");
|
||||
println!("二维码链接(如二维码无法显示):{}", qrcode_img_content);
|
||||
println!();
|
||||
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(timeout_secs);
|
||||
let mut scanned = false;
|
||||
let mut current_base = Self::fixed_base_url();
|
||||
|
||||
while tokio::time::Instant::now() < deadline {
|
||||
let status = self.poll_qr_status(&qrcode, ¤t_base).await?;
|
||||
|
||||
match status.status.as_str() {
|
||||
"wait" => {
|
||||
print!(".");
|
||||
std::io::Write::flush(&mut std::io::stdout()).ok();
|
||||
}
|
||||
"scaned" => {
|
||||
if !scanned {
|
||||
println!("\n👀 已扫码,请在微信上确认登录...");
|
||||
scanned = true;
|
||||
}
|
||||
}
|
||||
"scaned_but_redirect" => {
|
||||
if let Some(host) = &status.redirect_host {
|
||||
current_base = format!("https://{}", host);
|
||||
info!(target: "ias::auth", "IDC 重定向到: {}", current_base);
|
||||
}
|
||||
}
|
||||
"confirmed" => {
|
||||
let token = status
|
||||
.bot_token
|
||||
.ok_or_else(|| "登录成功但未返回 bot_token".to_string())?;
|
||||
let account_id = status
|
||||
.ilink_bot_id
|
||||
.ok_or_else(|| "登录成功但未返回 ilink_bot_id".to_string())?;
|
||||
let user_id = status.ilink_user_id.unwrap_or_default();
|
||||
let base_url = status
|
||||
.baseurl
|
||||
.unwrap_or_else(|| Self::DEFAULT_BASE_URL.to_string());
|
||||
|
||||
// 保存到内存状态
|
||||
*self.token.lock().await = token.clone();
|
||||
*self.account_id.lock().await = account_id.clone();
|
||||
|
||||
info!(target: "ias::auth", "✅ 登录成功! bot_id={}", account_id);
|
||||
return Ok(LoginResult {
|
||||
token,
|
||||
account_id,
|
||||
base_url,
|
||||
user_id,
|
||||
});
|
||||
}
|
||||
"expired" => {
|
||||
return Err("二维码已过期".to_string());
|
||||
}
|
||||
_ => {
|
||||
warn!(target: "ias::auth", "未知状态: {}", status.status);
|
||||
}
|
||||
}
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
Err("登录超时".to_string())
|
||||
}
|
||||
|
||||
/// 注册监听器(通知微信服务端本客户端已启动)
|
||||
pub async fn notify_start(&self) -> Result<(), String> {
|
||||
let body = serde_json::json!({ "base_info": BaseInfo::new() });
|
||||
|
||||
let url = format!("{}/ilink/bot/msg/notifystart", self.base_url);
|
||||
let token = self.token.lock().await.clone();
|
||||
|
||||
let _resp: NotifyResp = self
|
||||
.post_json(&url, &body, Some(&token))
|
||||
.await?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("解析 notifyStart 响应失败: {}", e))?;
|
||||
|
||||
if _resp.ret != 0 {
|
||||
return Err(format!(
|
||||
"notifyStart 失败: ret={} errmsg={:?}",
|
||||
_resp.ret, _resp.errmsg
|
||||
));
|
||||
}
|
||||
|
||||
info!(target: "ias::auth", "监听器已注册");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 注销监听器
|
||||
#[allow(dead_code)]
|
||||
pub async fn notify_stop(&self) -> Result<(), String> {
|
||||
let body = serde_json::json!({ "base_info": BaseInfo::new() });
|
||||
|
||||
let url = format!("{}/ilink/bot/msg/notifystop", self.base_url);
|
||||
let token = self.token.lock().await.clone();
|
||||
|
||||
let _resp: NotifyResp = self
|
||||
.post_json(&url, &body, Some(&token))
|
||||
.await?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("解析 notifyStop 响应失败: {}", e))?;
|
||||
|
||||
info!(target: "ias::auth", "监听器已注销");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 长轮询接收消息
|
||||
pub async fn receive_messages(&self) -> Result<GetUpdatesResp, String> {
|
||||
let buf = self.updates_buf.lock().await.clone();
|
||||
|
||||
let body = GetUpdatesReq {
|
||||
get_updates_buf: buf.clone(),
|
||||
base_info: BaseInfo::new(),
|
||||
};
|
||||
|
||||
let url = format!("{}/ilink/bot/getupdates", self.base_url);
|
||||
let token = self.token.lock().await.clone();
|
||||
|
||||
let resp: GetUpdatesResp = match self.post_json(&url, &body, Some(&token)).await {
|
||||
Ok(resp) => {
|
||||
let resp: GetUpdatesResp = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("解析 getUpdates 响应失败: {}", e))?;
|
||||
if resp.ret != 0 || resp.errcode.unwrap_or(0) != 0 {
|
||||
tracing::warn!(
|
||||
target: "ias::auth",
|
||||
"getUpdates 返回错误: ret={} errcode={:?} errmsg={:?}",
|
||||
resp.ret,
|
||||
resp.errcode,
|
||||
resp.errmsg
|
||||
);
|
||||
}
|
||||
resp
|
||||
}
|
||||
Err(e) => {
|
||||
// 如果超时,返回空响应
|
||||
if e.contains("超时") || e.contains("timeout") {
|
||||
return Ok(GetUpdatesResp {
|
||||
ret: 0,
|
||||
errcode: None,
|
||||
errmsg: None,
|
||||
msgs: vec![],
|
||||
get_updates_buf: buf.clone(),
|
||||
longpolling_timeout_ms: None,
|
||||
});
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
// 更新 buf
|
||||
if !resp.get_updates_buf.is_empty() {
|
||||
*self.updates_buf.lock().await = resp.get_updates_buf.clone();
|
||||
}
|
||||
|
||||
Ok(resp)
|
||||
}
|
||||
|
||||
/// 发送文本消息
|
||||
pub async fn send_text(
|
||||
&self,
|
||||
to: &str,
|
||||
text: &str,
|
||||
context_token: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
let client_id = uuid::Uuid::new_v4().to_string();
|
||||
|
||||
let msg = WeixinMessage {
|
||||
from_user_id: Some(String::new()),
|
||||
to_user_id: Some(to.to_string()),
|
||||
client_id: Some(client_id.clone()),
|
||||
msg_type: Some(WeixinMessage::TYPE_BOT),
|
||||
message_state: Some(2), // FINISH
|
||||
item_list: Some(vec![MessageItem::text(text)]),
|
||||
context_token: context_token.map(|s| s.to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let body = SendMessageReq { msg };
|
||||
|
||||
let url = format!("{}/ilink/bot/sendmessage", self.base_url);
|
||||
let token = self.token.lock().await.clone();
|
||||
|
||||
let _resp_text = self
|
||||
.post_json(&url, &body, Some(&token))
|
||||
.await?
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| format!("发送消息网络错误: {}", e))?;
|
||||
|
||||
Ok(client_id)
|
||||
}
|
||||
|
||||
/// 设置 auth 状态(从持久化恢复)
|
||||
pub async fn set_auth(&mut self, token: &str, account_id: &str, base_url: &str) {
|
||||
*self.token.lock().await = token.to_string();
|
||||
*self.account_id.lock().await = account_id.to_string();
|
||||
if !base_url.is_empty() {
|
||||
self.base_url = base_url.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取当前 updates_buf(用于持久化)
|
||||
#[allow(dead_code)]
|
||||
pub async fn get_updates_buf(&self) -> String {
|
||||
self.updates_buf.lock().await.clone()
|
||||
}
|
||||
|
||||
/// 设置 get_updates_buf(从持久化恢复)
|
||||
pub async fn set_updates_buf(&self, buf: &str) {
|
||||
*self.updates_buf.lock().await = buf.to_string();
|
||||
}
|
||||
|
||||
// ─── 内部方法 ───
|
||||
|
||||
/// ## 公共请求头
|
||||
///
|
||||
/// 每个请求都携带以下头信息:
|
||||
/// * `Content-Type: application/json`
|
||||
/// * `iLink-App-ClientVersion` — 客户端版本号编码
|
||||
/// * `X-WECHAT-UIN` — 随机 uint32 → base64 编码的会话标识
|
||||
fn common_headers() -> reqwest::header::HeaderMap {
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
headers.insert(
|
||||
"Content-Type",
|
||||
reqwest::header::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
|
||||
if !Self::ILINK_APP_ID.is_empty() {
|
||||
headers.insert(
|
||||
"iLink-App-Id",
|
||||
reqwest::header::HeaderValue::from_static(Self::ILINK_APP_ID),
|
||||
);
|
||||
}
|
||||
|
||||
headers.insert(
|
||||
"iLink-App-ClientVersion",
|
||||
reqwest::header::HeaderValue::from_str(&Self::CLIENT_VERSION.to_string()).unwrap(),
|
||||
);
|
||||
|
||||
// X-WECHAT-UIN: random uint32 -> decimal -> base64
|
||||
let uin = rand::random::<u32>();
|
||||
let uin_b64 = base64::engine::general_purpose::STANDARD.encode(uin.to_string());
|
||||
headers.insert(
|
||||
"X-WECHAT-UIN",
|
||||
reqwest::header::HeaderValue::from_str(&uin_b64).unwrap(),
|
||||
);
|
||||
|
||||
headers
|
||||
}
|
||||
|
||||
fn auth_headers(token: &str) -> reqwest::header::HeaderMap {
|
||||
let mut headers = Self::common_headers();
|
||||
if !token.is_empty() {
|
||||
headers.insert(
|
||||
reqwest::header::AUTHORIZATION,
|
||||
reqwest::header::HeaderValue::from_str(&format!("Bearer {}", token)).unwrap(),
|
||||
);
|
||||
headers.insert(
|
||||
"AuthorizationType",
|
||||
reqwest::header::HeaderValue::from_static("ilink_bot_token"),
|
||||
);
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
async fn post_json(
|
||||
&self,
|
||||
url: &str,
|
||||
body: &impl serde::Serialize,
|
||||
token: Option<&str>,
|
||||
) -> Result<reqwest::Response, String> {
|
||||
let body_str =
|
||||
serde_json::to_string(body).map_err(|e| format!("序列化请求体失败: {}", e))?;
|
||||
|
||||
debug!("POST {} body_len={}", url, body_str.len());
|
||||
|
||||
let mut headers = if let Some(t) = token {
|
||||
Self::auth_headers(t)
|
||||
} else {
|
||||
Self::common_headers()
|
||||
};
|
||||
|
||||
// 设置 Content-Length
|
||||
headers.insert(
|
||||
"Content-Length",
|
||||
reqwest::header::HeaderValue::from_str(&body_str.len().to_string()).unwrap(),
|
||||
);
|
||||
|
||||
self.http
|
||||
.post(url)
|
||||
.headers(headers)
|
||||
.body(body_str)
|
||||
.send()
|
||||
.await
|
||||
.and_then(|r| r.error_for_status())
|
||||
.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
format!("请求超时: {}", url)
|
||||
} else {
|
||||
format!("请求失败 ({}): {}", url, e)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! ## 微信 iLink Bot 通道
|
||||
//!
|
||||
//! 封装与微信 iLink Bot API 的所有通信:
|
||||
//!
|
||||
//! - `client` — HTTP 客户端(登录、长轮询收消息、发消息、生命周期管理)
|
||||
//! - `types` — API 协议类型定义(消息结构、请求/响应体)
|
||||
//!
|
||||
//! ### 核心流程
|
||||
//! 1. `login()` — 扫码登录,获取 token + account_id
|
||||
//! 2. `notify_start()` — 注册监听器
|
||||
//! 3. `receive_messages()` — 长轮询接收消息
|
||||
//! 4. `send_text()` — 发送文本回复
|
||||
//! 5. `notify_stop()` — 注销监听器
|
||||
|
||||
pub mod client;
|
||||
pub mod types;
|
||||
@@ -0,0 +1,330 @@
|
||||
//! ## 微信 iLink Bot API 协议类型
|
||||
//!
|
||||
//! 定义了与微信 iLink Bot API 通信的全部数据结构:
|
||||
//!
|
||||
//! - `BaseInfo` — 公共请求元数据
|
||||
//! - `WeixinMessage` — 微信消息结构(支持 text/image/voice/file/video)
|
||||
//! - `MessageItem` — 消息条目(5 种类型)
|
||||
//! - `GetUpdatesReq/Resp` — 长轮询收消息的请求/响应
|
||||
//! - `SendMessageReq` — 发送消息请求
|
||||
//! - `QRCodeResponse` / `StatusResponse` — 扫码登录相关
|
||||
//! - `LoginResult` / `MessageEvent` — 业务层结果类型
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// ─── 基础类型 ───
|
||||
|
||||
/// 公共请求元数据
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub struct BaseInfo {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub channel_version: Option<String>,
|
||||
}
|
||||
|
||||
impl BaseInfo {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
channel_version: Some(env!("CARGO_PKG_VERSION").to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 消息类型 ───
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TextItem {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CDNMedia {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub encrypt_query_param: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub aes_key: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub encrypt_type: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub full_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ImageItem {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub media: Option<CDNMedia>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thumb_media: Option<CDNMedia>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub aeskey: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub mid_size: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thumb_size: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thumb_height: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thumb_width: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub hd_size: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VoiceItem {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub media: Option<CDNMedia>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub encode_type: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bits_per_sample: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sample_rate: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub playtime: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FileItem {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub media: Option<CDNMedia>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub file_name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub md5: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub len: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VideoItem {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub media: Option<CDNMedia>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub video_size: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub play_length: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub video_md5: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thumb_media: Option<CDNMedia>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thumb_size: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thumb_height: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thumb_width: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RefMessage {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub message_item: Option<Box<MessageItem>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub title: Option<String>,
|
||||
}
|
||||
|
||||
/// ## 消息条目 —— 消息的具体内容
|
||||
///
|
||||
/// 支持 5 种消息类型:text(1), image(2), voice(3), file(4), video(5)。
|
||||
/// 每种类型有对应的 `*_item` 字段,其他字段保持 None。
|
||||
///
|
||||
/// `text()` 便捷方法用于快速构造文本消息(发送消息时使用)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct MessageItem {
|
||||
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
|
||||
pub item_type: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub create_time_ms: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub update_time_ms: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_completed: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub msg_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ref_msg: Option<Box<RefMessage>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub text_item: Option<TextItem>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub image_item: Option<ImageItem>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub voice_item: Option<VoiceItem>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub file_item: Option<FileItem>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub video_item: Option<VideoItem>,
|
||||
}
|
||||
|
||||
impl MessageItem {
|
||||
pub const TYPE_TEXT: i32 = 1;
|
||||
#[allow(dead_code)]
|
||||
pub const TYPE_IMAGE: i32 = 2;
|
||||
#[allow(dead_code)]
|
||||
pub const TYPE_VOICE: i32 = 3;
|
||||
#[allow(dead_code)]
|
||||
pub const TYPE_FILE: i32 = 4;
|
||||
#[allow(dead_code)]
|
||||
pub const TYPE_VIDEO: i32 = 5;
|
||||
|
||||
pub fn text(text: &str) -> Self {
|
||||
Self {
|
||||
item_type: Some(Self::TYPE_TEXT),
|
||||
text_item: Some(TextItem {
|
||||
text: Some(text.to_string()),
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ## 微信消息结构
|
||||
///
|
||||
/// 对应 iLink API 返回的单个消息。所有字段都是 Option 的,
|
||||
/// 因为不同消息类型携带不同字段。
|
||||
///
|
||||
/// ### 关键字段
|
||||
/// * `msg_type` — 消息类型:1=用户消息(TYPE_USER), 2=机器人消息(TYPE_BOT)
|
||||
/// * `from_user_id` — 发送者微信 ID
|
||||
/// * `to_user_id` — 接收者微信 ID
|
||||
/// * `item_list` — 消息内容列表(支持 text/image/voice/file/video)
|
||||
/// * `context_token` — 微信上下文令牌(用于多轮对话的上下文恢复)
|
||||
/// * `group_id` — 群聊 ID(群消息时非空)
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct WeixinMessage {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub seq: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub message_id: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub from_user_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub to_user_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub client_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub create_time_ms: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub update_time_ms: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub delete_time_ms: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub session_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub group_id: Option<String>,
|
||||
#[serde(rename = "message_type", skip_serializing_if = "Option::is_none")]
|
||||
pub msg_type: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub message_state: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub item_list: Option<Vec<MessageItem>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub context_token: Option<String>,
|
||||
}
|
||||
|
||||
impl WeixinMessage {
|
||||
#[allow(dead_code)]
|
||||
pub const TYPE_NONE: i32 = 0;
|
||||
pub const TYPE_USER: i32 = 1;
|
||||
pub const TYPE_BOT: i32 = 2;
|
||||
|
||||
/// 获取文本内容(如果有纯文本 item)
|
||||
pub fn text_content(&self) -> Option<&str> {
|
||||
self.item_list
|
||||
.as_ref()?
|
||||
.iter()
|
||||
.find(|item| item.item_type == Some(MessageItem::TYPE_TEXT))
|
||||
.and_then(|item| item.text_item.as_ref())
|
||||
.and_then(|t| t.text.as_deref())
|
||||
}
|
||||
}
|
||||
|
||||
// ─── API 请求/响应 ───
|
||||
|
||||
/// 获取二维码响应
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct QRCodeResponse {
|
||||
pub qrcode: String,
|
||||
pub qrcode_img_content: String,
|
||||
}
|
||||
|
||||
/// 扫码状态响应
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct StatusResponse {
|
||||
pub status: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bot_token: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ilink_bot_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub baseurl: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ilink_user_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub redirect_host: Option<String>,
|
||||
}
|
||||
|
||||
/// GetUpdates 请求
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct GetUpdatesReq {
|
||||
pub get_updates_buf: String,
|
||||
pub base_info: BaseInfo,
|
||||
}
|
||||
|
||||
/// GetUpdates 响应
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct GetUpdatesResp {
|
||||
#[serde(default)]
|
||||
pub ret: i32,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub errcode: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub errmsg: Option<String>,
|
||||
#[serde(default)]
|
||||
pub msgs: Vec<WeixinMessage>,
|
||||
#[serde(default)]
|
||||
pub get_updates_buf: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[allow(dead_code)]
|
||||
pub longpolling_timeout_ms: Option<i64>,
|
||||
}
|
||||
|
||||
/// SendMessage 请求
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SendMessageReq {
|
||||
pub msg: WeixinMessage,
|
||||
}
|
||||
|
||||
/// NotifyStart/NotifyStop 响应
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct NotifyResp {
|
||||
#[serde(default)]
|
||||
pub ret: i32,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub errmsg: Option<String>,
|
||||
}
|
||||
|
||||
/// 登录结果
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LoginResult {
|
||||
pub token: String,
|
||||
pub account_id: String,
|
||||
pub base_url: String,
|
||||
#[allow(dead_code)]
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
/// 收到的消息事件
|
||||
#[derive(Debug, Clone)]
|
||||
#[allow(dead_code)]
|
||||
pub struct MessageEvent {
|
||||
pub from_user_id: String,
|
||||
pub text: String,
|
||||
pub context_token: Option<String>,
|
||||
pub message_id: i64,
|
||||
}
|
||||
Reference in New Issue
Block a user