215 lines
7.6 KiB
Python
215 lines
7.6 KiB
Python
import httpx
|
|
import os
|
|
import json
|
|
from typing import List, Dict, Any
|
|
|
|
class LarkService:
|
|
def __init__(self):
|
|
self.app_id = os.getenv("LARK_APP_ID", "")
|
|
self.app_secret = os.getenv("LARK_APP_SECRET", "")
|
|
self.verification_token = os.getenv("LARK_VERIFICATION_TOKEN", "")
|
|
self.tenant_access_token = ""
|
|
|
|
async def get_tenant_access_token(self):
|
|
"""
|
|
Get tenant_access_token from Lark Open Platform
|
|
"""
|
|
if not self.app_id or not self.app_secret:
|
|
print("[LARK] Missing App ID or Secret. Simulation mode.")
|
|
return "mock_token"
|
|
|
|
url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
|
|
headers = {"Content-Type": "application/json; charset=utf-8"}
|
|
payload = {
|
|
"app_id": self.app_id,
|
|
"app_secret": self.app_secret
|
|
}
|
|
|
|
async with httpx.AsyncClient() as client:
|
|
try:
|
|
response = await client.post(url, headers=headers, json=payload)
|
|
data = response.json()
|
|
if data.get("code") == 0:
|
|
self.tenant_access_token = data.get("tenant_access_token")
|
|
return self.tenant_access_token
|
|
else:
|
|
print(f"[LARK] Failed to get token: {data}")
|
|
return None
|
|
except Exception as e:
|
|
print(f"[LARK] Token request failed: {e}")
|
|
return None
|
|
|
|
async def send_card_message(self, chat_id: str, content: str, tasks: List[Dict[str, Any]]):
|
|
"""
|
|
Send a card message to Lark with task breakdown
|
|
"""
|
|
token = await self.get_tenant_access_token()
|
|
if not token:
|
|
print("[LARK] Cannot send message without token.")
|
|
return
|
|
|
|
url = f"https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id"
|
|
headers = {
|
|
"Authorization": f"Bearer {token}",
|
|
"Content-Type": "application/json; charset=utf-8"
|
|
}
|
|
|
|
# Construct Card Content
|
|
task_elements = []
|
|
for task in tasks:
|
|
task_elements.append({
|
|
"tag": "div",
|
|
"text": {
|
|
"tag": "lark_md",
|
|
"content": f"**{task.get('task_name')}**\nType: {task.get('type')} | Est: {task.get('estimated_hours')}h"
|
|
}
|
|
})
|
|
task_elements.append({
|
|
"tag": "hr"
|
|
})
|
|
|
|
card_content = {
|
|
"config": {
|
|
"wide_screen_mode": True
|
|
},
|
|
"header": {
|
|
"template": "blue",
|
|
"title": {
|
|
"content": "🚀 任务拆解完成 (Synced to Plane)",
|
|
"tag": "plain_text"
|
|
}
|
|
},
|
|
"elements": [
|
|
{
|
|
"tag": "div",
|
|
"text": {
|
|
"tag": "lark_md",
|
|
"content": f"收到需求:**{content}**\n已为您拆解为以下任务并同步至项目看板:"
|
|
}
|
|
},
|
|
{
|
|
"tag": "hr"
|
|
},
|
|
*task_elements,
|
|
{
|
|
"tag": "note",
|
|
"elements": [
|
|
{
|
|
"tag": "plain_text",
|
|
"content": f"共 {len(tasks)} 个子任务"
|
|
}
|
|
]
|
|
}
|
|
]
|
|
}
|
|
|
|
payload = {
|
|
"receive_id": chat_id,
|
|
"msg_type": "interactive",
|
|
"content": json.dumps(card_content)
|
|
}
|
|
|
|
if token == "mock_token":
|
|
print(f"[LARK SIMULATION] Sending Card to {chat_id}: {json.dumps(card_content, indent=2, ensure_ascii=False)}")
|
|
return
|
|
|
|
async with httpx.AsyncClient() as client:
|
|
try:
|
|
response = await client.post(url, headers=headers, json=payload)
|
|
print(f"[LARK] Send message response: {response.json()}")
|
|
except Exception as e:
|
|
print(f"[LARK] Send message failed: {e}")
|
|
|
|
async def send_strategic_alert(self, chat_id: str, signal_content: str, decision: Dict[str, Any], tasks: List[Dict[str, Any]]):
|
|
"""
|
|
Send a strategic alert card message to Lark.
|
|
"""
|
|
token = await self.get_tenant_access_token()
|
|
if not token:
|
|
print("[LARK] Cannot send message without token.")
|
|
return
|
|
|
|
url = f"https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id"
|
|
headers = {
|
|
"Authorization": f"Bearer {token}",
|
|
"Content-Type": "application/json; charset=utf-8"
|
|
}
|
|
|
|
# Construct Card Content
|
|
# Color: Red for Strategic
|
|
|
|
card_content = {
|
|
"config": {
|
|
"wide_screen_mode": True
|
|
},
|
|
"header": {
|
|
"template": "red",
|
|
"title": {
|
|
"content": "🚨 战略级信号预警 (Strategic Alert)",
|
|
"tag": "plain_text"
|
|
}
|
|
},
|
|
"elements": [
|
|
{
|
|
"tag": "div",
|
|
"text": {
|
|
"tag": "lark_md",
|
|
"content": f"**信号摘要**:\n{signal_content}"
|
|
}
|
|
},
|
|
{
|
|
"tag": "hr"
|
|
},
|
|
{
|
|
"tag": "div",
|
|
"text": {
|
|
"tag": "lark_md",
|
|
"content": f"**🤖 AI 决策建议**:\n{decision.get('recommendation', '无建议')}\n\n**预期收益**: {decision.get('expected_benefits', '未评估')}"
|
|
}
|
|
},
|
|
{
|
|
"tag": "hr"
|
|
},
|
|
{
|
|
"tag": "div",
|
|
"text": {
|
|
"tag": "lark_md",
|
|
"content": f"**已自动创建 P0 级任务 ({len(tasks)}个)**:\n" + "\n".join([f"- {t.get('task_name')} ({t.get('estimated_hours')}h)" for t in tasks[:3]]) + (f"\n...等 {len(tasks)-3} 个任务" if len(tasks) > 3 else "")
|
|
}
|
|
},
|
|
{
|
|
"tag": "action",
|
|
"actions": [
|
|
{
|
|
"tag": "button",
|
|
"text": {
|
|
"tag": "plain_text",
|
|
"content": "👀 查看指挥部仪表盘"
|
|
},
|
|
"type": "primary",
|
|
"url": "http://localhost:5173/" # Replace with actual deployed URL
|
|
}
|
|
]
|
|
}
|
|
]
|
|
}
|
|
|
|
payload = {
|
|
"receive_id": chat_id,
|
|
"msg_type": "interactive",
|
|
"content": json.dumps(card_content)
|
|
}
|
|
|
|
if token == "mock_token":
|
|
print(f"[LARK SIMULATION] Sending Strategic Alert to {chat_id}: {json.dumps(card_content, indent=2, ensure_ascii=False)}")
|
|
return
|
|
|
|
async with httpx.AsyncClient() as client:
|
|
try:
|
|
response = await client.post(url, headers=headers, json=payload)
|
|
print(f"[LARK] Send alert response: {response.json()}")
|
|
except Exception as e:
|
|
print(f"[LARK] Send alert failed: {e}")
|
|
|
|
lark_service = LarkService()
|