```
feat(feishu): 添加飞书长连接支持并重构事件处理 添加了 FeishuEventService 来统一处理飞书消息事件, 新增 long_connection.py 实现长连接客户端, 修改 webhook 路由使用新的事件处理服务, 添加了 lark-oapi 依赖支持长连接功能, 更新测试用例覆盖新的事件处理逻辑。 BREAKING CHANGE: 飞书事件处理逻辑重构,统一使用 FeishuEventService 进行消息处理和审计记录。 ```
This commit is contained in:
43
app/modules/feishu/events.py
Normal file
43
app/modules/feishu/events.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.modules.audit.schemas import AuditLogCreate
|
||||
from app.modules.feishu.commands import FeishuCommandService
|
||||
from app.modules.feishu.service import FeishuService
|
||||
|
||||
|
||||
class FeishuEventService:
|
||||
"""Handle Feishu message events from webhook or long connection."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
self.feishu = FeishuService(db)
|
||||
self.commands = FeishuCommandService(db)
|
||||
|
||||
def handle_event(
|
||||
self,
|
||||
payload: dict[str, Any],
|
||||
source: str,
|
||||
auto_reply: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
self.feishu.verify_event(payload)
|
||||
self.feishu.audit.log(
|
||||
AuditLogCreate(
|
||||
actor="feishu",
|
||||
source="feishu",
|
||||
action=f"{source}_event",
|
||||
request_payload=payload,
|
||||
response_payload={"accepted": True},
|
||||
)
|
||||
)
|
||||
command = self.commands.extract_event_command(payload)
|
||||
if not command:
|
||||
return {"ok": True, "handled": False}
|
||||
result = self.commands.handle_text(
|
||||
command["text"],
|
||||
chat_id=command["chat_id"],
|
||||
actor=command["actor"],
|
||||
auto_reply=auto_reply,
|
||||
)
|
||||
return {"ok": True, "handled": True, "result": result}
|
||||
79
app/modules/feishu/long_connection.py
Normal file
79
app/modules/feishu/long_connection.py
Normal file
@@ -0,0 +1,79 @@
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from app.core.config import get_settings
|
||||
from app.core.database import SessionLocal
|
||||
from app.modules.feishu.events import FeishuEventService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _sdk_domain(base_url: str) -> str:
|
||||
parsed = urlsplit(base_url)
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
return "https://open.feishu.cn"
|
||||
return f"{parsed.scheme}://{parsed.netloc}"
|
||||
|
||||
|
||||
def _sdk_event_to_payload(event: Any) -> dict[str, Any]:
|
||||
try:
|
||||
from lark_oapi.core.json import JSON
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("lark-oapi is required for Feishu long connection") from exc
|
||||
|
||||
data = JSON.marshal(event)
|
||||
if not data:
|
||||
return {}
|
||||
return json.loads(data)
|
||||
|
||||
|
||||
def _handle_message_event(event: Any) -> None:
|
||||
payload = _sdk_event_to_payload(event)
|
||||
db = SessionLocal()
|
||||
try:
|
||||
result = FeishuEventService(db).handle_event(
|
||||
payload,
|
||||
source="long_connection",
|
||||
auto_reply=True,
|
||||
)
|
||||
logger.info("Handled Feishu long connection event: %s", result)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def run_long_connection() -> None:
|
||||
"""Start the Feishu long connection client and block forever."""
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.feishu_app_id or not settings.feishu_app_secret:
|
||||
raise RuntimeError("FEISHU_APP_ID and FEISHU_APP_SECRET are required")
|
||||
|
||||
try:
|
||||
import lark_oapi as lark
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("Install lark-oapi before starting Feishu long connection") from exc
|
||||
|
||||
event_handler = (
|
||||
lark.EventDispatcherHandler.builder(
|
||||
settings.feishu_encrypt_key or "",
|
||||
settings.feishu_verification_token or "",
|
||||
)
|
||||
.register_p2_im_message_receive_v1(_handle_message_event)
|
||||
.build()
|
||||
)
|
||||
client = lark.ws.Client(
|
||||
app_id=settings.feishu_app_id,
|
||||
app_secret=settings.feishu_app_secret,
|
||||
event_handler=event_handler,
|
||||
log_level=lark.LogLevel.WARNING,
|
||||
domain=_sdk_domain(settings.feishu_base_url),
|
||||
)
|
||||
logger.info("Starting Feishu long connection client")
|
||||
client.start()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
run_long_connection()
|
||||
@@ -3,8 +3,8 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import require_api_key
|
||||
from app.modules.audit.schemas import AuditLogCreate
|
||||
from app.modules.feishu.commands import FeishuCommandService
|
||||
from app.modules.feishu.events import FeishuEventService
|
||||
from app.modules.feishu.schemas import (
|
||||
FeishuCardMessage,
|
||||
FeishuCommandRequest,
|
||||
@@ -26,25 +26,7 @@ async def feishu_webhook(request: Request, db: Session = Depends(get_db)) -> dic
|
||||
service.verify_event(payload)
|
||||
if payload.get("challenge"):
|
||||
return {"challenge": payload["challenge"]}
|
||||
service.audit.log(
|
||||
AuditLogCreate(
|
||||
actor="feishu",
|
||||
source="feishu",
|
||||
action="webhook_event",
|
||||
request_payload=payload,
|
||||
response_payload={"accepted": True},
|
||||
)
|
||||
)
|
||||
command = FeishuCommandService(db).extract_event_command(payload)
|
||||
if not command:
|
||||
return {"ok": True, "handled": False}
|
||||
result = FeishuCommandService(db).handle_text(
|
||||
command["text"],
|
||||
chat_id=command["chat_id"],
|
||||
actor=command["actor"],
|
||||
auto_reply=True,
|
||||
)
|
||||
return {"ok": True, "handled": True, "result": result}
|
||||
return FeishuEventService(db).handle_event(payload, source="webhook", auto_reply=True)
|
||||
|
||||
|
||||
@router.post("/send-text", response_model=FeishuSendResult, dependencies=[Depends(require_api_key)])
|
||||
|
||||
@@ -20,7 +20,8 @@ class FeishuService:
|
||||
def verify_event(self, payload: dict[str, Any]) -> None:
|
||||
settings = get_settings()
|
||||
expected = settings.feishu_verification_token
|
||||
token = payload.get("token")
|
||||
header = payload.get("header") or {}
|
||||
token = payload.get("token") or header.get("token")
|
||||
if expected and token and token != expected:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
|
||||
Reference in New Issue
Block a user