diff --git a/app/api/endpoints/botx.py b/app/api/endpoints/botx.py index 50fc306..b22e57b 100644 --- a/app/api/endpoints/botx.py +++ b/app/api/endpoints/botx.py @@ -3,7 +3,6 @@ from http import HTTPStatus from fastapi import APIRouter, Request -from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse from pybotx import ( Bot, @@ -11,14 +10,8 @@ build_bot_disabled_response, build_command_accepted_response, ) -from pybotx_smartapp_rpc import SmartApp -from pybotx_smartapp_rpc.models.request import RPCRequest from app.api.dependencies.bot import bot_dependency -from app.schemas.sync_request import ( - SyncRequest, - transfrorm_sync_request_to_smartapp_event, -) from app.logger import logger router = APIRouter() @@ -66,23 +59,3 @@ async def callback_handler(request: Request, bot: Bot = bot_dependency) -> JSONR build_command_accepted_response(), status_code=HTTPStatus.ACCEPTED, ) - - -@router.post("/smartapps/request") -async def sync_request_handler( - request: SyncRequest, bot: Bot = bot_dependency -) -> JSONResponse: - smartapp_event = transfrorm_sync_request_to_smartapp_event(request, bot) - smartapp = SmartApp( - bot, smartapp_event.bot.id, smartapp_event.chat.id, smartapp_event - ) - rpc_request = RPCRequest(**smartapp_event.data) - - rpc_response = ( - await bot.state.smartapp_rpc._router.perform_rpc_request( # noqa: WPS437 - smartapp, rpc_request - ) - ) - - json = jsonable_encoder(rpc_response.jsonable_dict()) - return JSONResponse(json) diff --git a/app/bot/commands/common.py b/app/bot/commands/common.py index b965568..709963a 100644 --- a/app/bot/commands/common.py +++ b/app/bot/commands/common.py @@ -13,18 +13,10 @@ ) from app.resources import strings -from app.services.answers import build_incoming_command_text collector = HandlerCollector() -@collector.default_message_handler -async def default_handler(message: IncomingMessage, bot: Bot) -> None: - """Show bot command data.""" - if isinstance(message.data, dict) and message.data.get("command") is not None: - await bot.answer_message(build_incoming_command_text(message)) - - @collector.smartapp_event async def handle_smartapp_event(event: SmartAppEvent, bot: Bot) -> None: await bot.state.smartapp_rpc.handle_smartapp_event(event, bot) diff --git a/app/bot/middlewares/debug.py b/app/bot/middlewares/debug.py index 5e2c4df..ae8aeaf 100644 --- a/app/bot/middlewares/debug.py +++ b/app/bot/middlewares/debug.py @@ -2,14 +2,14 @@ from pybotx_smartapp_rpc import RPCArgsBaseModel, SmartApp from pybotx_smartapp_rpc.typing import Handler, RPCResponse +from app.services.answers import build_incoming_smartapp_event_text + async def debug_middleware( smartapp: SmartApp, rpc_arguments: RPCArgsBaseModel, call_next: Handler ) -> RPCResponse: - """TODO: uncomment code after pybotx implements sync requests. - await smartapp.bot.answer_message( - build_incoming_smartapp_event_text(smartapp.event.raw_command) + build_incoming_smartapp_event_text(smartapp.event.raw_command) ) - """ + return await call_next(smartapp, rpc_arguments) diff --git a/app/main.py b/app/main.py index 2091180..46b1362 100644 --- a/app/main.py +++ b/app/main.py @@ -47,8 +47,3 @@ def get_application() -> FastAPI: app = get_application() - - -if __name__ == "__main__": - import uvicorn - uvicorn.run("app.main:app", host='0.0.0.0', port=4004, reload=True, debug=True, workers=3) diff --git a/app/schemas/sync_request.py b/app/schemas/sync_request.py deleted file mode 100644 index 22fe3f5..0000000 --- a/app/schemas/sync_request.py +++ /dev/null @@ -1,132 +0,0 @@ -"""Sync request models.""" -from typing import Any, Dict -from uuid import UUID - -from pybotx import ( # noqa: WPS235 - AttachmentTypes, - Bot, - Chat, - ChatTypes, - ClientPlatforms, - Document, - File, - Image, - SmartAppEvent, - UserDevice, - UserSender, - Video, - Voice, -) -from pydantic import BaseModel, validator - - -class SyncUserInfo(BaseModel): - user_huid: UUID - udid: UUID - platform: ClientPlatforms - - @validator("platform", pre=True) - @classmethod - def transform_platform(cls, platform: str) -> ClientPlatforms: - return ClientPlatforms[platform.upper()] - - -class SyncRequestPayload(BaseModel): - bot_id: UUID - data: Dict[str, Any] = {} # noqa: WPS110 - files: list[File] = [] - opts: Dict[str, Any] = {} - ref: UUID - smartapp_api_version: int - smartapp_id: UUID - - @validator("files", pre=True) - @classmethod - def transform_files(cls, files: list[Dict[str, Any]]) -> list[File]: - return list(map(transform_dict_to_file, files)) - - -class SyncRequest(BaseModel): - """Sync request data model.""" - - bot_id: UUID - group_chat_id: UUID - sender_info: SyncUserInfo - method: str - payload: SyncRequestPayload - - -def transform_dict_to_file(file: Dict[str, Any]) -> File: # noqa: WPS110 - attachment_type = AttachmentTypes[str(file["type"]).upper()] - duration = int(file["duration"]) if "duration" in file else 0 - - args = { - "type": attachment_type, - "filename": file["file_name"], - "size": int(file["file_size"]), - "duration": duration, - "is_async_file": True, - "_file_id": UUID(file["file_id"]), - "_file_mimetype": file["file_mime_type"], - "_file_url": file["file"], - "_file_hash": file["file_hash"], - } - - if attachment_type == AttachmentTypes.IMAGE: - return Image(**args) - - if attachment_type == AttachmentTypes.VIDEO: - return Video(**args) - - if attachment_type == AttachmentTypes.DOCUMENT: - return Document(**args) - - if attachment_type == AttachmentTypes.VOICE: - return Voice(**args) - - raise NotImplementedError(f"Unsupported attachment type: {attachment_type}") - - -def transfrorm_sync_request_to_smartapp_event( - request: SyncRequest, bot: Bot -) -> SmartAppEvent: - device = UserDevice( - platform=request.sender_info.platform, - manufacturer="", - device_name="", - os="", - pushes=True, - timezone="", - permissions={}, - platform_package_id="", - app_version="", - locale="", - ) - sender = UserSender( - huid=request.sender_info.user_huid, - udid=request.sender_info.udid, - device=device, - ad_login="", - ad_domain="", - username="", - is_chat_admin=False, - is_chat_creator=True, - ) - chat = Chat( - id=request.group_chat_id, - type=ChatTypes.PERSONAL_CHAT, - ) - account = next(acc for acc in bot.bot_accounts if acc.id == request.bot_id) - - return SmartAppEvent( - bot=account, - chat=chat, - raw_command={}, # ???? - ref=request.payload.ref, - smartapp_id=request.payload.smartapp_id, - data=request.payload.data, # noqa: WPS110 - opts=request.payload.opts, - smartapp_api_version=request.payload.smartapp_api_version, - files=request.payload.files, - sender=sender, - ) diff --git a/app/services/answers.py b/app/services/answers.py index 0cc21ca..2fbf437 100644 --- a/app/services/answers.py +++ b/app/services/answers.py @@ -2,7 +2,7 @@ from typing import Any, Dict from aiofiles.tempfile import SpooledTemporaryFile -from pybotx import File, Image, IncomingMessage, UserFromSearch +from pybotx import File, Image, UserFromSearch from pybotx_smartapp_rpc import SmartApp from app.services.beautify import beautify_dict @@ -64,11 +64,3 @@ async def build_static_image_url(image_file: Image, smartapp: SmartApp) -> str: ) return link - - -def build_incoming_command_text(message: IncomingMessage) -> str: - return ( - f"Incoming command:\n\n" - f"body:\n```\n{message.body}\n```\n\n" - f"data:\n```\n{beautify_dict(message.data)}\n```" - )