fache 0.1.351

发车工具箱
Documentation
use crate::wework::group::mtype::*;
use reqwest::{Client, multipart};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::time::Duration;
#[derive(PartialEq, Serialize, Deserialize, Debug, Clone)]
pub struct Group {
    pub key: String,
}
impl Group {
    pub async fn send<T: Serialize + std::fmt::Debug>(&self, msg: T) -> SendMsgResp {
        let webhook_url = format!(
            "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}",
            &self.key
        );
        // 构建带超时的HTTP客户端
        let client = Client::builder()
            .timeout(Duration::from_secs(30))
            .build()
            .expect("发送消息到企业微信群失败");
        let response = client
            .post(webhook_url)
            .header("Content-Type", "application/json")
            .json(&msg)
            .send()
            .await
            .expect("发送消息到企业微信群失败");
        // println!("{:?}发送消息到企业微信群: \n", response);

        response
            .json::<SendMsgResp>()
            .await
            .expect("解析WeChatWebhookResponse失败")
    }
    /// 上传文件到企业微信
    pub async fn upfile(&self, file_path: &str, file_type: &str) -> UploadFileResp {
        // 构建上传URL
        let upload_url = format!(
            "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={}&type={}",
            &self.key, file_type
        );
        // 读取文件内容
        let mut file = File::open(file_path).expect("打开文件失败");
        let mut file_content = Vec::new();
        file.read_to_end(&mut file_content).expect("读取文件失败");

        let file_name = Path::new(file_path)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("file.dat")
            .to_string();
        // 创建multipart表单数据
        let part = reqwest::multipart::Part::bytes(file_content)
            .file_name(file_name)
            .mime_str("application/octet-stream")
            .expect("读取文件流失败");
        let form = reqwest::multipart::Form::new().part("media", part);
        let client = Client::builder()
            .timeout(Duration::from_secs(60))
            .build()
            .expect("构建请求超时的设置失败");
        let response = client
            .post(upload_url)
            .multipart(form)
            .send()
            .await
            .expect("发送上传请求失败");

        response
            .json::<UploadFileResp>()
            .await
            .expect("wework解析上传文件返回的信息失败")
    }
    /// 发送文件消息
    ///
    /// # 参数
    /// - `media_id`: 通过upfile方法获取的media_id
    ///
    /// # 返回
    /// 消息发送结果
    pub async fn send_file(&self, media_id: &str) -> SendMsgResp {
        let message = WeWorkMsg::File {
            file: MediaIdContent {
                media_id: media_id.to_string(),
            },
        };
        self.send(message).await
    }
}