made websockets able to run functions
This commit is contained in:
@@ -0,0 +1,39 @@
|
|||||||
|
# Discord Commands
|
||||||
|
|
||||||
|
### `/bk_week_add [url] [approve]`
|
||||||
|
Adds a URL to the list of posts. This is done automatically by the bot for certain posts.
|
||||||
|
- **`[approve]`**: `true` or `false`, determines whether to pre-approve the post.
|
||||||
|
|
||||||
|
### `/bk_week_remove [url]`
|
||||||
|
Removes an existing URL from the list of posts.
|
||||||
|
|
||||||
|
### `/bk_week_approve [url]`
|
||||||
|
Flags the post as **human_approved**, confirming that the artwork is original.
|
||||||
|
|
||||||
|
### `/bk_week_disapprove [url]`
|
||||||
|
Reverses the effect of `/bk_week_approve`.
|
||||||
|
|
||||||
|
#### **Examples**
|
||||||
|
```
|
||||||
|
/bk_week_add https://reddit.com/post_url false
|
||||||
|
/bk_week_add https://reddit.com/post_url
|
||||||
|
/bk_week_approve https://reddit.com/post_url
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Reddit Commands
|
||||||
|
|
||||||
|
To execute a command on the Reddit bot, include `"u/ByteDiceAssistant [args]"` in a comment.
|
||||||
|
- **`[args]`**: The command you want to run.
|
||||||
|
|
||||||
|
### `bk_week_add`
|
||||||
|
Adds the post to the list of posts.
|
||||||
|
- **Only moderators of a subreddit or the OP (Original Poster) can use this command.**
|
||||||
|
|
||||||
|
#### **Examples**
|
||||||
|
```
|
||||||
|
"u/ByteDiceAssistant bk_week_add"
|
||||||
|
"Cool art, let me add that. u/ByteDiceAssistant bk_week_add"
|
||||||
|
"Cool art. Just gonna u/ByteDiceAssistant bk_week_add so it can become featured."
|
||||||
|
```
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
```
|
|
||||||
--- Discord commands ---
|
|
||||||
/bk_week_add [url] [approve] - Takes a URL and adds it to the list of posts.
|
|
||||||
This is done automatically by the bot for certain posts.
|
|
||||||
[approve] is true or false, and determines wether to pre-
|
|
||||||
approve the post.
|
|
||||||
/bk_week_remove [url] - Takes an existing URL and removes it from the list of posts.
|
|
||||||
/bk_week_approve [url] - Takes an existing URL and flags the post as human_approved.
|
|
||||||
Approve a post to tell the bot that an art piece is original art.
|
|
||||||
/bk_week_disapprove [url] - Does what /bk_week_approve does, but opposite.
|
|
||||||
|
|
||||||
EXAMPLES:
|
|
||||||
/bk_week_add https://reddit.com/abc123 false
|
|
||||||
/bk_week_approve https://reddit.com/def456
|
|
||||||
|
|
||||||
--- Reddit commands ---
|
|
||||||
To execute a command on the Reddit bot, type "u/ByteDiceAssistant [args]" in a comment.
|
|
||||||
[args] should be replaced with a command:
|
|
||||||
|
|
||||||
add - Adds the post the command was ran in to the list of posts.
|
|
||||||
|
|
||||||
EXAMPLES:
|
|
||||||
u/ByteDiceAssistant add
|
|
||||||
|
|
||||||
You can even do this: (without the quotes)
|
|
||||||
"""
|
|
||||||
Hey guys welcome back to my lets play, today we are checking out original art.
|
|
||||||
Wow, this art is original and cool.
|
|
||||||
|
|
||||||
u/ByteDiceAssistant add
|
|
||||||
|
|
||||||
I want this art to be recognized
|
|
||||||
"""
|
|
||||||
and this:
|
|
||||||
"Cool art. u/ByteDiceAssistant add
|
|
||||||
and this:
|
|
||||||
"""
|
|
||||||
Cool art. u/ByteDiceAssistant add
|
|
||||||
Very cool.
|
|
||||||
"""
|
|
||||||
|
|
||||||
But you cant do this: (without the quotes)
|
|
||||||
"Cool art. u/ByteDiceAssistant add very cool."
|
|
||||||
"Cool art. u/ByteDiceAssistant add. Very cool."
|
|
||||||
"Cool art. u/ByteDiceAssistant add." (Notice the period?)
|
|
||||||
```
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"file_created_correctly": true,
|
"file_created_correctly": true,
|
||||||
"bk_weekly_art_posts": {
|
"bk_weekly_art_posts": {
|
||||||
"EXAMPLE VALUE DO NOT INCLUDE IN FINAL": {
|
"EXAMPLE VALUE": {
|
||||||
"post_data": {
|
"post_data": {
|
||||||
"title": "I JUST BOUGHT THE CONTINENT OF NORTH AMERICA FOR A DOLLAR!",
|
"title": "I JUST BOUGHT THE CONTINENT OF NORTH AMERICA FOR A DOLLAR!",
|
||||||
"upvotes": 69420,
|
"upvotes": 69420,
|
||||||
|
|||||||
+6
-5
@@ -1,4 +1,7 @@
|
|||||||
use crate::{rs_println, websocket, Context, Error};
|
use serde_json::json;
|
||||||
|
|
||||||
|
use crate::websocket::send_cmd_json;
|
||||||
|
use crate::{Context, Error};
|
||||||
use crate::messages::send_msg;
|
use crate::messages::send_msg;
|
||||||
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
@@ -8,7 +11,7 @@ pub async fn bk_week_help(
|
|||||||
ctx: Context<'_>,
|
ctx: Context<'_>,
|
||||||
) -> Result<(), Error>
|
) -> Result<(), Error>
|
||||||
{
|
{
|
||||||
let help = fs::read_to_string("./bk_week_help.txt").unwrap();
|
let help = fs::read_to_string("./bk_week_help.md").unwrap();
|
||||||
send_msg(ctx, help, true, true).await;
|
send_msg(ctx, help, true, true).await;
|
||||||
|
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -21,9 +24,7 @@ pub async fn bk_week_get(
|
|||||||
#[description = "The post URL"] url: Option<String>
|
#[description = "The post URL"] url: Option<String>
|
||||||
) -> Result<(), Error>
|
) -> Result<(), Error>
|
||||||
{
|
{
|
||||||
// log all posts in a thread
|
send_cmd_json("update_data_file", json!([])).await;
|
||||||
rs_println!("Sending hello to python...");
|
|
||||||
websocket::send_msg("Hello from Rust!").await;
|
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-4
@@ -1,9 +1,8 @@
|
|||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! rs_println {
|
macro_rules! rs_println {
|
||||||
($($arg:tt)*) => {
|
($($arg:tt)*) => {
|
||||||
println!("{}RS{} - {}",
|
println!("{}RS - {}",
|
||||||
"\x1b[31m",
|
"\x1b[31m",
|
||||||
"\x1b[0m",
|
|
||||||
format!($($arg)*)
|
format!($($arg)*)
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -13,10 +12,9 @@ macro_rules! rs_println {
|
|||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! rs_errln {
|
macro_rules! rs_errln {
|
||||||
($($arg:tt)*) => {
|
($($arg:tt)*) => {
|
||||||
println!("{}ERROR{} RS{} - {}",
|
println!("{}ERROR{} RS - {}",
|
||||||
"\x1b[41m",
|
"\x1b[41m",
|
||||||
"\x1b[0m\x1b[31m",
|
"\x1b[0m\x1b[31m",
|
||||||
"\x1b[0m",
|
|
||||||
format!($($arg)*)
|
format!($($arg)*)
|
||||||
);
|
);
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ def read_data(bot: botPy.Bot):
|
|||||||
|
|
||||||
|
|
||||||
def write_data(bot: botPy.Bot):
|
def write_data(bot: botPy.Bot):
|
||||||
|
bot.data["TEST"] = True
|
||||||
bot.data_f.seek(0)
|
bot.data_f.seek(0)
|
||||||
json.dump(bot.data, bot.data_f, indent=2)
|
json.dump(bot.data, bot.data_f, indent=2)
|
||||||
bot.data_f.truncate()
|
bot.data_f.truncate()
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ from printColors import PrintColors
|
|||||||
|
|
||||||
def py_print(*args: str):
|
def py_print(*args: str):
|
||||||
print(
|
print(
|
||||||
PrintColors.FG.blue + "Py" + PrintColors.Special.reset,
|
PrintColors.FG.blue + "Py",
|
||||||
"-",
|
"-",
|
||||||
" ".join(args)
|
" ".join(args)
|
||||||
)
|
)
|
||||||
@@ -10,7 +10,7 @@ def py_print(*args: str):
|
|||||||
def py_error(*args: str):
|
def py_error(*args: str):
|
||||||
print(
|
print(
|
||||||
PrintColors.BG.red + "ERROR" + PrintColors.Special.reset,
|
PrintColors.BG.red + "ERROR" + PrintColors.Special.reset,
|
||||||
PrintColors.FG.blue + "Py" + PrintColors.Special.reset,
|
PrintColors.FG.blue + "Py",
|
||||||
"-",
|
"-",
|
||||||
" ".join(args)
|
" ".join(args)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import websockets
|
import websockets
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import json
|
||||||
|
|
||||||
from macros import py_print
|
from macros import py_print
|
||||||
import bot as botPy
|
import bot as botPy
|
||||||
|
import data
|
||||||
|
|
||||||
ws_global = None
|
ws_global = None
|
||||||
is_connected = False
|
is_connected = False
|
||||||
@@ -23,9 +25,37 @@ async def websocket_client(bot: botPy.Bot):
|
|||||||
while True:
|
while True:
|
||||||
response = await ws.recv()
|
response = await ws.recv()
|
||||||
py_print(f"Received from Rust: {response}")
|
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):
|
def run_thread(bot: botPy.Bot):
|
||||||
loop = asyncio.new_event_loop()
|
loop = asyncio.new_event_loop()
|
||||||
asyncio.set_event_loop(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")
|
||||||
@@ -4,6 +4,7 @@ use tokio::net::TcpListener;
|
|||||||
use tokio_tungstenite::{accept_async, tungstenite};
|
use tokio_tungstenite::{accept_async, tungstenite};
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::rs_println;
|
use crate::rs_println;
|
||||||
use crate::Args;
|
use crate::Args;
|
||||||
@@ -33,6 +34,22 @@ pub async fn send_msg(msg: &str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pub async fn send_cmd_json(func_name: &str, func_args: Value) {
|
||||||
|
unsafe {
|
||||||
|
if let Some(sender) = &GLOBAL_SENDER {
|
||||||
|
let mut sender = sender.lock().await;
|
||||||
|
if let Some(s) = sender.as_mut() {
|
||||||
|
let json_str: String = format!(
|
||||||
|
"json:{{\"type\": \"function\", \"value\":\"{}\", \"args\": {}}}",
|
||||||
|
func_name, func_args
|
||||||
|
);
|
||||||
|
s.send(tungstenite::Message::Text(json_str.into())).await.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
pub async fn start(args: Args) {
|
pub async fn start(args: Args) {
|
||||||
rs_println!("Starting local websocket...");
|
rs_println!("Starting local websocket...");
|
||||||
let ip = format!("127.0.0.1:{}", args.port);
|
let ip = format!("127.0.0.1:{}", args.port);
|
||||||
|
|||||||
Reference in New Issue
Block a user