又是一大堆更新

This commit is contained in:
shenjack 2024-02-18 22:43:54 +08:00
parent dffe101223
commit 877402fcd9
Signed by: shenjack
GPG Key ID: 7B1134A979775551
10 changed files with 103 additions and 24 deletions

View File

@ -13,6 +13,7 @@ rust_socketio = "0.4.4"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
chrono = "0.4.34"
toml = "0.8.10"
colored = "2.1.0"

View File

@ -3,6 +3,7 @@ use crate::config::IcaConfig;
use ed25519_dalek::{Signature, Signer, SigningKey};
use rust_socketio::{Payload, RawClient};
use serde_json::Value;
use tracing::debug;
pub struct IcalinguaSinger {
pub host: String,
@ -40,7 +41,7 @@ impl IcalinguaSinger {
.expect("Payload should be Json data");
let (auth_key, version) = (&require_data[0], &require_data[1]);
println!("auth_key: {:?}, version: {:?}", auth_key, version);
debug!("auth_key: {:?}, version: {:?}", auth_key, version);
let auth_key = match &require_data.get(0) {
Some(Value::String(auth_key)) => Some(auth_key),
_ => None,

View File

@ -4,6 +4,7 @@ use std::fs;
use serde::Deserialize;
use toml;
/// Icalingua bot 的配置
#[derive(Debug, Deserialize)]
pub struct IcaConfig {
/// icalingua 私钥

View File

@ -1 +1,2 @@
pub mod online_data;
pub mod new_message;

View File

@ -0,0 +1,73 @@
use chrono::NaiveDateTime;
use serde_json::Value as JsonValue;
use tracing::warn;
/// {"message":{"_id":"QCa04gA4ZRAABa7T9QljGGXSFjYB","anonymousId":null,"anonymousflag":null,"bubble_id":0,"content":"test","date":"2024/02/18","files":[],"role":"admin","senderId":3695888,"subid":1,"time":1708267062000,"timestamp":"22:37:42","title":"索引管理员","username":"shenjack"},"roomId":-1076278498}
/// {"message":{"_id":"poke-1708267065000-1076278498-3695888","content":"摆烂振荡中继戳了戳shenjack的书问老师啥时候上课","date":"2024/02/18","files":[],"senderId":3286043682,"system":true,"time":1708267065000,"timestamp":"22:37:45","username":""},"roomId":-1076278498}
#[derive(Debug, Clone)]
pub struct NewMessage {
/// 发送者 id
pub sender_id: i64,
/// 房间 id
pub roomd_id: i64,
/// 发送者名字
pub sender_name: String,
/// 消息 id
pub msg_id: String,
/// 消息时间
pub time: NaiveDateTime,
/// 消息时间戳
pub timestamp: String,
/// 身份
pub role: String,
/// 消息内容
pub content: String,
/// 消息标题
pub title: String,
/// 原始消息
pub raw: JsonValue,
}
impl NewMessage {
pub fn new_from_json(json: &JsonValue) -> Self {
let message = json.get("message").unwrap();
let sender_id = message.get("senderId").unwrap().as_i64().unwrap();
let roomd_id = json.get("roomId").unwrap().as_i64().unwrap();
let sender_name = message.get("username").unwrap().as_str().unwrap().to_string();
let msg_id = message.get("_id").unwrap().as_str().unwrap().to_string();
let time = message.get("date").unwrap().as_str().unwrap();
let timestamp = message.get("timestamp").unwrap().as_str().unwrap().to_string();
let role = message.get("role").unwrap().as_str().unwrap().to_string();
let content = message.get("content").unwrap().as_str().unwrap().to_string();
let title = message.get("title").unwrap().as_str().unwrap().to_string();
let raw = json.clone();
Self {
sender_id,
roomd_id,
sender_name,
msg_id,
time: NaiveDateTime::parse_from_str(time, "%Y/%m/%d").unwrap(),
timestamp,
role,
content,
title,
raw,
}
}
}
#[cfg(test)]
mod test {
use serde_json::json;
use super::*;
#[test]
fn test_new_from_json() {
let value = json!({"message": {"_id":"QCa04gA4ZRAABa7T9QljGGXSFjYB","anonymousId":null,"anonymousflag":null,"bubble_id":0,"content":"test","date":"2024/02/18","files":[],"role":"admin","senderId":3695888,"subid":1,"time":1708267062000,"timestamp":"22:37:42","title":"索引管理员","username":"shenjack"},"roomId":-1076278498});
}
}

View File

@ -14,13 +14,26 @@ pub fn get_online_data(payload: Payload, _client: RawClient) {
}
}
pub fn add_message(payload: Payload, _client: RawClient) {
if let Payload::Text(values) = payload {
if let Some(value) = values.first() {
info!("add_message {}", value);
}
}
}
pub fn any_event(event: Event, payload: Payload, _client: RawClient) {
let handled = vec![
// 真正处理过的
"authSucceed",
"authFailed",
"authRequired",
"requireAuth",
"onlineData",
"addMessage",
// 忽略的
"notify",
"updateRoom",
];
match &event {
Event::Custom(event_name) => {
@ -48,9 +61,6 @@ pub fn connect_callback(payload: Payload, _client: RawClient) {
match payload {
Payload::Text(values) => {
if let Some(value) = values.first() {
// if let Some("authSucceed") = value.as_str() {
// println!("{}", "已经登录到 icalingua!".green());
// }
match value.as_str() {
Some("authSucceed") => {
py::run();

View File

@ -9,7 +9,6 @@ mod events;
mod py;
fn ws_main() {
py::init_py();
// 从命令行获取 host 和 key
// 从命令行获取配置文件路径
@ -19,12 +18,12 @@ fn ws_main() {
let socket = ClientBuilder::new(ica_singer.host.clone())
.transport_type(rust_socketio::TransportType::Websocket)
.on_any(events::any_event)
.on("onlineData", events::get_online_data)
.on("message", events::connect_callback)
.on("requireAuth", move |a, b| ica_singer.sign_callback(a, b))
.on("authRequired", events::connect_callback)
.on("authSucceed", events::connect_callback)
.on("authFailed", events::connect_callback)
.on("onlineData", events::get_online_data)
.on("addMessage", events::add_message)
.connect()
.expect("Connection failed");
@ -37,5 +36,6 @@ fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
py::init_py();
ws_main();
}

View File

@ -1,5 +1,4 @@
// use inline_python::{python, Context};
use tracing::{info, debug};
use pyo3::{prelude::*, types::IntoPyDict};
#[pyclass]
@ -16,12 +15,7 @@ pub fn run() {
}
pub fn init_py() {
debug!("initing python threads");
pyo3::prepare_freethreaded_python();
info!("python inited")
}
// pub fn run() {
// let con: Context = python! {
// print("Hello, world!");
// };
// }

View File

@ -1,2 +0,0 @@
def yw():
return "🚧 TODO"

View File

@ -6,7 +6,7 @@ from lib_not_dr.loggers import config
from main import BOTCONFIG, _version_
from data_struct import SendMessage, ReplyMessage, NewMessage
from plugins import bmcl, yw, safe_eval
from plugins import bmcl, safe_eval
logger = config.get_logger("router")
@ -23,8 +23,9 @@ async def route(data, sio):
reply_msg = SendMessage(content="", room_id=room_id, reply_to=ReplyMessage(id=msg_id))
if content == "/bot":
message = reply_msg.to_content(f"icalingua bot pong v{_version_}")
message = reply_msg.to_content(f"icalingua bot-python pong v{_version_}")
await sio.emit("sendMessage", message.to_json())
elif content.startswith("=="):
evals: str = content[2:]
@ -44,6 +45,7 @@ async def route(data, sio):
await asyncio.sleep(random.random() * 2)
await sio.emit("sendMessage", message.to_json())
elif content == "!!jrrp":
randomer = random.Random(
f'{sender_id}-{data["message"]["date"]}-jrrp-{_version_}'
@ -53,10 +55,8 @@ async def route(data, sio):
message = reply_msg.to_content(f"{sender_name} 今日人品为 {result}")
await asyncio.sleep(0.5)
await sio.emit("sendMessage", message.to_json())
elif content == "/bmcl":
await bmcl.bmcl(sio, reply_msg, msg)
# elif content == "/yw":
# message = yw.yw()
# await asyncio.sleep(random.random() * 2)
# await sio.emit("sendMessage", message.to_json())