From e2869fb8a2d72960a88ea8378bfdc4313dd21dfd Mon Sep 17 00:00:00 2001 From: Byte Dice Date: Fri, 7 Feb 2025 21:16:33 +0100 Subject: [PATCH] Made them communicate but somehow broke "hello" messages --- Cargo.toml | 2 + src/bk_week_cmds.rs | 4 +- src/cmds.rs | 3 ++ src/main.rs | 7 +++- src/python/main.py | 8 ++++ src/python/py_websocket.py | 20 +++++++++ src/python/websocket.py | 0 src/websocket.rs | 83 ++++++++++++++++++++++++++++++++++++++ 8 files changed, 125 insertions(+), 2 deletions(-) create mode 100644 src/python/py_websocket.py delete mode 100644 src/python/websocket.py diff --git a/Cargo.toml b/Cargo.toml index fd2c47d..5b6175f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,8 +6,10 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +futures = "0.3.31" poise = "0.6.1" pyo3 = "0.23.4" rand = "0.9.0" serde_json = "1.0.138" tokio = { version = "1.43.0", features = ["rt-multi-thread"] } +tokio-tungstenite = "0.26.1" diff --git a/src/bk_week_cmds.rs b/src/bk_week_cmds.rs index 1737ce9..521900d 100644 --- a/src/bk_week_cmds.rs +++ b/src/bk_week_cmds.rs @@ -1,4 +1,4 @@ -use crate::{Context, Error}; +use crate::{rs_println, websocket, Context, Error}; use crate::messages::send_msg; use std::fs; @@ -23,6 +23,8 @@ pub async fn bk_week_get( ) -> Result<(), Error> { // log all posts in a thread + rs_println!("Sending hello to python..."); + websocket::send_msg("Hello from Rust!").await; return Ok(()); } diff --git a/src/cmds.rs b/src/cmds.rs index e900496..1fd2120 100644 --- a/src/cmds.rs +++ b/src/cmds.rs @@ -1,3 +1,5 @@ +use std::process; + use crate::{Context, Error}; use crate::messages::{send_embed, send_msg, edit_msg, EmbedOptions}; @@ -33,6 +35,7 @@ pub async fn stop( send_msg(ctx, "Shutting down...".to_string(), true, true).await; ctx.serenity_context().set_presence(None, OnlineStatus::Invisible); ctx.framework().shard_manager.shutdown_all().await; + process::exit(0); } else if !is_creator { send_msg(ctx, "Failed to shut down: Invalid permissions.".to_string(), true, true).await; diff --git a/src/main.rs b/src/main.rs index 5c0b9a1..e99330f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,12 @@ +#![warn(unused_extern_crates)] + mod cmds; mod bk_week_cmds; mod events; mod messages; mod python; mod macros; +mod websocket; use std::env; use std::process; @@ -58,6 +61,7 @@ async fn main() { let rust = thread::spawn(move || { rt.block_on(async { + websocket::start(rust_args.clone()).await; start(rust_args).await; }); }); @@ -117,7 +121,8 @@ async fn gen_bot(data: Data) -> Client { cmds::eight_ball(), cmds::write_json(), //cmds::rule(), - bk_week_cmds::bk_week_help() + bk_week_cmds::bk_week_help(), + bk_week_cmds::bk_week_get() ], event_handler: events::event_handler, ..Default::default() diff --git a/src/python/main.py b/src/python/main.py index ea44e4d..f90b787 100644 --- a/src/python/main.py +++ b/src/python/main.py @@ -1,8 +1,10 @@ import sys +import asyncio from macros import * import bot as botPy import data +import py_websocket def main(): @@ -17,5 +19,11 @@ def main(): py_print("Reading data...") data.read_data(bot) + if "--py" not in bot.args: + py_print("Connecting to local websocket...") + asyncio.run(py_websocket.websocket_client()) + + py_websocket.send_message("[Connection test] Hello from Python!") + main() \ No newline at end of file diff --git a/src/python/py_websocket.py b/src/python/py_websocket.py new file mode 100644 index 0000000..0c6995f --- /dev/null +++ b/src/python/py_websocket.py @@ -0,0 +1,20 @@ +import websockets +from macros import py_print + +ws_global = None + +async def send_message(message: str): + global ws_global + if ws_global: + await ws_global.send(message) + + +async def websocket_client(): + global ws_global + async with websockets.connect("ws://127.0.0.1:9001") as ws: + ws_global = ws + py_print("Connected webSocket server on ws://127.0.0.1:9001") + + while True: + response = await ws.recv() + py_print(f"Received from Rust: {response}") \ No newline at end of file diff --git a/src/python/websocket.py b/src/python/websocket.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/websocket.rs b/src/websocket.rs index e69de29..06b4b0e 100644 --- a/src/websocket.rs +++ b/src/websocket.rs @@ -0,0 +1,83 @@ +use tokio::sync::Mutex; +use futures::SinkExt; +use tokio::net::TcpListener; +use tokio_tungstenite::{accept_async, tungstenite}; +use futures::StreamExt; +use std::sync::Arc; + +use crate::rs_println; + +type Sender = Arc, tungstenite::Message>>>>; + +static mut GLOBAL_SENDER: Option = None; +static mut REPLY_HELLO: bool = false; + + +async fn set_sender(sender: Sender) { + unsafe { + GLOBAL_SENDER = Some(sender); + } +} + + +pub async fn send_msg(msg: &str) { + unsafe { + if let Some(sender) = &GLOBAL_SENDER { + let mut sender = sender.lock().await; + if let Some(s) = sender.as_mut() { + s.send(tungstenite::Message::Text(msg.to_string().into())).await.unwrap(); + } + } + } +} + + +pub async fn start(args: Vec) { + rs_println!("Starting local websocket..."); + let listener = TcpListener::bind("127.0.0.1:9001").await.unwrap(); + rs_println!("WebSocket server running on ws://127.0.0.1:9001"); + + tokio::spawn(handle_connections(listener, args)); +} + + +async fn handle_connections(listener: TcpListener, args: Vec) { + while let Ok((stream, _)) = listener.accept().await { + let ws_stream = accept_async(stream).await.unwrap(); + let (sender, mut receiver) = ws_stream.split(); + + let sender_arc = Arc::new(Mutex::new(Some(sender))); + set_sender(sender_arc.clone()).await; + + while let Some(Ok(msg)) = receiver.next().await { + handle_message(msg, &args).await; + } + } +} + + +async fn handle_message(msg: tungstenite::protocol::Message, args: &[String]) { + match msg { + tungstenite::Message::Text(text) => { + rs_println!("Received from Python: {}", text); + + unsafe { + if !REPLY_HELLO { + rs_println!("Replying to python..."); + send_msg("[Connection test] Hello from Rust!").await; + REPLY_HELLO = true; + } + } + } + tungstenite::Message::Binary(bytes) => { + if args.contains(&"--dev".to_string()) { + rs_println!("[Binary] from Python: {:?}", bytes); + } + } + _ => { + if args.contains(&"--dev".to_string()) { + rs_println!("Received from Python: [UNKNOWN / OTHER]"); + } + } + } +} \ No newline at end of file