本次提交包含多个Slack适配器相关的代码优化: 1. 统一多个文件中datetime和UTC的导入顺序 2. 调整collection.abc导入的参数顺序 3. 修复normalizer.py的文件末尾空行问题 4. 重新排序blocks.py中的函数导入 5. 调整directory_config.py中的函数顺序 6. 重构http_handler中的channel_manager调用方式 7. 新增Slack原生流探测逻辑和相关状态管理 8. 扩展消息动作分类和默认配置 9. 新增大量Slack消息块构建工具函数 10. 大幅重构__init__.py的导出内容,整理导入顺序 11. 为adapter新增熔断机制、缓存持久化和更多API方法 12. 新增多种系统事件处理逻辑
58 lines
1.9 KiB
Python
58 lines
1.9 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, Request, status
|
|
from fastapi.responses import JSONResponse, PlainTextResponse
|
|
|
|
from yuxi.channels.manager import get_channel_manager
|
|
from yuxi.utils.logging_config import logger
|
|
|
|
slack_webhook = APIRouter(tags=["slack-webhook"])
|
|
|
|
|
|
@slack_webhook.post("/api/webhook/slack")
|
|
async def slack_event_receiver(request: Request):
|
|
adapter = get_channel_manager()._adapters.get("slack")
|
|
if not adapter:
|
|
return JSONResponse(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
content={"error": "Slack adapter is not running"},
|
|
)
|
|
|
|
body = await request.body()
|
|
headers = dict(request.headers)
|
|
|
|
if not await adapter.verify_webhook_signature(headers, body):
|
|
return JSONResponse(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
content={"error": "Invalid webhook signature"},
|
|
)
|
|
|
|
try:
|
|
payload: dict[str, Any] = json.loads(body.decode("utf-8"))
|
|
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
|
logger.error(f"Slack webhook: failed to parse JSON body: {e}")
|
|
return JSONResponse(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
content={"error": "Invalid JSON body"},
|
|
)
|
|
|
|
event_type = payload.get("type", "")
|
|
|
|
if event_type == "url_verification":
|
|
challenge = payload.get("challenge", "")
|
|
logger.info("Slack URL verification challenge received, responding with challenge")
|
|
return PlainTextResponse(content=challenge, status_code=200)
|
|
|
|
if event_type == "event_callback":
|
|
try:
|
|
await adapter._handle_http_event(payload)
|
|
except Exception as e:
|
|
logger.error(f"Slack webhook event handling error: {e}", exc_info=True)
|
|
return JSONResponse(content={"ok": True})
|
|
|
|
logger.debug(f"Slack webhook: unhandled event type '{event_type}'")
|
|
return JSONResponse(content={"ok": True})
|