This commit is contained in:
shenjack 2024-06-28 23:19:10 +08:00
parent 4b1ed03b9a
commit 17f3a36540
Signed by: shenjack
GPG Key ID: 7B1134A979775551
8 changed files with 52 additions and 18 deletions

2
Cargo.lock generated
View File

@ -659,7 +659,7 @@ dependencies = [
[[package]]
name = "ica-rs"
version = "0.6.8"
version = "0.6.9"
dependencies = [
"anyhow",
"base64 0.22.1",

View File

@ -1,6 +1,6 @@
[package]
name = "ica-rs"
version = "0.6.8"
version = "0.6.9"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -1,6 +1,6 @@
# Python 兼容版本 3.8+
from typing import Callable, Tuple, NewType, TYPE_CHECKING, TypeVar, Optional, Union
from typing import Callable, Tuple, NewType, Optional, Union
"""
ica.rs
@ -236,13 +236,12 @@ class TailchatSendingMessage:
"""
self.content = content
return self
# def set_img(self, file: bytes, file_type: str, as_sticker: bool):
# """
# 设置消息的图片
# @param file: 图片文件 (实际上是 vec<u8>)
# @param file_type: 图片类型 (MIME) (image/png; image/jpeg)
# @param as_sticker: 是否作为贴纸发送
# """
def set_img(self, file: bytes, file_name: str):
"""
设置消息的图片
@param file: 图片文件 (实际上是 vec<u8>)
@param file_name: 图片名称 (just_img.png)
"""
class TailchatClient:

View File

@ -1,4 +1,7 @@
from typing import TYPE_CHECKING, TypeVar
import platform
import PIL.Image
import io
if TYPE_CHECKING:
from ica_typing import IcaNewMessage, IcaClient
@ -22,3 +25,12 @@ def on_tailchat_message(msg: TailchatReciveMessage, client: TailchatClient) -> N
if msg.content == "/bot":
reply = msg.reply_with(f"tailchat-async-rs({client.version})-sync-py {client.tailchat_version}")
client.send_message(reply)
elif msg.content == "/image":
image = PIL.Image.new("RGB", (100, 100), (255, 255, 255))
img_cache = io.BytesIO()
image.save(img_cache, format="JPEG")
raw_img = img_cache.getvalue()
img_cache.close()
reply = msg.reply_with("Here is an image")
reply.set_img(raw_img, "just_img.png")
client.send_message(reply)

View File

@ -1,3 +1,4 @@
pub mod api;
pub mod messages;
pub mod status;

View File

@ -0,0 +1,8 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct FileUpload {
pub etag: String,
pub path: String,
pub url: String,
}

View File

@ -114,7 +114,17 @@ impl SendingFile {
_ => "".to_string(),
}
}
pub fn gen_markdown(&self, response_data: JsonValue) {}
pub fn gen_markdown(&self, backend_path: &str) -> String {
match self {
Self::Image { .. } => {
format!("[img]{}[/img]", backend_path)
}
Self::File { name, .. } => {
format!("[card type=file url={}]{}[/card]", backend_path, name)
}
_ => unreachable!(),
}
}
}
#[derive(Debug, Clone, Serialize)]

View File

@ -10,15 +10,14 @@ use tracing::{event, span, Level};
pub async fn send_message(client: &Client, message: &SendingMessage) -> bool {
let span = span!(Level::INFO, "tailchat send message");
let _enter = span.enter();
let mut value: Value = message.as_value();
if message.contain_file() {
// 处理文件
let mut header = reqwest::header::HeaderMap::new();
header
.insert(
"X-Token",
crate::MainStatus::global_tailchat_status().jwt_token.clone().parse().unwrap(),
)
.unwrap();
header.append(
"X-Token",
crate::MainStatus::global_tailchat_status().jwt_token.clone().parse().unwrap(),
);
let file_client = match reqwest::ClientBuilder::new().default_headers(header).build() {
Ok(client) => client,
Err(e) => {
@ -73,8 +72,13 @@ pub async fn send_message(client: &Client, message: &SendingMessage) -> bool {
}
};
event!(Level::INFO, "file upload success with data:{}", format!("{:#?}", data).cyan());
let content = format!(
"{}\n{}",
message.content,
message.file.gen_markdown(data["url"].as_str().unwrap())
);
value["content"] = json!(content);
}
let value: Value = message.as_value();
match client.emit("chat.message.sendMessage", value).await {
Ok(_) => {
event!(Level::DEBUG, "send message {}", format!("{:#?}", message).cyan());