Skip to content

Commit

Permalink
Fixed all the typing error and variable names
Browse files Browse the repository at this point in the history
- AsyncLemmyPy user class is now python class to have better control over the class.
  • Loading branch information
isFakeAccount committed Dec 21, 2023
1 parent 2b96891 commit e186765
Show file tree
Hide file tree
Showing 7 changed files with 123 additions and 107 deletions.
2 changes: 2 additions & 0 deletions async_lemmy_py/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from async_lemmy_py.async_lemmy import AsyncLemmyPy

__all__ = ["AsyncLemmyPy"]
4 changes: 2 additions & 2 deletions async_lemmy_py/models/comment.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import datetime
from typing import Self, Any
from typing import Self, Any, Union

from async_lemmy_py.models.community import Community
from async_lemmy_py.models.post import Post
Expand Down Expand Up @@ -54,7 +54,7 @@ def from_dict(cls, *, comment_view: dict[str, Any], request_builder: RequestBuil
comment_dict=comment_dict,
)

async def parent(self) -> Self | Post:
async def parent(self) -> Union["Comment", Post]:
parent_ids = self.path.split(".")
parent_id = int(parent_ids[-2])
if parent_id == 0 or len(parent_ids) <= 1:
Expand Down
54 changes: 27 additions & 27 deletions async_lemmy_py/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,39 +14,39 @@ class UserFlair:
mod_only: bool


@dataclass
class User:
id: int
name: str
banned: bool
published: datetime
actor_id: str
local: bool
deleted: bool
bot_account: bool
instance_id: int
admin: Optional[bool] = None
bio: Optional[str] = None
inbox_url: Optional[str] = None
matrix_user_id: Optional[str] = None
display_name: Optional[str] = None
avatar: Optional[str] = None
ban_expires: Optional[str] = None
banner: Optional[str] = None
updated: Optional[str] = None
def __init__(self, user: dict[str, Any]):
self.actor_id = user.get("actor_id", "")
self.admin = user.get("admin")
self.avatar = user.get("avatar", "")
self.ban_expires = user.get("ban_expires", "")
self.banned = user.get("banned", False)
self.banner = user.get("banner", "")
self.bio = user.get("bio", "")
self.bot_account = user.get("bot_account", False)
self.deleted = user.get("deleted", False)
self.display_name = user.get("display_name", "")
self.id = user.get("id", -1)
self.inbox_url = user.get("inbox_url", "")
self.instance_id = user.get("instance_id", -1)
self.local = user.get("local", False)
self.matrix_user_id = user.get("matrix_user_id", "")
self.name = user.get("name", "")
self.published = datetime.fromisoformat(user.get("published", "1970-01-01T00:00:00Z"))
self.updated = datetime.fromisoformat(user.get("updated", "1970-01-01T00:00:00Z"))

@classmethod
def from_dict(cls, data: dict[Any, Any]) -> Self:
data_copy = data.copy()

published_str = data_copy.get("published")
def from_dict(cls, data: dict[str, Any]) -> Self:
return cls(data)

if published_str:
data_copy["published"] = datetime.fromisoformat(published_str)
async def get_flair(self) -> Optional[UserFlair]:
"""Retrieve user flair information from the Lemmy API.
return cls(**data_copy)
:returns: An instance of UserFlair if the user has flair, else None.
:rtype: Optional[UserFlair]
:rtype: Awaitable[Optional[UserFlair]]
async def get_flair(self) -> Optional[UserFlair]:
"""
async with ClientSession() as session:
params = {"community_actor_id": "https://lemmy.basedcount.com/c/pcm", "user_actor_id": self.actor_id}
async with session.get("https://lemmy.basedcount.com/flair/api/v1/user", params=params) as resp:
Expand Down
52 changes: 26 additions & 26 deletions basedcount_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import aiofiles
from aiohttp import ClientResponseError
from dotenv import load_dotenv
from motor.motor_asyncio import AsyncIOMotorClient
from motor.motor_asyncio import AsyncIOMotorDatabase
from yaml import safe_load

from async_lemmy_py import AsyncLemmyPy
Expand All @@ -20,31 +20,31 @@
from bot_commands import get_based_count, most_based, based_and_pilled, my_compass, remove_pill, add_to_based_history, set_subscription, check_unsubscribed
from utility_functions import (
create_logger,
get_mongo_client,
get_databased,
send_traceback_to_discord,
)

load_dotenv()


def exception_wrapper(func: Callable[[AsyncLemmyPy, AsyncIOMotorClient], Awaitable[None]]) -> Callable[[AsyncLemmyPy, AsyncIOMotorClient], Awaitable[None]]:
def exception_wrapper(func: Callable[[AsyncLemmyPy, AsyncIOMotorDatabase], Awaitable[None]]) -> Callable[[AsyncLemmyPy, AsyncIOMotorDatabase], Awaitable[None]]:
"""Decorator to handle the exceptions and to ensure the code doesn't exit unexpectedly.
:param func: function that needs to be called
:returns: wrapper function
:rtype: Callable[[Reddit, AsyncIOMotorClient], Awaitable[None]]
:rtype: Callable[[Reddit, AsyncIOMotorDatabase], Awaitable[None]]
"""

async def wrapper(lemmy_instance: AsyncLemmyPy, mongo_client: AsyncIOMotorClient) -> None:
async def wrapper(lemmy_instance: AsyncLemmyPy, mongo_client: AsyncIOMotorDatabase) -> None:
global cool_down_timer

while True:
try:
await func(lemmy_instance, mongo_client)
except ClientResponseError as response_err_exc:
main_logger.exception("AsyncPrawcoreException", exc_info=True)
main_logger.exception("AsyncLemmyPyExpection", exc_info=True)
await send_traceback_to_discord(
exception_name=type(response_err_exc).__name__, exception_message=str(response_err_exc), exception_body=format_exc()
)
Expand All @@ -63,12 +63,12 @@ async def wrapper(lemmy_instance: AsyncLemmyPy, mongo_client: AsyncIOMotorClient
return wrapper


async def bot_commands(command: Comment, command_body_lower: str, mongo_client: AsyncIOMotorClient) -> None:
async def bot_commands(command: Comment, command_body_lower: str, databased: AsyncIOMotorDatabase) -> None:
"""Responsible for the basic based count bot commands
:param command: Lemmy post that triggered the command, could be a message or comment
:param command_body_lower: The body of that message or command
:param mongo_client: MongoDB Client used to get the collections
:param databased: MongoDB Client used to get the collections
:returns: None
Expand All @@ -83,31 +83,31 @@ async def bot_commands(command: Comment, command_body_lower: str, mongo_client:
await command.reply(replies.get("info_message"))

elif command_body_lower.startswith("/mybasedcount"):
my_based_count = await get_based_count(user_name=command.user.name, is_me=True, mongo_client=mongo_client)
my_based_count = await get_based_count(user_name=command.user.name, is_me=True, databased=databased)
await command.reply(my_based_count)

elif result := re.match(r"/basedcount\s*(u/)?([A-Za-z0-9_-]+)", command.content, re.IGNORECASE):
user_name = result.group(2)
user_based_count = await get_based_count(user_name=user_name, is_me=False, mongo_client=mongo_client)
user_based_count = await get_based_count(user_name=user_name, is_me=False, databased=databased)
await command.reply(user_based_count)

elif command_body_lower.startswith("/mostbased"):
await command.reply(await most_based())

elif command_body_lower.startswith("/removepill"):
response = await remove_pill(user_name=command.user.name, pill=command_body_lower.replace("/removepill ", ""), mongo_client=mongo_client)
response = await remove_pill(user_name=command.user.name, pill=command_body_lower.replace("/removepill ", ""), databased=databased)
await command.reply(response)

elif command_body_lower.startswith("/mycompass"):
response = await my_compass(user_name=command.user.name, compass=command_body_lower.replace("/mycompass ", ""), mongo_client=mongo_client)
response = await my_compass(user_name=command.user.name, compass=command_body_lower.replace("/mycompass ", ""), databased=databased)
await command.reply(response)

elif command_body_lower.startswith("/unsubscribe"):
response = await set_subscription(subscribe=False, user_name=command.user.name, mongo_client=mongo_client)
response = await set_subscription(subscribe=False, user_name=command.user.name, databased=databased)
await command.reply(response)

elif command_body_lower.startswith("/subscribe"):
response = await set_subscription(subscribe=True, user_name=command.user.name, mongo_client=mongo_client)
response = await set_subscription(subscribe=True, user_name=command.user.name, databased=databased)
await command.reply(response)


Expand Down Expand Up @@ -151,12 +151,12 @@ async def bot_commands(command: Comment, command_body_lower: str, mongo_client:
PILL_REGEX = re.compile("(?<=(and|but))(.+)pilled", re.IGNORECASE)


async def is_valid_comment(comment: Comment, parent_info: ParentInfo, mongo_client: AsyncIOMotorClient) -> bool:
async def is_valid_comment(comment: Comment, parent_info: ParentInfo, databased: AsyncIOMotorDatabase) -> bool:
"""Runs checks for self based/pills, unflaired users, and cheating in general
:param comment: Comment which triggered the bot command
:param parent_info: The parent comment/submission info.
:param mongo_client: MongoDB Client used to get the collections
:param databased: MongoDB Client used to get the collections
:returns: True if checks passed and False if checks failed
Expand All @@ -178,7 +178,7 @@ async def is_valid_comment(comment: Comment, parent_info: ParentInfo, mongo_clie
return False

# fire and forget background tasks
task = asyncio.create_task(add_to_based_history(comment.user.actor_id, parent_info.parent_actor_id, mongo_client=mongo_client))
task = asyncio.create_task(add_to_based_history(comment.user.actor_id, parent_info.parent_actor_id, databased=databased))
background_tasks.add(task)
task.add_done_callback(background_tasks.discard)
return True
Expand Down Expand Up @@ -213,17 +213,17 @@ async def get_parent_info(comment: Comment | Post) -> ParentInfo:


@exception_wrapper
async def read_comments(lemmy_instance: AsyncLemmyPy, mongo_client: AsyncIOMotorClient) -> None:
async def read_comments(lemmy_instance: AsyncLemmyPy, databased: AsyncIOMotorDatabase) -> None:
"""Checks comments as they come on r/PoliticalCompassMemes and performs actions accordingly.
:param lemmy_instance: The AsyncLemmyPy Instance. Used to make API calls.
:param mongo_client: MongoDB Client used to get the collections
:param databased: MongoDB Client used to get the collections
:returns: Nothing is returned
"""
main_logger.info(f"Logged into {lemmy_instance.request_builder.username} Account.")
async for comment in lemmy_instance.stream_comments(skip_existing=True): # Comment
async for comment in lemmy_instance.stream_comments(skip_existing=False): # Comment
# Skips its own comments
if comment.user.actor_id == "https://lemmy.basedcount.com/u/basedcount_bot":
continue
Expand All @@ -236,7 +236,7 @@ async def read_comments(lemmy_instance: AsyncLemmyPy, mongo_client: AsyncIOMotor
main_logger.warn("Parent Removed or Deleted")
continue
# Skip Unflaired scums and low effort based
if not await is_valid_comment(comment, parent_info, mongo_client=mongo_client):
if not await is_valid_comment(comment, parent_info, databased=databased):
continue
main_logger.info("Checks passed")

Expand All @@ -257,22 +257,22 @@ async def read_comments(lemmy_instance: AsyncLemmyPy, mongo_client: AsyncIOMotor
parent_flair = "Unflaired"
else:
parent_flair = parent_info.parent_flair.display_name
reply_message = await based_and_pilled(parent_info.parent_actor_id, parent_flair, pill, mongo_client=mongo_client)
reply_message = await based_and_pilled(parent_info.parent_actor_id, parent_flair, pill, databased=databased)
if reply_message is not None:
if await check_unsubscribed(parent_info.parent_actor_id, mongo_client):
if await check_unsubscribed(parent_info.parent_actor_id, databased):
continue
await comment.reply(reply_message)
else:
await bot_commands(comment, comment_body_lower, mongo_client=mongo_client)
await bot_commands(comment, comment_body_lower, databased=databased)


async def main() -> None:
async with (
get_mongo_client() as mongo_client,
get_databased() as databased,
AsyncLemmyPy(base_url="https://lemmy.basedcount.com", username=getenv("LEMMY_USERNAME", "username"), password=getenv("LEMMY_PASSWORD", "pas")) as lemmy,
):
await asyncio.gather(
read_comments(lemmy, mongo_client),
read_comments(lemmy, databased),
)


Expand Down
Loading

0 comments on commit e186765

Please sign in to comment.