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,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