feat: Implement recent chats feature with API endpoint and UI integration
This commit is contained in:
@@ -1,10 +1,13 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
from typing import List, Optional
|
||||
|
||||
from telethon import TelegramClient, errors
|
||||
from telethon.tl import types
|
||||
from telethon.utils import get_display_name, get_peer_id
|
||||
|
||||
from .config import get_settings
|
||||
from .models import RecentChat
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -124,5 +127,63 @@ class TelegramService:
|
||||
def get_login_state(self) -> LoginState:
|
||||
return self._login_state
|
||||
|
||||
async def fetch_recent_chats(self, limit: int = 50) -> List[RecentChat]:
|
||||
await self.ensure_connected()
|
||||
authorized = self.client.is_user_authorized()
|
||||
if asyncio.iscoroutine(authorized):
|
||||
authorized = await authorized
|
||||
if not authorized:
|
||||
raise PermissionError("Telegram session is not authorized")
|
||||
|
||||
dialogs = await self.client.get_dialogs(limit=limit)
|
||||
results: List[RecentChat] = []
|
||||
for dialog in dialogs:
|
||||
entity = dialog.entity
|
||||
if entity is None:
|
||||
chat_id = str(getattr(dialog, "id", ""))
|
||||
display_name = getattr(dialog, "name", chat_id) or chat_id
|
||||
chat_type = "unknown"
|
||||
username = None
|
||||
phone = None
|
||||
else:
|
||||
try:
|
||||
chat_id = str(get_peer_id(entity))
|
||||
except Exception: # noqa: BLE001
|
||||
chat_id = str(getattr(entity, "id", ""))
|
||||
|
||||
try:
|
||||
display_name = get_display_name(entity) or chat_id
|
||||
except Exception: # noqa: BLE001
|
||||
display_name = chat_id
|
||||
|
||||
chat_type = self._classify_entity(entity)
|
||||
username = getattr(entity, "username", None)
|
||||
phone = getattr(entity, "phone", None) if isinstance(entity, types.User) else None
|
||||
|
||||
results.append(
|
||||
RecentChat(
|
||||
chat_id=chat_id,
|
||||
display_name=display_name,
|
||||
chat_type=chat_type,
|
||||
username=username,
|
||||
phone_number=phone,
|
||||
last_used_at=getattr(dialog, "date", None),
|
||||
)
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
def _classify_entity(entity: object) -> str:
|
||||
if isinstance(entity, types.User):
|
||||
if getattr(entity, "bot", False):
|
||||
return "bot"
|
||||
return "user"
|
||||
if isinstance(entity, types.Chat):
|
||||
return "group"
|
||||
if isinstance(entity, types.Channel):
|
||||
return "channel" if getattr(entity, "broadcast", False) else "group"
|
||||
return "unknown"
|
||||
|
||||
|
||||
telegram_service = TelegramService()
|
||||
|
||||
Reference in New Issue
Block a user