Compare commits

..

No commits in common. "18df7d1a89ad8721d3968f00e5159c39039d4a76" and "4b1ed03b9af3ff9326647d47c94bb1ff1c0fe6fc" have entirely different histories.

10 changed files with 24 additions and 108 deletions

2
Cargo.lock generated
View File

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

Binary file not shown.

View File

@ -1,6 +1,6 @@
[package]
name = "ica-rs"
version = "0.6.9"
version = "0.6.8"
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, Optional, Union
from typing import Callable, Tuple, NewType, TYPE_CHECKING, TypeVar, Optional, Union
"""
ica.rs
@ -236,12 +236,13 @@ class TailchatSendingMessage:
"""
self.content = content
return self
def set_img(self, file: bytes, file_name: str):
"""
设置消息的图片
@param file: 图片文件 (实际上是 vec<u8>)
@param file_name: 图片名称 (just_img.png)
"""
# 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: 是否作为贴纸发送
# """
class TailchatClient:

View File

@ -1,8 +1,4 @@
import io
import psutil
import platform
from typing import TYPE_CHECKING, TypeVar
from PIL import (Image, ImageDraw, ImageFont)
if TYPE_CHECKING:
from ica_typing import IcaNewMessage, IcaClient
@ -13,59 +9,16 @@ else:
TailchatReciveMessage = TypeVar("TailchatReciveMessage")
TailchatClient = TypeVar("TailchatClient")
# 生成一张本地信息图
def local_env_info() -> str:
cache = io.StringIO()
# 参考 DR 的 (crash report)
cache.write(f"系统: {platform.platform()}\n")
# 处理器
try:
cache.write("|".join([f"{x}%" for x in psutil.cpu_percent(interval=1, percpu=True)]))
cache.write("\n")
except OSError:
cache.write("CPU: 未知\n")
# Python 版本信息
cache.write(f"{platform.python_implementation()}: {platform.python_version()}-{platform.python_branch()}({platform.python_compiler()})\n")
# 内存信息
try:
memory = psutil.virtual_memory()
cache.write(f"内存: {memory.free / 1024 / 1024 / 1024:.3f}GB/{memory.total / 1024 / 1024 / 1024:.3f}GB\n")
except OSError:
cache.write("内存: 未知\n")
return cache.getvalue()
def local_env_image() -> bytes:
img = Image.new("RGB", (800, 140), (255, 255, 255))
# 往图片上写入一些信息
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("./SMILEYSANS-OBLIQUE.TTF", size=25)
draw.text((10, 10), local_env_info(), fill=(0, 0, 0), font=font)
img_cache = io.BytesIO()
img.save(img_cache, format="PNG")
raw_img = img_cache.getvalue()
img_cache.close()
return raw_img
def on_ica_message(msg: IcaNewMessage, client: IcaClient) -> None:
if not (msg.is_from_self or msg.is_reply):
if msg.content == "/bot":
reply = msg.reply_with(f"ica-async-rs({client.version})-sync-py {client.ica_version}")
client.send_message(reply)
elif msg.content == "/bot-sys":
datas = local_env_info()
reply = msg.reply_with(datas)
reply.set_img(local_env_image(), "image/png", False)
client.send_message(reply)
def on_tailchat_message(msg: TailchatReciveMessage, client: TailchatClient) -> None:
if not (msg.is_reply or msg.is_from_self):
# if not (msg.is_from_self or msg.is_reply):
if not (msg.is_reply):
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 == "/bot-sys":
datas = local_env_info()
reply = msg.reply_with(datas)
reply.set_img(local_env_image(), "just_img.png")
client.send_message(reply)

View File

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

View File

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

View File

@ -114,17 +114,7 @@ impl SendingFile {
_ => "".to_string(),
}
}
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!(),
}
}
pub fn gen_markdown(&self, response_data: JsonValue) {}
}
#[derive(Debug, Clone, Serialize)]

View File

@ -100,29 +100,13 @@ macro_rules! call_py_func {
tokio::spawn(async move {
Python::with_gil(|py| {
if let Ok(py_func) = get_func($plugin.py_module.bind(py), $func_name) {
if let Err(py_err) = py_func.call1($args) {
if let Err(e) = py_func.call1($args) {
let e = PyPluginError::FuncCallError(
py_err,
e,
$func_name.to_string(),
$plugin_path.to_string_lossy().to_string(),
);
event!(
Level::WARN,
"failed to call function<{}>: {}\ntraceback: {}",
$func_name,
e,
// 获取 traceback
match &e {
PyPluginError::FuncCallError(py_err, _, _) => match py_err.traceback_bound(py) {
Some(traceback) => match traceback.format() {
Ok(trace) => trace,
Err(trace_e) => format!("failed to format traceback: {:?}", trace_e),
},
None => "no traceback".to_string(),
},
_ => unreachable!(),
}
);
event!(Level::WARN, "failed to call function<{}>: {:?}", $func_name, e);
}
}
})

View File

@ -10,14 +10,15 @@ 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.append(
header
.insert(
"X-Token",
crate::MainStatus::global_tailchat_status().jwt_token.clone().parse().unwrap(),
);
)
.unwrap();
let file_client = match reqwest::ClientBuilder::new().default_headers(header).build() {
Ok(client) => client,
Err(e) => {
@ -71,13 +72,9 @@ pub async fn send_message(client: &Client, message: &SendingMessage) -> bool {
return false;
}
};
let content = format!(
"{}{}",
message.content,
message.file.gen_markdown(data["url"].as_str().unwrap())
);
value["content"] = json!(content);
event!(Level::INFO, "file upload success with data:{}", format!("{:#?}", data).cyan());
}
let value: Value = message.as_value();
match client.emit("chat.message.sendMessage", value).await {
Ok(_) => {
event!(Level::DEBUG, "send message {}", format!("{:#?}", message).cyan());