made websockets able to run functions

This commit is contained in:
2025-02-08 20:18:00 +01:00
parent bf2e1e347f
commit b816c12a6c
9 changed files with 99 additions and 59 deletions
+1
View File
@@ -79,6 +79,7 @@ def read_data(bot: botPy.Bot):
def write_data(bot: botPy.Bot):
bot.data["TEST"] = True
bot.data_f.seek(0)
json.dump(bot.data, bot.data_f, indent=2)
bot.data_f.truncate()
+2 -2
View File
@@ -2,7 +2,7 @@ from printColors import PrintColors
def py_print(*args: str):
print(
PrintColors.FG.blue + "Py" + PrintColors.Special.reset,
PrintColors.FG.blue + "Py",
"-",
" ".join(args)
)
@@ -10,7 +10,7 @@ def py_print(*args: str):
def py_error(*args: str):
print(
PrintColors.BG.red + "ERROR" + PrintColors.Special.reset,
PrintColors.FG.blue + "Py" + PrintColors.Special.reset,
PrintColors.FG.blue + "Py",
"-",
" ".join(args)
)
+31 -1
View File
@@ -1,8 +1,10 @@
import websockets
import asyncio
import json
from macros import py_print
import bot as botPy
import data
ws_global = None
is_connected = False
@@ -23,9 +25,37 @@ async def websocket_client(bot: botPy.Bot):
while True:
response = await ws.recv()
py_print(f"Received from Rust: {response}")
parse_json(response, bot)
def parse_json(response: str, bot: botPy.Bot):
if response.startswith("json:"):
json_str = response[5:]
try:
json_response = json.loads(json_str)
json_to_func(json_response, bot)
except json.JSONDecodeError as e:
if bot.args["dev"]: py_print(f"failed to parse json: {json_str}\n reason: {e}")
def run_thread(bot: botPy.Bot):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(websocket_client(bot))
loop.run_until_complete(websocket_client(bot))
def json_to_func(v: dict, bot: botPy.Bot):
if "type" not in v or "value" not in v or not isinstance(v, dict):
if bot.args["dev"]: py_print("JSON is not a dictionary or does not include \"type\" and \"value\" keys.")
return
if v["type"] != "function":
if bot.args["dev"]: py_print(f"Type \"{v['type']}\" is not supported.")
return
value_supported = True
match v["value"]:
case "update_data_file": data.write_data(bot)
case _: value_supported = False
if bot.args["dev"] and not value_supported:
print(f"Value {v['value']} is not supported")