feat: iPet → iAs 完整迁移,Rust 版微信 AI 助手
Phase 1 ✅ CLI 框架 + 配置系统 - clap 子命令: login / listen / send / whoami / usage - config.json + env var 替换 - tracing 日志系统 - state 持久化(auth/runtime 文件存 + PostgreSQL) Phase 2 ✅ 微信通道 - wechat::client — 完整 iLink Bot HTTP API 实现 - 扫码登录(终端二维码 + 轮询状态) - 长轮询 getupdates / 消息收发 / 监听注册 Phase 3 ✅ AI 对话(纯文本 + function calling) - LlmProvider trait: DeepSeek + LM Studio 实现 - SSE 流式解析(text / reasoning / tool_calls delta / usage) - Conversation: 消息历史 + chat / chat_with_tools 工具循环 Phase 4 ✅ PostgreSQL 集成 - app_state(认证 KV 存储) - chat_records(消息收发记录) - llm_usage(Token 用量统计缓存命中率) - user_memories(长期记忆持久化) - pending_approvals(审批确认码) - scheduled_tasks(定时任务表) Phase 5 ✅ 一切皆 Skill(工具系统) - SkillRegistry: 系统 + 用户 skills 双目录合并 - SKILL.md 解析器 + 子进程执行器(stdin JSON → stdout) - 9 个系统 Skills: datetime / weather / search / email / shell / schedule / memos / read_memories / read_summaries - ApprovalManager: High 风险技能 → 确认码审批(透明模式) - High 风险技能:确认码审批(透明模式) Phase 6 ✅ 定时任务调度器 上下文管理 - ChatSession: checkpoint + token budget (28K) + summaries - Token 估算器(中英文自适应) - 12h 空闲 → trigger_idle_summary(不入会话) - Budget 溢出 → trigger_overflow_summary(入会话 + drain 旧消息) - Summarizer: LLM 生成自然语言摘要(fallback 简单截断) - 长期记忆 / 摘要 通过 read_memories / read_summaries 工具按需读取 工具调用日志 + Token 统计 - INFO: 工具名 + 参数 + 结果摘要 - DEBUG: 子进程 exit/stdout/stderr - ias usage --since --until --model 查看用量和缓存命中率
This commit is contained in:
@@ -0,0 +1,436 @@
|
||||
use crate::wechat::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 客户端
|
||||
#[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 地址
|
||||
const DEFAULT_BASE_URL: &'static str = "https://ilinkai.weixin.qq.com";
|
||||
/// 二维码固定 API 地址
|
||||
const FIXED_BASE_URL: &'static str = "https://ilinkai.weixin.qq.com";
|
||||
/// 版本号编码:0x00MMNNPP
|
||||
const CLIENT_VERSION: u32 = 0x000100_00; // 1.0.0
|
||||
|
||||
pub fn new(base_url: Option<String>) -> Self {
|
||||
let base = base_url.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())),
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 公共方法 ───
|
||||
|
||||
/// 获取登录二维码链接
|
||||
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))
|
||||
}
|
||||
|
||||
/// 轮询扫码状态
|
||||
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!("轮询二维码状态网络错误: {},继续等待", 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!("开始微信扫码登录...");
|
||||
|
||||
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.to_string();
|
||||
|
||||
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!("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!("✅ 登录成功! bot_id={}", account_id);
|
||||
return Ok(LoginResult {
|
||||
token,
|
||||
account_id,
|
||||
base_url,
|
||||
user_id,
|
||||
});
|
||||
}
|
||||
"expired" => {
|
||||
return Err("二维码已过期".to_string());
|
||||
}
|
||||
_ => {
|
||||
warn!("未知状态: {}", 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))?;
|
||||
|
||||
info!("监听器已注册");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 注销监听器
|
||||
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!("监听器已注销");
|
||||
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) => resp.json().await.map_err(|e| format!("解析 getUpdates 响应失败: {}", e))?,
|
||||
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(&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() {
|
||||
// 只更新 base_url 如果传入了非空值
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取当前 token(用于持久化)
|
||||
pub async fn get_token(&self) -> String {
|
||||
self.token.lock().await.clone()
|
||||
}
|
||||
|
||||
/// 获取当前 account_id(用于持久化)
|
||||
pub async fn get_account_id(&self) -> String {
|
||||
self.account_id.lock().await.clone()
|
||||
}
|
||||
|
||||
/// 获取当前 updates_buf(用于持久化)
|
||||
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();
|
||||
}
|
||||
|
||||
// ─── 内部方法 ───
|
||||
|
||||
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
|
||||
.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
format!("请求超时: {}", url)
|
||||
} else {
|
||||
format!("请求失败 ({}): {}", url, e)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod client;
|
||||
pub mod types;
|
||||
@@ -0,0 +1,333 @@
|
||||
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>,
|
||||
}
|
||||
|
||||
/// 消息条目(支持 text/image/voice/file/video)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
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;
|
||||
pub const TYPE_IMAGE: i32 = 2;
|
||||
pub const TYPE_VOICE: i32 = 3;
|
||||
pub const TYPE_FILE: i32 = 4;
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for MessageItem {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
item_type: None,
|
||||
create_time_ms: None,
|
||||
update_time_ms: None,
|
||||
is_completed: None,
|
||||
msg_id: None,
|
||||
ref_msg: None,
|
||||
text_item: None,
|
||||
image_item: None,
|
||||
voice_item: None,
|
||||
file_item: None,
|
||||
video_item: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 微信消息 ───
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
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 Default for WeixinMessage {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
seq: None,
|
||||
message_id: None,
|
||||
from_user_id: None,
|
||||
to_user_id: None,
|
||||
client_id: None,
|
||||
create_time_ms: None,
|
||||
update_time_ms: None,
|
||||
delete_time_ms: None,
|
||||
session_id: None,
|
||||
group_id: None,
|
||||
msg_type: None,
|
||||
message_state: None,
|
||||
item_list: None,
|
||||
context_token: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WeixinMessage {
|
||||
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")]
|
||||
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,
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
/// 收到的消息事件
|
||||
#[derive(Debug, Clone)]
|
||||
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