噫,好,成了

This commit is contained in:
shenjack 2024-02-22 12:47:20 +08:00
parent e5fde06837
commit bbaf8cf0c9
Signed by: shenjack
GPG Key ID: 7B1134A979775551
7 changed files with 101 additions and 52 deletions

View File

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

View File

@ -44,11 +44,25 @@ class SendMessage:
class NewMessage: class NewMessage:
def reply_with(self, message: str) -> SendMessage: def reply_with(self, message: str) -> SendMessage:
... ...
def __str__(self) -> str:
...
@property
def content(self) -> str:
...
@property
def sender_id(self) -> int:
...
@property
def is_from_self(self) -> bool:
...
class IcaClient: class IcaClient:
@staticmethod @staticmethod
async def send_message(client: "IcaClient", message: SendMessage) -> bool: async def send_message_a(client: "IcaClient", message: SendMessage) -> bool:
...
def send_message(self, message: SendMessage) -> bool:
... ...

View File

@ -0,0 +1,20 @@
from typing import TYPE_CHECKING, TypeVar
if TYPE_CHECKING:
from ica_typing import NewMessage, IcaClient
else:
NewMessage = TypeVar("NewMessage")
IcaClient = TypeVar("IcaClient")
_version_ = "0.1.0"
def on_message(msg: NewMessage, client: IcaClient) -> None:
# print(msg)
# reply = msg.reply_with("Hello, world!")
# print(reply)
# print(msg.content)
# print(msg.is_from_self)
if not msg.is_from_self:
if msg.content == "/bot-rs-py":
reply = msg.reply_with(f"ica-async-rs-sync-py {_version_}")
client.send_message(reply)

View File

@ -31,15 +31,15 @@ pub async fn add_message(payload: Payload, client: Client) {
if let Some(value) = values.first() { if let Some(value) = values.first() {
let message = NewMessage::new_from_json(value); let message = NewMessage::new_from_json(value);
info!("add_message {}", format!("{:#?}", message).cyan()); info!("add_message {}", format!("{:#?}", message).cyan());
if message.is_reply() { // if message.is_reply() {
return; // return;
} // }
if message.is_from_self() { // if message.is_from_self() {
return; // return;
} // }
// 就在这里处理掉最基本的消息 // 就在这里处理掉最基本的消息
// 之后的处理交给插件 // 之后的处理交给插件
if message.content.eq("/bot-rs") { if message.content.eq("/bot-rs") && !message.is_from_self() && !message.is_reply() {
let reply = message.reply_with(&format!("ica-async-rs pong v{}", VERSION)); let reply = message.reply_with(&format!("ica-async-rs pong v{}", VERSION));
send_message(&client, &reply).await; send_message(&client, &reply).await;
} }

View File

@ -1,5 +1,6 @@
use pyo3::prelude::*; use pyo3::prelude::*;
use rust_socketio::asynchronous::Client; use rust_socketio::asynchronous::Client;
use tokio::runtime::Runtime;
use crate::client::send_message; use crate::client::send_message;
use crate::data_struct::messages::{NewMessage, ReplyMessage, SendMessage}; use crate::data_struct::messages::{NewMessage, ReplyMessage, SendMessage};
@ -120,6 +121,23 @@ impl NewMessagePy {
pub fn reply_with(&self, content: String) -> SendMessagePy { pub fn reply_with(&self, content: String) -> SendMessagePy {
SendMessagePy::new(self.msg.reply_with(&content)) SendMessagePy::new(self.msg.reply_with(&content))
} }
pub fn __str__(&self) -> String {
format!("{:?}", self.msg)
}
#[getter]
pub fn get_content(&self) -> String {
self.msg.content.clone()
}
#[getter]
pub fn get_sender_id(&self) -> i64 {
self.msg.sender_id
}
#[getter]
pub fn get_is_from_self(&self) -> bool {
self.msg.is_from_self()
}
} }
impl NewMessagePy { impl NewMessagePy {
@ -134,6 +152,13 @@ pub struct ReplyMessagePy {
pub msg: ReplyMessage, pub msg: ReplyMessage,
} }
#[pymethods]
impl ReplyMessagePy {
pub fn __str__(&self) -> String {
format!("{:?}", self.msg)
}
}
impl ReplyMessagePy { impl ReplyMessagePy {
pub fn new(msg: ReplyMessage) -> Self { pub fn new(msg: ReplyMessage) -> Self {
Self { msg } Self { msg }
@ -147,6 +172,13 @@ pub struct SendMessagePy {
pub msg: SendMessage, pub msg: SendMessage,
} }
#[pymethods]
impl SendMessagePy {
pub fn __str__(&self) -> String {
format!("{:?}", self.msg)
}
}
impl SendMessagePy { impl SendMessagePy {
pub fn new(msg: SendMessage) -> Self { pub fn new(msg: SendMessage) -> Self {
Self { msg } Self { msg }
@ -173,8 +205,17 @@ impl IcaClientPy {
// // }); // // });
// // Ok(future.await) // // Ok(future.await)
// } // }
pub fn send_message(&self, message: SendMessagePy) -> bool {
// let handle = tokio::runtime::Handle::current();
// handle.block_on(send_message(&self.client, &message.msg))
tokio::task::block_in_place(|| {
let rt = Runtime::new().unwrap();
rt.block_on(send_message(&self.client, &message.msg))
})
}
#[staticmethod] #[staticmethod]
pub fn send_message( pub fn send_message_a(
py: Python, py: Python,
client: IcaClientPy, client: IcaClientPy,
message: SendMessagePy, message: SendMessagePy,

View File

@ -10,8 +10,6 @@ use tracing::{debug, info, warn};
use crate::config::IcaConfig; use crate::config::IcaConfig;
use crate::data_struct::messages::NewMessage; use crate::data_struct::messages::NewMessage;
use self::class::{IcaClientPy, NewMessagePy};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct PyStatus { pub struct PyStatus {
pub files: Option<HashMap<PathBuf, (Option<SystemTime>, Py<PyAny>)>>, pub files: Option<HashMap<PathBuf, (Option<SystemTime>, Py<PyAny>)>>,
@ -149,55 +147,23 @@ pub fn init_py(config: &IcaConfig) {
info!("python inited") info!("python inited")
} }
// #[pyfunction]
// pub fn call_new_message(py: Python, func: PyA,msg: NewMessagePy, client: IcaClientPy) -> PyResult<&PyAny> {
// pyo3_asyncio::tokio::future_into_py(py, async move {
// let py_sleep = Python::with_gil(|py| {
// pyo3_asyncio::tokio::into_future(
// // py.import("asyncio")?.call_method1("sleep", (1,))?
// )
// })?;
// py_sleep.await?;
// Ok(Python::with_gil(|py| py.None()))
// })
// }
/// 执行 new message 的 python 插件 /// 执行 new message 的 python 插件
pub async fn new_message_py(message: &NewMessage, client: &Client) { pub async fn new_message_py(message: &NewMessage, client: &Client) {
let cwd = std::env::current_dir().unwrap();
let plugins = PyStatus::get_files(); let plugins = PyStatus::get_files();
for (_, (_, py_module)) in plugins.iter() { for (path, (_, py_module)) in plugins.iter() {
// 切换工作目录到运行的插件的位置
if let Err(e) = std::env::set_current_dir(path.parent().unwrap()) {
warn!("failed to set current dir: {:?}", e);
}
Python::with_gil(|py| { Python::with_gil(|py| {
let msg = class::NewMessagePy::new(message); let msg = class::NewMessagePy::new(message);
let client = class::IcaClientPy::new(client); let client = class::IcaClientPy::new(client);
let args = (("message", msg), ("client", client)); let args = (msg, client);
// py.run("message.reply_with('')", None, Some(locals))
// .unwrap();
let async_py_func = py_module.getattr(py, "on_message"); let async_py_func = py_module.getattr(py, "on_message");
match async_py_func { match async_py_func {
Ok(async_py_func) => { Ok(async_py_func) => {
// pyo3_asyncio::tokio::future_into_py(py, async move { async_py_func.as_ref(py).call1(args).unwrap();
// let call = pyo3_asyncio::tokio::into_future({
// async_py_func.call1(py, args)
// })
// .unwrap();
// Ok(call.await?)
// });
let future = pyo3_asyncio::tokio::into_future(
async_py_func.as_ref(py).call1(args).unwrap(),
)
.unwrap();
tokio::spawn(async move {
match future.await {
Ok(_) => {
info!("python 插件执行成功");
}
Err(e) => {
warn!("python 插件执行失败: {:?}", e);
}
}
});
} }
Err(e) => { Err(e) => {
warn!("failed to get on_message function: {:?}", e); warn!("failed to get on_message function: {:?}", e);
@ -205,4 +171,8 @@ pub async fn new_message_py(message: &NewMessage, client: &Client) {
} }
}); });
} }
// 最后切换回来
if let Err(e) = std::env::set_current_dir(cwd) {
warn!("failed to set current dir: {:?}", e);
}
} }

View File

@ -1,5 +1,9 @@
# 更新日志 # 更新日志
## 0.4.3
噫! 好! 我成了!
## 0.4.2 ## 0.4.2
现在是 async 版本啦! 现在是 async 版本啦!