PaperParser/paper/parser.py

92 lines
3.3 KiB
Python

import asyncio
from loguru import logger
from app.extensions import db
from paper.client import PaperClient
from paper.errors import IgnoreException, NeedPasswordException, UserPrivacyException
class PaperParser:
def __init__(self, session: str) -> None:
if not session:
raise ValueError("Session name can't be None")
self.client = PaperClient(session)
async def invite_users(self, users, group, task):
await self.client.invite_self(group)
group_participants = await self.client.get_participants(group)
if group_participants:
participants_usernames = [participant.username for participant in group_participants if participant.username]
users = filter(lambda user: user.username not in participants_usernames and not user.delete, users)
for user in users:
try:
if task.is_aborted():
return self.users_to_delete
await self.client.invite_user(user, group)
except (UserPrivacyException, IgnoreException):
logger.warning(f"Exception occurred. Marking {user.username} for deletion...")
user.delete = True
db.session.commit()
finally:
if not task.is_aborted():
await asyncio.sleep(70) # FIXME: Change to config value
async def send_messages(self, users, message: str, file: str | None = None, task = None):
# TODO: Filter users, that already get this message
# for dialog in await self.client.get_dialogs():
# if dialog.is_user:
# messages = tuple(filter(lambda chat_message: message.text == chat_message.text, await self.client.get_messages(dialog)))
# print(messages)
if not task:
return
for user in users:
try:
if task.is_aborted():
return self.users_to_delete
await self.client.send_message(user, message, file)
except (UserPrivacyException, IgnoreException):
logger.warning(f"Exception occurred. Marking {user.username} for deletion...")
user.delete = True
db.session.commit()
finally:
if not task.is_aborted():
await asyncio.sleep(70) # FIXME: Change to config value
async def get_participants(self, group):
await self.client.invite_self(group)
return await self.client.get_participants(group)
async def get_full_info(self, user):
return await self.client.get_full_info(user)
async def sign_in(self, phone: str, password: str | None = None, code: str | None = None, phone_hash: str | None = None, **kwargs):
if not await self.client.is_user_authorized():
try:
return await self.client.sign_in(phone=phone, code=code, phone_code_hash=phone_hash) #type: ignore
except:
if not password:
raise NeedPasswordException()
return await self.client.sign_in(password=password)
async def __aenter__(self, *args, **kwargs):
await self.client.connect()
return self
async def __aexit__(self, *args, **kwargs):
await self.client.disconnect()