fix: detect missed recipient names and expose QQ mention diagnostics
This commit is contained in:
1 parent
f89aadb5da
commit
9c5b87772f
9 files changed
+277
-9
No files matched your search
@@ -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.0.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.3.1.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` 查看帮助。
|
||||
|
||||
@@ -96,6 +96,12 @@ v1.2.2 修复 SDK 的非空 `mentions` 列表丢失成员字段时覆盖完整
|
||||
|
||||
v1.3.0 会从机器人收到的成员消息和真实 @ 中学习用户名、群名片及昵称,按平台和群保存,重启后仍可使用。已识别成员也支持直接输入 `@小明`;带空格的名字支持 `@"小 明"` 或 `@小 明`(后者需名字已被识别)。同名时请从 QQ 的 @ 列表选择具体成员,实际选择优先于昵称缓存。收到新名字时更新记录,不继续按旧昵称匹配。
|
||||
|
||||
v1.3.1 修复昵称紧挨中文正文(`开会@小明`)、全角 `@` 和昵称位于命令前(`@小明 /tx 1分钟 开会`)时漏掉对象的情况;未知昵称仍明确拒绝创建,不会改成提醒自己。邮件地址如 `test@example.com` 保留在正文中。到期消息不再给普通括号和提醒编号添加多余反斜杠,例如 `小慧(代码版)`、`(提醒 #14)`。
|
||||
|
||||
若成员识别仍失败,先 `/tx status` 确认已加载的插件版本,再发送 `@机器人 /tx diagnose 1分钟 测试 @小明`(照正常方式 @ 对方)。诊断不会创建提醒;会返回 AstrBot 正文、QQ 原始正文、两层 mentions、At 消息段和解析结果。ID 转为一致的哈希标记,仅显示选定的成员字段,不输出 token 或整个 SDK 对象。把诊断回复及失败的完整命令提供给维护者,可确认是平台未下发成员信息、适配器丢字段还是解析问题。
|
||||
|
||||
“显示对象名字正确,但实际 @ 发起人”时,还可 `/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)。
|
||||
|
||||
创建回复始终显示“提醒对象”。发起人仍管理该任务,到期只 @ 保存的接收者。旧版已错误保存为提醒自己的任务无法从数据库还原原定接收者,请 `/tx cancel 编号` 后重新设置,并检查创建回复中的提醒对象。不同群里的成员记录不会混用。OneBot 模式会查询目标是否是本群成员。私聊只能提醒自己。
|
||||
|
||||
@@ -24,6 +24,7 @@ from .services.delivery import (
|
||||
reply_unavailable,
|
||||
route,
|
||||
)
|
||||
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
|
||||
@@ -45,6 +46,8 @@ HELP = """⏰ 栗子提醒
|
||||
/tx retry 编号 恢复投递失败的提醒
|
||||
/tx identity 查看当前平台、群和用户标识
|
||||
/tx status 查看提醒调度器状态
|
||||
/tx diagnose 时间 内容 @对方 检查成员识别(不创建提醒)
|
||||
/tx diagnose 编号 核对提醒保存的成员 ID
|
||||
/tx permission 查看主动消息权限说明
|
||||
/tx permission check 发送主动消息验证权限
|
||||
/cxzd 管理员重启提醒调度器
|
||||
@@ -255,6 +258,14 @@ class ReminderPlugin(Star):
|
||||
raise
|
||||
|
||||
async def _fire(self, platform, rem, reply=None):
|
||||
logger.info(
|
||||
"[Reminder] 投递 #%s(%s):创建者=%s,目标=%s,目标昵称=%s",
|
||||
rem["id"],
|
||||
VERSION,
|
||||
identity(rem["creator_id"]),
|
||||
identity(rem["target_id"]),
|
||||
rem["target_name"],
|
||||
)
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
deliver(
|
||||
@@ -436,6 +447,26 @@ class ReminderPlugin(Star):
|
||||
f"平台:{event.get_platform_id()}\n群标识:{event.get_group_id() or '私聊'}\n用户标识:{user}\n本群管理员授权标识:{event.get_platform_id()}|{event.get_group_id()}|{user}",
|
||||
)
|
||||
return
|
||||
if action in {"diagnose", "诊断"}:
|
||||
if tail.isdecimal():
|
||||
rem = await self.store.get(int(tail), scope)
|
||||
if not rem or (rem["creator_id"] != user and not self._admin(event)):
|
||||
raise ValueError("当前会话中找不到该提醒,或你没有查看权限。")
|
||||
await self._reply(
|
||||
event,
|
||||
f"提醒投递诊断({VERSION},不会创建或发送提醒)\n"
|
||||
f"提醒:#{rem['id']}\n创建者:{rem['creator_name']} / {identity(rem['creator_id'])}\n"
|
||||
f"保存对象:{rem['target_name']} / {identity(rem['target_id'])}\n"
|
||||
f"发起人与对象 ID 相同:{'是' if rem['creator_id'] == rem['target_id'] else '否'}\n"
|
||||
f"到期 @ 使用:{identity(rem['target_id'])}\n状态:{rem['status']}\n"
|
||||
"请将本条与成员识别 diagnose 回复一起提供,核对创建与投递两端。",
|
||||
)
|
||||
return
|
||||
await self._reply(
|
||||
event,
|
||||
"成员识别诊断(不会创建提醒)\n" + await diagnose(event, tail, self.store, scope),
|
||||
)
|
||||
return
|
||||
if action in {"status", "状态"}:
|
||||
reminders = await self.store.list(scope, None if self._admin(event) else user)
|
||||
running = self._scheduler is not None and not self._scheduler.done()
|
||||
@@ -446,7 +477,7 @@ class ReminderPlugin(Star):
|
||||
)
|
||||
await self._reply(
|
||||
event,
|
||||
f"调度器:{'运行中' if running else '停止'}\n当前会话活跃提醒:{len(reminders)}\n扫描间隔:{self.interval} 秒\n时区:{self.timezone}\n最近扫描:{last}\n官方发送方式:{self.delivery_mode}"
|
||||
f"插件版本:{VERSION}\n调度器:{'运行中' if running else '停止'}\n当前会话活跃提醒:{len(reminders)}\n扫描间隔:{self.interval} 秒\n时区:{self.timezone}\n最近扫描:{last}\n官方发送方式:{self.delivery_mode}"
|
||||
+ (f"\n扫描错误:{self.last_scan_error}" if self.last_scan_error else ""),
|
||||
)
|
||||
return
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
name: astrbot_plugin_tixing
|
||||
display_name: 栗子提醒
|
||||
desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。
|
||||
version: v1.3.0
|
||||
version: v1.3.1
|
||||
author: itxiaohui
|
||||
repo: https://github.com/itxiaohui66/astrbot_plugin_tixing
|
||||
support_platforms:
|
||||
|
||||
@@ -137,9 +137,11 @@ def official_mention(user_id):
|
||||
|
||||
def reminder_markdown(rem):
|
||||
# Keep the mention outside user-provided text/code blocks. Preserve reminder
|
||||
# text literally instead of interpreting its punctuation as Markdown syntax.
|
||||
# text literally instead of interpreting formatting delimiters as Markdown.
|
||||
# QQ exposes unnecessary backslashes before ordinary parentheses and the
|
||||
# inline reminder number, so do not escape every CommonMark punctuation mark.
|
||||
text = escape(reminder_text(rem), quote=False)
|
||||
text = re.sub(r"([\\`*_{}\[\]()#+.!|~\-])", r"\\\1", text)
|
||||
text = re.sub(r"([\\`*_{}\[\]|~])", r"\\\1", text)
|
||||
return official_mention(rem["target_id"]) + "\n\n" + text.replace("\n", "\n\n")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Show the actual incoming mention fields without exposing tokens or full IDs."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from .delivery import field
|
||||
from .targets import MARKUP, mention_data, resolve_target
|
||||
|
||||
VERSION = "v1.3.1"
|
||||
|
||||
|
||||
def identity(value):
|
||||
if not value:
|
||||
return ""
|
||||
return "id#" + hashlib.sha256(str(value).encode()).hexdigest()[:10]
|
||||
|
||||
|
||||
async def diagnose(event, args, store, scope):
|
||||
raw = event.message_obj.raw_message
|
||||
data = field(raw, "raw_data", raw)
|
||||
trusted, _, aliases, bot_ids, _, payload, sdk = mention_data(event)
|
||||
ids = set(aliases) | set(aliases.values()) | set(trusted) | bot_ids
|
||||
ids.add(str(event.get_sender_id()))
|
||||
|
||||
def redact(text):
|
||||
text = str(text or "")
|
||||
text = MARKUP.sub(
|
||||
lambda match: (
|
||||
"[QQ @ " + identity(next(g for g in match.groups() if g is not None)) + "]"
|
||||
),
|
||||
text,
|
||||
)
|
||||
for value in sorted(ids, key=len, reverse=True):
|
||||
if value:
|
||||
text = text.replace(value, identity(value))
|
||||
return text[:600]
|
||||
|
||||
def member(value):
|
||||
# Select only incoming member fields; never serialize bot/api/session objects.
|
||||
return {
|
||||
key: identity(field(value, key))
|
||||
if key in {"id", "member_openid"}
|
||||
else field(value, key)
|
||||
for key in (
|
||||
"id",
|
||||
"member_openid",
|
||||
"username",
|
||||
"nickname",
|
||||
"nick",
|
||||
"card",
|
||||
"is_you",
|
||||
"bot",
|
||||
)
|
||||
if field(value, key) is not None
|
||||
}
|
||||
|
||||
report = {
|
||||
"插件版本": VERSION,
|
||||
"适配器": event.get_platform_name(),
|
||||
"消息对象类型": type(raw).__name__,
|
||||
"发起人": identity(event.get_sender_id()),
|
||||
"AstrBot正文": redact(event.message_str),
|
||||
"QQ原始正文": redact(field(data, "content") or field(raw, "content", "")),
|
||||
"QQ原始mentions": [member(item) for item in payload[:10]],
|
||||
"SDK mentions": [member(item) for item in sdk[:10]],
|
||||
"At消息段": [
|
||||
{"id": identity(field(c, "qq")), "name": field(c, "name", "")}
|
||||
for c in event.get_messages()
|
||||
if field(c, "type") in {"At", "at"} or type(c).__name__ == "At"
|
||||
][:10],
|
||||
"本群已知名字数": len(await store.member_names(scope)),
|
||||
"原始author": member(field(data, "author", {})),
|
||||
}
|
||||
try:
|
||||
_, target, name = await resolve_target(event, args, store, scope)
|
||||
report["解析结果"] = {
|
||||
"对象": identity(target),
|
||||
"名字": name,
|
||||
"提醒自己": target == str(event.get_sender_id()),
|
||||
}
|
||||
except ValueError as exc:
|
||||
report["解析失败"] = redact(str(exc))
|
||||
return json.dumps(report, ensure_ascii=False, indent=2)
|
||||
+7
-1
@@ -107,7 +107,7 @@ def text_mentions(names):
|
||||
# reminder text after a shorter name. Quoted names work before registration.
|
||||
known = "|".join(re.escape(n) for n in sorted(set(names), key=len, reverse=True) if n)
|
||||
pattern = re.compile(
|
||||
r'(?<![\w@])@(?:"([^"\n]+)"|“([^”\n]+)”|'
|
||||
r'(?<![A-Za-z0-9_.@@])[@@](?:"([^"\n]+)"|“([^”\n]+)”|'
|
||||
+ (rf"({known})(?=\s|$)|" if known else "")
|
||||
+ r"([^\s@]+))"
|
||||
)
|
||||
@@ -131,6 +131,12 @@ async def resolve_target(event, args, store, scope):
|
||||
known_names + [n for values in names.values() for n in values] + list(bot_names)
|
||||
)
|
||||
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)
|
||||
if command:
|
||||
prefix = MARKUP.sub(" ", event.message_str[: command.start()])
|
||||
textual.extend(pattern.finditer(prefix))
|
||||
for match in textual:
|
||||
value = next(g for g in match.groups() if g is not None)
|
||||
if value in bot_names or aliases.get(value, value) in bot_ids:
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from test_reminders import plugin as plugin
|
||||
from test_reminders import record
|
||||
|
||||
from services.diagnostics import VERSION, diagnose, identity
|
||||
|
||||
|
||||
async def test_diagnostic_uses_actual_payload_and_does_not_create_task(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
event = event_factory(
|
||||
"/tx diagnose 1分钟 测试 <@other_generic>",
|
||||
raw=SimpleNamespace(
|
||||
group_openid="group_1",
|
||||
mentions=[SimpleNamespace(member_openid=None)],
|
||||
raw_data={
|
||||
"content": "/tx diagnose 1分钟 测试 <@other_generic>",
|
||||
"mentions": [
|
||||
{"id": "other_generic", "member_openid": "other_member", "username": "小明"}
|
||||
],
|
||||
"token": "must_not_be_printed",
|
||||
"author": {"member_openid": "user_1"},
|
||||
},
|
||||
),
|
||||
)
|
||||
await instance.tx(event)
|
||||
result, _ = json.JSONDecoder().raw_decode(event.replies[0].split("\n", 1)[1])
|
||||
assert result["插件版本"] == VERSION
|
||||
assert result["解析结果"]["对象"] == identity("other_member")
|
||||
assert not result["解析结果"]["提醒自己"]
|
||||
assert result["QQ原始mentions"][0]["id"] == identity("other_generic")
|
||||
assert result["SDK mentions"] == [{}]
|
||||
assert "other_generic" not in event.replies[0] and "other_member" not in event.replies[0]
|
||||
assert "must_not_be_printed" not in event.replies[0]
|
||||
assert "<@" not in event.replies[0]
|
||||
assert not await instance.store.list(record()["scope"])
|
||||
|
||||
|
||||
async def test_diagnostic_explains_missing_member_id(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
event = event_factory(
|
||||
"/tx diagnose 1分钟 测试 @小明",
|
||||
raw={"group_openid": "group_1", "content": "1分钟 测试 @小明"},
|
||||
)
|
||||
result = json.loads(
|
||||
await diagnose(event, "1分钟 测试 @小明", instance.store, record()["scope"])
|
||||
)
|
||||
assert result["QQ原始mentions"] == [] and result["At消息段"] == []
|
||||
assert "还未识别" in result["解析失败"]
|
||||
|
||||
|
||||
async def test_status_reports_installed_plugin_version(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
event = event_factory("/tx status")
|
||||
await instance.tx(event)
|
||||
assert f"插件版本:{VERSION}" in event.replies[0]
|
||||
assert f"version: {VERSION}" in (
|
||||
Path(__file__).resolve().parents[1] / "metadata.yaml"
|
||||
).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
async def test_saved_reminder_diagnostic_compares_creator_and_target_without_sending(
|
||||
plugin, event_factory
|
||||
):
|
||||
instance, platform = plugin
|
||||
number = await instance.store.add(record(target_id="other_member", target_name="xh"), 10)
|
||||
event = event_factory(f"/tx diagnose {number}")
|
||||
await instance.tx(event)
|
||||
assert f"保存对象:xh / {identity('other_member')}" in event.replies[0]
|
||||
assert f"到期 @ 使用:{identity('other_member')}" in event.replies[0]
|
||||
assert "发起人与对象 ID 相同:否" in event.replies[0]
|
||||
assert "other_member" not in event.replies[0] and "user_1" not in event.replies[0]
|
||||
assert len(await instance.store.list(record()["scope"])) == 1
|
||||
platform.get_client().api.post_group_message.assert_not_called()
|
||||
|
||||
|
||||
async def test_reminder_diagnostic_respects_creator_and_group_access(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
number = await instance.store.add(record(creator_id="another_creator"), 10)
|
||||
event = event_factory(f"/tx diagnose {number}")
|
||||
await instance.tx(event)
|
||||
assert "没有查看权限" in event.replies[0]
|
||||
assert "保存对象" not in event.replies[0]
|
||||
event = event_factory(f"/tx diagnose {number}", group="another_group")
|
||||
event.admin = True
|
||||
await instance.tx(event)
|
||||
assert "找不到该提醒" in event.replies[0]
|
||||
@@ -165,3 +165,47 @@ async def test_at_component_name_is_learned(plugin, event_factory):
|
||||
event.messages = [SimpleNamespace(qq="target_member", name="小明", type="At")]
|
||||
await observe_members(event, instance.store, record()["scope"])
|
||||
assert (await instance.store.member(record()["scope"], "小明"))["user_id"] == "target_member"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
[
|
||||
"/tx 1分钟 开会@小明",
|
||||
"/tx 1分钟 开会@小明",
|
||||
"@小明 /tx 1分钟 开会",
|
||||
"@小明 /提醒 1分钟 开会",
|
||||
"@小明 /remind 1分钟 开会",
|
||||
],
|
||||
)
|
||||
async def test_adjacent_and_before_command_nicknames_are_recipients(plugin, event_factory, text):
|
||||
instance, platform = plugin
|
||||
await instance.store.observe(record()["scope"], "target_member", "小明")
|
||||
event = event_factory(text)
|
||||
await instance.tx(event)
|
||||
rem = (await instance.store.list(record()["scope"]))[0]
|
||||
assert rem["target_id"] == "target_member" and rem["content"] == "开会"
|
||||
await instance.store._run(
|
||||
lambda db: db.execute(
|
||||
"UPDATE reminders SET remind_at=? WHERE id=?", (time.time() - 1, rem["id"])
|
||||
)
|
||||
)
|
||||
await instance._check_due()
|
||||
body = platform.get_client().api.post_group_message.call_args.kwargs["markdown"]["content"]
|
||||
assert body.startswith('<qqbot-at-user id="target_member" />') and 'id="user_1"' not in body
|
||||
|
||||
|
||||
async def test_adjacent_unknown_nickname_is_not_silently_self(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
event = event_factory("/tx 1分钟 开会@陌生人")
|
||||
await instance.tx(event)
|
||||
assert "未创建提醒" in event.replies[0]
|
||||
assert not await instance.store.list(record()["scope"])
|
||||
|
||||
|
||||
async def test_email_in_reminder_content_is_not_a_recipient(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
event = event_factory("/tx 1分钟 给 test@example.com 发邮件")
|
||||
await instance.tx(event)
|
||||
rem = (await instance.store.list(record()["scope"]))[0]
|
||||
assert rem["target_id"] == rem["creator_id"]
|
||||
assert rem["content"] == "给 test@example.com 发邮件"
|
||||
@@ -57,7 +57,7 @@ async def test_self_reminder_has_one_native_mention_without_visible_id(platform_
|
||||
platform = platform_factory()
|
||||
await deliver(platform, rem)
|
||||
sent = platform.get_client().api.post_group_message.call_args.kwargs["markdown"]["content"]
|
||||
assert sent == '<qqbot-at-user id="MEMBER_OPENID" />\n\n⏰ 吃饭\n\n(提醒 \\#1)'
|
||||
assert sent == '<qqbot-at-user id="MEMBER_OPENID" />\n\n⏰ 吃饭\n\n(提醒 #1)'
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sdk_object", [False, True])
|
||||
@@ -132,7 +132,7 @@ async def test_approved_template_keeps_native_mention_and_reply_context(platform
|
||||
"params": [
|
||||
{
|
||||
"key": "body",
|
||||
"values": ['<qqbot-at-user id="user_1" />\n\n⏰ 吃饭\n\n(提醒 \\#1)'],
|
||||
"values": ['<qqbot-at-user id="user_1" />\n\n⏰ 吃饭\n\n(提醒 #1)'],
|
||||
}
|
||||
],
|
||||
}
|
||||
@@ -146,7 +146,14 @@ def test_markdown_preserves_literal_content_and_keeps_mention_outside_code():
|
||||
assert body.startswith('<qqbot-at-user id="user_1" />\n\n')
|
||||
assert "\\`\\`\\`" in body and "\\*\\*测试\\*\\*" in body
|
||||
assert "<qqbot-at-everyone" not in body
|
||||
assert "<qqbot\\-at\\-everyone />" in body
|
||||
assert "<qqbot-at-everyone />" in body
|
||||
|
||||
|
||||
def test_reported_display_name_and_reminder_number_have_no_added_backslashes():
|
||||
body = reminder_markdown({**record(creator_name="小慧(代码版)", target_id="xh"), "id": 14})
|
||||
assert body.startswith('<qqbot-at-user id="xh" />')
|
||||
assert "来自 小慧(代码版) 的提醒" in body and "(提醒 #14)" in body
|
||||
assert "\\(" not in body and "\\#" not in body
|
||||
|
||||
|
||||
async def test_md_rejection_never_falls_back_to_literal_tag(platform_factory):
|
||||
|
||||
Reference in new issue
Block a user