wecom.py
6.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
"""企业微信:机器人登记、接收对象(发到哪个群 / 哪个人、做什么用)、收发记录、测试发送。"""
from __future__ import annotations
import datetime as dt
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from ..services import aitrace, audit, im, msglog, settings
from .deps import Scope, current_store
router = APIRouter(prefix="/api/wecom", tags=["wecom"])
class BotIn(BaseModel):
name: str
bot_id: str
channel: str = "yjy_ww"
enabled: bool = True
note: str = ""
class TargetIn(BaseModel):
name: str
bot_ref: int
kind: str = "group"
contact_id: str
# 单人对象库里这几项存的是 NULL,编辑时前端会原样带回来:允许 None,按空串处理(im.save_target 里统一清洗)
contact_name: str | None = ""
at_ids: str | None = ""
bot_names: str | None = ""
purposes: list[str] = ["chat"]
alert_min: str = "warn"
enabled: bool = True
@router.get("/overview")
def overview(s: Scope = Depends(current_store)):
ts = [t | {"sync": im.sync_status(t["id"]) if "chat" in t["purposes"] else None} for t in im.targets(s.store_id)]
return {"bots": im.bots(), "targets": ts, "purposes": im.PURPOSES,
"contact_types": im.CONTACT_TYPES, "gateway": settings.get().im_api_base}
@router.get("/contacts")
def contacts(bot_ref: int, type: str = "", keyword: str = "", page: int = 1, size: int = 20,
s: Scope = Depends(current_store)):
"""从网关通讯录选群 / 选人(只开放企微外部群、内部群、同事、客户四种)。"""
try:
return im.contacts(s.store_id, bot_ref, type, keyword.strip(), page, size)
except ValueError as e:
raise HTTPException(400, str(e))
except RuntimeError as e:
raise HTTPException(502, str(e))
@router.post("/bots")
def create_bot(body: BotIn, s: Scope = Depends(current_store)):
try:
bid = im.save_bot(body.model_dump())
except ValueError as e:
raise HTTPException(400, str(e))
audit.record(s.store_id, s.actor, "im.bot.save", target_type="im_bot", target_id=str(bid), after=body.model_dump())
return {"id": bid}
@router.put("/bots/{bid}")
def update_bot(bid: int, body: BotIn, s: Scope = Depends(current_store)):
before = im.bot(bid)
if not before:
raise HTTPException(404, "机器人不存在")
try:
im.save_bot(body.model_dump(), bid)
except ValueError as e:
raise HTTPException(400, str(e))
audit.record(s.store_id, s.actor, "im.bot.save", target_type="im_bot", target_id=str(bid),
before={k: before[k] for k in ("name", "bot_id", "channel", "enabled")}, after=body.model_dump())
return {"ok": True}
@router.delete("/bots/{bid}")
def delete_bot(bid: int, s: Scope = Depends(current_store)):
before = im.bot(bid)
try:
im.delete_bot(bid)
except ValueError as e:
raise HTTPException(409, str(e))
audit.record(s.store_id, s.actor, "im.bot.delete", target_type="im_bot", target_id=str(bid), before=before)
return {"ok": True}
@router.post("/targets")
def create_target(body: TargetIn, s: Scope = Depends(current_store)):
try:
tid = im.save_target(s.store_id, body.model_dump())
except ValueError as e:
raise HTTPException(400, str(e))
audit.record(s.store_id, s.actor, "im.target.save", target_type="im_target", target_id=str(tid),
after=body.model_dump())
return {"id": tid}
@router.put("/targets/{tid}")
def update_target(tid: int, body: TargetIn, s: Scope = Depends(current_store)):
before = im.target(tid)
if not before or before["store_id"] != s.store_id:
raise HTTPException(404, "接收对象不存在")
try:
im.save_target(s.store_id, body.model_dump(), tid)
except ValueError as e:
raise HTTPException(400, str(e))
audit.record(s.store_id, s.actor, "im.target.save", target_type="im_target", target_id=str(tid),
before={k: before[k] for k in ("name", "bot_ref", "kind", "contact_id", "at_ids", "bot_names", "purposes",
"alert_min", "enabled")}, after=body.model_dump())
return {"ok": True}
@router.delete("/targets/{tid}")
def delete_target(tid: int, s: Scope = Depends(current_store)):
before = im.target(tid)
if before and before["store_id"] != s.store_id:
before = None
im.delete_target(s.store_id, tid)
audit.record(s.store_id, s.actor, "im.target.delete", target_type="im_target", target_id=str(tid), before=before)
return {"ok": True}
@router.post("/targets/{tid}/test")
def test_target(tid: int, s: Scope = Depends(current_store)):
t = im.target(tid)
if not t or t["store_id"] != s.store_id:
raise HTTPException(404, "接收对象不存在")
ok, err = im.test_send(t, s.actor.name)
return {"ok": ok, "error": err}
@router.get("/logs")
def logs(page: int = 1, size: int = 30, direction: str = "", since: dt.date | None = None,
until: dt.date | None = None, keyword: str = "", category: str = "", target_id: int | None = None,
sender: str = "", result: str = "", channel: str = "", severity: str = "", doc_no: str = "",
s: Scope = Depends(current_store)):
"""消息记录:全部收发(对话 / 被忽略 / 告警 / 群机器人 / 测试 / 系统提示 / 非本系统发送),category 逗号分隔多选,留空 = 全部。"""
try:
return msglog.query(s.store_id, categories=category.split(","), target_id=target_id, since=since, until=until,
direction=direction, sender=sender, keyword=keyword, result=result, channel=channel,
severity=severity, doc_no=doc_no, page=page, size=min(max(size, 1), 200))
except LookupError as e:
raise HTTPException(404, str(e))
except ValueError as e:
raise HTTPException(400, str(e))
@router.get("/logs/{log_id}/trace")
def log_trace(log_id: int, s: Scope = Depends(current_store)):
"""一句收到的话的完整处理过程:给模型的输入、每一轮模型调用、工具执行、最终结果。"""
t = aitrace.get(s.store_id, log_id)
if not t:
raise HTTPException(404, "这条消息没有处理记录(没交给助手,或已过保留期被清理)")
return t