Render official group reminder mentions through Markdown messages

This commit is contained in:
itxiaohui committed 2026-10-05 22:25:55 +08:00
1 parent 88cadbac0b
commit d4a8177acf
8 files changed
+316 -17

No files matched your search

+12 -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.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.2.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` 查看帮助。
@@ -102,7 +102,15 @@ v1.2.0 默认采用 **主动发送**。新群的 `GROUP_ADD_ROBOT` 事件到来
如需使用被动回复,可关闭 `proactive_reminders`。这时只有存在有效的近期用户消息和回复额度才投递,超出窗口则等待下一条同会话消息。群、频道、频道私信保守采用 4 分钟窗口,C2C 59 分钟;每条消息最多投递 3 条提醒,给命令回复和其他插件预留额度。回复上下文按平台、场景和目标隔离;重复事件不会刷新有效期或额度,受限时不会切换为主动发送。被动模式无法保证长时间后准点提醒。
QQ 普通群使用 `<qqbot-at-user id="OpenID" />` 实现真正 @,频道使用频道成员 ID。群、C2C、频道、频道私信分别走对应 SDK 接口。插件自己的到期提醒使用普通文本,不要求 Markdown 模板;命令回复仍由 AstrBot 当前事件的配置发送。
v1.2.1 修复官方群到期提醒把 `<qqbot-at-user id="OpenID" />` 原样显示的问题:群提醒改用 `msg_type=2`,将原生 @ 标签放入 `markdown.content`,由 QQ 渲染为可点击的 @ 用户。主动和被动投递均使用该格式,仍保留原本的发送权限和回复上下文。提醒内容中的 Markdown 标点作为普通文字显示,@ 标签单独放在正文开头。
默认使用原生 Markdown。如果 QQ 返回“不允许发送原生 markdown”等错误,任务显示“等待 Markdown 配置”,保留并每 5 分钟重试,不会改回显示长串标签的普通文本消息。原生 Markdown 权限与群管理员的主动消息开关是两项不同设置;需在机器人应用中开通原生 Markdown,或配置已有的获批 Markdown 模板。
使用模板时,在插件配置填写 `official_markdown_template_id`;模板正文应包含 `{{.content}}`,并将 `official_markdown_parameter` 设置为 `content`。如果模板的变量名是 `body`,则正文使用 `{{.body}}`,参数设置为 `body`。插件向该变量填入完整的 @ 标签、提醒内容及编号。开通能力或配置模板后,可 `/tx retry 编号` 立即重试。
解析被 @ 成员时,官方群优先使用该成员的本群 `member_openid`,并统一消息段和原始标签里的别名;频道仍使用频道成员 ID。未提供昵称时,提醒正文不会把创建者 OpenID 当作昵称。群、C2C、频道、频道私信分别走对应 SDK 接口;私聊不发送 @ 标签,OneBot 继续发送原生 `at` 消息段。命令回复仍由 AstrBot 当前事件的配置发送。
格式依据 [腾讯官方文本交互与 @ 协议](https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/server-inter/message/trans/text-chain.md) 和 [Markdown 消息协议](https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/server-inter/message/type/markdown.md)。客户端最终显示需在实际 QQ 环境确认。
旧数据库里的数字 QQ 号/群号无法自动换算为官方 OpenID,所以本次迁移的是功能,没有修改或直接导入旧数据库。更换 QQ 应用或 AstrBot 平台 ID 时,原 OpenID/路由可能失效,需要重建对应提醒。备份时停止 AstrBot 后复制整个 `data/plugin_data/astrbot_plugin_tixing/`。
@@ -113,6 +121,8 @@ QQ 普通群使用 `<qqbot-at-user id="OpenID" />` 实现真正 @,频道使用
| 字段 | 默认值 | 说明 |
| --- | --- | --- |
| `proactive_reminders` | `true` | 默认到点主动投递并提示群权限;关闭后使用被动回复 |
| `official_markdown_template_id` | 空 | 官方群提醒默认原生 Markdown;应用不支持时填写已获批的模板 ID |
| `official_markdown_parameter` | `content` | 模板中接收完整提醒正文的变量名,未填模板时忽略 |
| `timezone` | `Asia/Shanghai` | IANA 时区 |
| `max_per_user` | `10` | 当前会话每人最多活跃任务 |
| `check_interval_seconds` | `30` | 扫描周期,最小 1 秒 |
+2
View File
@@ -1,5 +1,7 @@
{
"proactive_reminders": {"type": "bool", "description": "QQ 官方到点主动提醒", "hint": "默认开启;首次入群/使用提示管理员允许主动消息。关闭后使用有时效和额度限制的被动回复。v1.2 起替代旧 official_delivery_mode 配置。", "default": true},
"official_markdown_template_id": {"type": "string", "description": "官方群提醒 Markdown 模板 ID(可选)", "hint": "默认留空使用原生 Markdown,让 QQ 正确渲染 @。若应用不允许原生 Markdown,填入已获批的模板 ID,模板需使用 {{.content}} 等正文变量。", "default": ""},
"official_markdown_parameter": {"type": "string", "description": "提醒模板正文变量名", "hint": "填写模板中用于接收完整提醒正文的变量名,例如模板 {{.content}} 对应 content;未配置模板时忽略。", "default": "content"},
"timezone": {"type": "string", "description": "提醒时区", "hint": "IANA 时区名称,默认北京时间;修改只影响新建提醒。", "default": "Asia/Shanghai"},
"max_per_user": {"type": "int", "description": "每人在每个群/私聊最多活跃提醒数", "default": 10},
"check_interval_seconds": {"type": "int", "description": "到期扫描间隔(秒)", "default": 30},
+28 -1
View File
@@ -14,6 +14,7 @@ from astrbot.api.star import Context, Star, StarTools
from .services.delivery import (
OFFICIAL,
MentionDeliveryError,
available,
deliver,
field,
@@ -72,6 +73,10 @@ class ReminderPlugin(Star):
self.max_content = max(1, min(1500, int(config.get("max_content_length", 1000))))
# v1.2 replaces the old v1.1 passive default with a new configuration key.
self.delivery_mode = "proactive" if config.get("proactive_reminders", True) else "passive"
self.markdown_template_id = str(config.get("official_markdown_template_id", "")).strip()
self.markdown_parameter = (
str(config.get("official_markdown_parameter", "content")).strip() or "content"
)
self._wake = asyncio.Event()
self.store = ReminderStore(StarTools.get_data_dir("astrbot_plugin_tixing") / "reminders.db")
self.owner = uuid.uuid4().hex
@@ -250,8 +255,28 @@ class ReminderPlugin(Star):
async def _fire(self, platform, rem, reply=None):
try:
await asyncio.wait_for(deliver(platform, rem, reply), timeout=30)
await asyncio.wait_for(
deliver(
platform,
rem,
reply,
markdown_template_id=self.markdown_template_id,
markdown_parameter=self.markdown_parameter,
),
timeout=30,
)
except Exception as exc:
if isinstance(exc, MentionDeliveryError):
await self.store.wait_for_permission(
rem["id"],
self.owner,
f"Markdown @ 格式受限:{exc};任务保留,每 5 分钟重试",
time.time() + 300,
)
logger.warning(
"[Reminder] 提醒 #%s 等待 Markdown 配置,任务已保留:%s", rem["id"], exc
)
return
if reply is None and rem["platform_name"] in OFFICIAL and proactive_denied(exc):
if rem["scene"] == "group":
await self.store.set_permission(
@@ -466,6 +491,8 @@ class ReminderPlugin(Star):
if rem["waiting_reason"].startswith("主动消息权限")
else "等待可回复消息"
)
if rem["waiting_reason"].startswith("Markdown @"):
status = "等待 Markdown 配置"
content = (
rem["content"]
if detail
+1 -1
View File
@@ -1,7 +1,7 @@
name: astrbot_plugin_tixing
display_name: 栗子提醒
desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。
version: v1.2.0
version: v1.2.1
author: itxiaohui
repo: https://github.com/itxiaohui66/astrbot_plugin_tixing
support_platforms:
+65 -6
View File
@@ -1,5 +1,6 @@
"""Deliver through the current adapter using a validated incoming reply context."""
import re
import time
from datetime import datetime
from html import escape
@@ -7,6 +8,27 @@ from html import escape
OFFICIAL = {"qq_official", "qq_official_webhook"}
class MentionDeliveryError(RuntimeError):
"""The app cannot send the Markdown format required by this delivery path."""
def markdown_unavailable(exc):
text = str(exc).lower()
return ("markdown" in text or "模板" in text) and any(
token in text
for token in (
"不允许",
"权限",
"无效",
"不合法",
"不存在",
"not allowed",
"permission",
"invalid",
)
)
def proactive_denied(exc):
text = str(exc).lower()
return any(
@@ -100,12 +122,30 @@ def available(platform):
def reminder_text(rem):
creator = rem["creator_name"] or rem["creator_id"]
# AstrBot may use an OpenID as the display-name fallback. Keep IDs out of prose.
creator = rem["creator_name"]
if not creator or creator == rem["creator_id"]:
creator = "群成员" if rem["scene"] in {"group", "channel"} else "用户"
prefix = f"来自 {creator} 的提醒:\n" if rem["target_id"] != rem["creator_id"] else ""
return f"{prefix}⏰ {rem['content']}\n(提醒 #{rem['id']})"
async def deliver(platform, rem, reply=None):
def official_mention(user_id):
"""QQ native mention token; do not replace it with visible @OpenID text."""
return f'<qqbot-at-user id="{escape(str(user_id), quote=True)}" />'
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 = escape(reminder_text(rem), quote=False)
text = re.sub(r"([\\`*_{}\[\]()#+.!|~\-])", r"\\\1", text)
return official_mention(rem["target_id"]) + "\n\n" + text.replace("\n", "\n\n")
async def deliver(
platform, rem, reply=None, *, markdown_template_id="", markdown_parameter="content"
):
"""Official SDK return value must contain a message ID to count as sent."""
client = platform.get_client()
text = reminder_text(rem)
@@ -116,17 +156,36 @@ async def deliver(platform, rem, reply=None):
if scene not in {"group", "c2c"}:
kwargs.pop("msg_seq", None)
if scene == "group":
mention = f'<qqbot-at-user id="{escape(rem["target_id"], quote=True)}" />'
result = await api.post_group_message(
group_openid=rem["destination"], msg_type=0, content=f"{mention}\n{text}", **kwargs
body = reminder_markdown(rem)
markdown = (
{
"custom_template_id": markdown_template_id,
"params": [{"key": markdown_parameter, "values": [body]}],
}
if markdown_template_id
else {"content": body}
)
try:
result = await api.post_group_message(
group_openid=rem["destination"], msg_type=2, markdown=markdown, **kwargs
)
except Exception as exc:
if markdown_unavailable(exc):
raise MentionDeliveryError(
"QQ 拒绝 Markdown @ 消息,请开通原生 Markdown,或配置已获批的 "
"official_markdown_template_id / official_markdown_parameter;"
f"原始错误:{exc}"
) from exc
raise
elif scene == "c2c":
result = await api.post_c2c_message(
openid=rem["destination"], msg_type=0, content=text, **kwargs
)
elif scene == "channel":
result = await api.post_message(
channel_id=rem["destination"], content=f"<@{rem['target_id']}>\n{text}", **kwargs
channel_id=rem["destination"],
content=f"{official_mention(rem['target_id'])}\n{text}",
**kwargs,
)
elif scene == "guild_dm":
result = await api.post_dms(guild_id=rem["destination"], content=text, **kwargs)
+20 -6
View File
@@ -18,20 +18,32 @@ async def resolve_target(event, args, store, scope):
raw_data = field(raw, "raw_data", raw)
mentions = field(raw, "mentions", None) or field(raw_data, "mentions", []) or []
trusted = {}
aliases = {}
official_group = event.get_platform_name() in OFFICIAL and bool(
field(raw, "group_openid") or field(raw_data, "group_openid")
)
for mention in mentions:
user = str(field(mention, "id", None) or field(mention, "member_openid", ""))
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
if field(mention, "is_you", False) or field(mention, "bot", False):
bot_ids.add(user)
bot_ids.update({user, generic_id, member_id} - {""})
elif user:
trusted[user] = str(field(mention, "username", "") or "")
for component in event.get_messages():
if field(component, "type") in {"At", "at"} or type(component).__name__ == "At":
user = str(field(component, "qq", ""))
raw_user = str(field(component, "qq", ""))
user = aliases.get(raw_user, raw_user)
if user and user not in bot_ids:
trusted[user] = str(field(component, "name", "") or "")
trusted[user] = trusted.get(user) or str(field(component, "name", "") or "")
candidates = list(trusted)
for match in MARKUP.finditer(args):
user = next(g for g in match.groups() if g is not None)
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:
candidates.append(user)
args = MARKUP.sub(" ", args)
@@ -45,7 +57,9 @@ async def resolve_target(event, args, store, scope):
if len(names) > 1:
raise ValueError("被 @ 成员重名,请使用用户标识。")
member = await store.member(scope, value)
candidates.append(names[0] if names else member["user_id"] if member else value)
candidates.append(
names[0] if names else member["user_id"] if member else aliases.get(value, value)
)
args = TEXT_AT.sub(" ", args).strip()
candidates = list(dict.fromkeys(candidates))
if len(candidates) > 1:
+186
View File
@@ -0,0 +1,186 @@
from types import SimpleNamespace
import pytest
from test_reminders import plugin as plugin
from test_reminders import record
from services.delivery import MentionDeliveryError, deliver, reminder_markdown, reminder_text
from services.storage import ReminderStore
from services.targets import resolve_target
@pytest.mark.parametrize("name", ["qq_official", "qq_official_webhook"])
@pytest.mark.parametrize("reply", [None, {"msg_id": "incoming", "msg_seq": 20001}])
async def test_delivery_mentions_target_without_visible_creator_openid(
platform_factory, name, reply
):
platform = platform_factory(name)
rem = {
**record(
platform_name=name,
creator_id="LONG_CREATOR_OPENID",
creator_name="",
target_id="LONG_TARGET_MEMBER_OPENID",
target_name="",
),
"id": 9,
}
await deliver(platform, rem, reply)
sent = platform.get_client().api.post_group_message.call_args.kwargs
token = '<qqbot-at-user id="LONG_TARGET_MEMBER_OPENID" />'
assert sent["msg_type"] == 2 and "content" not in sent
body = sent["markdown"]["content"]
assert body.startswith(token + "\n\n")
assert body.count(token) == 1
assert "LONG_CREATOR_OPENID" not in body
assert "@LONG_TARGET_MEMBER_OPENID" not in body
assert "⏰ 吃饭" in body
assert sent.get("msg_id") == (reply["msg_id"] if reply else None)
@pytest.mark.parametrize("nickname", ["", "LONG_CREATOR_OPENID"])
def test_creator_id_is_not_used_as_a_nickname(nickname):
text = reminder_text(
{**record(creator_id="LONG_CREATOR_OPENID", creator_name=nickname), "id": 1}
)
assert "LONG_CREATOR_OPENID" not in text
assert "来自 群成员 的提醒" in text
async def test_self_reminder_has_one_native_mention_without_visible_id(platform_factory):
rem = {
**record(
creator_id="MEMBER_OPENID", target_id="MEMBER_OPENID", creator_name="", target_name=""
),
"id": 1,
}
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)'
@pytest.mark.parametrize("sdk_object", [False, True])
@pytest.mark.parametrize("name", ["qq_official", "qq_official_webhook"])
async def test_raw_group_member_openid_wins_over_generic_id_and_components(
tmp_path, event_factory, sdk_object, name
):
store = ReminderStore(tmp_path / "reminders.db")
await store.initialize()
raw_data = {
"group_openid": "group_1",
"mentions": [
{"id": "generic_target", "member_openid": "actual_member", "username": "小明"},
{"id": "generic_bot", "member_openid": "actual_bot", "is_you": True},
],
}
raw = SimpleNamespace(raw_data=raw_data, group_openid="group_1") if sdk_object else raw_data
event = event_factory(platform=name, raw=raw)
event.messages = [
SimpleNamespace(qq="generic_target", name="", type="At"),
SimpleNamespace(qq="generic_bot", name="", type="At"),
]
text, target, nickname = await resolve_target(
event,
'1分钟 开会 <qqbot-at-user id="generic_target" />',
store,
record()["scope"],
)
assert text == "1分钟 开会" and target == "actual_member" and nickname == "小明"
text, target, _ = await resolve_target(
event, "1分钟 开会 @generic_target", store, record()["scope"]
)
assert target == "actual_member"
async def test_channel_keeps_channel_member_id_and_native_token(
tmp_path, event_factory, platform_factory
):
store = ReminderStore(tmp_path / "reminders.db")
await store.initialize()
event = event_factory(
group="channel",
raw={
"channel_id": "channel",
"mentions": [
{"id": "channel_user", "member_openid": "group_user", "username": "小明"},
],
},
)
_, target, _ = await resolve_target(event, "1分钟 开会", store, record()["scope"])
assert target == "channel_user"
platform = platform_factory()
await deliver(platform, {**record(scene="channel", target_id=target), "id": 1})
sent = platform.get_client().api.post_message.call_args.kwargs["content"]
assert sent.startswith('<qqbot-at-user id="channel_user" />\n')
@pytest.mark.parametrize("reply", [None, {"msg_id": "incoming", "msg_seq": 20001}])
async def test_approved_template_keeps_native_mention_and_reply_context(platform_factory, reply):
platform = platform_factory()
await deliver(
platform,
{**record(), "id": 1},
reply,
markdown_template_id="approved_template",
markdown_parameter="body",
)
sent = platform.get_client().api.post_group_message.call_args.kwargs
assert sent["msg_type"] == 2 and "content" not in sent
assert sent["markdown"] == {
"custom_template_id": "approved_template",
"params": [
{
"key": "body",
"values": ['<qqbot-at-user id="user_1" />\n\n⏰ 吃饭\n\n(提醒 \\#1)'],
}
],
}
assert sent.get("msg_id") == (reply["msg_id"] if reply else None)
def test_markdown_preserves_literal_content_and_keeps_mention_outside_code():
body = reminder_markdown(
{**record(content="```\n**测试** <qqbot-at-everyone />\n```"), "id": 7}
)
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 "&lt;qqbot\\-at\\-everyone /&gt;" in body
async def test_md_rejection_never_falls_back_to_literal_tag(platform_factory):
platform = platform_factory()
platform.get_client().api.post_group_message.side_effect = RuntimeError(
"不允许发送原生 markdown"
)
with pytest.raises(MentionDeliveryError, match="official_markdown_template_id"):
await deliver(platform, {**record(), "id": 7})
assert platform.get_client().api.post_group_message.await_count == 1
async def test_scheduler_preserves_task_when_md_not_allowed(plugin):
instance, platform = plugin
platform.get_client().api.post_group_message.side_effect = RuntimeError(
"不允许发送原生 markdown"
)
rem_id = await instance.store.add(record(), 10)
await instance._check_due()
rem = await instance.store.get(rem_id, record()["scope"])
assert rem["status"] == "active" and rem["failure_count"] == 0
assert "等待 Markdown 配置" in instance._format(rem)
assert "official_markdown_template_id" in rem["waiting_reason"]
await instance._check_due()
assert platform.get_client().api.post_group_message.await_count == 1
async def test_scheduler_uses_configured_template(plugin):
instance, platform = plugin
instance.markdown_template_id = "approved_template"
instance.markdown_parameter = "body"
rem_id = await instance.store.add(record(), 10)
await instance._check_due()
sent = platform.get_client().api.post_group_message.call_args.kwargs
assert sent["markdown"]["custom_template_id"] == "approved_template"
assert sent["markdown"]["params"][0]["key"] == "body"
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "done"
+2 -1
View File
@@ -84,7 +84,8 @@ async def test_official_routes(platform_factory, scene, method, destination_key,
assert kwargs[destination_key] == "group_1"
assert "msg_id" not in kwargs
if scene == "group":
assert '<qqbot-at-user id="user_1" />' in kwargs["content"]
assert kwargs["msg_type"] == 2
assert '<qqbot-at-user id="user_1" />' in kwargs["markdown"]["content"]
async def test_empty_official_result_is_failure(platform_factory):