Introduce background scheduling and migrations for analytics ingest, expand parser management and map toolbar UX, and ignore local data/session files from version control. Co-authored-by: Cursor <cursoragent@cursor.com>
56 lines
2.0 KiB
Python
56 lines
2.0 KiB
Python
"""Единое подключение Telethon для listener и batch-заданий."""
|
|
|
|
from pathlib import Path
|
|
|
|
from telethon import TelegramClient
|
|
from telethon.errors import AuthKeyUnregisteredError, SessionPasswordNeededError
|
|
|
|
from workers.sources.telegram_settings import create_client, get_api_credentials, get_session_path
|
|
from workers.sources.telegram_client import TelegramAuthError, TelegramConfigError
|
|
|
|
_shared_client: TelegramClient | None = None
|
|
|
|
|
|
async def get_shared_client() -> TelegramClient:
|
|
global _shared_client
|
|
if _shared_client is not None and _shared_client.is_connected():
|
|
return _shared_client
|
|
|
|
try:
|
|
api_id, api_hash = get_api_credentials()
|
|
except ValueError as exc:
|
|
raise TelegramConfigError(str(exc)) from exc
|
|
|
|
session_path = get_session_path()
|
|
if not Path(session_path).exists():
|
|
raise TelegramAuthError(
|
|
f"Файл сессии не найден: {session_path}. "
|
|
"Выполните: python scripts/telegram_auth.py"
|
|
)
|
|
|
|
client = create_client(session_path, api_id, api_hash)
|
|
try:
|
|
await client.connect()
|
|
if not await client.is_user_authorized():
|
|
raise TelegramAuthError(
|
|
"Telegram-сессия не авторизована. Выполните: python scripts/telegram_auth.py"
|
|
)
|
|
except AuthKeyUnregisteredError as exc:
|
|
raise TelegramAuthError(
|
|
"Сессия Telegram недействительна. Переавторизуйтесь: python scripts/telegram_auth.py"
|
|
) from exc
|
|
except SessionPasswordNeededError as exc:
|
|
raise TelegramAuthError(
|
|
"Для аккаунта включена 2FA. Авторизуйтесь через scripts/telegram_auth.py."
|
|
) from exc
|
|
|
|
_shared_client = client
|
|
return client
|
|
|
|
|
|
async def close_shared_client() -> None:
|
|
global _shared_client
|
|
if _shared_client is not None:
|
|
await _shared_client.disconnect()
|
|
_shared_client = None
|