feat: 模块统一 ias- 前缀、独立版本与内网地址支持 (0.1.7)
- 所有 Rust crate 统一加 ias- 前缀:ai → ias-ai、common → ias-common、context → ias-context、mail → ias-mail、service → ias-service、wechat → ias-wechat - 新增 ias-main 模块承载 CLI 入口和二进制打包 - 各模块开始独立维护版本号,ias-main 0.1.7 代表整体版本 - 新增 IA_WEB_INTERNAL_URL 环境变量,版本通知同时发送公网和内网链接 - 将已有升级日志翻译为中文 - ias_upgrade_logs 新增 modules JSONB 字段 - 新增 VERSION 文件和 CHANGELOG.md - 新增 AGENTS.md 项目规则文件
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "ias-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,399 @@
|
||||
# wechat 模块使用文档
|
||||
|
||||
`wechat` 是微信 iLink Bot API 的 Rust 封装,提供两层能力:
|
||||
|
||||
- `WeChatClient`:单账号客户端,负责扫码登录、恢复登录态、注册监听器、长轮询收消息、发送文本消息。
|
||||
- `WeChatMultiAccountManager`:多账号运行时管理器,按账号启动多个独立长轮询任务,并通过事件队列把消息交给业务层。
|
||||
|
||||
设计原则:**一个 `WeChatClient` 只代表一个微信 Bot 账号;多账号监听就是每个账号一个独立长轮询任务**。这样可以保证 `token`、`base_url`、`get_updates_buf` 和 `context_token` 不串账号。
|
||||
|
||||
## 模块结构
|
||||
|
||||
```text
|
||||
wechat/
|
||||
src/
|
||||
lib.rs # 模块导出
|
||||
client.rs # 单账号 WeChatClient
|
||||
manager.rs # 多账号 WeChatMultiAccountManager
|
||||
types.rs # iLink Bot API 协议类型
|
||||
```
|
||||
|
||||
公开模块:
|
||||
|
||||
```rust
|
||||
pub mod client;
|
||||
pub mod manager;
|
||||
pub mod types;
|
||||
```
|
||||
|
||||
常用导入:
|
||||
|
||||
```rust
|
||||
use wechat::client::WeChatClient;
|
||||
use wechat::manager::{WeChatAccountConfig, WeChatEvent, WeChatMultiAccountManager};
|
||||
use wechat::types::{MessageItem, WeixinMessage};
|
||||
```
|
||||
|
||||
## Cargo 引用
|
||||
|
||||
workspace 内其他 crate 使用:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
wechat = { path = "../wechat" }
|
||||
```
|
||||
|
||||
## 环境变量
|
||||
|
||||
| 变量 | 必填 | 默认值 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `WEIXIN_BASE_URL` | 否 | `https://ilinkai.weixin.qq.com` | iLink Bot API 地址。显式传入 `base_url` 时优先使用显式值。 |
|
||||
|
||||
## 单账号使用
|
||||
|
||||
单账号生命周期:
|
||||
|
||||
```text
|
||||
WeChatClient::new
|
||||
login 或 set_auth
|
||||
set_updates_buf
|
||||
notify_start
|
||||
receive_messages loop
|
||||
send_text
|
||||
notify_stop
|
||||
```
|
||||
|
||||
### 扫码登录
|
||||
|
||||
```rust
|
||||
use wechat::client::WeChatClient;
|
||||
|
||||
#[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);
|
||||
println!("base_url={}", login.base_url);
|
||||
|
||||
// 业务层需要持久化:
|
||||
// login.token
|
||||
// login.account_id
|
||||
// login.base_url
|
||||
// login.user_id
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
### 恢复登录态并收消息
|
||||
|
||||
```rust
|
||||
use std::time::Duration;
|
||||
|
||||
use wechat::client::WeChatClient;
|
||||
use wechat::types::WeixinMessage;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), String> {
|
||||
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?;
|
||||
|
||||
loop {
|
||||
let updates = client.receive_messages().await?;
|
||||
let latest_buf = client.get_updates_buf().await;
|
||||
|
||||
// 建议每次成功 receive 后持久化 latest_buf。
|
||||
persist_updates_buf(&latest_buf).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;
|
||||
}
|
||||
}
|
||||
|
||||
async fn persist_updates_buf(_buf: &str) {}
|
||||
```
|
||||
|
||||
## 多账号监听
|
||||
|
||||
多账号监听使用 `WeChatMultiAccountManager`。它会为每个账号创建一个独立 `WeChatClient` 和一个独立 tokio 任务:
|
||||
|
||||
```text
|
||||
account A -> WeChatClient A -> getupdates(token A, buf A)
|
||||
account B -> WeChatClient B -> getupdates(token B, buf B)
|
||||
account C -> WeChatClient C -> getupdates(token C, buf C)
|
||||
```
|
||||
|
||||
这不是短轮询刷接口,而是长轮询。单次 `getupdates` 请求通常会被服务端挂起到有消息或超时,因此多个账号对应多个挂起请求是预期模型。
|
||||
|
||||
### 账号配置
|
||||
|
||||
```rust
|
||||
use wechat::manager::WeChatAccountConfig;
|
||||
|
||||
let account = WeChatAccountConfig::new(
|
||||
"account_id",
|
||||
"token",
|
||||
"base_url",
|
||||
"get_updates_buf",
|
||||
);
|
||||
```
|
||||
|
||||
字段说明:
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| `account_id` | 微信 iLink Bot 账号 ID,来自登录返回的 `LoginResult.account_id`。 |
|
||||
| `token` | 登录返回的 `LoginResult.token`。 |
|
||||
| `base_url` | 登录返回的 `LoginResult.base_url`。 |
|
||||
| `updates_buf` | 上次轮询保存的 `get_updates_buf`,新账号可传空字符串。 |
|
||||
|
||||
### 启动多个账号
|
||||
|
||||
```rust
|
||||
use wechat::manager::{WeChatAccountConfig, WeChatEvent, WeChatMultiAccountManager};
|
||||
use wechat::types::WeixinMessage;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), String> {
|
||||
let (mut manager, mut event_rx) = WeChatMultiAccountManager::new(1024);
|
||||
|
||||
let accounts = load_accounts().await;
|
||||
for account in accounts {
|
||||
manager.start_account(account).await?;
|
||||
}
|
||||
|
||||
while let Some(event) = event_rx.recv().await {
|
||||
match event {
|
||||
WeChatEvent::UpdatesBuf {
|
||||
account_id,
|
||||
updates_buf,
|
||||
} => {
|
||||
persist_updates_buf(&account_id, &updates_buf).await;
|
||||
}
|
||||
WeChatEvent::Message {
|
||||
account_id,
|
||||
message,
|
||||
updates_buf,
|
||||
} => {
|
||||
persist_updates_buf(&account_id, &updates_buf).await;
|
||||
|
||||
if message.msg_type != Some(WeixinMessage::TYPE_USER) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(from_user_id) = message.from_user_id.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
let Some(text) = message.text_content() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
manager
|
||||
.send_text(
|
||||
&account_id,
|
||||
from_user_id,
|
||||
&format!("账号 {account_id} 收到: {text}"),
|
||||
message.context_token.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
WeChatEvent::PollError { account_id, error } => {
|
||||
tracing::warn!("微信账号轮询失败 account_id={account_id}: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_accounts() -> Vec<WeChatAccountConfig> {
|
||||
vec![]
|
||||
}
|
||||
|
||||
async fn persist_updates_buf(_account_id: &str, _buf: &str) {}
|
||||
```
|
||||
|
||||
### 停止账号
|
||||
|
||||
停止单个账号:
|
||||
|
||||
```rust
|
||||
manager.stop_account("account_id").await?;
|
||||
```
|
||||
|
||||
停止全部账号:
|
||||
|
||||
```rust
|
||||
let results = manager.stop_all().await;
|
||||
for (account_id, result) in results {
|
||||
if let Err(err) = result {
|
||||
tracing::warn!("停止微信账号失败 account_id={account_id}: {err}");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`stop_account` 会先中止本地轮询任务,再尽力调用 `notify_stop()`。如果进程直接退出,`Drop` 会 abort 本地任务,但无法异步调用 `notify_stop()`,所以生产环境建议在收到退出信号时显式调用 `stop_all()`。
|
||||
|
||||
## 为什么不能一个轮询监听多个账号
|
||||
|
||||
iLink Bot 的 `getupdates` 是按 `Authorization: Bearer <token>` 鉴权的。一个 token 只对应一个 Bot 账号,服务端不会在同一个请求里返回其他账号的消息。
|
||||
|
||||
必须隔离的账号状态:
|
||||
|
||||
| 状态 | 为什么必须隔离 |
|
||||
| --- | --- |
|
||||
| `token` | 决定当前请求属于哪个账号。 |
|
||||
| `base_url` | 登录可能返回账号实际使用的 IDC 地址。 |
|
||||
| `get_updates_buf` | 轮询游标,混用会导致消息重复、丢失或串账号。 |
|
||||
| `context_token` | 回复上下文,混用会导致回复到错误会话或上下文断裂。 |
|
||||
|
||||
因此多账号正确模型是“多个长轮询任务”,不是“一个共享轮询”。
|
||||
|
||||
## 持久化建议
|
||||
|
||||
本 crate 不绑定数据库或文件系统,业务层应自行持久化以下数据。
|
||||
|
||||
账号表建议字段:
|
||||
|
||||
```text
|
||||
account_id string primary key
|
||||
token string
|
||||
base_url string
|
||||
user_id string optional
|
||||
updates_buf string
|
||||
updated_at timestamp
|
||||
```
|
||||
|
||||
收到 `WeChatEvent::Message` 后,使用事件里的 `updates_buf` 更新对应账号的游标。
|
||||
|
||||
如果要支持主动发送消息,建议额外维护:
|
||||
|
||||
```text
|
||||
account_id
|
||||
from_user_id
|
||||
context_token
|
||||
updated_at
|
||||
```
|
||||
|
||||
收到用户消息时按 `account_id + from_user_id` 保存 `context_token`。主动发送时优先显式传 `account_id`,再取对应用户最近的 `context_token`。
|
||||
|
||||
## 发送消息路由
|
||||
|
||||
多账号场景下发送消息必须明确使用哪个账号:
|
||||
|
||||
```rust
|
||||
manager
|
||||
.send_text(
|
||||
"account_id",
|
||||
"to_user_id",
|
||||
"回复内容",
|
||||
Some("context_token"),
|
||||
)
|
||||
.await?;
|
||||
```
|
||||
|
||||
不建议只按 `to_user_id` 自动推断账号。原因是同一个用户可能和多个 Bot 账号都有会话,自动推断会产生歧义。
|
||||
|
||||
## API 端点
|
||||
|
||||
当前封装使用以下 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` | 发送消息 |
|
||||
|
||||
登录后请求会带:
|
||||
|
||||
```text
|
||||
Authorization: Bearer <token>
|
||||
AuthorizationType: ilink_bot_token
|
||||
```
|
||||
|
||||
## 错误处理
|
||||
|
||||
| 场景 | 当前行为 | 建议 |
|
||||
| --- | --- | --- |
|
||||
| 二维码过期 | `login()` 返回 `二维码已过期` | 重新登录。 |
|
||||
| 登录超时 | `login()` 返回 `登录超时` | 增大超时或重新登录。 |
|
||||
| 长轮询超时 | `receive_messages()` 返回空消息 | 正常情况,继续轮询。 |
|
||||
| 游标更新 | manager 发送 `WeChatEvent::UpdatesBuf` | 立即持久化对应账号的 `updates_buf`。 |
|
||||
| 轮询错误 | manager 发送 `WeChatEvent::PollError` 并继续重试 | 记录日志,必要时触发重新登录。 |
|
||||
| token 失效 | API 返回错误或 HTTP 鉴权失败 | 清理该账号 token,重新扫码登录。 |
|
||||
| 多账号重复启动 | `start_account()` 返回错误 | 保证同一 `account_id` 只启动一次。 |
|
||||
|
||||
## 日志
|
||||
|
||||
模块使用 `tracing`,主要 target:
|
||||
|
||||
```text
|
||||
ias::auth
|
||||
```
|
||||
|
||||
推荐初始化:
|
||||
|
||||
```rust
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter("info,ias::auth=debug")
|
||||
.init();
|
||||
```
|
||||
|
||||
## 当前限制
|
||||
|
||||
- `send_text()` 只封装文本发送。
|
||||
- manager 不内置账号持久化,业务层负责数据库或文件存储。
|
||||
- manager 通过 `JoinHandle::abort()` 停止长轮询任务;如需立即优雅取消 HTTP 请求,可后续在 client 层增加 cancellation 支持。
|
||||
- `ILINK_APP_ID` 当前为空字符串;如果接入方要求 app id,需要在 `client.rs` 中配置或改为环境变量。
|
||||
|
||||
## 排障清单
|
||||
|
||||
1. 确认 `base_url` 可访问。
|
||||
2. 确认账号已经扫码登录并保存了 token。
|
||||
3. 每个账号只启动一个监听任务。
|
||||
4. 每个账号独立保存 `updates_buf`。
|
||||
5. 登录或恢复后先调用 `notify_start()`,再开始 `getupdates`。
|
||||
6. 发送消息时显式指定 `account_id`,并尽量透传 `context_token`。
|
||||
7. 打开 `ias::auth=debug` 查看请求和轮询状态。
|
||||
@@ -0,0 +1,562 @@
|
||||
//! ## 微信 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 = 0x0001_0000; // 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();
|
||||
self.send_text_with_client_id(to, text, context_token, &client_id)
|
||||
.await
|
||||
}
|
||||
|
||||
/// 发送“输入中”状态,返回用于最终完成消息的 client_id。
|
||||
pub async fn send_typing(
|
||||
&self,
|
||||
to: &str,
|
||||
context_token: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
let client_id = uuid::Uuid::new_v4().to_string();
|
||||
self.send_typing_with_client_id(to, context_token, &client_id)
|
||||
.await?;
|
||||
Ok(client_id.to_string())
|
||||
}
|
||||
|
||||
/// 用已有 client_id 刷新“输入中”状态。
|
||||
pub async fn send_typing_with_client_id(
|
||||
&self,
|
||||
to: &str,
|
||||
context_token: Option<&str>,
|
||||
client_id: &str,
|
||||
) -> Result<String, String> {
|
||||
self.send_bot_message(
|
||||
to,
|
||||
client_id,
|
||||
WeixinMessage::STATE_TYPING,
|
||||
None,
|
||||
context_token,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// 使用已有 client_id 完成文本消息。
|
||||
pub async fn send_text_with_client_id(
|
||||
&self,
|
||||
to: &str,
|
||||
text: &str,
|
||||
context_token: Option<&str>,
|
||||
client_id: &str,
|
||||
) -> Result<String, String> {
|
||||
self.send_bot_message(
|
||||
to,
|
||||
client_id,
|
||||
WeixinMessage::STATE_FINISH,
|
||||
Some(vec![MessageItem::text(text)]),
|
||||
context_token,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn send_bot_message(
|
||||
&self,
|
||||
to: &str,
|
||||
client_id: &str,
|
||||
message_state: i32,
|
||||
item_list: Option<Vec<MessageItem>>,
|
||||
context_token: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
let msg = WeixinMessage {
|
||||
from_user_id: Some(String::new()),
|
||||
to_user_id: Some(to.to_string()),
|
||||
client_id: Some(client_id.to_string()),
|
||||
msg_type: Some(WeixinMessage::TYPE_BOT),
|
||||
message_state: Some(message_state),
|
||||
item_list,
|
||||
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.to_string())
|
||||
}
|
||||
|
||||
/// 设置 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,18 @@
|
||||
//! ## 微信 iLink Bot 通道
|
||||
//!
|
||||
//! 封装与微信 iLink Bot API 的所有通信:
|
||||
//!
|
||||
//! - `client` — HTTP 客户端(登录、长轮询收消息、发消息、生命周期管理)
|
||||
//! - `manager` — 多账号监听管理器(每账号一个独立长轮询任务)
|
||||
//! - `types` — API 协议类型定义(消息结构、请求/响应体)
|
||||
//!
|
||||
//! ### 核心流程
|
||||
//! 1. `login()` — 扫码登录,获取 token + account_id
|
||||
//! 2. `notify_start()` — 注册监听器
|
||||
//! 3. `receive_messages()` — 长轮询接收消息
|
||||
//! 4. `send_text()` — 发送文本回复
|
||||
//! 5. `notify_stop()` — 注销监听器
|
||||
|
||||
pub mod client;
|
||||
pub mod manager;
|
||||
pub mod types;
|
||||
@@ -0,0 +1,295 @@
|
||||
//! ## 微信多账号监听管理器
|
||||
//!
|
||||
//! `WeChatClient` 表示一个账号的一条 iLink Bot 连接;本模块在其上提供
|
||||
//! 多账号运行时管理:每个账号独立 token、base_url、get_updates_buf 和轮询任务。
|
||||
|
||||
use crate::client::WeChatClient;
|
||||
use crate::types::WeixinMessage;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
use tracing::{info, warn};
|
||||
|
||||
/// 单个微信账号的恢复配置。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WeChatAccountConfig {
|
||||
pub account_id: String,
|
||||
pub token: String,
|
||||
pub base_url: String,
|
||||
pub updates_buf: String,
|
||||
}
|
||||
|
||||
impl WeChatAccountConfig {
|
||||
pub fn new(
|
||||
account_id: impl Into<String>,
|
||||
token: impl Into<String>,
|
||||
base_url: impl Into<String>,
|
||||
updates_buf: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
account_id: account_id.into(),
|
||||
token: token.into(),
|
||||
base_url: base_url.into(),
|
||||
updates_buf: updates_buf.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 多账号监听事件。
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum WeChatEvent {
|
||||
/// 账号游标已更新。即使本轮没有消息,业务层也应持久化该值。
|
||||
UpdatesBuf {
|
||||
account_id: String,
|
||||
updates_buf: String,
|
||||
},
|
||||
/// 收到一条微信消息。
|
||||
Message {
|
||||
account_id: String,
|
||||
message: Box<WeixinMessage>,
|
||||
updates_buf: String,
|
||||
},
|
||||
/// 某个账号的轮询发生错误。管理器会继续重试,除非任务被停止。
|
||||
PollError { account_id: String, error: String },
|
||||
}
|
||||
|
||||
struct AccountRuntime {
|
||||
client: WeChatClient,
|
||||
task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
/// 多账号监听管理器。
|
||||
///
|
||||
/// 设计约束:
|
||||
/// - 一个 `WeChatClient` 只代表一个账号。
|
||||
/// - 一个账号对应一个长轮询任务。
|
||||
/// - `get_updates_buf` 由账号独立维护,不能跨账号共享。
|
||||
pub struct WeChatMultiAccountManager {
|
||||
accounts: HashMap<String, AccountRuntime>,
|
||||
event_tx: mpsc::Sender<WeChatEvent>,
|
||||
poll_idle_sleep: Duration,
|
||||
error_retry_sleep: Duration,
|
||||
}
|
||||
|
||||
impl WeChatMultiAccountManager {
|
||||
/// 创建管理器并返回事件接收端。
|
||||
pub fn new(event_buffer: usize) -> (Self, mpsc::Receiver<WeChatEvent>) {
|
||||
let (event_tx, event_rx) = mpsc::channel(event_buffer.max(1));
|
||||
(
|
||||
Self {
|
||||
accounts: HashMap::new(),
|
||||
event_tx,
|
||||
poll_idle_sleep: Duration::from_secs(1),
|
||||
error_retry_sleep: Duration::from_secs(3),
|
||||
},
|
||||
event_rx,
|
||||
)
|
||||
}
|
||||
|
||||
/// 设置空轮询后的休眠时间。
|
||||
pub fn with_poll_idle_sleep(mut self, duration: Duration) -> Self {
|
||||
self.poll_idle_sleep = duration;
|
||||
self
|
||||
}
|
||||
|
||||
/// 设置轮询错误后的重试间隔。
|
||||
pub fn with_error_retry_sleep(mut self, duration: Duration) -> Self {
|
||||
self.error_retry_sleep = duration;
|
||||
self
|
||||
}
|
||||
|
||||
/// 启动一个账号的监听任务。
|
||||
///
|
||||
/// 如果同名账号已启动,返回错误,避免两个任务竞争同一个账号游标。
|
||||
pub async fn start_account(&mut self, config: WeChatAccountConfig) -> Result<(), String> {
|
||||
if self.accounts.contains_key(&config.account_id) {
|
||||
return Err(format!("微信账号已启动: {}", config.account_id));
|
||||
}
|
||||
|
||||
let mut client = WeChatClient::new(Some(config.base_url.clone()));
|
||||
client
|
||||
.set_auth(&config.token, &config.account_id, &config.base_url)
|
||||
.await;
|
||||
client.set_updates_buf(&config.updates_buf).await;
|
||||
client.notify_start().await?;
|
||||
|
||||
let account_id = config.account_id.clone();
|
||||
let loop_client = client.clone();
|
||||
let event_tx = self.event_tx.clone();
|
||||
let poll_idle_sleep = self.poll_idle_sleep;
|
||||
let error_retry_sleep = self.error_retry_sleep;
|
||||
|
||||
let task = tokio::spawn(async move {
|
||||
info!(target: "ias::auth", "微信账号监听已启动: {}", account_id);
|
||||
|
||||
loop {
|
||||
match loop_client.receive_messages().await {
|
||||
Ok(resp) => {
|
||||
let updates_buf = loop_client.get_updates_buf().await;
|
||||
if !updates_buf.is_empty() {
|
||||
let event = WeChatEvent::UpdatesBuf {
|
||||
account_id: account_id.clone(),
|
||||
updates_buf: updates_buf.clone(),
|
||||
};
|
||||
if event_tx.send(event).await.is_err() {
|
||||
warn!(
|
||||
target: "ias::auth",
|
||||
"微信事件接收端已关闭,停止账号监听: {}",
|
||||
account_id
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
for message in resp.msgs {
|
||||
let event = WeChatEvent::Message {
|
||||
account_id: account_id.clone(),
|
||||
message: Box::new(message),
|
||||
updates_buf: updates_buf.clone(),
|
||||
};
|
||||
if event_tx.send(event).await.is_err() {
|
||||
warn!(
|
||||
target: "ias::auth",
|
||||
"微信事件接收端已关闭,停止账号监听: {}",
|
||||
account_id
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
tokio::time::sleep(poll_idle_sleep).await;
|
||||
}
|
||||
Err(error) => {
|
||||
let event = WeChatEvent::PollError {
|
||||
account_id: account_id.clone(),
|
||||
error,
|
||||
};
|
||||
if event_tx.send(event).await.is_err() {
|
||||
warn!(
|
||||
target: "ias::auth",
|
||||
"微信事件接收端已关闭,停止账号监听: {}",
|
||||
account_id
|
||||
);
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(error_retry_sleep).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
self.accounts
|
||||
.insert(config.account_id, AccountRuntime { client, task });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 停止一个账号的监听任务,并尽力调用 notify_stop。
|
||||
pub async fn stop_account(&mut self, account_id: &str) -> Result<(), String> {
|
||||
let Some(runtime) = self.accounts.remove(account_id) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
runtime.task.abort();
|
||||
runtime.client.notify_stop().await
|
||||
}
|
||||
|
||||
/// 停止所有账号。
|
||||
pub async fn stop_all(&mut self) -> Vec<(String, Result<(), String>)> {
|
||||
let account_ids = self.account_ids();
|
||||
let mut results = Vec::with_capacity(account_ids.len());
|
||||
for account_id in account_ids {
|
||||
let result = self.stop_account(&account_id).await;
|
||||
results.push((account_id, result));
|
||||
}
|
||||
results
|
||||
}
|
||||
|
||||
/// 返回当前已启动的账号 ID。
|
||||
pub fn account_ids(&self) -> Vec<String> {
|
||||
self.accounts.keys().cloned().collect()
|
||||
}
|
||||
|
||||
/// 判断账号是否正在监听。
|
||||
pub fn is_running(&self, account_id: &str) -> bool {
|
||||
self.accounts.contains_key(account_id)
|
||||
}
|
||||
|
||||
/// 使用指定账号发送文本消息。
|
||||
pub async fn send_text(
|
||||
&self,
|
||||
account_id: &str,
|
||||
to: &str,
|
||||
text: &str,
|
||||
context_token: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
let runtime = self
|
||||
.accounts
|
||||
.get(account_id)
|
||||
.ok_or_else(|| format!("微信账号未启动: {}", account_id))?;
|
||||
|
||||
runtime.client.send_text(to, text, context_token).await
|
||||
}
|
||||
|
||||
/// 使用指定账号发送输入中状态,返回后续完成消息复用的 client_id。
|
||||
pub async fn send_typing(
|
||||
&self,
|
||||
account_id: &str,
|
||||
to: &str,
|
||||
context_token: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
let runtime = self
|
||||
.accounts
|
||||
.get(account_id)
|
||||
.ok_or_else(|| format!("微信账号未启动: {}", account_id))?;
|
||||
|
||||
runtime.client.send_typing(to, context_token).await
|
||||
}
|
||||
|
||||
/// 使用指定账号刷新输入中状态。
|
||||
pub async fn send_typing_with_client_id(
|
||||
&self,
|
||||
account_id: &str,
|
||||
to: &str,
|
||||
context_token: Option<&str>,
|
||||
client_id: &str,
|
||||
) -> Result<String, String> {
|
||||
let runtime = self
|
||||
.accounts
|
||||
.get(account_id)
|
||||
.ok_or_else(|| format!("微信账号未启动: {}", account_id))?;
|
||||
|
||||
runtime
|
||||
.client
|
||||
.send_typing_with_client_id(to, context_token, client_id)
|
||||
.await
|
||||
}
|
||||
|
||||
/// 使用指定账号完成已有输入中消息。
|
||||
pub async fn send_text_with_client_id(
|
||||
&self,
|
||||
account_id: &str,
|
||||
to: &str,
|
||||
text: &str,
|
||||
context_token: Option<&str>,
|
||||
client_id: &str,
|
||||
) -> Result<String, String> {
|
||||
let runtime = self
|
||||
.accounts
|
||||
.get(account_id)
|
||||
.ok_or_else(|| format!("微信账号未启动: {}", account_id))?;
|
||||
|
||||
runtime
|
||||
.client
|
||||
.send_text_with_client_id(to, text, context_token, client_id)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WeChatMultiAccountManager {
|
||||
fn drop(&mut self) {
|
||||
for runtime in self.accounts.values() {
|
||||
runtime.task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
//! ## 微信 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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BaseInfo {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 消息类型 ───
|
||||
|
||||
#[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;
|
||||
pub const STATE_TYPING: i32 = 1;
|
||||
pub const STATE_FINISH: 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