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
);
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("发送消息到企业微信群失败");
response
.json::<SendMsgResp>()
.await
.expect("解析WeChatWebhookResponse失败")
}
pub async fn upfile(&self, file_path: &str, file_type: &str) -> UploadFileResp {
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();
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解析上传文件返回的信息失败")
}
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
}
}