diff --git a/extensions/openmate-wechat/assistant/instructions.md b/extensions/openmate-wechat/assistant/instructions.md index 6108f15..325bdaf 100644 --- a/extensions/openmate-wechat/assistant/instructions.md +++ b/extensions/openmate-wechat/assistant/instructions.md @@ -3,6 +3,8 @@ - 这是用户本人的微信,以一台新电脑的身份登录。`matewechat_*` 工具读用户本人的微信会话;`matewechat_send` / `matewechat_send_dm` 以用户的身份发出,每次都要用户在确认卡片上确认。私聊和群里 @用户 的消息会进收件箱;私聊进知识库,群聊默认不进。 - 会话 id:群是 `…@chatroom`,私聊是对方的微信 id。名字查不到时用 `matewechat_search` 按名字找,或先 `matewechat_chats` 看最近的会话。 - 这台电脑只收到登录之后的消息,更早的聊天记录读不到。 +- 群公告用 `matewechat_group_notice`(chat 给群的会话 id `…@chatroom`):当场从微信读,返回公告正文、发布人和发布时间;只读,不会改公告。公告里可能有账号、密码之类的内容,回答时只用到用户问的部分,不要整段转发给别人。 +- 群接龙在消息里显示成「[接龙] 标题…」加完整的编号名单(1. …、2. …)。每有一个人接龙,群里就多一条带全部名单的新消息:要现在的名单,看最新的那一条。 - 图片、语音、视频、文件会自动下载到本机,消息里写着本地路径:`[图片] 本地文件:/…/123.jpg` 可以直接读图;语音是 WAV(设置了语音转文字才附文字,否则你听不到内容);视频给封面、视频文件和几张截图;合并转发的聊天记录直接展开成文字。还没下载完、下载失败或需要重新下载时用 `matewechat_media`(给消息 id)。下载不了时括号里写着原因(例如过期、超过 25 MB),如实转告,不要猜内容。能下载媒体之前收到的消息只有 `[图片]` 这样的占位,取不到内容。 - 微信不能编辑已发的消息,也没有表情回应:用户自己的 /agent 接单时,扩展会自动在原会话发一句“处理中”提示(设置里的“接单提示”);群里有人 @ 用户的自动代答不发这句。你只回复一次最终结果,不发中途进度。 连接 AgentWechat 时,撤回微信里的请求也会停止它触发的 Agent,包括 `@自己` 和自动代答。还没回复且提示发出不到两分钟时,它的「处理中」提示也会撤回。 diff --git a/extensions/openmate-wechat/openmate_wechat/__init__.py b/extensions/openmate-wechat/openmate_wechat/__init__.py index e836db4..dc6b927 100644 --- a/extensions/openmate-wechat/openmate_wechat/__init__.py +++ b/extensions/openmate-wechat/openmate_wechat/__init__.py @@ -124,6 +124,69 @@ def run(a: Dict) -> str: return {MEDIA_TOOL: (schema, run)} +NOTICE_TOOL = CONNECTOR_ID + "_group_notice" + + +def notice_tools(app) -> Dict: + """matewechat_group_notice: a group's announcement (群公告), read from WeChat when asked. Read only.""" + schema = { + "name": NOTICE_TOOL, + "description": "读一个微信群现在的群公告:公告正文、发布人、发布时间(当场从微信读)。chat 给群的会话 id(…@chatroom," + "matewechat_chats 或 matewechat_search 查到的)。不是群、群里没有公告时会说明。只读,不会改公告,也不会发任何消息。", + "input_schema": {"type": "object", "properties": { + "chat": {"type": "string", "description": "群的会话 id(…@chatroom)"}}, + "required": ["chat"]}, + } + + def run(a: Dict) -> str: + import datetime + + from openmate_core.wire import RPCError + + from .backend import is_group + + chat = str(a.get("chat") or "").strip() + if not chat: + raise RPCError("缺少群的会话 id(chat)") + if not is_group(chat): + return "%s 不是群(群的会话 id 以 @chatroom 结尾),没有群公告。" % chat + backend = app.backend + if backend is None or not app.signed_in: + raise RPCError("微信还没登录") + if not hasattr(backend, "group_notice"): + raise RPCError("这个微信连接读不了群公告") + try: + n = backend.group_notice(chat) + except BackendError as e: + raise RPCError(e.message) + where = "群「%s」(chat=%s)" % (n["name"], chat) if n.get("name") else "群(chat=%s)" % chat + text = str(n.get("text") or "").strip() + if not text: + return "%s现在没有群公告。" % where + lines = ["%s的群公告:" % where] + if n.get("editor"): + name = n.get("editor_name") or "" + lines.append("发布人:%s" % ("%s(%s)" % (name, n["editor"]) if name and name != n["editor"] else n["editor"])) + if n.get("published_at"): + tz = getattr(app, "tz", None) + when = datetime.datetime.fromtimestamp(n["published_at"], tz) if tz is not None else \ + datetime.datetime.fromtimestamp(n["published_at"]) + lines.append("发布时间:%s" % when.strftime("%Y-%m-%d %H:%M")) + if n.get("saved"): + lines.append("(这是 AgentWechat 保存的公告,读不到发布人和发布时间)") + lines += ["", text] + return "\n".join(lines) + + return {NOTICE_TOOL: (schema, run)} + + +def wechat_tools(app) -> Dict: + """The platform's own read tools: matewechat_media and matewechat_group_notice.""" + out = media_tools(app) + out.update(notice_tools(app)) + return out + + def platform(manifest_path: str = "") -> Platform: return Platform( extension_id=EXTENSION_ID, @@ -145,7 +208,7 @@ def platform(manifest_path: str = "") -> Platform: archive_chat=archive_chat, handle_kind="", # no sender handles in archive batches (WeChat ids are not a kind the knowledge base knows) today_api_callers=("extension:openmate-feishu",), # Feishu's 今天 shows these chats (its own HTTP) - tools=media_tools, + tools=wechat_tools, ) diff --git a/extensions/openmate-wechat/openmate_wechat/backend.py b/extensions/openmate-wechat/openmate_wechat/backend.py index 952f7e7..fb33419 100644 --- a/extensions/openmate-wechat/openmate_wechat/backend.py +++ b/extensions/openmate-wechat/openmate_wechat/backend.py @@ -1069,6 +1069,23 @@ def _roster(self, chat_id: str) -> Tuple[List[dict], int]: self.store.set_name(self._name_key(uid, chat_id), shown, shown) return members, int(r.get("member_count") or 0) + def group_notice(self, chat_id: str) -> Dict[str, Any]: + """A group's announcement (群公告), read now: {"text", "editor" (id), "editor_name", "published_at" (Unix + seconds, 0 unknown), "name" (the group's, as known here), "saved" (through AgentWechat: the copy it keeps, with + no editor or time)}. Read only; the text is never logged.""" + if not is_group(chat_id): + raise BackendError("这不是群的会话 id(群的以 @chatroom 结尾)", "rejected") + r = self._call(self._link(), "group_notice", 25, room_id=chat_id) + editor = str(r.get("editor") or "") + try: + at = int(r.get("published_at") or 0) + except (TypeError, ValueError): + at = 0 + row = self.store.chat(chat_id) + return {"text": str(r.get("announcement") or ""), "editor": editor, + "editor_name": self.user_name(editor, chat_id) if editor else "", "published_at": max(0, at), + "name": (row[0] if row else "") or "", "saved": bool(r.get("saved"))} + @staticmethod def _name_key(user_id: str, chat_id: Optional[str]) -> str: return "%s|%s" % (chat_id if chat_id and is_group(chat_id) else "", user_id) diff --git a/extensions/openmate-wechat/openmate_wechat/hub.py b/extensions/openmate-wechat/openmate_wechat/hub.py index eeed289..4adad84 100644 --- a/extensions/openmate-wechat/openmate_wechat/hub.py +++ b/extensions/openmate-wechat/openmate_wechat/hub.py @@ -122,6 +122,24 @@ def strip_label(body: str, label: str) -> str: ERROR_CODE = re.compile(r"[a-z]{1,12}(?:_[a-z]{1,12})+") +def group_note(body: str, summary: Any) -> str: + """A Group Note (群接龙, app message 53) as matewechat-native shows it: "[接龙] " and the whole note. The hub's body is + the note's text as WeChat shows it (title, example line, numbered entries, text after them); without one, the + note is written out from the hub's summary (kind group_note) the same way.""" + text = body.strip() + s = summary if isinstance(summary, dict) and summary.get("kind") == "group_note" else {} + if not text and s: + entries = [str(e.get("text") or "").strip() for e in s.get("entries") or [] if isinstance(e, dict)] + text = str(s.get("title") or "").strip() + if s.get("format"): + text += "\n" + str(s["format"]).strip() + text += "\n\n" + "\n".join("%d. %s" % (n, e) for n, e in enumerate(entries, 1)) + if s.get("extra"): + text += "\n\n" + str(s["extra"]).strip() + text = text.strip() + return ("[接龙] %s" % text) if text else "[接龙]" + + def frame_code(data: str) -> str: """The code of the hub's error frame ({"error":{"code":…}}), never its other text (a reason may end up in a log).""" try: @@ -662,6 +680,12 @@ def _op_room(self, timeout: float, room_id: str = "", **_: Any) -> dict: out["me_in"] = g["isInGroup"] # null on the hub: not known (never taken as gone) return out + def _op_group_notice(self, timeout: float, room_id: str = "", **_: Any) -> dict: + """The announcement AgentWechat keeps for the group (its text only: no editor, no time).""" + g = self._get("/groups/" + seg(room_id)) + return {"room_id": room_id, "announcement": str(g.get("announcement") or ""), "editor": "", "published_at": 0, + "saved": True} + def _op_groups(self, timeout: float, catalog: bool = False, **_: Any) -> dict: if catalog and time.time() - self._group_sync_at > GROUP_SYNC_EVERY: self._group_sync_at = time.time() @@ -1508,6 +1532,8 @@ def ref(quality: str) -> str: kind, text = "CARD", "[聊天记录] %s" % strip_label(body, "[Chat History]")[:RECORD_MOST] elif wire == 49 and app in (33, 36): kind, text = "CARD", "[小程序] %s" % (title or body) + elif wire == 49 and app == 53: + kind, text = "CARD", group_note(body, msg.get("summary")) elif wire == 49: kind, text = "CARD", ("[链接] %s" % title) if title else ( "[链接] %s" % strip_label(body, "[Link]") if body else "[卡片消息]") diff --git a/extensions/openmate-wechat/openmate_wechat/install.py b/extensions/openmate-wechat/openmate_wechat/install.py index 31805f7..03b359c 100644 --- a/extensions/openmate-wechat/openmate_wechat/install.py +++ b/extensions/openmate-wechat/openmate_wechat/install.py @@ -21,13 +21,13 @@ log = logging.getLogger("openmate.wechat.install") -VERSION = "0.1.11" +VERSION = "0.1.12" URL = "https://github.com/NginxL/openmate/releases/download/matewechat-native-v{version}/{name}" ASSETS = { ("darwin", "arm64"): { - "name": "matewechat-native-0.1.11-darwin-arm64", - "sha256": "34fd8e84e69050ab5b79f50dcd4bf2a16403ff30771590c723370aeccab07d43", - "size": 8332096, + "name": "matewechat-native-0.1.12-darwin-arm64", + "sha256": "a5cedb2dfe1987098b1f0e6023103025203e7929a9e1263006188b4a53a0930c", + "size": 8365440, }, } DOWNLOAD_TIMEOUT = 120.0 diff --git a/extensions/openmate-wechat/persona-extension.json b/extensions/openmate-wechat/persona-extension.json index fdee7c0..2646794 100644 --- a/extensions/openmate-wechat/persona-extension.json +++ b/extensions/openmate-wechat/persona-extension.json @@ -2,7 +2,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.74", + "version": "0.1.75", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -46,6 +46,7 @@ "matewechat_messages", "matewechat_search", "matewechat_media", + "matewechat_group_notice", "matewechat_agent_reply" ], "confirm_always": [ diff --git a/extensions/openmate-wechat/tests/fake_native.py b/extensions/openmate-wechat/tests/fake_native.py index c9fe490..24aeee1 100755 --- a/extensions/openmate-wechat/tests/fake_native.py +++ b/extensions/openmate-wechat/tests/fake_native.py @@ -102,6 +102,14 @@ def answer(req): return ok(room_id=req.get("room_id"), member_count=3, me_in=None if unknown else req.get("room_id") not in left, members=[{"id": "wxid_bob", "nickname": "Bob", "display": "群里的鲍勃"}, {"id": "wxid_me", "nickname": "我", "display": None}]) + if op == "group_notice": # MATEWECHAT_FAKE_NOTICES: {room: {"text", "editor", "at"}}; a room not there is refused + room = req.get("room_id", "") + if not room.endswith("@chatroom"): + return fail("unsupported", "企业微信的群读不到群公告") + n = json.loads(os.environ.get("MATEWECHAT_FAKE_NOTICES", "{}")).get(room) + if n is None: + return fail("rejected", "微信没有给出这个群的公告(可能已经不在这个群里)") + return ok(room_id=room, announcement=n.get("text", ""), editor=n.get("editor", ""), published_at=n.get("at", 0)) if op == "groups": return ok(groups=json.loads(os.environ.get("MATEWECHAT_FAKE_GROUPS", '["g1@chatroom", "g2@chatroom"]')), complete=os.environ.get("MATEWECHAT_FAKE_GROUPS_COMPLETE", "1") == "1", diff --git a/extensions/openmate-wechat/tests/test_backend.py b/extensions/openmate-wechat/tests/test_backend.py index bcfba70..440137d 100644 --- a/extensions/openmate-wechat/tests/test_backend.py +++ b/extensions/openmate-wechat/tests/test_backend.py @@ -897,6 +897,64 @@ def test_no_lookup_for_an_empty_id(self): self.assertEqual(self.requests("contacts"), []) +class GroupNoticeTest(Base): + """matewechat_group_notice: a group's announcement read from WeChat when asked (the program's group_notice).""" + + def tool(self, b, signed_in=True): + from openmate_wechat import notice_tools + + class App: + backend = b + + App.signed_in = signed_in + return notice_tools(App())["matewechat_group_notice"] + + def test_the_notice_its_editor_and_time(self): + import datetime + + from openmate_core.wire import RPCError + + os.environ["MATEWECHAT_FAKE_NOTICES"] = json.dumps({ + "1@chatroom": {"text": "周六 9 点集合\n地点:东门", "editor": "wxid_bob", "at": 1796400000}, + "2@chatroom": {"text": ""}}) + b = self.backend() + b.restore({"state": {"k": "v1"}}) + b.store.name_chat("1@chatroom", "项目群", 3) + n = b.group_notice("1@chatroom") + self.assertEqual((n["text"], n["editor"], n["editor_name"], n["published_at"], n["name"], n["saved"]), + ("周六 9 点集合\n地点:东门", "wxid_bob", "群里的鲍勃", 1796400000, "项目群", False)) + self.assertEqual(self.requests("group_notice")[-1]["room_id"], "1@chatroom") + schema, run = self.tool(b) + self.assertEqual(schema["input_schema"]["required"], ["chat"]) + self.assertIn("只读", schema["description"]) + out = run({"chat": "1@chatroom"}) + when = datetime.datetime.fromtimestamp(1796400000).strftime("%Y-%m-%d %H:%M") + self.assertEqual(out, "群「项目群」(chat=1@chatroom)的群公告:\n发布人:群里的鲍勃(wxid_bob)\n发布时间:%s\n\n" + "周六 9 点集合\n地点:东门" % when) + self.assertEqual(run({"chat": "2@chatroom"}), "群(chat=2@chatroom)现在没有群公告。") + asked = len(self.requests("group_notice")) + self.assertIn("不是群", run({"chat": "wxid_bob"})) + self.assertEqual(len(self.requests("group_notice")), asked, "a direct chat is not asked about") + with self.assertRaises(RPCError) as caught: + run({"chat": "9@chatroom"}) # WeChat gave nothing (the account left it, say) + self.assertIn("微信没有给出这个群的公告", str(caught.exception)) + with self.assertRaises(RPCError) as caught: + run({"chat": "3@im.chatroom"}) + self.assertIn("企业微信的群读不到群公告", str(caught.exception)) + with self.assertRaises(RPCError): + run({"chat": " "}) + + def test_signed_out_is_said(self): + from openmate_core.wire import RPCError + + b = self.backend() + _, run = self.tool(b, signed_in=False) + with self.assertRaises(RPCError) as caught: + run({"chat": "1@chatroom"}) + self.assertEqual(str(caught.exception), "微信还没登录") + self.assertEqual(self.requests("group_notice"), []) + + class NamesTest(Base): def test_names_and_kinds(self): b = self.backend() diff --git a/extensions/openmate-wechat/tests/test_hub.py b/extensions/openmate-wechat/tests/test_hub.py index 1cc78cb..51c707c 100644 --- a/extensions/openmate-wechat/tests/test_hub.py +++ b/extensions/openmate-wechat/tests/test_hub.py @@ -1229,6 +1229,28 @@ def test_a_cut_download_is_not_kept(self): self.assertIn("没能下载", text) +class GroupNoticeTest(Base): + def test_the_notice_agentwechat_keeps(self): + b = self.signed_in() + self.hub.groups[GROUP] = {"id": GROUP, "roomId": GROUP, "name": "项目群", "isInGroup": True, + "announcement": "周六 9 点集合"} + n = b.group_notice(GROUP) + self.assertEqual((n["text"], n["editor"], n["published_at"], n["saved"]), ("周六 9 点集合", "", 0, True)) + from openmate_wechat import notice_tools + + class App: + backend = b + signed_in = True + + out = notice_tools(App())["matewechat_group_notice"][1]({"chat": GROUP}) + self.assertEqual(out, "群(chat=%s)的群公告:\n(这是 AgentWechat 保存的公告,读不到发布人和发布时间)\n\n" + "周六 9 点集合" % GROUP) + self.hub.groups[GROUP]["announcement"] = None + self.assertEqual(b.group_notice(GROUP)["text"], "") + with self.assertRaises(BackendError): + b.group_notice("999@chatroom") # not a group AgentWechat has + + class MessageShapesTest(unittest.TestCase): """The hub's message shapes (v2.7.1) as the program's message events.""" @@ -1272,6 +1294,19 @@ def test_shapes(self): "source": "msgsource.atuserlist"}), "live") self.assertTrue(at["at_me"]) + def test_a_group_note_keeps_its_whole_list(self): + L = self.link() + body = "#接龙 周六羽毛球\n\n1. 张三\n2. 李四" + n = L.message_event(self.msg(type=49, appMessageType=53, body=body, link={"title": "#接龙 周六羽毛球"}), "live") + self.assertEqual((n["type"], n["text"]), ("CARD", "[接龙] " + body)) + summary = {"kind": "group_note", "noteId": "1_2", "title": "#接龙 周六羽毛球", "format": "写名字", "extra": "周五截止", + "entries": [{"text": "张三"}, {"text": "李四", "senderId": "wxid_b"}]} + n = L.message_event(self.msg(type=49, appMessageType=53, body=None, summary=summary), "live") + self.assertEqual(n["text"], "[接龙] #接龙 周六羽毛球\n写名字\n\n1. 张三\n2. 李四\n\n周五截止") + self.assertEqual(L.message_event(self.msg(type=49, appMessageType=53, body=None), "live")["text"], "[接龙]") + link = L.message_event(self.msg(type=49, appMessageType=5, body=None, link={"title": "文章"}), "live") + self.assertEqual(link["text"], "[链接] 文章", "other cards are as before") + def test_an_error_frame_ends_the_stream(self): import http.server diff --git a/extensions/openmate-wechat/tests/test_manifest.py b/extensions/openmate-wechat/tests/test_manifest.py index 110355f..5800ea9 100644 --- a/extensions/openmate-wechat/tests/test_manifest.py +++ b/extensions/openmate-wechat/tests/test_manifest.py @@ -14,6 +14,25 @@ def test_full_automatic_replies_are_off_by_default(self): self.assertEqual(setting["type"], "boolean") self.assertIs(setting["default"], False) + def test_the_pinned_program_is_the_version_of_its_source(self): + """install.py fetches the matewechat-native this repository's source is: a new operation in the program is + never shipped with the old program pinned.""" + import re + import sys + + root = os.path.dirname(os.path.dirname(os.path.dirname(HERE))) + for p in (os.path.join(root, "core"), os.path.dirname(HERE)): + if p not in sys.path: + sys.path.insert(0, p) + from openmate_wechat import install + + with open(os.path.join(root, "native", "matewechat-native", "Cargo.toml"), encoding="utf-8") as f: + source = re.search(r'(?m)^version = "([^"]+)"$', f.read()).group(1) + self.assertEqual(install.VERSION, source) + for asset in install.ASSETS.values(): + self.assertTrue(asset["name"].startswith("matewechat-native-%s-" % source), asset["name"]) + self.assertRegex(asset["sha256"], "^[0-9a-f]{64}$") + def test_sidebar_page_icon(self): nav = {u["id"]: u["icon"] for u in MANIFEST["contributes"]["ui"] if u["placement"] == "nav_page"} # person: a NavIcon name (sdk/go/wire/wire_gen.go) that none of the Feishu extension's pages uses; the plain diff --git a/native/matewechat-native/Cargo.lock b/native/matewechat-native/Cargo.lock index 8aff0e4..9761537 100644 --- a/native/matewechat-native/Cargo.lock +++ b/native/matewechat-native/Cargo.lock @@ -724,7 +724,7 @@ checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" [[package]] name = "matewechat-native" -version = "0.1.11" +version = "0.1.12" dependencies = [ "anyhow", "base64 0.22.1", diff --git a/native/matewechat-native/Cargo.toml b/native/matewechat-native/Cargo.toml index 650a54d..1137307 100644 --- a/native/matewechat-native/Cargo.toml +++ b/native/matewechat-native/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "matewechat-native" -version = "0.1.11" +version = "0.1.12" edition = "2021" license = "MIT" publish = false diff --git a/native/matewechat-native/src/main.rs b/native/matewechat-native/src/main.rs index 6612ae5..1b4ce3a 100644 --- a/native/matewechat-native/src/main.rs +++ b/native/matewechat-native/src/main.rs @@ -2,8 +2,9 @@ //! //! It speaks JSON lines on stdin/stdout with the extension's Python backend, which owns everything else (the store, //! the inbox, /agent, 自动代答). Only what those two features need is here: QR sign-in, restoring a saved sign-in, -//! the live message stream (push, sync, heartbeat), text sends (with real @s and quotes), names, and the media of a -//! message (a CDN object decrypted into a file the backend names; a voice note as WAV). +//! the live message stream (push, sync, heartbeat), text sends (with real @s and quotes), names, a group's +//! announcement (read only), and the media of a message (a CDN object decrypted into a file the backend names; a voice +//! note as WAV). //! //! The protocol is thisnick/agent-wechat's `wechat-protocol` library (MIT), used through its public API only; the //! online loop follows that project's daemon: heartbeat at the server's interval (30–180 s), a catch-up drain (scene @@ -837,6 +838,32 @@ fn op_room(app: &App, p: &Value) -> Result { "me_in": me_in})) } +/// A group's announcement (群公告) as WeChat has it now: its text, who published it (an id) and when (Unix seconds; 0 +/// when WeChat did not say), through wechat-protocol's public group_detail_raw / decode_group_detail +/// (getchatroominfodetail). Read only: nothing in the group is changed. The text is never logged. +fn op_group_notice(app: &App, p: &Value) -> Result { + let client = app.client()?; + let room = str_arg(p, "room_id")?.to_owned(); + if !message::is_group(&room) { + return Err(err("input", "不是群")); + } + if !room.ends_with("@chatroom") { + return Err(err("unsupported", "企业微信的群读不到群公告")); + } + let r = app.rt.block_on(async { tokio::time::timeout(Duration::from_secs(10), client.group_detail_raw(&room)).await }); + let raw = match r { + Ok(Ok(raw)) => raw, + Ok(Err(e)) => return Err(e), + Err(_) => return Err(anyhow!("读群公告超时")), + }; + let detail = wechat_protocol::decode_group_detail(&raw, &room).map_err(|e| { + log(&format!("group notice not read: {e:#}")); + err("rejected", "微信没有给出这个群的公告(可能已经不在这个群里)") + })?; + Ok(json!({"room_id": room, "announcement": detail.announcement, "editor": detail.editor, + "published_at": detail.published_at})) +} + /// Every group in the account's contacts (the 通讯录 list WeChat pages out at sign-in); groups never saved there show /// up only once they have a message. fn op_groups(app: &App, p: &Value) -> Result { @@ -1215,6 +1242,7 @@ fn handle(app: Arc, req: Value) { "send" => op_send(&app, &req), "contacts" => op_contacts(&app, &req), "room" => op_room(&app, &req), + "group_notice" => op_group_notice(&app, &req), "groups" => op_groups(&app, &req), "media" => op_media(&app, &req), "voice" => op_voice(&app, &req), diff --git a/native/matewechat-native/src/message.rs b/native/matewechat-native/src/message.rs index 62007be..756e6c3 100644 --- a/native/matewechat-native/src/message.rs +++ b/native/matewechat-native/src/message.rs @@ -127,12 +127,117 @@ fn app_message(content: &str) -> (&'static str, String, String, String, String) } "6" => ("FILE", format!("[文件] {title}"), String::new(), String::new(), String::new()), "19" => ("CARD", format!("[聊天记录] {title}"), String::new(), String::new(), String::new()), + "53" => ("CARD", group_note(app), String::new(), String::new(), String::new()), "33" | "36" => ("CARD", format!("[小程序] {title}"), String::new(), String::new(), String::new()), _ if title.is_empty() => ("CARD", "[卡片消息]".into(), String::new(), String::new(), String::new()), _ => ("CARD", format!("[链接] {title}"), String::new(), String::new(), String::new()), } } +const NOTE_TITLE_MOST: usize = 128 * 1024; // a note's holds its whole list +const NOTE_XML_MOST: usize = 256 * 1024; +const NOTE_PART_MOST: usize = 16 * 1024; // one part or entry + +/// A Group Note (群接龙, app message 53) as text: "[接龙] " and the whole note, its list included, as WeChat shows it. +/// +/// The shape is the one thisnick/agent-wechat (MIT) reads from the official client's messages +/// (packages/native-client-rust/crates/wechat-core/src/group_notes.rs at aba33f7c4534813d78181cad9c2229db22c1bff3): +/// the note's visible text is the app message's `<title>` (its title, the example line, the numbered entries and any +/// text after them), and `<extinfo><solitaire_info>` holds the same note as XML: `<solitaire>` with the ranges `tt` +/// (title), `ex` (example line), `tl` (text after the entries) and each entry's `<i><r>`, which are `offset-length` +/// spans of the `<title>` text in UTF-16 code units (`0-0`: the part is absent), and each entry's own text in `<c>`. +/// Every new entry posts a new message with the whole list again. The note is written out from its parts when all of +/// them can be read; otherwise the `<title>` as it is. +fn group_note(app: roxmltree::Node) -> String { + let title: String = app + .children() + .find(|c| c.is_element() && c.tag_name().name() == "title") + .map(|t| t.descendants().filter(|n| n.is_text()).filter_map(|n| n.text()).collect()) + .unwrap_or_default(); + let shown = solitaire(app, &title) + .unwrap_or_else(|| title.trim_matches(|c: char| c.is_ascii_whitespace() || c == '\u{3000}').to_owned()); + if shown.is_empty() { + "[接龙]".into() + } else { + format!("[接龙] {shown}") + } +} + +/// The note its `solitaire_info` describes, written the way the official clients write the `<title>`; None when it is +/// missing, malformed, too big, or any part or entry of it cannot be read. +fn solitaire(app: roxmltree::Node, title: &str) -> Option<String> { + if title.len() > NOTE_TITLE_MOST { + return None; + } + let xml = xml_text(app, &["extinfo", "solitaire_info"])?; + if xml.is_empty() || xml.len() > NOTE_XML_MOST { + return None; + } + let doc = roxmltree::Document::parse(&xml).ok()?; // a DTD is refused (roxmltree's default) + let root = doc.root_element(); + if root.tag_name().name() != "solitaire" { + return None; + } + let units: Vec<u16> = title.encode_utf16().collect(); + // an absent part is left out; one that is there but cannot be read gives up on the whole note + let part = |name: &str| match child(root, name) { + None => Some(None), + Some(n) => span(&units, &xml_text(n, &[])?), + }; + let (head, example, tail) = (part("tt")?, part("ex")?, part("tl")?); + let mut entries = vec![]; + for item in child(root, "content")?.children().filter(|n| n.is_element() && n.tag_name().name() == "i") { + // the entry's own text, else the part of the title its range selects + let text = match child(item, "c").and_then(|c| xml_text(c, &[])).filter(|t| !t.is_empty()) { + Some(t) => shown(&t)?, + None => span(&units, &xml_text(child(item, "r")?, &[])?)??, + }; + entries.push(text); + } + if head.is_none() && entries.is_empty() { + return None; + } + let mut text = head.unwrap_or_default(); + if let Some(example) = example { + text.push('\n'); + text.push_str(&example); + } + text.push_str("\n\n"); + for (n, entry) in entries.iter().enumerate() { + if n > 0 { + text.push('\n'); + } + text.push_str(&format!("{}. {entry}", n + 1)); + } + if let Some(tail) = tail { + text.push_str("\n\n"); + text.push_str(&tail); + } + Some(text.trim().to_owned()) +} + +fn child<'a, 'input>(node: roxmltree::Node<'a, 'input>, name: &str) -> Option<roxmltree::Node<'a, 'input>> { + node.children().find(|c| c.is_element() && c.tag_name().name() == name) +} + +/// The text an `offset-length` range (UTF-16 code units) selects in the title: Some(None) for an absent part (`0-0`), +/// None when it is malformed, falls outside the title or inside a surrogate pair, or is not text to show. +fn span(units: &[u16], range: &str) -> Option<Option<String>> { + let (offset, length) = range.trim().split_once('-')?; + let (offset, length) = (offset.parse::<usize>().ok()?, length.parse::<usize>().ok()?); + if length == 0 { + return (offset == 0).then_some(None); + } + let text = String::from_utf16(units.get(offset..offset.checked_add(length)?)?).ok()?; + Some(Some(shown(&text)?)) +} + +/// A part of a note as shown: bounded, no control characters but line breaks and tabs, trimmed. +fn shown(text: &str) -> Option<String> { + let ok = text.len() <= NOTE_PART_MOST && !text.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t')); + ok.then(|| text.trim().to_owned()).filter(|t| !t.is_empty()) +} + /// The identity a DelContact sync command removes: field 1 holds it as a nested string (field 1), as the daemon /// reads it; fields 2 and 3, when there, are small numbers. pub fn deleted_contact(payload: &[u8]) -> anyhow::Result<String> { @@ -599,6 +704,93 @@ mod tests { assert_eq!(media_info(49, &cdata).unwrap()["items"].as_array().unwrap().len(), 3); } + /// A received Group Note (49/53) after the group sender prefix, in the shape of agent-wechat's + /// group_notes_tests.rs at aba33f7c4534813d78181cad9c2229db22c1bff3 (the official Linux client's rows: a tab-indented + /// `<msg>`, self-closed empty elements, the note as CDATA in `<solitaire_info>`). Every value is made up. + fn note_xml(title: &str, solitaire: &str) -> String { + format!("<?xml version=\"1.0\"?>\n<msg>\n\t<appmsg appid=\"\" sdkver=\"0\">\n\t\t<title>{title}\n\t\t\n\t\t\n\t\t53\n\t\t0\n\t\t\n\t\t\n\t\t\n\t\t\t0\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\t\n\t\t\t\n\t\t\n\t\t\n\t\t\n\t\n\twxid_author\n\t0\n\t\n\t\t1\n\t\t\n\t\n\t\n") + } + + fn note_item(range: &str, text: Option<&str>) -> String { + let c = text.map(|t| format!("{t}")).unwrap_or_default(); + format!("wxid_member0.1796400000{range}{c}") + } + + fn solitaire(tt: &str, ex: &str, tl: &str, items: &[String]) -> String { + format!("{tt}{ex}{tl}.wxid_author101796400000000_4321{}{}", + items.len(), items.concat()) + } + + /// `offset-length` of part's first appearance in title, in UTF-16 code units. + fn range(title: &str, part: &str) -> String { + let at = title.find(part).unwrap(); + format!("{}-{}", title[..at].encode_utf16().count(), part.encode_utf16().count()) + } + + fn note_text(xml: &str) -> String { + let (e, _) = normalize(&raw("1@chatroom", "1@chatroom", false, 49, &format!("wxid_bob:\n{xml}"), None), "wxid_me", "live"); + assert_eq!(e["type"], "CARD"); + assert_eq!(e["sender"], "wxid_bob"); + e["text"].as_str().unwrap().to_owned() + } + + #[test] + fn group_note_shows_the_whole_list() { + // agent-wechat's own case, ranges counted by hand in UTF-16 code units: title 0..11, "Daniel 拉面" 16..25, + // "Alex 饺子 🥟" 29..39, the text after the list 41..58 (code points would put it at 39) + let title = "周末 lunch 🍜\n\n1. Daniel 拉面\n2. Alex 饺子 🥟\n\nReply by Friday ✅"; + let items = [note_item("16-9", Some("Daniel 拉面")), note_item("29-10", Some("Alex 饺子 🥟"))]; + let text = note_text(¬e_xml(title, &solitaire("0-11", "0-0", "41-17", &items))); + assert_eq!(text, format!("[接龙] {title}")); + // a range that ends inside the noodle emoji's surrogate pair (10-1: its low half) gives up on the parts: the + // title as it is (here the same text) + let half = note_xml(title, &solitaire("0-11", "0-0", "10-1", &items)); + assert_eq!(solitaire_of(&half, title), None); + assert_eq!(note_text(&half), format!("[接龙] {title}")); + } + + fn solitaire_of(xml: &str, title: &str) -> Option { + let doc = roxmltree::Document::parse(xml).unwrap(); + super::solitaire(element(&doc, "appmsg").unwrap(), title) + } + + #[test] + fn group_note_with_an_example_line_and_entries_by_range() { + let title = "#接龙\n周六羽毛球,写名字和几点到\n\n1. 张三 9点\n2. 李四 10点 🏸\n3. 王五"; + let items: Vec = ["张三 9点", "李四 10点 🏸", "王五"].iter().map(|e| note_item(&range(title, e), None)).collect(); + let sol = solitaire(&range(title, "#接龙"), &range(title, "周六羽毛球,写名字和几点到"), "0-0", &items); + assert_eq!(note_text(¬e_xml(title, &sol)), format!("[接龙] {title}")); + } + + #[test] + fn group_note_list_comes_from_the_note_when_the_title_lacks_it() { + let title = "#接龙 周六羽毛球"; + let items = [note_item("0-0", Some("张三")), note_item("0-0", Some("李四"))]; + let text = note_text(¬e_xml(title, &solitaire(&range(title, title), "0-0", "0-0", &items))); + assert_eq!(text, "[接龙] #接龙 周六羽毛球\n\n1. 张三\n2. 李四"); + } + + #[test] + fn group_note_that_cannot_be_read_shows_its_title() { + let title = "#接龙 晚饭\n\n1. 张三\n2. 李四"; + let good = note_item(&range(title, "张三"), None); + for xml in [ + format!("{title}53"), + note_xml(title, "not a note"), + note_xml(title, "0-2"), + note_xml(title, "]>0-2"), + note_xml(title, &solitaire("0-200", "0-0", "0-0", std::slice::from_ref(&good))), // past the end + note_xml(title, &solitaire("0-6", "3-0", "0-0", std::slice::from_ref(&good))), // an offset with no length + note_xml(title, &solitaire("0-6", "0-0", "0-0", &[good.clone(), note_item("x", None)])), // an entry unread + note_xml(title, &solitaire("0-6", "0-0", "0-0", &[good]).replace("", "").replace("", "")), + ] { + assert_eq!(note_text(&xml), format!("[接龙] {title}"), "{xml}"); + } + assert_eq!(note_text("53"), "[接龙]"); + // a link card is still a link + assert_eq!(note_text("t5"), "[链接] t"); + } + #[test] fn inline_data() { let mut silk = vec![2u8]; diff --git a/packages/openmate-wechat/0.1.75/openmate-wechat-0.1.75.tar.gz b/packages/openmate-wechat/0.1.75/openmate-wechat-0.1.75.tar.gz new file mode 100644 index 0000000..5447099 Binary files /dev/null and b/packages/openmate-wechat/0.1.75/openmate-wechat-0.1.75.tar.gz differ diff --git a/persona-extensions.json b/persona-extensions.json index d5f30c5..ef41744 100644 --- a/persona-extensions.json +++ b/persona-extensions.json @@ -551,7 +551,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.74", + "version": "0.1.75", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -587,6 +587,7 @@ "matewechat_messages", "matewechat_search", "matewechat_media", + "matewechat_group_notice", "matewechat_agent_reply" ], "confirm_always": [ @@ -848,9 +849,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-wechat/0.1.74/openmate-wechat-0.1.74.tar.gz", - "sha256": "dcae7d4e7b59bc6ef6a8f4d7a9d8868578fee234a7c2eb608918f4363fe05f77", - "size": 316149 + "url": "packages/openmate-wechat/0.1.75/openmate-wechat-0.1.75.tar.gz", + "sha256": "f71af229d40540ecf4b84f57408cfcb46c1567dc8cd45c9fc0b1c7c598671e74", + "size": 318008 } ] } diff --git a/tests/test_wechat_platform.py b/tests/test_wechat_platform.py index 024a567..9b2e613 100644 --- a/tests/test_wechat_platform.py +++ b/tests/test_wechat_platform.py @@ -50,12 +50,16 @@ def test_its_own_page_and_tools(self): with self.assertRaises(Exception): page(h, "chats") # Feishu's id is not this extension's names = [t["name"] for t in h.c("tools.list")["tools"]] - self.assertEqual(names, [CID + "_" + n for n in ("status", "chats", "messages", "search", "agent_reply", "media")]) + self.assertEqual(names, [CID + "_" + n for n in ("status", "chats", "messages", "search", "agent_reply", "media", + "group_notice")]) media = [t for t in h.c("tools.list")["tools"] if t["name"] == CID + "_media"][0] self.assertEqual(media["input_schema"]["required"], ["message"]) with open(os.path.join(ROOT, "extensions", "openmate-wechat", "persona-extension.json"), encoding="utf-8") as f: agent_tools = json.load(f)["contributes"]["connectors"][0]["agent_tools"] self.assertIn(CID + "_media", agent_tools, "the Agent gets it too") + self.assertIn(CID + "_group_notice", agent_tools, "the group notice too") + notice = [t for t in h.c("tools.list")["tools"] if t["name"] == CID + "_group_notice"][0] + self.assertEqual(notice["input_schema"]["required"], ["chat"]) reply = [t for t in h.c("tools.list")["tools"] if t["name"] == CID + "_agent_reply"][0] self.assertNotIn("progress", reply["input_schema"]["properties"], "WeChat cannot edit: no progress") self.assertIn("只回复一次最终结果", reply["description"])