Бот для капчи в чатах
Roman Sergienko
12 hours ago 7cd2882023553d4cc27db04e8d05a6b8653645a6
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
import io
import mimetypes
from typing import Dict, Optional, Tuple
 
from aiohttp import web
 
import db
from cfg import bot, logger
 
# Кэш в памяти: file_id -> (байты, content-type).
_cache: Dict[str, Tuple[bytes, str]] = {}
 
 
async def get_media(file_id: str) -> Optional[Tuple[bytes, str]]:
    if file_id in _cache:
        return _cache[file_id]
    try:
        f = await bot.get_file(file_id)
        buf = io.BytesIO()
        await bot.download_file(f.file_path, buf)
        data = buf.getvalue()
    except Exception as e:
        logger.warning("media download: %s", e)
        return None
    ctype = mimetypes.guess_type(f.file_path or "")[0] or "application/octet-stream"
    _cache[file_id] = (data, ctype)
    return data, ctype
 
 
async def media_handler(request) -> web.Response:
    try:
        msg_id = int(request.match_info["msg_id"])
    except ValueError:
        raise web.HTTPNotFound()
    row = await db.get_msg(msg_id)
    if not row or not row.get("media_file_id"):
        raise web.HTTPNotFound()
    result = await get_media(row["media_file_id"])
    if not result:
        raise web.HTTPNotFound()
    data, ctype = result
    return web.Response(
        body=data, content_type=ctype, headers={"Cache-Control": "public, max-age=86400"}
    )