| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- """
- api.v1.feishu — 飞书机器人 Webhook 端点
- 飞书开放平台事件订阅 URL: http://your-server:8000/api/v1/feishu/webhook
- """
- from __future__ import annotations
- import json
- import os
- from fastapi import APIRouter, Request
- from fastapi.responses import JSONResponse
- router = APIRouter(prefix="/feishu", tags=["feishu"])
- # Agent runner(延迟初始化)
- _runner = None
- def _get_runner():
- global _runner
- if _runner is None:
- agent_id = os.environ.get("FEISHU_AGENT_ID", "")
- if agent_id:
- from agentpaas.services.feishu import make_paas_runner
- _runner = make_paas_runner(agent_id)
- return _runner
- @router.post("/webhook")
- async def feishu_webhook(request: Request):
- """
- 飞书事件回调端点。
- 飞书开放平台配置:
- 请求地址: http://your-server:8000/api/v1/feishu/webhook
- 加密策略: 不加密(开发阶段)
- """
- try:
- body = await request.json()
- except Exception:
- return JSONResponse({"code": -1, "msg": "invalid json"})
- from agentpaas.services.feishu import handle_event
- # 使用线程池执行 Agent(避免阻塞 event loop)
- import asyncio
- loop = asyncio.get_event_loop()
- result = await loop.run_in_executor(None, handle_event, body, _get_runner())
- return JSONResponse(result)
- @router.post("/bind")
- async def feishu_bind(request: Request):
- """绑定 Agent 到飞书机器人。"""
- global _runner
- try:
- data = await request.json()
- except Exception:
- return JSONResponse({"error": "invalid json"}, status_code=400)
- agent_id = data.get("agent_id", "")
- if not agent_id:
- return JSONResponse({"error": "agent_id required"}, status_code=400)
- from agentpaas.services.feishu import make_paas_runner
- _runner = make_paas_runner(agent_id)
- os.environ["FEISHU_AGENT_ID"] = agent_id
- return {"status": "ok", "agent_id": agent_id, "message": f"飞书机器人已绑定 Agent {agent_id}"}
- @router.get("/status")
- async def feishu_status():
- """查看飞书机器人状态。"""
- from agentpaas.services.feishu import FEISHU_APP_ID, FEISHU_AGENT_ID
- return {
- "app_id": FEISHU_APP_ID,
- "agent_id": FEISHU_AGENT_ID or os.environ.get("FEISHU_AGENT_ID", "(未绑定)"),
- "webhook_url": "/api/v1/feishu/webhook",
- "runner_active": _runner is not None,
- }
|