Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions extensions/openmate-wechat/assistant/instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,包括 `@自己` 和自动代答。还没回复且提示发出不到两分钟时,它的「处理中」提示也会撤回。
Expand Down
65 changes: 64 additions & 1 deletion extensions/openmate-wechat/openmate_wechat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
)


Expand Down
17 changes: 17 additions & 0 deletions extensions/openmate-wechat/openmate_wechat/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
26 changes: 26 additions & 0 deletions extensions/openmate-wechat/openmate_wechat/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 "[卡片消息]")
Expand Down
8 changes: 4 additions & 4 deletions extensions/openmate-wechat/openmate_wechat/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion extensions/openmate-wechat/persona-extension.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -46,6 +46,7 @@
"matewechat_messages",
"matewechat_search",
"matewechat_media",
"matewechat_group_notice",
"matewechat_agent_reply"
],
"confirm_always": [
Expand Down
8 changes: 8 additions & 0 deletions extensions/openmate-wechat/tests/fake_native.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
58 changes: 58 additions & 0 deletions extensions/openmate-wechat/tests/test_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
35 changes: 35 additions & 0 deletions extensions/openmate-wechat/tests/test_hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down Expand Up @@ -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

Expand Down
19 changes: 19 additions & 0 deletions extensions/openmate-wechat/tests/test_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion native/matewechat-native/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion native/matewechat-native/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "matewechat-native"
version = "0.1.11"
version = "0.1.12"
edition = "2021"
license = "MIT"
publish = false
Expand Down
Loading
Loading