migrated to asyncPRAW (i fucking hate it but it made reddit shut the fuck up)
This commit is contained in:
+27
-15
@@ -1,30 +1,42 @@
|
||||
from io import TextIOWrapper
|
||||
from praw import models
|
||||
import praw
|
||||
import asyncpraw as praw
|
||||
import os
|
||||
|
||||
from macros import *
|
||||
|
||||
|
||||
class Bot:
|
||||
args: dict = {"NO_RUST": True, "dev": True, "py": True, "port": 2920}
|
||||
password: str = os.environ.get("ASSISTANT_R_PASS")
|
||||
secret: str = os.environ.get("ASSISTANT_R_TOKEN")
|
||||
secret: str = os.environ.get("ASSISTANT_R_TOKEN")
|
||||
|
||||
if password is None:
|
||||
py_error("Environment variable \"ASSISTANT_R_PASS\" is null!")
|
||||
if secret is None:
|
||||
py_error("Environment variable \"ASSISTANT_R_TOKEN\" is null!")
|
||||
|
||||
r: praw.Reddit = praw.Reddit(
|
||||
client_id = "iCSRWS6PMlTLwmylCJRYmA",
|
||||
client_secret = secret,
|
||||
username = "ByteDiceAssistant",
|
||||
password = password,
|
||||
user_agent = "Byte Dice Assistant by u/RandomPersonDotExe aka u/Byte_Dice"
|
||||
)
|
||||
sr: models.Subreddit = r.subreddit("bytedicetesting") #r.subreddit("boykisser")
|
||||
data_f: TextIOWrapper = None
|
||||
data: dict = {}
|
||||
def __init__(self):
|
||||
self.r: praw.Reddit = praw.Reddit(
|
||||
client_id="iCSRWS6PMlTLwmylCJRYmA",
|
||||
client_secret=self.secret,
|
||||
username="ByteDiceAssistant",
|
||||
password=self.password,
|
||||
user_agent="Byte Dice Assistant by u/RandomPersonDotExe aka u/Byte_Dice"
|
||||
)
|
||||
self.sr = None
|
||||
self.data_f: TextIOWrapper = None
|
||||
self.data: dict = {}
|
||||
|
||||
def set_args(self, args: dict):
|
||||
self.args = args
|
||||
async def initialize(self):
|
||||
self.sr = await self.r.subreddit("bytedicetesting")#boykisser")
|
||||
|
||||
async def set_args(self, args: dict):
|
||||
self.args = args
|
||||
|
||||
async def stop(self) -> bool:
|
||||
if self.r:
|
||||
await self.r.close()
|
||||
py_print("Stopped Reddit bot.")
|
||||
return True
|
||||
|
||||
return False
|
||||
+4
-2
@@ -95,12 +95,14 @@ def write_data(bot: botPy.Bot) -> 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)")
|
||||
if bot.args["dev"]:
|
||||
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}\"")
|
||||
if bot.args["dev"]:
|
||||
py_print(f"Added post \"{new_data.url}\"")
|
||||
return True
|
||||
|
||||
elif "removed" in bot.data[BK_WEEKLY][new_data.url]:
|
||||
|
||||
+17
-7
@@ -7,13 +7,21 @@ from macros import *
|
||||
import bot as botPy
|
||||
import data
|
||||
import py_websocket
|
||||
import posts
|
||||
|
||||
|
||||
def main():
|
||||
async def main():
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
py_print("Creating Reddit bot...")
|
||||
bot = botPy.Bot()
|
||||
try: bot.set_args(args)
|
||||
|
||||
await bot.initialize()
|
||||
py_print(f"Successfully created Reddit bot: {await bot.r.user.me()}")
|
||||
|
||||
# args is supposed to be undefined.
|
||||
# It gets defined in Rust.
|
||||
try: await bot.set_args(args)
|
||||
except NameError:
|
||||
py_print("No command args found from Rust. Don't worry though, we have backup in place.")
|
||||
|
||||
@@ -24,16 +32,18 @@ def main():
|
||||
|
||||
if not bot.args["py"]:
|
||||
py_print("Connecting to local websocket...")
|
||||
ws_thread = threading.Thread(target=py_websocket.run_thread, args=(bot,))
|
||||
ws_thread.start()
|
||||
await py_websocket.websocket_client(bot)
|
||||
""" ws_thread = threading.Thread(target=py_websocket.run_thread, args=(bot,))
|
||||
ws_thread.start() """
|
||||
|
||||
while not py_websocket.is_connected:
|
||||
py_print("Awaiting connection...")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
asyncio.run(py_websocket.send_message("[Connection test] Hello from Python!"))
|
||||
await py_websocket.send_message("[Connection test] Hello from Python!")
|
||||
|
||||
await bot.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
asyncio.run(main())
|
||||
+9
-11
@@ -1,17 +1,17 @@
|
||||
import emoji
|
||||
from praw import models
|
||||
from asyncpraw import models
|
||||
|
||||
import data
|
||||
import bot as botPy
|
||||
from macros import *
|
||||
|
||||
|
||||
def add_new_posts(bot: botPy.Bot):
|
||||
async 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 = fetch_posts_with_flair(bot, "Original Art")
|
||||
posts = await fetch_posts_with_flair(bot, "Original Art")
|
||||
|
||||
py_print("Evaluating posts...")
|
||||
|
||||
@@ -51,11 +51,11 @@ def add_new_posts(bot: botPy.Bot):
|
||||
data.write_data(bot)
|
||||
|
||||
|
||||
def fetch_posts_with_flair(bot: botPy.Bot, flair_name: str) -> list[models.Submission]:
|
||||
async 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):
|
||||
async for post in bot.sr.search(f"flair:\"{flair_name}\"", sort="new", limit=10):
|
||||
posts.append(post)
|
||||
|
||||
return posts
|
||||
@@ -91,10 +91,8 @@ def has_media(post: models.Submission) -> tuple[bool, str, int, list[str]]:
|
||||
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)
|
||||
async def from_url(bot: botPy.Bot, url: str) -> tuple[bool, models.Submission]:
|
||||
post: models.Submission = await bot.r.submission(url=url)
|
||||
|
||||
if hasattr(post, "id"):
|
||||
return True, post
|
||||
@@ -116,8 +114,8 @@ def get_post_details(post: models.Submission) -> data.PostData:
|
||||
)
|
||||
|
||||
|
||||
def add_post_url(bot, url: str) -> bool:
|
||||
result, post = from_url(bot, url)
|
||||
async def add_post_url(bot, url: str) -> bool:
|
||||
result, post = await from_url(bot, url)
|
||||
|
||||
if not result:
|
||||
return result
|
||||
|
||||
@@ -36,7 +36,6 @@ async def parse_json(response: str, bot: botPy.Bot):
|
||||
json_response = json.loads(json_str)
|
||||
result = await json_to_func(json_response, bot)
|
||||
await ws_global.ping()
|
||||
print(result)
|
||||
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}")
|
||||
@@ -60,12 +59,17 @@ async def json_to_func(v: dict, bot: botPy.Bot) -> dict:
|
||||
result = {"type": "result", "value": False}
|
||||
|
||||
match v["value"]:
|
||||
case "update_data_file": result = {"type": "result", "value": data.write_data(bot)}
|
||||
case "add_post_url": result = {"type": "result", "value": posts.add_post_url(bot, *v["args"])}
|
||||
case "set_approve_post": result = {"type": "result", "value": data.set_approve_post(bot, *v["args"])}
|
||||
case "update_data_file": result = result_json(data.write_data(bot))
|
||||
case "add_post_url": result = result_json(await posts.add_post_url(bot, *v["args"]))
|
||||
case "set_approve_post": result = result_json(data.set_approve_post(bot, *v["args"]))
|
||||
case "stop_praw": result = result_json(bot.stop())
|
||||
case _: value_supported = False
|
||||
|
||||
if bot.args["dev"] and not value_supported:
|
||||
py_print(f"Value {v['value']} is not supported")
|
||||
|
||||
return result
|
||||
return result
|
||||
|
||||
|
||||
def result_json(bool: bool) -> dict:
|
||||
return {"type": "result", "value": bool}
|
||||
@@ -1,43 +0,0 @@
|
||||
from praw import models
|
||||
|
||||
import bot as botPy
|
||||
|
||||
|
||||
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 or 75
|
||||
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)
|
||||
Reference in New Issue
Block a user