gateway.py
6.07 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
"""企业微信网关(imhub,yjy_ww 通道)收发。协议与 demo/im_server/adapters/yjy.py 一致,已用真实机器人实测:
拉消息 GET {api}/core/msgs?channel=yjy_ww&bot_id=&contact_id=&start_time=&end_time=&limit=50&offset=0
发文字 POST {api}/yjy/send/text {robot_key: bot_id, friends: [contact_id], content, at_user_list: []}
传图片 POST {api}/common/upload multipart file → {"url": OSS 公网地址}
发图片 POST {api}/yjy/send/image {robot_key, friends, pic_url}
所有发送都记 rsk_sys_chat_messages;失败写运行日志(error)并返回 (False, 原因),调用方负责告知用户/页面。
"""
from __future__ import annotations
import re
import threading
import time
from pathlib import Path
from urllib.parse import quote
import requests
from .. import db, events
from ..settings import S
TIMEOUT = 30
_LOCK = threading.Lock()
_last_send = 0.0
SEND_GAP = 1.2 # 两条消息之间至少间隔(秒),避免触发网关频控、保证顺序
def _api() -> str:
return str(S.get("im.api_base")).rstrip("/")
def _headers() -> dict:
tok = S.env("IM_API_TOKEN")
return {"Authorization": f"Bearer {tok}"} if tok else {}
def _record(direction: str, kind: str, content: str, ok: bool, error: str = "", sender: str = "", msg_id: str = ""):
try:
db.q(db.insert(db.chat_t).values(ts=db.now(), direction=direction, kind=kind, sender=sender,
content=content, ok=ok, error=error or None, msg_id=msg_id or None))
except Exception as e: # noqa: BLE001
events.log.error("写会话记录失败:%s", e)
def _post(path: str, payload: dict) -> tuple[bool, str, dict]:
global _last_send
with _LOCK:
wait = _last_send + SEND_GAP - time.time()
if wait > 0:
time.sleep(wait)
try:
r = requests.post(_api() + path, json=payload, headers=_headers(), timeout=TIMEOUT)
_last_send = time.time()
except Exception as e: # noqa: BLE001
return False, f"网关不可达:{e}", {}
try:
res = r.json()
except ValueError:
res = {"raw": r.text[:200]}
ok = r.status_code == 200 and str(res.get("code", "")).strip() in ("0", "200", "202", "")
return ok, "" if ok else f"HTTP {r.status_code} code={res.get('code')} msg={res.get('msg') or res.get('message')} body={r.text[:200]}", res
def configured() -> tuple[bool, str]:
if not S.get("im.enabled"):
return False, "企业微信未启用(设置 im.enabled)"
if not S.get("im.bot_id") or not S.get("im.contact_id"):
return False, "没有配置机器人 bot_id 或联系人 contact_id"
return True, ""
def is_group() -> bool:
return "group" in str(S.get("im.contact_type") or "").lower()
def needs_at() -> bool:
"""群聊且要求 @ 机器人才回复。"""
return is_group() and bool(S.get("im.require_at"))
def strip_at_bot(text: str) -> str | None:
"""文本里 @ 了机器人(im.bot_name,多个别名逗号分隔)→ 返回去掉 @昵称 后的正文;没 @ 到返回 None。
企微 @ 后面跟的是特殊空格(U+2005 / U+00A0),一并去掉。"""
names = S.list("im.bot_name")
if not names:
return None
pat = re.compile("@(?:" + "|".join(re.escape(n) for n in sorted(names, key=len, reverse=True)) + r")[\s ]*",
re.IGNORECASE)
if not pat.search(text):
return None
return pat.sub("", text).strip()
def send_text(text: str) -> tuple[bool, str]:
ok, why = configured()
if not ok:
_record("out", "text", text, False, why)
return False, why
ok, err, _ = _post("/yjy/send/text", {"robot_key": S.get("im.bot_id"), "friends": [str(S.get("im.contact_id"))],
"content": text, "at_user_list": []})
_record("out", "text", text, ok, err)
if not ok:
events.emit(f"发微信文字失败:{err}", "error", source="im")
return ok, err
def upload(path: Path) -> tuple[str | None, str]:
try:
with open(path, "rb") as f:
r = requests.post(_api() + "/common/upload", files={"file": (path.name, f, "image/png")},
headers=_headers(), timeout=90)
obj = r.json()
except Exception as e: # noqa: BLE001
return None, f"上传截图到网关失败:{e}"
url = obj.get("url") or (obj.get("data") or {}).get("url") if isinstance(obj, dict) else None
return (url, "") if url else (None, f"上传截图没拿到 url:{str(obj)[:200]}")
def send_image(path: Path, public_url: str = "") -> tuple[bool, str]:
"""image_mode=upload:先传网关 OSS(云端没有公网地址时必须这样);url:直接用 public_url。"""
ok, why = configured()
if not ok:
_record("out", "image", str(path.name), False, why)
return False, why
if S.get("im.image_mode") == "url" and public_url:
pic = public_url
else:
pic, err = upload(path)
if not pic:
_record("out", "image", path.name, False, err)
events.emit(err, "error", source="im")
return False, err
ok, err, _ = _post("/yjy/send/image", {"robot_key": S.get("im.bot_id"), "friends": [str(S.get("im.contact_id"))],
"pic_url": pic})
_record("out", "image", pic, ok, err)
if not ok:
events.emit(f"发微信图片失败:{err}", "error", source="im")
return ok, err
def fetch_msgs(start: str, end: str) -> list[dict] | None:
url = (f"{_api()}/core/msgs?channel={S.get('im.channel')}&bot_id={S.get('im.bot_id')}"
f"&contact_id={quote(str(S.get('im.contact_id')), safe='')}&start_time={quote(start)}&end_time={quote(end)}&limit=50&offset=0")
try:
r = requests.get(url, headers=_headers(), timeout=TIMEOUT)
if r.status_code != 200:
return None
return r.json().get("msgs") or []
except Exception: # noqa: BLE001
return None
def record_incoming(text: str, sender: str, msg_id: str) -> None:
_record("in", "text", text, True, sender=sender, msg_id=msg_id)