From 800f267b667daefe1e86bc38c5b364cb2477bc55 Mon Sep 17 00:00:00 2001
From: itxiaohui <177289791+itxiaohui66@users.noreply.github.com>
Date: Wed, 7 Oct 2026 14:23:48 +0800
Subject: [PATCH] Add registered nickname recipients for QQ events without
mentions
---
README.md | 33 +++--
main.py | 62 +++++++---
metadata.yaml | 2 +-
services/diagnostics.py | 12 +-
services/storage.py | 45 ++++++-
services/targets.py | 73 +++++++++--
tests/test_member_names.py | 2 +-
tests/test_name_registration.py | 207 ++++++++++++++++++++++++++++++++
tests/test_reminders.py | 2 +-
9 files changed, 396 insertions(+), 42 deletions(-)
create mode 100644 tests/test_name_registration.py
diff --git a/README.md b/README.md
index 2693546..e362502 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@
https://github.com/itxiaohui66/astrbot_plugin_tixing
```
-也可以从 [GitHub Releases](https://github.com/itxiaohui66/astrbot_plugin_tixing/releases/latest) 下载 `astrbot_plugin_tixing-v1.3.1.zip`,在插件页上传安装。手动安装时,把 ZIP 中的 `astrbot_plugin_tixing` 文件夹解压到 AstrBot 的 `data/plugins/` 下,然后重启或重载插件。运行文件 `main.py`、`metadata.yaml` 和 `_conf_schema.json` 必须直接位于该插件文件夹中。
+也可以从 [GitHub Releases](https://github.com/itxiaohui66/astrbot_plugin_tixing/releases/latest) 下载 `astrbot_plugin_tixing-v1.4.0.zip`,在插件页上传安装。手动安装时,把 ZIP 中的 `astrbot_plugin_tixing` 文件夹解压到 AstrBot 的 `data/plugins/` 下,然后重启或重载插件。运行文件 `main.py`、`metadata.yaml` 和 `_conf_schema.json` 必须直接位于该插件文件夹中。
安装时 AstrBot 会读取 `requirements.txt` 安装 `tzdata`。配置默认采用北京时间 `Asia/Shanghai`;每人在每个群或私聊最多 10 个活跃提醒,每 30 秒扫描一次。确认机器人已经接入 QQ 官方适配器,群内使用 `@机器人 /tx help` 查看帮助。
@@ -49,6 +49,8 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
/tx 每周一 9:00 周报
/tx 每周7 20:00 总结
/tx 1小时 开会 @某人
+/tx to xh 1分钟 测试
+/tx to "小 明" 每天9:00 打卡
```
时间和内容之间要有空格。内容可以包含空格、换行,默认最多 1000 个字符。单次 `HH:MM` 表示今天该时刻,已经过去则提示改用未来时间;每天和每周自动计算下一次。提醒间隔必须大于 0,小时范围 0–23,分钟范围 0–59。
@@ -62,6 +64,9 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
| 命令 | 行为 |
| --- | --- |
| `/tx help` | 全部帮助 |
+| `/tx to 昵称 时间 内容` / `/tx 给 昵称 时间 内容` | 按名字提醒本群已识别的成员;不用 @ 对方或填写 ID |
+| `/tx name 昵称` / `/tx 昵称 昵称` / `/tx 登记 昵称` | 给自己登记一个本群唯一的提醒昵称,每人一个,可再次登记修改 |
+| `/tx name` | 查看自己登记的提醒昵称 |
| `/tx list [页码]` / `/cktx` / `/提醒列表` | 当前会话中自己创建的活跃提醒 |
| `/tx history [页码]` | 自己的全部记录,包括完成、取消、失败 |
| `/tx detail 编号` | 查看全文、时间、状态、失败次数和最近错误 |
@@ -84,17 +89,31 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
## 官方 QQ 的对象和发送权限
-**提醒别人直接 @ 对方的名字,无需填写或复制长串 ID。** 在 QQ 输入 `@` 后,从群成员列表选中对方,例如:
+**官方 QQ 不保证在“@机器人”事件中提供被 @ 的其他成员信息。** 已确认的部署事件中,用户发送 `@xh` 后,QQ 原始 `mentions` 和 SDK `mentions` 都为空;实际 @ 还可能从正文中被删除,插件无法恢复没有下发的目标名字或 ID。此前说明中“从 QQ 列表选中对方就一定能识别”的说法不准确。
+
+v1.4.0 增加不需要复制长串 ID 的可靠路径。若机器人已经收到过该成员带昵称的群消息,可以直接按已知昵称提醒;否则让被提醒的成员在**同一个群**登记一次,例如 **xh 本人**发送:
```text
-@机器人 /tx 30分钟 开会 @小明
+@机器人 /tx name xh
```
-v1.2.2 修复 SDK 的非空 `mentions` 列表丢失成员字段时覆盖完整原始数据,导致“提醒别人”退回提醒发起人的情况。解析会合并原始 QQ payload 和 SDK 信息,并从当前消息的原始正文恢复被适配器省略的真实 @,包括命令前的 @;不从引用消息中选取接收者。已知机器人及其别名始终排除在提醒对象之外。收到无法解析的额外 @ 元数据时会提示“未创建提醒”,不静默改成提醒自己。
+机器人从**登记者这条消息的发送者 ID** 自动绑定名字,发起提醒的人无需填写 ID。之后其他人发送:
+
+```text
+@机器人 /tx to xh 1分钟 测试
+```
+
+`to` 后直接写名字,不从 QQ 的 @ 列表选择对方,这样名字不会被 QQ 删除。带空格的名字用双引号,例如 `/tx name "小 明"`、`/tx to "小 明" 1分钟 测试`。昵称登记仅能登记自己,不能用自己的消息登记别人的 ID。已被其他已识别成员使用的名字会拒绝登记;重名时选择不同提醒昵称。登记按平台、群保存,重载或收到新的 QQ 昵称后仍保留。更改登记不会改变已有任务保存的接收者 ID。
+
+显式 `to` 的对象未识别、与真实 @ 冲突或无法解析时会拒绝创建,绝不改成提醒自己。原来的 `/tx 时间 内容` 仍用于提醒自己;若 QQ 已完全删除另一个 @,插件无法区分这条命令原本是否要提醒他人,所以确认回复会明确警示“未识别到其他成员”,并提示取消后用 `to` 重建。
+
+腾讯公开文档中的 [群成员列表接口](https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/server-inter/group/manage/README.md) 标为内邀能力,列出的返回项是成员 OpenID 和入群时间,不能作为普通机器人普遍可用的陌生昵称查询方案。昵称登记使用现有群消息事件,不要求成员查询权限。
+
+平台确实提供被 @ 成员 ID 时,原 `/tx 30分钟 开会 @小明` 仍可使用。v1.2.2 的解析会合并原始 QQ payload 和 SDK 信息,并从当前消息的原始正文恢复被适配器省略的真实 @,包括命令前的 @;不从引用消息中选取接收者。已知机器人及其别名始终排除在提醒对象之外。收到无法解析的额外 @ 元数据时会提示“未创建提醒”。v1.4.0 同时优先从 QQ 原始命令解析参数,避免 AstrBot 正文省略了仍存在于原始正文中的 `@昵称`。
机器人从实际 @ 的消息段、原始正文和 mentions 自动读取并保存对方的本群 ID,到期用 QQ 原生 @ 提醒对方。用户看到的是名字,ID 由插件内部处理。QQ 未提供昵称时,创建确认显示“你选中的群成员”,不把长串 ID 当作人名。
-v1.3.0 会从机器人收到的成员消息和真实 @ 中学习用户名、群名片及昵称,按平台和群保存,重启后仍可使用。已识别成员也支持直接输入 `@小明`;带空格的名字支持 `@"小 明"` 或 `@小 明`(后者需名字已被识别)。同名时请从 QQ 的 @ 列表选择具体成员,实际选择优先于昵称缓存。收到新名字时更新记录,不继续按旧昵称匹配。
+v1.3.0 会从机器人收到的成员消息和真实 @ 中学习用户名、群名片及昵称,按平台和群保存,重启后仍可使用。已识别成员也支持手打 `@小明`(不要从 QQ @ 列表选择,避免被删除);带空格的名字支持 `@"小 明"` 或 `@小 明`(后者需名字已被识别)。平台下发真实 @ 的 ID 时,实际选择优先于昵称缓存。收到新名字时更新观察记录,不继续按旧昵称匹配;v1.4.0 的自定义登记昵称独立保留。
v1.3.1 修复昵称紧挨中文正文(`开会@小明`)、全角 `@` 和昵称位于命令前(`@小明 /tx 1分钟 开会`)时漏掉对象的情况;未知昵称仍明确拒绝创建,不会改成提醒自己。邮件地址如 `test@example.com` 保留在正文中。到期消息不再给普通括号和提醒编号添加多余反斜杠,例如 `小慧(代码版)`、`(提醒 #14)`。
@@ -102,7 +121,7 @@ v1.3.1 修复昵称紧挨中文正文(`开会@小明`)、全角 `@` 和昵
“显示对象名字正确,但实际 @ 发起人”时,还可 `/tx diagnose 提醒编号` 查看该任务保存的创建者与接收者标记,以及到期 @ 所用标记。此操作受创建者/管理员权限及群隔离限制,不发送提醒。实际投递前日志记录相同的标记,供核对创建、数据库和发送三处的 ID。接口成功不代表已经验证了 QQ 客户端最终 @ 的成员;需要实际事件数据定位映射问题。
-仅手打一个机器人从未收到过的昵称时,插件无法凭空获得该成员 ID;请从 QQ 的 @ 列表选择对方。若平台连实际 @ 的成员信息也没有下发,可让对方先在本群 `@机器人` 发一条消息;平台提供昵称后即可按昵称匹配。解析失败会明确提示“未创建提醒”,不会退回提醒发起人,也不会要求复制 OpenID。官方群事件的基础字段及其成员标识见 [腾讯事件文档](https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/server-inter/message/send-receive/event.md)。
+仅手打一个机器人从未收到过的昵称时,插件无法凭空获得该成员 ID;请按上述流程让对方 `/tx name 昵称` 登记,或先收到对方的带昵称消息。解析失败会明确提示“未创建提醒”,不会退回提醒发起人,也不会要求复制 OpenID。官方群事件的基础字段及其发送者成员标识见 [腾讯事件文档](https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/server-inter/message/send-receive/event.md)。
创建回复始终显示“提醒对象”。发起人仍管理该任务,到期只 @ 保存的接收者。旧版已错误保存为提醒自己的任务无法从数据库还原原定接收者,请 `/tx cancel 编号` 后重新设置,并检查创建回复中的提醒对象。不同群里的成员记录不会混用。OneBot 模式会查询目标是否是本群成员。私聊只能提醒自己。
@@ -165,7 +184,7 @@ python tools/package.py
1. 首次命令或入群时确认收到权限开启提示;管理员开启“允许机器人主动发送消息”后,`@机器人 /tx permission check` 确认主动验证成功。
2. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,到期收到真正 @ 的通知;`/tx history` 检查状态,失败时查看原因和日志。
3. `/tx 5分钟 重启测试`,重载插件后用 `/tx list` 确认仍在,再 `/tx cancel 编号` 确认取消。
-4. `@机器人 /tx 1分钟 他人提醒测试 @另一成员`,从 QQ 的 @ 列表选择对方,确认创建回复中的提醒对象;到期只 @ 对方,不 @ 发起人。成员名字被识别后,再测试手打 `@昵称` 以及重载后的昵称匹配。
+4. 让另一成员发送 `@机器人 /tx name xh`,你发送 `@机器人 /tx to xh 1分钟 他人提醒测试`,确认创建回复中的提醒对象是 xh;到期只 @ 对方,不 @ 发起人。再验证重载后仍可按登记昵称提醒。若平台确实下发真实 @ 的成员 ID,再验证从 QQ 列表选择成员的旧语法。
5. `@机器人 /tx 6分钟 主动提醒测试`,期间不再 @机器人,确认到期仍收到提醒。若因权限不足显示等待,开好权限并再次验证;旧版已自动取消的任务需先 `/tx retry 编号` 恢复。
## 来源
diff --git a/main.py b/main.py
index 9f59010..95606dd 100644
--- a/main.py
+++ b/main.py
@@ -27,12 +27,20 @@ from .services.delivery import (
from .services.diagnostics import VERSION, diagnose, identity
from .services.permissions import NOTICE, PermissionBridge
from .services.storage import ReminderStore, scope_key
-from .services.targets import MARKUP, observe_members, resolve_target
+from .services.targets import (
+ command_args,
+ named_recipient,
+ observe_members,
+ registration_name,
+ resolve_target,
+)
from .services.time_parser import describe, next_occurrence, parse_time
HELP = """⏰ 栗子提醒
/tx 30分钟 开会(也支持分钟后、小时、天、min/h/d)
/tx 1小时 开会 @某人
+/tx to xh 1分钟 测试(直接写名字,不用 @ 对方或填写 ID)
+/tx name xh 登记自己的提醒昵称(对方在本群登记一次即可)
/tx 10:00 开会(今天)
/tx 明天10:00 开会
/tx 2026-12-31 20:00 跨年
@@ -53,8 +61,9 @@ HELP = """⏰ 栗子提醒
/cxzd 管理员重启提醒调度器
命令别名:/提醒、/remind
群内官方 QQ 需要 @机器人;时间按配置时区计算。
-提醒他人:输入 @ 后从 QQ 群成员列表选中对方,机器人自动识别,无需填 ID。
-已识别的本群成员也支持 @昵称;昵称带空格可用 @"小 明"。
+QQ 有时不下发被 @ 成员的 ID,请优先 /tx to 昵称 时间 内容。
+机器人从成员发言学习 ID;未认识的成员可自己 /tx name 昵称 登记,无需复制 ID。
+平台提供完整真实 @ 时也支持;昵称带空格可用 /tx to "小 明" 1分钟 测试。
默认到点主动提醒;群主/管理员需开启“允许机器人主动发送消息”。
管理员可 /tx list all 和 /tx cancel 编号 管理当前群提醒。"""
@@ -391,16 +400,7 @@ class ReminderPlugin(Star):
@filter.command("tx", alias={"提醒", "remind"})
async def tx(self, event: AstrMessageEvent):
"""设置、查看、取消单次或循环提醒。"""
- # Raw text preserves spaces/newlines in reminder content. Remove only the bot mention.
- text = event.message_str
- bot_id = str(event.message_obj.self_id)
- text = MARKUP.sub(
- lambda m: " " if next(g for g in m.groups() if g is not None) == bot_id else m.group(0),
- text,
- )
- match = re.search(r"(?:^|\s)/?(?:tx|提醒|remind)(?=\s|$)", text, re.I)
- args = text[match.end() :].strip() if match else ""
- await self._guard(event, lambda: self._command(event, args))
+ await self._guard(event, lambda: self._command(event, command_args(event)))
async def _command(self, event, args):
if not args or args.lower() in {"help", "帮助"}:
@@ -414,6 +414,23 @@ class ReminderPlugin(Star):
parts = args.split(maxsplit=1)
action = parts[0].lower()
tail = parts[1].strip() if len(parts) == 2 else ""
+ if action in {"name", "昵称", "登记"}:
+ if not event.get_group_id():
+ raise ValueError("请在需要使用提醒的群内登记昵称,私聊记录不能用于群聊。")
+ if not tail:
+ name = await self.store.registered_name(scope, user)
+ await self._reply(
+ event, f"你的提醒昵称:{name or '尚未登记'}\n用法:/tx name xh(仅登记自己)"
+ )
+ return
+ name = registration_name(tail)
+ await self.store.register_name(scope, user, name)
+ quoted = f'"{name}"' if any(c.isspace() for c in name) else name
+ await self._reply(
+ event,
+ f"✅ 已将提醒昵称“{name}”登记给你自己。\n其他人可发送 /tx to {quoted} 1分钟 测试 提醒你,无需填写 ID。",
+ )
+ return
if action in {"list", "列表", "查看", "history", "历史"}:
await self._list(event, scope, user, tail, action in {"history", "历史"})
return
@@ -481,7 +498,12 @@ class ReminderPlugin(Star):
+ (f"\n扫描错误:{self.last_scan_error}" if self.last_scan_error else ""),
)
return
- args, target, target_name = await resolve_target(event, args, self.store, scope)
+ explicit_name = None
+ if action in {"to", "给", "提醒他人"}:
+ explicit_name, args = named_recipient(tail)
+ args, target, target_name = await resolve_target(
+ event, args, self.store, scope, explicit_name
+ )
parsed = parse_time(args, datetime.now(self.tz))
if len(parsed.content) > self.max_content:
raise ValueError(f"提醒内容最多 {self.max_content} 个字符。")
@@ -510,11 +532,23 @@ class ReminderPlugin(Star):
message += f"\n提醒对象:{target_name or '你选中的群成员'}"
else:
message += "\n提醒对象:你自己"
+ if (
+ explicit_name is None
+ and event.get_platform_name() in OFFICIAL
+ and event.get_group_id()
+ ):
+ message += f"\n本次未识别到其他成员。若要提醒他人,请 /tx cancel {reminder_id} 后改用 /tx to 昵称 时间 内容;QQ 可能未下发实际 @ 的成员信息。"
if event.get_platform_name() in OFFICIAL:
if self.delivery_mode == "passive":
message += "\n使用被动回复:到期有有效回复窗口时发送,否则等待下次 @机器人 补发。"
else:
message += "\n到点主动提醒;权限受限时保留任务,等待开启权限后补发。"
+ if scene == "group":
+ permission = await self.store.permission(
+ str(event.get_platform_id()), destination
+ )
+ if permission["state"] in {"error", "denied", "removed"}:
+ message += "\n⚠️ 当前已检测到主动发送受限,请群主/管理员开启权限后 /tx permission check 验证;否则到期仍无法发送。"
await self._reply(event, message)
def _format(self, rem, detail=False):
diff --git a/metadata.yaml b/metadata.yaml
index 1630b19..628cb6c 100644
--- a/metadata.yaml
+++ b/metadata.yaml
@@ -1,7 +1,7 @@
name: astrbot_plugin_tixing
display_name: 栗子提醒
desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。
-version: v1.3.1
+version: v1.4.0
author: itxiaohui
repo: https://github.com/itxiaohui66/astrbot_plugin_tixing
support_platforms:
diff --git a/services/diagnostics.py b/services/diagnostics.py
index 503576b..0b521a7 100644
--- a/services/diagnostics.py
+++ b/services/diagnostics.py
@@ -4,9 +4,9 @@ import hashlib
import json
from .delivery import field
-from .targets import MARKUP, mention_data, resolve_target
+from .targets import MARKUP, mention_data, named_recipient, resolve_target
-VERSION = "v1.3.1"
+VERSION = "v1.4.0"
def identity(value):
@@ -72,7 +72,13 @@ async def diagnose(event, args, store, scope):
"原始author": member(field(data, "author", {})),
}
try:
- _, target, name = await resolve_target(event, args, store, scope)
+ parts = args.split(maxsplit=1)
+ first = parts[0] if parts else ""
+ tail = parts[1] if len(parts) == 2 else ""
+ explicit_name = None
+ if first in {"to", "给", "提醒他人"}:
+ explicit_name, args = named_recipient(tail)
+ _, target, name = await resolve_target(event, args, store, scope, explicit_name)
report["解析结果"] = {
"对象": identity(target),
"名字": name,
diff --git a/services/storage.py b/services/storage.py
index 260267b..6dc5d30 100644
--- a/services/storage.py
+++ b/services/storage.py
@@ -69,6 +69,10 @@ class ReminderStore:
PRIMARY KEY(scope, user_id, name)
);
CREATE INDEX IF NOT EXISTS member_names_lookup ON member_names(scope, name);
+ CREATE TABLE IF NOT EXISTS member_aliases (
+ scope TEXT NOT NULL, user_id TEXT NOT NULL, name TEXT NOT NULL,
+ PRIMARY KEY(scope, user_id), UNIQUE(scope, name)
+ );
INSERT OR IGNORE INTO member_names
SELECT scope,user_id,nickname FROM members WHERE nickname!='';
CREATE TABLE IF NOT EXISTS reply_contexts (
@@ -217,7 +221,9 @@ class ReminderStore:
lambda db: [
r[0]
for r in db.execute(
- "SELECT DISTINCT name FROM member_names WHERE scope=?", (scope,)
+ "SELECT name FROM member_names WHERE scope=? UNION "
+ "SELECT name FROM member_aliases WHERE scope=?",
+ (scope, scope),
)
]
)
@@ -227,18 +233,49 @@ class ReminderStore:
rows = db.execute(
"SELECT DISTINCT m.* FROM members m LEFT JOIN member_names n "
"ON m.scope=n.scope AND m.user_id=n.user_id "
- "WHERE m.scope=? AND (m.user_id=? OR n.name=?)",
- (scope, value, value),
+ "LEFT JOIN member_aliases a ON m.scope=a.scope AND m.user_id=a.user_id "
+ "WHERE m.scope=? AND (m.user_id=? OR n.name=? OR a.name=?)",
+ (scope, value, value, value),
).fetchall()
exact = [r for r in rows if r["user_id"] == value]
if exact:
return dict(exact[0])
if len(rows) > 1:
- raise ValueError("本群有重名用户,请在 QQ 的 @ 群成员列表中选中对方后发送。")
+ raise ValueError(
+ "本群有重名用户,请让成员 /tx name 登记不同提醒昵称,或使用平台能识别的真实 @。"
+ )
return dict(rows[0]) if rows else None
return await self._run(read)
+ async def register_name(self, scope, user_id, name):
+ def write(db):
+ db.execute("BEGIN IMMEDIATE")
+ occupied = db.execute(
+ "SELECT user_id FROM member_names WHERE scope=? AND name=? UNION "
+ "SELECT user_id FROM member_aliases WHERE scope=? AND name=? UNION "
+ "SELECT user_id FROM members WHERE scope=? AND user_id=?",
+ (scope, name, scope, name, scope, name),
+ ).fetchall()
+ if any(row[0] != user_id for row in occupied):
+ raise ValueError("该名字已经对应本群其他成员,请选择一个唯一的提醒昵称。")
+ db.execute(
+ "INSERT INTO member_aliases VALUES (?,?,?) "
+ "ON CONFLICT(scope,user_id) DO UPDATE SET name=excluded.name",
+ (scope, user_id, name),
+ )
+
+ await self._run(write)
+
+ async def registered_name(self, scope, user_id):
+ def read(db):
+ row = db.execute(
+ "SELECT name FROM member_aliases WHERE scope=? AND user_id=?", (scope, user_id)
+ ).fetchone()
+ return row["name"] if row else ""
+
+ return await self._run(read)
+
async def add(self, record, limit):
def insert(db):
db.execute("BEGIN IMMEDIATE")
diff --git a/services/targets.py b/services/targets.py
index 28d3aeb..0ee8b33 100644
--- a/services/targets.py
+++ b/services/targets.py
@@ -8,6 +8,47 @@ MARKUP = re.compile(
r"|<@!?([^>]+)>|\[CQ:at,qq=([^,\]]+)[^\]]*\]"
)
VALID_ID = re.compile(r"[A-Za-z0-9_-]{1,128}\Z")
+COMMAND = re.compile(r"(?:^|\s)/?(?:tx|提醒|remind)(?=\s|$)", re.I)
+
+
+def message_text(event):
+ """Prefer the original command when AstrBot has removed a textual mention."""
+ if event.get_platform_name() in OFFICIAL:
+ raw = event.message_obj.raw_message
+ data = field(raw, "raw_data", raw)
+ content = field(data, "content") or field(raw, "content", "") or ""
+ if isinstance(content, str) and COMMAND.search(content):
+ return content
+ return event.message_str
+
+
+def command_args(event):
+ text = message_text(event)
+ _, _, _, bot_ids, *_ = mention_data(event)
+ text = MARKUP.sub(
+ lambda m: " " if next(g for g in m.groups() if g is not None) in bot_ids else m.group(0),
+ text,
+ )
+ command = COMMAND.search(text)
+ return text[command.end() :].strip() if command else ""
+
+
+def named_recipient(text):
+ match = re.fullmatch(r'(?:"([^"\n]+)"|“([^”\n]+)”|(\S+))\s+(.+)', text, re.S)
+ if not match:
+ raise ValueError('用法:/tx to xh 1分钟 测试;名字带空格用 /tx to "小 明" 1分钟 测试。')
+ return next(g for g in match.groups()[:3] if g is not None), match.group(4).strip()
+
+
+def registration_name(text):
+ name = text.strip()
+ if len(name) >= 2 and (name[0], name[-1]) in {('"', '"'), ("“", "”")}:
+ name = name[1:-1].strip()
+ if not name or len(name) > 64 or any(ord(c) < 32 or c in "@@<>[]" for c in name):
+ raise ValueError("提醒昵称需要 1–64 个字符,不要加 @ 或填入 @ 标签。")
+ if name in {"all", "everyone", "全体成员"}:
+ raise ValueError("不能使用全体成员作为提醒昵称。")
+ return name
def member_names(member):
@@ -114,7 +155,7 @@ def text_mentions(names):
return pattern
-async def resolve_target(event, args, store, scope):
+async def resolve_target(event, args, store, scope, explicit_name=None):
sender = str(event.get_sender_id())
trusted, names, aliases, bot_ids, bot_names, payload_mentions, sdk_mentions = mention_data(
event
@@ -133,13 +174,19 @@ async def resolve_target(event, args, store, scope):
textual = list(pattern.finditer(args))
# A QQ mention can precede the command. Without native mention metadata,
# tx()'s argument slicing previously discarded this explicit recipient.
- command = re.search(r"(?:^|\s)/?(?:tx|提醒|remind)(?=\s|$)", event.message_str, re.I)
+ text = message_text(event)
+ command = COMMAND.search(text)
if command:
- prefix = MARKUP.sub(" ", event.message_str[: command.start()])
+ prefix = MARKUP.sub(" ", text[: command.start()])
textual.extend(pattern.finditer(prefix))
- for match in textual:
- value = next(g for g in match.groups() if g is not None)
+ values = [next(g for g in match.groups() if g is not None) for match in textual]
+ if explicit_name is not None:
+ values.append(explicit_name)
+ selected_name = ""
+ for value in values:
if value in bot_names or aliases.get(value, value) in bot_ids:
+ if value == explicit_name:
+ raise ValueError("提醒对象不能是机器人,请填写本群成员的提醒昵称。")
continue
# @all must not be allowed as a recipient.
if value in {"all", "everyone", "全体成员"}:
@@ -155,13 +202,17 @@ async def resolve_target(event, args, store, scope):
and aliases.get(value, value) not in trusted
and event.get_platform_name() in OFFICIAL
):
+ quoted = f'"{value}"' if any(c.isspace() for c in value) else value
raise ValueError(
- f"还未识别本群成员“{value}”,未创建提醒。请输入 @ 后从 QQ 群成员列表中选中对方;"
- "也可以让对方先在本群 @机器人发一条消息,再用 @昵称。无需填写 OpenID。"
+ f"还未识别本群成员“{value}”,未创建提醒。"
+ f"QQ 没有提供这个名字对应的成员 ID。请让对方在本群发送 @机器人 /tx name {quoted} "
+ f"登记自己,然后使用 /tx to {quoted} 1分钟 测试。无需复制 ID。"
)
candidates.append(
matching[0] if matching else member["user_id"] if member else aliases.get(value, value)
)
+ if member and value != member["user_id"]:
+ selected_name = value
args = pattern.sub(" ", args).strip()
candidates = list(dict.fromkeys(candidates))
if not candidates:
@@ -188,7 +239,7 @@ async def resolve_target(event, args, store, scope):
if unknown or (not payload_mentions and sdk_unknown and len(sdk_mentions) > 1):
raise ValueError(
"收到 @ 成员信息,但无法识别提醒对象,未创建提醒。"
- "请输入 @ 后从 QQ 群成员列表中选中对方,或让对方先 @机器人发一条消息再用 @昵称。"
+ "QQ 没有提供完整成员标识。可让对方 /tx name 昵称 登记自己,再 /tx to 昵称 时间 内容。"
)
if len(candidates) > 1:
raise ValueError("一次提醒只能指定一个成员。")
@@ -202,8 +253,8 @@ async def resolve_target(event, args, store, scope):
if event.get_platform_name() in OFFICIAL:
if target not in trusted and not member:
raise ValueError(
- "无法识别本群提醒对象,未创建提醒。请输入 @ 后从 QQ 群成员列表中选中对方,"
- "或让对方先 @机器人发一条消息再用 @昵称。无需填写 OpenID。"
+ "无法识别本群提醒对象,未创建提醒。请让对方 /tx name 昵称 登记自己,"
+ "再使用 /tx to 昵称 时间 内容。无需复制 ID。"
)
elif event.get_platform_name() == "aiocqhttp":
try:
@@ -212,7 +263,7 @@ async def resolve_target(event, args, store, scope):
)
except Exception as exc:
raise ValueError("无法在本群找到该成员,请重新 @ 群成员。") from exc
- name = trusted.get(target) or (member["nickname"] if member else "")
+ name = selected_name or trusted.get(target) or (member["nickname"] if member else "")
if target == sender:
name = event.get_sender_name() or ""
return args, target, name
diff --git a/tests/test_member_names.py b/tests/test_member_names.py
index bd04274..7f3805b 100644
--- a/tests/test_member_names.py
+++ b/tests/test_member_names.py
@@ -108,7 +108,7 @@ async def test_unknown_or_cross_group_nickname_never_creates_self_reminder(plugi
await instance.store.observe("another_scope", "target_member", "小明")
event = event_factory("/tx 1分钟 开会 @小明")
await instance.tx(event)
- assert "未创建提醒" in event.replies[0] and "群成员列表" in event.replies[0]
+ assert "未创建提醒" in event.replies[0] and "/tx name" in event.replies[0]
assert "/tx identity" not in event.replies[0]
assert not await instance.store.list(record()["scope"])
diff --git a/tests/test_name_registration.py b/tests/test_name_registration.py
new file mode 100644
index 0000000..74d22f7
--- /dev/null
+++ b/tests/test_name_registration.py
@@ -0,0 +1,207 @@
+import time
+from types import SimpleNamespace
+
+import pytest
+from test_reminders import plugin as plugin
+from test_reminders import record
+
+from services.diagnostics import identity
+from services.targets import command_args
+
+
+def official_event(event_factory, text, user="user_1", normalized=None, platform="qq_official"):
+ # Reproduce the user's QQ payload: no mentions, only the triggering bot At.
+ event = event_factory(
+ normalized or text.lstrip("/"),
+ user=user,
+ platform=platform,
+ raw=SimpleNamespace(
+ group_openid="group_1",
+ mentions=[],
+ raw_data={
+ "group_openid": "group_1",
+ "content": " " + text,
+ "mentions": [],
+ "author": {"id": user, "member_openid": user, "username": "QQ昵称_" + user},
+ },
+ ),
+ )
+ event.messages = [SimpleNamespace(qq="bot_id", name="", type="At")]
+ return event
+
+
+@pytest.mark.parametrize("platform_name", ["qq_official", "qq_official_webhook"])
+@pytest.mark.parametrize("name", ["xh", '"小 明"'])
+async def test_register_and_remind_by_name_without_incoming_mentions_or_typed_ids(
+ plugin, plugin_class, event_factory, platform_name, name
+):
+ instance, platform = plugin
+ platform.meta = lambda: SimpleNamespace(id="platform_1", name=platform_name)
+ register = official_event(
+ event_factory, f"/tx name {name}", "target_member", platform=platform_name
+ )
+ await instance.tx(register)
+ assert "登记给你自己" in register.replies[0]
+ assert "target_member" not in register.replies[0]
+ # A later message / rename must not erase the explicitly registered nickname.
+ await instance.observe_member(
+ official_event(event_factory, "你好", "target_member", platform=platform_name)
+ )
+ await instance.terminate()
+ restored = plugin_class(instance.context, {})
+ await restored.store.initialize()
+ restored._ready = True
+ try:
+ event = official_event(event_factory, f"/tx to {name} 1分钟 测试", platform=platform_name)
+ await restored.tx(event)
+ rem = (await restored.store.list(record()["scope"]))[0]
+ assert rem["creator_id"] == "user_1" and rem["target_id"] == "target_member"
+ assert rem["target_name"] == name.strip('"') and rem["content"] == "测试"
+ assert "你自己" not in event.replies[0] and "target_member" not in event.replies[0]
+ await restored.store._run(
+ lambda db: db.execute(
+ "UPDATE reminders SET remind_at=? WHERE id=?", (time.time() - 1, rem["id"])
+ )
+ )
+ await restored._check_due()
+ sent = platform.get_client().api.post_group_message.call_args.kwargs["markdown"]["content"]
+ assert sent.startswith('')
+ assert 'id="user_1"' not in sent
+ finally:
+ await restored.terminate()
+
+
+async def test_raw_textual_nickname_survives_normalized_command_loss(plugin, event_factory):
+ instance, _ = plugin
+ await instance.store.observe(record()["scope"], "target_member", "xh")
+ event = official_event(event_factory, "/tx 1分钟 测试 @xh", normalized="/tx 1分钟 测试")
+ assert command_args(event) == "1分钟 测试 @xh"
+ await instance.tx(event)
+ assert (await instance.store.list(record()["scope"]))[0]["target_id"] == "target_member"
+
+
+async def test_unknown_name_never_creates_self_reminder_and_guides_registration(
+ plugin, event_factory
+):
+ instance, _ = plugin
+ for text in ("/tx to xh 1分钟 测试", "/tx 1分钟 测试 @xh"):
+ event = official_event(event_factory, text)
+ await instance.tx(event)
+ assert "未创建提醒" in event.replies[0] and "/tx name xh" in event.replies[0]
+ assert "无需复制 ID" in event.replies[0]
+ assert not await instance.store.list(record()["scope"])
+
+
+async def test_fully_stripped_at_cannot_be_inferred_and_self_confirmation_warns(
+ plugin, event_factory
+):
+ instance, _ = plugin
+ event = official_event(event_factory, "/tx 1分钟 测试")
+ await instance.tx(event)
+ assert "本次未识别到其他成员" in event.replies[0] and "/tx to" in event.replies[0]
+
+
+async def test_registration_is_only_for_sender_and_isolated_by_group(plugin, event_factory):
+ instance, _ = plugin
+ register = official_event(event_factory, "/tx name xh", "target_member")
+ await instance.tx(register)
+ occupied = official_event(event_factory, "/tx name xh", "another_user")
+ await instance.tx(occupied)
+ assert "已经对应本群其他成员" in occupied.replies[0]
+ assert (await instance.store.member(record()["scope"], "xh"))["user_id"] == "target_member"
+ event = event_factory("/tx to xh 1分钟 测试", group="other_group")
+ await instance.tx(event)
+ assert "未创建提醒" in event.replies[0]
+
+
+async def test_change_registration_releases_old_alias_without_changing_existing_reminders(
+ plugin, event_factory
+):
+ instance, _ = plugin
+ number = await instance.store.add(record(target_id="target_member", target_name="xh"), 10)
+ for name in ("xh", "xh新名字"):
+ await instance.tx(official_event(event_factory, f"/tx name {name}", "target_member"))
+ assert await instance.store.member(record()["scope"], "xh") is None
+ assert (await instance.store.member(record()["scope"], "xh新名字"))[
+ "user_id"
+ ] == "target_member"
+ saved = await instance.store.get(number, record()["scope"])
+ assert saved["target_id"] == "target_member" and saved["target_name"] == "xh"
+
+
+async def test_known_permission_failure_is_visible_on_new_named_reminder(plugin, event_factory):
+ instance, _ = plugin
+ await instance.store.observe(record()["scope"], "target_member", "xh")
+ await instance.store.set_permission("platform_1", "group_1", "error")
+ event = official_event(event_factory, "/tx to xh 1分钟 测试")
+ await instance.tx(event)
+ assert "提醒对象:xh" in event.replies[0]
+ assert "当前已检测到主动发送受限" in event.replies[0]
+ assert "/tx permission check" in event.replies[0]
+
+
+async def test_registered_literal_at_nickname_works_without_mention_payload(plugin, event_factory):
+ instance, _ = plugin
+ await instance.tx(official_event(event_factory, "/tx name xh", "target_member"))
+ await instance.tx(official_event(event_factory, "/tx 1分钟 测试 @xh"))
+ saved = (await instance.store.list(record()["scope"]))[0]
+ assert saved["target_id"] == "target_member" and saved["target_name"] == "xh"
+
+
+async def test_registration_conflicts_with_observed_other_member_name(plugin, event_factory):
+ instance, _ = plugin
+ await instance.store.observe(record()["scope"], "another_member", "xh")
+ event = official_event(event_factory, "/tx name xh", "target_member")
+ await instance.tx(event)
+ assert "已经对应" in event.replies[0]
+
+
+async def test_explicit_name_must_agree_with_native_selection(plugin, event_factory):
+ instance, _ = plugin
+ await instance.store.observe(record()["scope"], "target_member", "xh")
+ event = event_factory(
+ "/tx to xh 1分钟 测试",
+ raw={
+ "group_openid": "group_1",
+ "mentions": [{"member_openid": "different_member", "username": "另一个人"}],
+ },
+ )
+ await instance.tx(event)
+ assert "只能指定一个成员" in event.replies[0]
+ assert not await instance.store.list(record()["scope"])
+
+
+async def test_bot_cannot_be_explicit_named_recipient(plugin, event_factory):
+ instance, _ = plugin
+ event = event_factory("/tx to bot_id 1分钟 测试")
+ await instance.tx(event)
+ assert "不能是机器人" in event.replies[0]
+ assert not await instance.store.list(record()["scope"])
+
+
+async def test_named_diagnostic_and_registered_name_query(plugin, event_factory):
+ instance, _ = plugin
+ await instance.tx(official_event(event_factory, "/tx name xh", "target_member"))
+ event = official_event(event_factory, "/tx diagnose to xh 1分钟 测试")
+ await instance.tx(event)
+ assert identity("target_member") in event.replies[0]
+ assert not await instance.store.list(record()["scope"])
+ event = official_event(event_factory, "/tx name", "target_member")
+ await instance.tx(event)
+ assert "你的提醒昵称:xh" in event.replies[0]
+
+
+async def test_group_registration_not_accepted_in_private(plugin, event_factory):
+ instance, _ = plugin
+ event = event_factory("/tx name xh", group="")
+ await instance.tx(event)
+ assert "群内登记" in event.replies[0]
+
+
+@pytest.mark.parametrize("tail", ["", "@xh", "<@id>", "all", "x" * 65])
+async def test_invalid_registration_rejected(plugin, event_factory, tail):
+ instance, _ = plugin
+ event = official_event(event_factory, f"/tx name {tail}")
+ await instance.tx(event)
+ assert "登记给你自己" not in event.replies[0]
+ assert not await instance.store.registered_name(record()["scope"], "user_1")
diff --git a/tests/test_reminders.py b/tests/test_reminders.py
index aa85107..4b11c25 100644
--- a/tests/test_reminders.py
+++ b/tests/test_reminders.py
@@ -128,7 +128,7 @@ async def test_member_and_mentions(tmp_path, event_factory):
await resolve_target(event, '1小时 开会', store, scope)
)[1] == "opaque_new"
event.message_obj.raw_message = {"group_openid": "group_1"}
- with pytest.raises(ValueError, match="OpenID"):
+ with pytest.raises(ValueError, match="未创建提醒"):
await resolve_target(event, "1小时 开会 @123456789", store, scope)
await store.observe("other_scope", "unknown", "跨群用户")
with pytest.raises(ValueError):