Made them communicate but somehow broke "hello" messages

This commit is contained in:
2025-02-07 21:16:33 +01:00
parent 9425c2cccc
commit e2869fb8a2
8 changed files with 125 additions and 2 deletions
+2
View File
@@ -6,8 +6,10 @@ 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
[dependencies] [dependencies]
futures = "0.3.31"
poise = "0.6.1" poise = "0.6.1"
pyo3 = "0.23.4" pyo3 = "0.23.4"
rand = "0.9.0" rand = "0.9.0"
serde_json = "1.0.138" serde_json = "1.0.138"
tokio = { version = "1.43.0", features = ["rt-multi-thread"] } tokio = { version = "1.43.0", features = ["rt-multi-thread"] }
tokio-tungstenite = "0.26.1"
+3 -1
View File
@@ -1,4 +1,4 @@
use crate::{Context, Error}; use crate::{rs_println, websocket, Context, Error};
use crate::messages::send_msg; use crate::messages::send_msg;
use std::fs; use std::fs;
@@ -23,6 +23,8 @@ pub async fn bk_week_get(
) -> Result<(), Error> ) -> Result<(), Error>
{ {
// log all posts in a thread // log all posts in a thread
rs_println!("Sending hello to python...");
websocket::send_msg("Hello from Rust!").await;
return Ok(()); return Ok(());
} }
+3
View File
@@ -1,3 +1,5 @@
use std::process;
use crate::{Context, Error}; use crate::{Context, Error};
use crate::messages::{send_embed, send_msg, edit_msg, EmbedOptions}; 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; send_msg(ctx, "Shutting down...".to_string(), true, true).await;
ctx.serenity_context().set_presence(None, OnlineStatus::Invisible); ctx.serenity_context().set_presence(None, OnlineStatus::Invisible);
ctx.framework().shard_manager.shutdown_all().await; ctx.framework().shard_manager.shutdown_all().await;
process::exit(0);
} }
else if !is_creator { else if !is_creator {
send_msg(ctx, "Failed to shut down: Invalid permissions.".to_string(), true, true).await; send_msg(ctx, "Failed to shut down: Invalid permissions.".to_string(), true, true).await;
+6 -1
View File
@@ -1,9 +1,12 @@
#![warn(unused_extern_crates)]
mod cmds; mod cmds;
mod bk_week_cmds; mod bk_week_cmds;
mod events; mod events;
mod messages; mod messages;
mod python; mod python;
mod macros; mod macros;
mod websocket;
use std::env; use std::env;
use std::process; use std::process;
@@ -58,6 +61,7 @@ async fn main() {
let rust = thread::spawn(move || { let rust = thread::spawn(move || {
rt.block_on(async { rt.block_on(async {
websocket::start(rust_args.clone()).await;
start(rust_args).await; start(rust_args).await;
}); });
}); });
@@ -117,7 +121,8 @@ async fn gen_bot(data: Data) -> Client {
cmds::eight_ball(), cmds::eight_ball(),
cmds::write_json(), cmds::write_json(),
//cmds::rule(), //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, event_handler: events::event_handler,
..Default::default() ..Default::default()
+8
View File
@@ -1,8 +1,10 @@
import sys import sys
import asyncio
from macros import * from macros import *
import bot as botPy import bot as botPy
import data import data
import py_websocket
def main(): def main():
@@ -17,5 +19,11 @@ def main():
py_print("Reading data...") py_print("Reading data...")
data.read_data(bot) 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() main()
+20
View File
@@ -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}")
View File
+83
View File
@@ -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<Mutex<Option<futures::stream::SplitSink<tokio_tungstenite::WebSocketStream<tokio::net::TcpStream>, tungstenite::Message>>>>;
static mut GLOBAL_SENDER: Option<Sender> = 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<String>) {
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<String>) {
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]");
}
}
}
}