PaperParser/paper/parser.py

88 lines
3.1 KiB
Python
Raw Normal View History

2024-01-31 19:37:01 +10:00
import asyncio
from loguru import logger
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)
self.users_to_delete = []
2024-03-08 16:39:04 +10:00
async def invite_users(self, users, group, task):
2024-01-31 19:37:01 +10:00
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)
2024-03-08 16:39:04 +10:00
except (UserPrivacyException, IgnoreException):
2024-01-31 19:37:01 +10:00
self.users_to_delete.append(user)
logger.warning("Exception occurred. Skipping user...")
finally:
if not task.is_aborted():
2024-02-08 17:59:17 +10:00
await asyncio.sleep(70) # FIXME: Change to config value
2024-01-31 19:37:01 +10:00
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)
2024-03-08 16:39:04 +10:00
if not task:
return
2024-01-31 19:37:01 +10:00
for user in users:
try:
if task.is_aborted():
return self.users_to_delete
await self.client.send_message(user, message, file)
2024-03-08 16:39:04 +10:00
except (UserPrivacyException, IgnoreException):
2024-01-31 19:37:01 +10:00
self.users_to_delete.append(user)
logger.warning("Exception occurred. Skipping user...")
finally:
if not task.is_aborted():
2024-02-08 17:59:17 +10:00
await asyncio.sleep(70) # FIXME: Change to config value
2024-01-31 19:37:01 +10:00
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):
2024-03-08 16:39:04 +10:00
await self.client.disconnect()