Бот для капчи в чатах
Roman Sergienko
8 hours ago 0b66bae39759a5553d8ce46131dca3026325097b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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"},
    )