refactor(core): add robust init and flag handling

This commit is contained in:
2026-08-02 00:44:35 +05:00
parent 60d67b613a
commit b2eab58b0c
2 changed files with 24 additions and 9 deletions
+17 -8
View File
@@ -10,6 +10,8 @@ from telethon.types import User, Chat, Channel
from telethon.tl.functions.payments import GetStarsStatusRequest
from telethon.tl.functions.contacts import GetContactsRequest
from opentele2.exception import OpenTeleException
from modules.tdata import TDATA
logger = logging.getLogger(__name__)
@@ -47,7 +49,14 @@ class Checker:
async def __aenter__(self):
logger.debug("Вход в контекстный менеджер Checker")
await self.__ensure_client()
if self.desktop is None:
logger.error("TDATA не инициализирована")
raise SessionInvalid()
try:
await self.__ensure_client()
except (OpenTeleException, Exception) as e:
logger.error(f"Не удалось инициализировать клиент: {e}")
raise SessionInvalid()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
@@ -61,10 +70,6 @@ class Checker:
async def __ensure_client(self):
if self.client is None:
if self.desktop is None:
logger.error("Попытка инициализации клиента с неинициализированной TDATA")
raise Exception("TDATA не инициализирована")
logger.debug("Конвертация TDATA в Telethon клиент")
self.client = await self.desktop.convert()
logger.debug("Telethon клиент успешно создан")
@@ -85,7 +90,7 @@ class Checker:
logger.debug(f"Определение страны для номера +{me.phone}")
try:
phone_parse = parse(str(f"+{me.phone}"))
country = geocoder.description_for_number(phone_parse, "ru")
country = geocoder.description_for_number(phone_parse, "en")
logger.debug(f"Страна определена: {country}")
return country
@@ -146,7 +151,9 @@ class Checker:
except Exception as e:
logger.debug(f"Не удалось проверить права для канала: {e}")
logger.debug(f"Проверено каналов: {checked}, найдено админских: {len(admin_channels)}")
logger.debug(
f"Проверено каналов: {checked}, найдено админских: {len(admin_channels)}"
)
return admin_channels
except Exception as e:
@@ -168,7 +175,9 @@ class Checker:
contacts = await self.check_contacts()
chats = await self.check_chats()
channels = await self.check_channels(chats=chats) if chats else []
admin_channels = await self.check_admin_channels(channels=channels) if channels else []
admin_channels = (
await self.check_admin_channels(channels=channels) if channels else []
)
logger.debug("Полная проверка завершена успешно")
return Result(
+7 -1
View File
@@ -99,8 +99,14 @@ class Worker:
def __template(self, result: Result):
logger.debug(f"Создание шаблона для пользователя {result.me.id}")
try:
flag = getflag(countries=result.country)
except Exception as e:
logger.debug(f"Не удалось получить флаг для страны '{result.country}': {e}")
flag = "🌐"
return (
f"👤 [{getflag(countries=result.country)} {result.country}] {result.me.phone}{result.me.id}\n"
f"👤 [{flag} {result.country}] {result.me.phone}{result.me.id}\n"
f"⭐️ {result.stars}\n"
f"💎 Premium: {'true' if result.me.premium else 'false'}\n"
f"👥 {len(result.chats)}/{len(result.contacts)}\n"