Files
PWF/CoreRouters/callback.py

79 lines
2.4 KiB
Python
Raw Normal View History

2025-11-05 16:21:05 +08:00
"""Callback路由处理"""
2025-11-05 17:27:15 +08:00
from ..Convention.Runtime.GlobalConfig import ProjectConfig
2025-11-05 16:21:05 +08:00
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
2025-11-05 17:27:15 +08:00
from ..CoreModules.models import CallbackRequest
from ..CoreModules.plugin_interface import PluginInterface
2025-11-05 16:21:05 +08:00
2025-11-05 17:27:15 +08:00
config = ProjectConfig()
ALWAYS_RETURN_OK = config.FindItem("always_return_ok", True) # 返回ok可以避免重试
2025-11-05 16:21:05 +08:00
router = APIRouter()
@router.get("/callback")
async def callback_verify():
2025-11-05 17:27:15 +08:00
"""Callback可用性校验"""
config.Log("Info", "收到Callback验证请求")
2025-11-05 16:21:05 +08:00
return JSONResponse({"result": "ok"})
@router.post("/callback")
async def callback_receive(request: Request):
2025-11-05 17:27:15 +08:00
"""Callback消息"""
2025-11-05 16:21:05 +08:00
try:
# 解析请求数据
data = await request.json()
2025-11-05 17:27:15 +08:00
config.Log("Info", f"完整callback数据: {data}")
2025-11-05 16:21:05 +08:00
# 验证请求
try:
callback_data = CallbackRequest(**data)
except Exception as e:
2025-11-05 17:27:15 +08:00
config.Log("Error", f"请求数据验证失败: {e}")
if ALWAYS_RETURN_OK:
return JSONResponse({"result": "ok"})
else:
return JSONResponse({"result": "error", "message": str(e)})
2025-11-05 16:21:05 +08:00
# 解析指令
2025-11-05 17:27:15 +08:00
content = callback_data.content
command = content.split(" ")[0]
config.Log("Info", f"识别指令: command={command}")
2025-11-05 16:21:05 +08:00
2025-11-05 17:27:15 +08:00
# TODO: 处理指令
return await handle_command(command, content, callback_data.chatid, callback_data.creator)
2025-11-05 16:21:05 +08:00
except Exception as e:
2025-11-05 17:27:15 +08:00
config.Log("Error", f"处理Callback异常: {e}", exc_info=True)
if ALWAYS_RETURN_OK:
return JSONResponse({"result": "ok"})
else:
return JSONResponse({"result": "error", "message": str(e)})
2025-11-05 16:21:05 +08:00
2025-11-05 17:27:15 +08:00
async def handle_command(command: str, content: str,
2025-11-05 16:21:05 +08:00
chat_id: int, user_id: int) -> str:
"""处理游戏指令
Args:
2025-11-05 17:27:15 +08:00
command: 指令
content: 消息内容
2025-11-05 16:21:05 +08:00
chat_id: 会话ID
user_id: 用户ID
Returns:
回复文本
"""
try:
2025-11-05 17:27:15 +08:00
plugin = PluginInterface.plugin_instances.get(command, None)
if plugin:
return plugin.callback(content, chat_id, user_id)
2025-11-05 16:21:05 +08:00
else:
2025-11-05 17:27:15 +08:00
return f"❌ 未识别指令: {command}"
2025-11-05 16:21:05 +08:00
except Exception as e:
2025-11-05 17:27:15 +08:00
config.Log("Error", f"处理指令异常: {e}", exc_info=True)
return f"❌ 处理指令时出错: {str(e)}"
2025-11-05 16:21:05 +08:00