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: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ OpenMate 是一组开源(MIT)的 [Persona](https://github.com/nwverse/person
| 功能 | 说明 |
| --- | --- |
| 登录 | 扫码登录,支持飞书和 Lark(国际版),可以配置代理 |
| 收件箱 | 最近 3 天、最多 200 个会话,每个会话一条:私聊里没回的、群里 @我 没回的、群里的新消息。没有 @我 的群消息按规则直接判为噪音,不调用模型;我最后回复了就算结束。可以写自己的分拣规则 |
| 收件箱 | 最近 3 天、最多 200 个会话:私聊里没回的、群里 @我 没回的、群里的新消息。私聊每个会话一条;群里话题外说的话是这个群的一条(id 照旧是会话 id),每个话题再各一条:话题里的上下文、“我回复了就算结束”、会话页(可往前翻、可在页里回复)和回复(发进这个话题)都只算这个话题;普通群里话题的根消息是在群聊主界面说的,仍算在群的那条里,我在这个话题里回复了,群的那条也算结束;话题模式的群每个话题一条。没有 @我 的群消息按规则直接判为噪音,不调用模型;在飞书里设了“消息免打扰”的群,没有 @我 的消息直接算已读、不留在待处理里(照旧存进知识库;@我 的照常分拣,之后的闲聊不顶掉它;读不出免打扰状态时照旧)。设置“照常分拣的群”里列的群,没有 @我 的消息也交给 AI 分拣(免打扰也一样);设置“不交给收件箱 AI 的私聊”里列的私聊照常进收件箱,但不调用模型,一律算“要你处理”,条目里也不带消息内容(打开会话看)。两项默认都空。我最后回复了就算结束。可以写自己的分拣规则 |
| 收件箱回复 | 以你本人身份发出,同一条回复只发一次 |
| 会话页 | 每页最多 50 条,可以往前翻,本地没有的旧消息会从飞书补拉;图片 4 MB 以内可以预览 |
| 知识库 | 按游标增量归档聊天记录,附件 20 MB 以内按需下载 |
Expand Down
196 changes: 182 additions & 14 deletions core/openmate_core/app.py

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions core/openmate_core/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,16 @@ def create_chat(self, user_id: str) -> str:
#: that have none yet, or whose picture is a day old
has_avatars: bool = False

#: Whether chat_mute works: the service says whether the account muted a chat (Feishu's 消息免打扰). The core then
#: asks it about the groups in the Inbox now and then (in the background): a muted group's messages that do not @
#: the user stay out of the Inbox (still archived); a group it could not tell about stays as before
has_mute: bool = False

def chat_mute(self, chat_id: str) -> Optional[bool]:
"""Whether the account muted this chat in the service's own client: True muted, False surely not, None when
the service did not say (or said both). BackendError when it could not be asked. With has_mute."""
return None

#: Whether send_image works now (an /agent reply may carry a picture then; the tool offers it only then)
can_send_images: bool = False

Expand Down
16 changes: 16 additions & 0 deletions core/openmate_core/fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ def __init__(self, now: Optional[float] = None, seed: bool = True):
self.format_ok = True # the backend sends formatted texts (rich=True: the Markdown subset)
self.image_threads = False # …where a text with the same reply_to and root would go (Backend.image_threads)
self.avatars_ok = False # chat_info says a chat's picture (Backend.has_avatars)
self.mute_ok = False # chat_mute says whether a group is muted (Backend.has_mute)
self.mutes: Dict[str, Optional[bool]] = {} # chat id → what chat_mute answers (missing: None)
self.mute_fail = False # chat_mute raises
self.mute_asked: List[str] = [] # chat_mute's calls, in order
self.info_asked: List[str] = [] # chat_info's calls, in order
self.image_fail: Optional[str] = None # "rejected" | "uncertain" for the next picture
self.send_delay = 0.0
Expand Down Expand Up @@ -336,6 +340,18 @@ def search(self, query: str, limit: int = 20) -> List[Person]:
out.append(Person("group", c.id, c.name, "%d 人" % c.members if c.members else ""))
return out[:limit]

@property
def has_mute(self) -> bool:
return self.world.mute_ok

def chat_mute(self, chat_id: str) -> Optional[bool]:
w = self.world
with w.lock:
w.mute_asked.append(chat_id)
if w.mute_fail:
raise BackendError("飞书暂时没有回答", "unreachable")
return w.mutes.get(chat_id)

@property
def has_avatars(self) -> bool:
return self.world.avatars_ok
Expand Down
7 changes: 7 additions & 0 deletions core/openmate_core/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ class Platform:
media_tool: str = ""
#: /agent can turn structured replies into pictures when the backend sends images but has no rich text.
render_cards: bool = False
#: a group's Inbox items go by topic: each topic (a thread, by its root) is an item of its own ("<chat>:<root>"),
#: its context, done state, page and reply that topic's; what is said outside any topic stays the chat's item
#: (its id the chat's, as before). Feishu: yes. WeChat: no (no topics; one item per chat as always)
inbox_topics: bool = False


@dataclass
Expand Down Expand Up @@ -121,4 +125,7 @@ class Timing:
avatar_ttl: float = 86400.0 # a chat's picture (has_avatars) is asked of the service again when it is this old…
avatar_retry: float = 3600.0 # …or this long after asking failed…
avatar_batch: int = 30 # …at most this many chats per round, in the background (an Inbox read never waits for it)
mute_ttl: float = 3600.0 # a group's mute state (has_mute) is asked of the service again when it is this old…
mute_retry: float = 600.0 # …and never sooner than this after it was asked (a failed read is "unknown" till mute_ttl)…
mute_batch: int = 10 # …at most this many groups per round, in the background (an Inbox read never waits for it)
extra: Dict[str, float] = field(default_factory=dict)
30 changes: 29 additions & 1 deletion core/openmate_core/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@
# a chat's picture (Chat.avatar: "" when the service said it has none) and when the service was last asked; a
# table of its own, so an older version opening the store (a rollback) finds every table as it knew it
"CREATE TABLE IF NOT EXISTS avatars (chat_id TEXT PRIMARY KEY, value TEXT NOT NULL, checked REAL NOT NULL)",
# whether the account muted a group in the service's own client (Backend.chat_mute): state "muted", "normal" or
# "unknown" (asked, and the service did not say), and when it was last asked; a table of its own, like avatars
# (owner: the account it was asked for; an older version's account switch does not empty this table, so a row of
# another account's is never read)
"CREATE TABLE IF NOT EXISTS mutes (chat_id TEXT PRIMARY KEY, state TEXT NOT NULL, checked REAL NOT NULL, "
"owner TEXT NOT NULL DEFAULT '')",
# one row per guest run started (自动代答, 文档代答): the hourly and daily most count these, not the pruned runs
"CREATE TABLE IF NOT EXISTS guest_quota (chat_id TEXT NOT NULL, kind TEXT NOT NULL, at REAL NOT NULL)",
"CREATE INDEX IF NOT EXISTS guest_quota_chat ON guest_quota (chat_id, kind, at)",
Expand Down Expand Up @@ -245,6 +251,8 @@ def __init__(self, path: str, legacy_blocked_texts: Iterable[str] = ()):
self._migrate([str(t) for t in legacy_blocked_texts if t])
for stmt in _SCHEMA:
self._db.execute(stmt)
if "owner" not in {r[1] for r in self._db.execute("PRAGMA table_info(mutes)").fetchall()}:
self._db.execute("ALTER TABLE mutes ADD COLUMN owner TEXT NOT NULL DEFAULT ''") # (made without it)
if self._db.execute("PRAGMA user_version").fetchone()[0] == 0:
# a new store; an older one's version is _migrate's to set (with what it marks), never set over here
self._db.execute("PRAGMA user_version=%d" % SCHEMA_VERSION)
Expand Down Expand Up @@ -366,6 +374,26 @@ def avatars(self, ids: Iterable[str]) -> Dict[str, Tuple[str, float]]:
out.update({r["chat_id"]: (r["value"], float(r["checked"])) for r in rows})
return out

def set_mute(self, chat_id: str, state: str, owner: str = "", now: Optional[float] = None) -> None:
"""A group's mute state as the service says it now: "muted", "normal" or "unknown", for the account owner."""
if state not in ("muted", "normal", "unknown"):
state = "unknown"
self._tx(lambda db: db.execute(
"INSERT INTO mutes (chat_id, state, checked, owner) VALUES (?, ?, ?, ?) "
"ON CONFLICT(chat_id) DO UPDATE SET state = excluded.state, checked = excluded.checked, owner = excluded.owner",
(str(chat_id), state, now or time.time(), owner or "")))

def mutes(self, ids: Iterable[str], owner: str = "") -> Dict[str, Tuple[str, float]]:
"""{chat id: (state, when it was asked)} of those of ids the service was asked about for the account owner."""
ids = sorted({str(i) for i in ids if i})
out: Dict[str, Tuple[str, float]] = {}
for i in range(0, len(ids), 500):
part = ids[i:i + 500]
rows = self._all("SELECT chat_id, state, checked FROM mutes WHERE owner = ? AND chat_id IN (%s)"
% ",".join("?" * len(part)), [owner or ""] + part)
out.update({r["chat_id"]: (r["state"], float(r["checked"])) for r in rows})
return out

def people_kinds(self, ids: Iterable[str]) -> Dict[str, str]:
"""{id: "bot" | "user"} of those of ids the service told about."""
ids = sorted({str(i) for i in ids if i})
Expand Down Expand Up @@ -1114,7 +1142,7 @@ def run(db):
runs = [r["id"] for r in db.execute("SELECT id FROM runs").fetchall()]
# the groups marked for 自动代答 and who is a person were the old account's choices and knowledge
for table in ("chats", "messages", "names", "runs", "seen", "autoreply", "people", "guest_quota", "gone",
"channel_msgs", "channel_asks", "avatars"):
"channel_msgs", "channel_asks", "avatars", "mutes"):
db.execute("DELETE FROM " + table)
db.execute("DELETE FROM dismissed WHERE key LIKE 'chat:%'") # its chats' 处理完 (and 恢复) marks
# its history marks, and its name (the next one's is written next, when it has one)
Expand Down
25 changes: 20 additions & 5 deletions core/openmate_core/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import logging
import re
import time
from typing import Any, Dict, List, Optional
from typing import Any, Dict, List, Optional, Tuple

from . import cards, modelimages, views
from .backend import BackendError
Expand Down Expand Up @@ -580,10 +580,25 @@ def _opens_topic(app, chat_id: str) -> bool:
return False


def _send_card(app, a: dict) -> tuple:
def _topic_of(app, a: dict) -> Tuple[str, str]:
"""(chat id, topic root) the send's chat names: an Inbox topic's thread ("<chat>:<root>", inbox_topics: its page's
reply) is that chat, into that topic; any other chat id is itself ("" root)."""
chat_id = _need(a, "chat", "会话 id")
if getattr(app.platform, "inbox_topics", False) and ":" in chat_id:
cid, _, root = chat_id.partition(":")
if cid and root:
return cid, root
return chat_id, ""


def _send_card(app, a: dict) -> tuple:
chat_id, topic = _topic_of(app, a)
text = _check_text(_need(a, "text", "消息内容"))
reply_to = str(a.get("reply_to") or "").strip()
reply_to = str(a.get("reply_to") or "").strip() or topic
if topic and reply_to != topic and app.store is not None: # into that topic: what it quotes is one of its lines
quoted = app.store.message(chat_id, reply_to)
if quoted is not None and (quoted.get("root_id") or quoted["id"]) != topic: # (one not kept yet: as asked)
raise RPCError("reply_to 不是这个话题里的消息:要回复别的话题,chat 只填会话 id")
mentions = _mentions(app, a, chat_id)
names = [n for _, n in mentions]
rich = _rich(app, text, names)
Expand Down Expand Up @@ -702,8 +717,8 @@ def as_asked() -> None:
if name == c + "_send":
try:
chat_id, text, reply_to, visible, _, mentions, rich = _send_card(app, a)
root = None
if reply_to:
root = _topic_of(app, a)[1] or None # an Inbox topic's page: into that topic
if reply_to and root is None:
quoted = app.store.message(chat_id, reply_to)
if quoted is not None and quoted.get("root_id"):
root = quoted["root_id"]
Expand Down
Loading
Loading