Skip to content

Commit

Permalink
修改文件结构
Browse files Browse the repository at this point in the history
  • Loading branch information
ExquisiteCore committed Dec 22, 2023
1 parent c33457d commit 5d1fe55
Show file tree
Hide file tree
Showing 11 changed files with 226 additions and 157 deletions.
7 changes: 7 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"rust-analyzer.linkedProjects": [
".\\Cargo.toml",
".\\Cargo.toml",
".\\Cargo.toml"
]
}
47 changes: 24 additions & 23 deletions src/bot.rs → src/bot/mod.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
use std::time::Duration;

use tokio_tungstenite::WebSocketStream;
use tokio::{net::TcpStream,time::sleep};
use tokio_tungstenite::tungstenite::protocol::Message;
use futures_util::StreamExt;
use tokio::{net::TcpStream, time::sleep};
use tokio_tungstenite::tungstenite::protocol::Message;
use tokio_tungstenite::WebSocketStream;
use url::Url;

// 连接 WebSocket
pub async fn connect(url: &str) -> WebSocketStream<TcpStream> {
// 解析 WebSocket URL
let server_url = Url::parse(url).expect("Failed to parse WebSocket URL");

// 获取主机地址和端口
let host = server_url.host_str().expect("No host found in the given URL");
let port = server_url.port_or_known_default().expect("No port found in the given URL");
let host = server_url
.host_str()
.expect("No host found in the given URL");
let port = server_url
.port_or_known_default()
.expect("No port found in the given URL");

// 构建主机地址字符串,包含端口
let host_with_port = format!("{}:{}", host, port);
Expand All @@ -33,23 +37,24 @@ pub struct Bot {
ws_stream: WebSocketStream<TcpStream>,
reconnecting: bool,
}
impl Bot {
pub async fn new(server_url: &str,wsport:i32) -> Self {

impl Bot {
// 创建 Bot 实例
pub async fn new(server_url: &str, wsport: i32) -> Self {
let ws_server_url = format!("ws://{}:{}", server_url, wsport);

let ws_stream = connect(&ws_server_url)
.await;
let ws_stream = connect(&ws_server_url).await;
Bot {
ws_server_url,
ws_stream,
reconnecting : false,
reconnecting: false,
}
}
//ws返回json数据
pub async fn receive_message(&mut self) -> Option<Result<Message, tokio_tungstenite::tungstenite::Error>> {
//self.ws_stream.next().await
loop{
// 接收 WebSocket 的消息
pub async fn receive_message(
&mut self,
) -> Option<Result<Message, tokio_tungstenite::tungstenite::Error>> {
loop {
match self.ws_stream.next().await {
Some(Ok(message)) => {
// 成功接收消息时,重置 reconnecting 字段
Expand All @@ -58,7 +63,6 @@ impl Bot {
}
Some(Err(err)) => {
eprintln!("Error receiving message: {:?}", err);

// 处理错误,例如可以尝试重新连接
println!("WebSocket连接已断开,尝试重新连接");
self.start_reconnect().await;
Expand All @@ -69,9 +73,9 @@ impl Bot {
self.start_reconnect().await;
}
}
}
}

}

// 关闭 WebSocket 连接
pub async fn close_websocket(&mut self) {
// 使用 WebSocketStream 的 close 方法,无需特定的 CloseFrame
Expand All @@ -80,21 +84,18 @@ impl Bot {
}
}

// 尝试重新连接
pub async fn start_reconnect(&mut self) {
// 防止同时进行多次重连
if !self.reconnecting {
self.reconnecting = true;

println!("尝试重新连接...");

// 重新连接前等待一段时间
sleep(Duration::from_secs(5)).await;

// 尝试重新连接
self.ws_stream = connect(&self.ws_server_url).await;

// 重置 reconnecting 字段
self.reconnecting = false;
}
}
}
}
29 changes: 21 additions & 8 deletions src/event/message.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use serde_json::Value;
pub fn process_message_event(json: &Value) {

pub async fn process_message_event(json: &Value, request: &crate::postrequest::Request) {
// 处理 message 类型的逻辑
// 提取消息类型和子类型
let message_type = json["message_type"].as_str().unwrap_or("未知消息类型");
Expand All @@ -9,14 +10,19 @@ pub fn process_message_event(json: &Value) {
match (message_type, sub_type) {
("private", "friend") => process_private_friend_message(json),
("group", "normal") => process_group_normal_message(json),
_ => println!("Unknown message_type or sub_type: {} - {}", message_type, sub_type),
_ => println!(
"Unknown message_type or sub_type: {} - {}",
message_type, sub_type
),
}
}

pub fn process_message_sent_event(json: &Value) {
pub async fn process_message_send_event(json: &Value, request: &crate::postrequest::Request) {
// 处理 message_sent 类型的逻辑
// 提取消息内容
let message_content = json["message"][0]["data"]["text"].as_str().unwrap_or_default();
let message_content = json["message"][0]["data"]["text"]
.as_str()
.unwrap_or_default();

// 提取发送者昵称
let sender_nickname = json["sender"]["nickname"].as_str().unwrap_or("未知用户");
Expand All @@ -27,7 +33,9 @@ pub fn process_message_sent_event(json: &Value) {
fn process_private_friend_message(json: &Value) {
// 提取私聊消息的发送者昵称和消息内容
let sender_nickname = json["sender"]["nickname"].as_str().unwrap_or("未知用户");
let message_content = json["message"][0]["data"]["text"].as_str().unwrap_or("未知消息内容");
let message_content = json["message"][0]["data"]["text"]
.as_str()
.unwrap_or("未知消息内容");

// 打印私聊消息信息
println!("{}发送了消息:{}", sender_nickname, message_content);
Expand All @@ -36,8 +44,13 @@ fn process_private_friend_message(json: &Value) {
fn process_group_normal_message(json: &Value) {
// 提取群消息的发送者群名片、昵称和消息内容
let sender_nickname = json["sender"]["nickname"].as_str().unwrap_or("未知用户");
let message_content = json["message"][0]["data"]["text"].as_str().unwrap_or("未知消息内容");
let message_content = json["message"][0]["data"]["text"]
.as_str()
.unwrap_or("未知消息内容");

// 打印群消息信息
println!("来自{}的{}发送了消息:{}", json["group_id"], sender_nickname, message_content);
}
println!(
"来自{}的{}发送了消息:{}",
json["group_id"], sender_nickname, message_content
);
}
17 changes: 14 additions & 3 deletions src/event/meta_event.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
use serde_json::Value;
pub fn process_meta_event(json: &Value) {

pub async fn process_meta_event(json: &Value, request: &crate::postrequest::Request) {
// 处理 meta_event 类型的逻辑
// 获取 meta_event_type 值
if let Some(meta_event_type) = json["meta_event_type"].as_str() {
match meta_event_type {
"lifecycle" => println!("生活周期"),
"lifecycle" => {
println!("生活周期");
match request.send_private_msg_api(&2977926714, "Bot启动").await {
Ok(text) => {
println!("post 返回{}", text);
}
Err(err) => {
eprintln!("Error sending HTTP request: {:?}", err);
}
}
}
"heartbeat" => println!("心跳一次"),
_ => println!("Unknown meta_event_type: {:?}", meta_event_type),
}
} else {
println!("Missing meta_event_type field in meta_event");
}
}
}
16 changes: 8 additions & 8 deletions src/event.rs → src/event/mod.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
mod message;
mod meta_event;
mod notice;
mod request;
mod meta_event;

use serde_json::Value;

pub fn process_json(json_str: &str) {
pub async fn process_message(json_str: &str, request: &crate::postrequest::Request) {
// 使用 serde_json 解析 JSON 字符串
let json: Value = serde_json::from_str(json_str).expect("Failed to parse JSON");

// 获取 post_type 值
let post_type = json["post_type"].as_str();
// 根据 post_type 值进行分类处理
match post_type {
Some("message") => message::process_message_event(&json),
Some("message_sent") => message::process_message_sent_event(&json),
Some("notice") => notice::process_notice_event(&json),
Some("request") => request::process_request_event(&json),
Some("meta_event") => meta_event::process_meta_event(&json),
Some("message") => message::process_message_event(&json, &&request).await,
Some("message_sent") => message::process_message_send_event(&json, &&request).await,
Some("notice") => notice::process_notice_event(&json, &&request).await,
Some("request") => request::process_request_event(&json, &&request).await,
Some("meta_event") => meta_event::process_meta_event(&json, &&request).await,
_ => println!("未知 post_type: {:?}", post_type),
}
}
}
23 changes: 15 additions & 8 deletions src/event/notice.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use serde_json::Value;

use crate::postrequest;
pub fn process_notice_event(json: &Value) {
pub async fn process_notice_event(json: &Value, request: &crate::postrequest::Request) {
// 处理 notice 类型的逻辑
// 提取 notice_type 值
if let Some(notice_type) = json["notice_type"].as_str() {
Expand Down Expand Up @@ -98,12 +97,20 @@ fn group_upload(json: &Value) {
);
}


fn private_upload(json: &Value) {
if let (Some(user_id), Some(sender), Some(private_file)) =
(json["user_id"].as_i64(), json["sender"].as_i64(), json["private_file"].as_object())
{
if let (Some(file_id), Some(file_name), Some(file_size), Some(file_url), Some(sub_id), Some(expire)) = (
if let (Some(user_id), Some(sender), Some(private_file)) = (
json["user_id"].as_i64(),
json["sender"].as_i64(),
json["private_file"].as_object(),
) {
if let (
Some(file_id),
Some(file_name),
Some(file_size),
Some(file_url),
Some(sub_id),
Some(expire),
) = (
private_file["id"].as_str(),
private_file["name"].as_str(),
private_file["size"].as_i64(),
Expand Down Expand Up @@ -253,4 +260,4 @@ fn process_title(json: &Value) {
}
fn print_error(json: &Value, message: &str) {
println!("事件处理失败,{}:\n{}", message, json);
}
}
5 changes: 3 additions & 2 deletions src/event/request.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use serde_json::Value;
pub fn process_request_event(json: &Value) {

pub async fn process_request_event(json: &Value, request: &crate::postrequest::Request) {
if let Some(request_type) = json["request_type"].as_str() {
match request_type {
"friend" => process_friend_request(json),
Expand Down Expand Up @@ -42,4 +43,4 @@ fn process_group_request(json: &Value) {
} else {
println!("群请求字段缺失或类型不匹配");
}
}
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod bot;
pub mod event;
pub mod postrequest;
43 changes: 23 additions & 20 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,32 @@
mod bot;
mod event;
mod postrequest;

use postrequest::Request;
use bot::Bot;
use q_bot::bot::Bot;
use q_bot::event::process_message;
use q_bot::postrequest::Request;
use tokio::signal::ctrl_c;
use tokio_tungstenite::tungstenite::Message;
use event::process_json;

#[tokio::main]
async fn main() {

let server_url = "192.168.1.8";
let request = Request::new(server_url, 5700).await;
let mut bot = Bot::new(server_url, 5800,).await;

let mut bot = Bot::new(server_url, 5800).await;

// match request.send_private_msg_api(&2977926714, "hello").await {
// Ok(text) => {
// println!("post 返回{}", text);
// }
// Err(err) => {
// eprintln!("Error sending HTTP request: {:?}", err);
// }
// }

match request.send_private_msg_api(&2977926714u32,"hello").await{
Ok(text) => {
println!("post 返回{}", text);
}
Err(err) => {
eprintln!("Error sending HTTP request: {:?}", err);
}
}
// match request.send_group_msg_api(&758145931, "hello").await {
// Ok(text) => {
// println!("post 返回{}", text);
// }
// Err(err) => {
// eprintln!("Error sending HTTP request: {:?}", err);
// }
// }

let mut exit_flag = false;

Expand All @@ -40,7 +43,7 @@ async fn main() {
Some(Ok(message)) => {
if let Message::Text(text) = message {
let json = text;
process_json(&json);
process_message(&json,&&request).await;
}
}
Some(Err(err)) => {
Expand All @@ -51,7 +54,7 @@ async fn main() {
}
}
} => {},

};

if exit_flag {
Expand Down
Loading

0 comments on commit 5d1fe55

Please sign in to comment.