Preserve explicit recipients from original QQ mentions through reminder creation

This commit is contained in:
itxiaohui committed 2026-10-05 22:58:35 +08:00
1 parent d4a8177acf
commit 61ed965d38
5 files changed
+217 -10

No files matched your search

+6 -2
View File
@@ -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.2.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.2.2.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` 查看帮助。
@@ -90,6 +90,10 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
/tx 30分钟 开会 @对方的用户标识
```
v1.2.2 修复 SDK 的非空 `mentions` 列表丢失成员字段时覆盖完整原始数据,导致“提醒别人”退回提醒发起人的情况。解析会合并原始 QQ payload 和 SDK 信息,并从当前消息的原始正文恢复被适配器省略的真实 @,包括命令前的 @;不从引用消息中选取接收者。已知机器人及其别名始终排除在提醒对象之外。收到无法解析的额外 @ 元数据时会提示“未创建提醒”,不静默改成提醒自己。
创建回复始终显示“提醒对象”:自己显示“你自己”,他人显示昵称或成员标识。发起人仍管理该任务,到期只 @ 保存的接收者。旧版已错误保存为提醒自己的任务无法从数据库还原原定接收者,请 `/tx cancel 编号` 后重新设置,并检查创建回复中的提醒对象。
插件会记住本群里机器人实际收到的成员消息,名字唯一且官方提供昵称时也支持 `@昵称`。不同群里的成员记录不会混用,重名时要求明确标识。OneBot 模式会查询目标是否是本群成员。私聊只能提醒自己。
v1.2.0 默认采用 **主动发送**。新群的 `GROUP_ADD_ROBOT` 事件到来时,插件使用该真实事件的 `event_id` 回复管理员开启说明;若事件缺失、发送失败或插件是后来才安装的,则在首次提醒命令回复中附加说明。提示按平台和群持久化,成功提示后不会在每次命令中重复。
@@ -151,7 +155,7 @@ python tools/package.py
1. 首次命令或入群时确认收到权限开启提示;管理员开启“允许机器人主动发送消息”后,`@机器人 /tx permission check` 确认主动验证成功。
2. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,到期收到真正 @ 的通知;`/tx history` 检查状态,失败时查看原因和日志。
3. `/tx 5分钟 重启测试`,重载插件后用 `/tx list` 确认仍在,再 `/tx cancel 编号` 确认取消。
4. 让另一成员先发送 `/tx identity`,测试本群的他人提醒。
4. `@机器人 /tx 1分钟 他人提醒测试 @另一成员`,确认创建回复中的提醒对象是对方;到期只 @ 对方,不 @ 发起人。若平台缺少标识,让对方先 `/tx identity` 再使用本群用户标识。
5. `@机器人 /tx 6分钟 主动提醒测试`,期间不再 @机器人,确认到期仍收到提醒。若因权限不足显示等待,开好权限并再次验证;旧版已自动取消的任务需先 `/tx retry 编号` 恢复。
## 来源
+2
View File
@@ -476,6 +476,8 @@ class ReminderPlugin(Star):
message = f"⏰ 提醒已设置 #{reminder_id}\n时间:{describe(record['remind_at'], parsed.repeat, self.timezone)}\n时区:{self.timezone}\n内容:{parsed.content}"
if target != user:
message += f"\n提醒对象:{target_name or target}"
else:
message += "\n提醒对象:你自己"
if event.get_platform_name() in OFFICIAL:
if self.delivery_mode == "passive":
message += "\n使用被动回复:到期有有效回复窗口时发送,否则等待下次 @机器人 补发。"
+1 -1
View File
@@ -1,7 +1,7 @@
name: astrbot_plugin_tixing
display_name: 栗子提醒
desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。
version: v1.2.1
version: v1.2.2
author: itxiaohui
repo: https://github.com/itxiaohui66/astrbot_plugin_tixing
support_platforms:
+57 -7
View File
@@ -16,24 +16,48 @@ async def resolve_target(event, args, store, scope):
bot_ids = {str(event.message_obj.self_id)}
raw = event.message_obj.raw_message
raw_data = field(raw, "raw_data", raw)
mentions = field(raw, "mentions", None) or field(raw_data, "mentions", []) or []
# botpy may expose a nonempty mentions list whose objects have lost id,
# is_you or username. It must not hide the adapter's original QQ payload.
payload_mentions = field(raw_data, "mentions", []) or []
sdk_mentions = field(raw, "mentions", []) or []
mentions = list(payload_mentions)
if raw_data is not raw:
mentions.extend(sdk_mentions)
trusted = {}
aliases = {}
official_group = event.get_platform_name() in OFFICIAL and bool(
field(raw, "group_openid") or field(raw_data, "group_openid")
)
# Learn alias mappings from complete raw records before processing SDK objects.
for mention in mentions:
generic_id = str(field(mention, "id", "") or "")
member_id = str(field(mention, "member_openid", "") or "")
canonical = (member_id or generic_id) if official_group else (generic_id or member_id)
if canonical:
for value in (generic_id, member_id):
if value:
aliases.setdefault(value, canonical)
for mention in mentions:
generic_id = str(field(mention, "id", "") or "")
member_id = str(field(mention, "member_openid", "") or "")
user = (member_id or generic_id) if official_group else (generic_id or member_id)
if user:
for value in (generic_id, member_id):
if value:
aliases[value] = user
user = aliases.get(user, user)
if field(mention, "is_you", False) or field(mention, "bot", False):
bot_ids.update({user, generic_id, member_id} - {""})
elif user:
trusted[user] = str(field(mention, "username", "") or "")
elif user and user not in bot_ids:
trusted[user] = str(field(mention, "username", "") or "") or trusted.get(user, "")
trusted = {user: name for user, name in trusted.items() if user not in bot_ids}
# Read only this message's original content, never a quoted message. Some
# adapters normalize away mention tokens from message_str / message components.
if event.get_platform_name() in OFFICIAL:
content = field(raw_data, "content", None) or field(raw, "content", "") or ""
for match in MARKUP.finditer(str(content)):
if not match.group(0).startswith("<"):
continue
raw_user = next(g for g in match.groups() if g is not None)
user = aliases.get(raw_user, raw_user)
if user not in bot_ids and VALID_ID.fullmatch(user):
trusted.setdefault(user, "")
for component in event.get_messages():
if field(component, "type") in {"At", "at"} or type(component).__name__ == "At":
raw_user = str(field(component, "qq", ""))
@@ -62,6 +86,32 @@ async def resolve_target(event, args, store, scope):
)
args = TEXT_AT.sub(" ", args).strip()
candidates = list(dict.fromkeys(candidates))
if not candidates:
unknown = [
mention
for mention in payload_mentions
if not (
field(mention, "id")
or field(mention, "member_openid")
or field(mention, "is_you", False)
or field(mention, "bot", False)
)
]
sdk_unknown = [
mention
for mention in sdk_mentions
if not (
field(mention, "id")
or field(mention, "member_openid")
or field(mention, "is_you", False)
or field(mention, "bot", False)
)
]
if unknown or (not payload_mentions and sdk_unknown and len(sdk_mentions) > 1):
raise ValueError(
"收到 @ 成员信息,但无法识别提醒对象,未创建提醒。"
"请重新真实 @ 对方,或让对方先 /tx identity 后使用 @本群用户标识。"
)
if len(candidates) > 1:
raise ValueError("一次提醒只能指定一个成员。")
target = candidates[0] if candidates else sender
+151
View File
@@ -0,0 +1,151 @@
import time
from types import SimpleNamespace
import pytest
from test_reminders import plugin as plugin
from test_reminders import record
from services.targets import resolve_target
def recipient_event(event_factory, platform, source):
bot = {"id": "bot_id", "is_you": True}
person = {"id": "target_generic", "member_openid": "target_member", "username": "小明"}
if source == "lossy_sdk":
payload = {
"group_openid": "group_1",
"mentions": [bot, person],
"content": '/tx 1分钟 开会 <qqbot-at-user id="target_generic" />',
}
raw = SimpleNamespace(
group_openid="group_1",
raw_data=payload,
mentions=[SimpleNamespace(member_openid=None), SimpleNamespace(member_openid=None)],
)
elif source == "raw_content":
raw = SimpleNamespace(
group_openid="group_1",
mentions=[],
content=(
'<qqbot-at-user id="bot_id" /> /tx 1分钟 开会 <qqbot-at-user id="target_member" />'
),
)
else:
raw = {
"group_openid": "group_1",
"content": (
'<qqbot-at-user id="bot_id" /> <qqbot-at-user id="target_member" /> /tx 1分钟 开会'
),
}
event = event_factory("/tx 1分钟 开会", platform=platform, raw=raw)
# The adapter exposes only the triggering bot mention, not the other member.
event.messages = [SimpleNamespace(qq="bot_id", name="机器人", type="At")]
return event
@pytest.mark.parametrize("platform_name", ["qq_official", "qq_official_webhook"])
@pytest.mark.parametrize("source", ["lossy_sdk", "raw_content", "at_before_command"])
async def test_other_recipient_is_saved_and_delivered_after_reload(
plugin,
plugin_class,
event_factory,
platform_name,
source,
):
instance, platform = plugin
platform.meta = lambda: SimpleNamespace(id="platform_1", name=platform_name)
event = recipient_event(event_factory, platform_name, source)
await instance.tx(event)
rows = await instance.store.list(record()["scope"])
assert len(rows) == 1
rem = rows[0]
assert rem["creator_id"] == "user_1"
assert rem["target_id"] == "target_member" and "提醒对象" in event.replies[0]
assert rem["content"] == "开会"
await instance.store._run(
lambda db: db.execute(
"UPDATE reminders SET remind_at=? WHERE id=?", (time.time() - 1, rem["id"])
)
)
await instance.terminate()
restored = plugin_class(instance.context, {})
await restored.store.initialize()
try:
await restored._check_due()
sent = platform.get_client().api.post_group_message.call_args.kwargs
body = sent["markdown"]["content"]
assert body.startswith('<qqbot-at-user id="target_member" />\n\n')
assert '<qqbot-at-user id="user_1"' not in body
assert body.count("qqbot-at-user") == 1
assert (await restored.store.get(rem["id"], record()["scope"]))["status"] == "done"
finally:
await restored.terminate()
async def test_partial_sdk_mentions_do_not_create_second_recipient(plugin, event_factory):
instance, _ = plugin
raw = SimpleNamespace(
group_openid="group_1",
mentions=[SimpleNamespace(id="target_generic")],
raw_data={
"group_openid": "group_1",
"mentions": [
{"id": "target_generic", "member_openid": "target_member", "username": "小明"}
],
},
)
event = event_factory(raw=raw)
_, target, name = await resolve_target(event, "1分钟 开会", instance.store, record()["scope"])
assert target == "target_member" and name == "小明"
async def test_sdk_lost_bot_flag_cannot_turn_triggering_bot_into_recipient(plugin, event_factory):
instance, _ = plugin
raw = SimpleNamespace(
group_openid="group_1",
mentions=[SimpleNamespace(id="bot_generic"), SimpleNamespace(id="target_generic")],
raw_data={
"group_openid": "group_1",
"mentions": [
{"id": "bot_generic", "member_openid": "bot_member", "is_you": True},
{"id": "target_generic", "member_openid": "target_member", "username": "小明"},
],
},
)
event = event_factory(raw=raw)
_, target, name = await resolve_target(event, "1分钟 开会", instance.store, record()["scope"])
assert target == "target_member" and name == "小明"
async def test_missing_target_metadata_is_not_silently_self_reminder(plugin, event_factory):
instance, _ = plugin
event = event_factory(
raw=SimpleNamespace(
group_openid="group_1",
mentions=[SimpleNamespace(member_openid=None), SimpleNamespace(member_openid=None)],
)
)
event.messages = [SimpleNamespace(qq="bot_id", name="机器人", type="At")]
await instance.tx(event)
assert "未创建提醒" in event.replies[0]
assert not await instance.store.list(record()["scope"])
async def test_quoted_mentions_do_not_change_recipient(plugin, event_factory):
instance, _ = plugin
event = event_factory(
raw={
"group_openid": "group_1",
"content": "/tx 1分钟 开会",
"message_type": 103,
"msg_elements": [{"content": '<qqbot-at-user id="quoted_user" />'}],
}
)
event.messages = [
SimpleNamespace(qq="bot_id", name="机器人", type="At"),
SimpleNamespace(type="Reply", chain=[SimpleNamespace(qq="quoted_user", type="At")]),
]
await instance.tx(event)
rem = (await instance.store.list(record()["scope"]))[0]
assert rem["target_id"] == rem["creator_id"] == "user_1"
assert "提醒对象:你自己" in event.replies[0]