GPQBot

Форк
0
/
botx.py 
133 строки · 4.1 Кб
1
from http import HTTPStatus
2

3
from fastapi import APIRouter, Request
4
from fastapi.responses import JSONResponse
5
from pybotx import (
6
    Bot,
7
    BotXMethodCallbackNotFoundError,
8
    UnknownBotAccountError,
9
    UnsupportedBotAPIVersionError,
10
    UnverifiedRequestError,
11
    build_bot_disabled_response,
12
    build_command_accepted_response,
13
    build_unverified_request_response,
14
)
15
from pybotx.constants import BOT_API_VERSION
16

17
from dependencies.bot import bot_dependency
18
#from app.logger import logger
19
from settings import settings
20

21
router = APIRouter()
22

23

24
@router.post("/command")
25
async def command_handler(request: Request, bot: Bot = bot_dependency) -> JSONResponse:
26
    """Receive commands from users. Max timeout - 5 seconds."""
27

28
    try:  # noqa: WPS225
29
        bot.async_execute_raw_bot_command(
30
            await request.json(),
31
            request_headers=request.headers,
32
        )
33
    except ValueError:
34
        error_label = "Bot command validation error"
35

36
        if settings.DEBUG:
37
            logger.exception(error_label)
38
        else:
39
            logger.warning(error_label)
40

41
        return JSONResponse(
42
            build_bot_disabled_response(error_label),
43
            status_code=HTTPStatus.SERVICE_UNAVAILABLE,
44
        )
45
    except UnknownBotAccountError as exc:
46
        error_label = f"No credentials for bot {exc.bot_id}"
47
        logger.warning(error_label)
48

49
        return JSONResponse(
50
            build_bot_disabled_response(error_label),
51
            status_code=HTTPStatus.SERVICE_UNAVAILABLE,
52
        )
53
    except UnsupportedBotAPIVersionError as exc:
54
        error_label = (
55
            f"Unsupported Bot API version: `{exc.version}`. "
56
            f"Set protocol version to `{BOT_API_VERSION}` in Admin panel."
57
        )
58
        logger.warning(error_label)
59

60
        return JSONResponse(
61
            build_bot_disabled_response(error_label),
62
            status_code=HTTPStatus.SERVICE_UNAVAILABLE,
63
        )
64
    except UnverifiedRequestError as exc:
65
        logger.warning(f"UnverifiedRequestError: {exc.args[0]}")
66
        return JSONResponse(
67
            content=build_unverified_request_response(
68
                status_message=exc.args[0],
69
            ),
70
            status_code=HTTPStatus.UNAUTHORIZED,
71
        )
72

73
    return JSONResponse(
74
        build_command_accepted_response(), status_code=HTTPStatus.ACCEPTED
75
    )
76

77

78
@router.get("/status")
79
async def status_handler(request: Request, bot: Bot = bot_dependency) -> JSONResponse:
80
    """Show bot status and commands list."""
81

82
    try:
83
        status = await bot.raw_get_status(
84
            dict(request.query_params),
85
            request_headers=request.headers,
86
        )
87
    except UnknownBotAccountError as exc:
88
        error_label = f"Unknown bot_id: {exc.bot_id}"
89
        logger.warning(exc)
90
        return JSONResponse(
91
            build_bot_disabled_response(error_label),
92
            status_code=HTTPStatus.SERVICE_UNAVAILABLE,
93
        )
94
    except ValueError:
95
        error_label = "Invalid params"
96
        logger.warning(error_label)
97
        return JSONResponse(
98
            build_bot_disabled_response(error_label), status_code=HTTPStatus.BAD_REQUEST
99
        )
100
    except UnverifiedRequestError as exc:
101
        logger.warning(f"UnverifiedRequestError: {exc.args[0]}")
102
        return JSONResponse(
103
            content=build_unverified_request_response(
104
                status_message=exc.args[0],
105
            ),
106
            status_code=HTTPStatus.UNAUTHORIZED,
107
        )
108

109
    return JSONResponse(status)
110

111

112
@router.post("/notification/callback")
113
async def callback_handler(request: Request, bot: Bot = bot_dependency) -> JSONResponse:
114
    """Process BotX methods callbacks."""
115

116
    try:
117
        await bot.set_raw_botx_method_result(
118
            await request.json(),
119
            verify_request=False,
120
        )
121
    except BotXMethodCallbackNotFoundError as exc:
122
        error_label = f"Unexpected callback with sync_id: {exc.sync_id}"
123
        logger.warning(error_label)
124

125
        return JSONResponse(
126
            build_bot_disabled_response(error_label),
127
            status_code=HTTPStatus.SERVICE_UNAVAILABLE,
128
        )
129

130
    return JSONResponse(
131
        build_command_accepted_response(),
132
        status_code=HTTPStatus.ACCEPTED,
133
    )

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.