partially made /bk_week_add command

This commit is contained in:
2025-02-09 21:22:44 +01:00
parent 9a723a2332
commit 99215d17e2
9 changed files with 233 additions and 57 deletions
+8 -2
View File
@@ -85,13 +85,19 @@ def read_data(bot: botPy.Bot):
raise Exception("reddit_data.json file wasn't created properly. Delete the file and retry.")
def write_data(bot: botPy.Bot):
def write_data(bot: botPy.Bot) -> bool:
bot.data_f.seek(0)
json.dump(bot.data, bot.data_f, indent=2)
bot.data_f.truncate()
return True
def add_post_to_data(bot: botPy.Bot, new_data: PostData) -> bool:
def add_post_to_data(bot: botPy.Bot, new_data: PostData, bypass_conditions: bool = False) -> bool:
if bypass_conditions:
bot.data[BK_WEEKLY][new_data.url] = new_data.to_json()
py_print(f"Added post \"{new_data.url}\" (Conditions bypassed)")
return True
if new_data.url not in bot.data[BK_WEEKLY]:
bot.data[BK_WEEKLY][new_data.url] = new_data.to_json()
py_print(f"Added post \"{new_data.url}\"")
-1
View File
@@ -7,7 +7,6 @@ from macros import *
import bot as botPy
import data
import py_websocket
import posts
def main():
+89 -19
View File
@@ -1,15 +1,17 @@
import emoji
import reddit
from praw import models
import data
import bot as botPy
from macros import *
def add_new_posts(bot: botPy.Bot):
check_emoji = emoji.emojize(":check_mark_button:")
cross_emoji = emoji.emojize(":cross_mark:")
py_print("Fetching posts...")
posts = reddit.fetch_posts_with_flair(bot, "Original Art")
posts = fetch_posts_with_flair(bot, "Original Art")
py_print("Evaluating posts...")
@@ -17,16 +19,17 @@ def add_new_posts(bot: botPy.Bot):
without_media = 0
not_added = 0
for post in posts:
media = reddit.has_media(post)
media = has_media(post)
media_urls = "\n ".join(media[3])
if bot.args["dev"]: py_print(
f"\n{post.title}",
f"\n {post.shortlink}"
f"\n {check_emoji if media[0] else cross_emoji} Media ({media[1]}) [{media[2]}]",
f"\n {media_urls}\n"
)
if bot.args["dev"]:
py_print(
f"\n{post.title}",
f"\n {post.shortlink}"
f"\n {check_emoji if media[0] else cross_emoji} Media ({media[1]}) [{media[2]}]",
f"\n {media_urls}\n"
)
if not media[0]:
without_media += 1
@@ -34,15 +37,7 @@ def add_new_posts(bot: botPy.Bot):
post_added = data.add_post_to_data(
bot,
data.PostData(
post.shortlink,
post.title,
post.score,
int(post.created_utc),
media[1],
media[3],
added_by_bot = True,
)
get_post_details(post)
)
if post_added: added_posts += 1
@@ -53,4 +48,79 @@ def add_new_posts(bot: botPy.Bot):
f" {without_media} had no media, " +
f"and {not_added} weren't added because they are removed or already existed")
data.write_data(bot)
data.write_data(bot)
def fetch_posts_with_flair(bot: botPy.Bot, flair_name: str) -> list[models.Submission]:
posts: list[models.Submission] = []
# ~36 OG-art posts per week, round limit to 50, 75 or 100
for post in bot.sr.search(f"flair:\"{flair_name}\"", sort="new", limit=10):
posts.append(post)
return posts
def has_media(post: models.Submission) -> tuple[bool, str, int, list[str]]:
media_type: str = None
media_count = 0
media_urls: list[str] = []
if hasattr(post, "post_hint"):
media_type = post.post_hint
media_count = 1
media_urls.append(post.url)
elif getattr(post, "is_gallery", False):
if not post.is_gallery: pass
media_type = "multiple"
gallery_items = getattr(post, "gallery_data", {}).get("items", [])
media_metadata = getattr(post, "media_metadata", {})
media_count = len(gallery_items)
for item in gallery_items:
media_id = item.get("media_id")
image_url = media_metadata.get(media_id, {}).get("s", {}).get("u")
if image_url:
media_urls.append(image_url)
return (media_type != None, media_type, media_count, media_urls)
# TODO: convert to asyncpraw because praw wont SHUT THE FUCK UP
# Gosh i gotta handle so much pain dont i?
def from_url(bot: botPy.Bot, url: str) -> tuple[bool, models.Submission]:
post = bot.r.submission(url=url)
if hasattr(post, "id"):
return True, post
else:
return False, None
def get_post_details(post: models.Submission):
media = has_media(post)
return data.PostData(
post.shortlink,
post.title,
post.score,
int(post.created_utc),
media[1],
media[3],
added_by_bot = True,
)
async def add_post_url(bot, url: str) -> bool:
result, post = from_url(bot, url)
if not result:
return result
post_data = get_post_details(post)
data.add_post_to_data(bot, post_data, True)
+14 -6
View File
@@ -5,6 +5,7 @@ import json
from macros import py_print
import bot as botPy
import data
import posts
ws_global = None
is_connected = False
@@ -25,15 +26,17 @@ async def websocket_client(bot: botPy.Bot):
while True:
response = await ws.recv()
py_print(f"Received from Rust: {response}")
parse_json(response, bot)
await parse_json(response, bot)
def parse_json(response: str, bot: botPy.Bot):
async 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)
result = await json_to_func(json_response, bot)
await ws_global.ping()
await send_message(f"json:{json.dumps(result)}")
except json.JSONDecodeError as e:
if bot.args["dev"]: py_print(f"failed to parse json: {json_str}\n reason: {e}")
@@ -44,7 +47,7 @@ def run_thread(bot: botPy.Bot):
loop.run_until_complete(websocket_client(bot))
def json_to_func(v: dict, bot: botPy.Bot):
async def json_to_func(v: dict, bot: botPy.Bot) -> dict:
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
@@ -53,9 +56,14 @@ def json_to_func(v: dict, bot: botPy.Bot):
return
value_supported = True
result = {"type": "result", "value": False}
match v["value"]:
case "update_data_file": data.write_data(bot)
case "update_data_file": result = {"type": "result", "value": data.write_data(bot)}
case "add_post_url": result = {"type": "result", "value": await posts.add_post_url(bot, *v["args"])}
case _: value_supported = False
if bot.args["dev"] and not value_supported:
py_print(f"Value {v['value']} is not supported")
py_print(f"Value {v['value']} is not supported")
return result