import asyncio import os from loguru import logger from paper.client import PaperClient from paper.errors import IgnoreException, NeedPasswordException, UserPrivacyException from paper.models import Message class PaperParser: def __init__(self, session: str) -> None: if not session: raise ValueError("Session name can't be None") self.client = PaperClient(session) self.users_to_delete = [] async def invite_users(self, users, group, task = None): 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, 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) as e: self.users_to_delete.append(user) logger.exception(e) logger.warning("Exception occurred. Skipping user...") except Exception as e: logger.exception(e) finally: if not task.is_aborted(): await asyncio.sleep(50) # 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) 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) as e: self.users_to_delete.append(user) logger.exception(e) logger.warning("Exception occurred. Skipping user...") finally: if not task.is_aborted(): await asyncio.sleep(50) # 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 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()