import io from typing import Dict, Optional from aiohttp import web from cfg import BOT_ID, bot, logger # Кэш аватарок в памяти: chat_id -> байты изображения. _photo: Dict[int, bytes] = {} # Кэш идентификаторов файлов: chat_id -> file_id (или None, если аватарки нет). _fid: Dict[int, Optional[str]] = {} async def _file_id(chat_id: int) -> Optional[str]: if chat_id in _fid: return _fid[chat_id] fid: Optional[str] = None try: chat = await bot.get_chat(chat_id) photo = getattr(chat, "photo", None) if photo is not None: fid = photo.big_file_id or photo.small_file_id except Exception as e: logger.warning("avatar get_chat %s: %s", chat_id, e) _fid[chat_id] = fid return fid async def get_avatar(chat_id: int) -> Optional[bytes]: if chat_id in _photo: return _photo[chat_id] fid = await _file_id(chat_id) if not fid: return None try: file = await bot.get_file(fid) buf = io.BytesIO() await bot.download_file(file.file_path, buf) data = buf.getvalue() except Exception as e: logger.warning("avatar download %s: %s", chat_id, e) return None _photo[chat_id] = data return data async def avatar_handler(request) -> web.Response: raw = request.match_info["chat_id"] chat_id = BOT_ID if raw == "bot" else int(raw) if not chat_id: raise web.HTTPNotFound() data = await get_avatar(chat_id) if not data: raise web.HTTPNotFound() return web.Response( body=data, content_type="image/jpeg", headers={"Cache-Control": "public, max-age=3600"}, )