2 Commits
9 changed files with 527 additions and 21 deletions

No files matched your search

+17 -3
View File
@@ -12,7 +12,7 @@
https://github.com/itxiaohui66/astrbot_plugin_tixing 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.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` 查看帮助。 安装时 AstrBot 会读取 `requirements.txt` 安装 `tzdata`。配置默认采用北京时间 `Asia/Shanghai`;每人在每个群或私聊最多 10 个活跃提醒,每 30 秒扫描一次。确认机器人已经接入 QQ 官方适配器,群内使用 `@机器人 /tx help` 查看帮助。
@@ -90,6 +90,10 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
/tx 30分钟 开会 @对方的用户标识 /tx 30分钟 开会 @对方的用户标识
``` ```
v1.2.2 修复 SDK 的非空 `mentions` 列表丢失成员字段时覆盖完整原始数据,导致“提醒别人”退回提醒发起人的情况。解析会合并原始 QQ payload 和 SDK 信息,并从当前消息的原始正文恢复被适配器省略的真实 @,包括命令前的 @;不从引用消息中选取接收者。已知机器人及其别名始终排除在提醒对象之外。收到无法解析的额外 @ 元数据时会提示“未创建提醒”,不静默改成提醒自己。
创建回复始终显示“提醒对象”:自己显示“你自己”,他人显示昵称或成员标识。发起人仍管理该任务,到期只 @ 保存的接收者。旧版已错误保存为提醒自己的任务无法从数据库还原原定接收者,请 `/tx cancel 编号` 后重新设置,并检查创建回复中的提醒对象。
插件会记住本群里机器人实际收到的成员消息,名字唯一且官方提供昵称时也支持 `@昵称`。不同群里的成员记录不会混用,重名时要求明确标识。OneBot 模式会查询目标是否是本群成员。私聊只能提醒自己。 插件会记住本群里机器人实际收到的成员消息,名字唯一且官方提供昵称时也支持 `@昵称`。不同群里的成员记录不会混用,重名时要求明确标识。OneBot 模式会查询目标是否是本群成员。私聊只能提醒自己。
v1.2.0 默认采用 **主动发送**。新群的 `GROUP_ADD_ROBOT` 事件到来时,插件使用该真实事件的 `event_id` 回复管理员开启说明;若事件缺失、发送失败或插件是后来才安装的,则在首次提醒命令回复中附加说明。提示按平台和群持久化,成功提示后不会在每次命令中重复。 v1.2.0 默认采用 **主动发送**。新群的 `GROUP_ADD_ROBOT` 事件到来时,插件使用该真实事件的 `event_id` 回复管理员开启说明;若事件缺失、发送失败或插件是后来才安装的,则在首次提醒命令回复中附加说明。提示按平台和群持久化,成功提示后不会在每次命令中重复。
@@ -102,7 +106,15 @@ v1.2.0 默认采用 **主动发送**。新群的 `GROUP_ADD_ROBOT` 事件到来
如需使用被动回复,可关闭 `proactive_reminders`。这时只有存在有效的近期用户消息和回复额度才投递,超出窗口则等待下一条同会话消息。群、频道、频道私信保守采用 4 分钟窗口,C2C 59 分钟;每条消息最多投递 3 条提醒,给命令回复和其他插件预留额度。回复上下文按平台、场景和目标隔离;重复事件不会刷新有效期或额度,受限时不会切换为主动发送。被动模式无法保证长时间后准点提醒。 如需使用被动回复,可关闭 `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/`。 旧数据库里的数字 QQ 号/群号无法自动换算为官方 OpenID,所以本次迁移的是功能,没有修改或直接导入旧数据库。更换 QQ 应用或 AstrBot 平台 ID 时,原 OpenID/路由可能失效,需要重建对应提醒。备份时停止 AstrBot 后复制整个 `data/plugin_data/astrbot_plugin_tixing/`。
@@ -113,6 +125,8 @@ QQ 普通群使用 `<qqbot-at-user id="OpenID" />` 实现真正 @,频道使用
| 字段 | 默认值 | 说明 | | 字段 | 默认值 | 说明 |
| --- | --- | --- | | --- | --- | --- |
| `proactive_reminders` | `true` | 默认到点主动投递并提示群权限;关闭后使用被动回复 | | `proactive_reminders` | `true` | 默认到点主动投递并提示群权限;关闭后使用被动回复 |
| `official_markdown_template_id` | 空 | 官方群提醒默认原生 Markdown;应用不支持时填写已获批的模板 ID |
| `official_markdown_parameter` | `content` | 模板中接收完整提醒正文的变量名,未填模板时忽略 |
| `timezone` | `Asia/Shanghai` | IANA 时区 | | `timezone` | `Asia/Shanghai` | IANA 时区 |
| `max_per_user` | `10` | 当前会话每人最多活跃任务 | | `max_per_user` | `10` | 当前会话每人最多活跃任务 |
| `check_interval_seconds` | `30` | 扫描周期,最小 1 秒 | | `check_interval_seconds` | `30` | 扫描周期,最小 1 秒 |
@@ -141,7 +155,7 @@ python tools/package.py
1. 首次命令或入群时确认收到权限开启提示;管理员开启“允许机器人主动发送消息”后,`@机器人 /tx permission check` 确认主动验证成功。 1. 首次命令或入群时确认收到权限开启提示;管理员开启“允许机器人主动发送消息”后,`@机器人 /tx permission check` 确认主动验证成功。
2. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,到期收到真正 @ 的通知;`/tx history` 检查状态,失败时查看原因和日志。 2. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,到期收到真正 @ 的通知;`/tx history` 检查状态,失败时查看原因和日志。
3. `/tx 5分钟 重启测试`,重载插件后用 `/tx list` 确认仍在,再 `/tx cancel 编号` 确认取消。 3. `/tx 5分钟 重启测试`,重载插件后用 `/tx list` 确认仍在,再 `/tx cancel 编号` 确认取消。
4. 让另一成员先发送 `/tx identity`,测试本群的他人提醒。 4. `@机器人 /tx 1分钟 他人提醒测试 @另一成员`,确认创建回复中的提醒对象是对方;到期只 @ 对方,不 @ 发起人。若平台缺少标识,让对方先 `/tx identity` 再使用本群用户标识。
5. `@机器人 /tx 6分钟 主动提醒测试`,期间不再 @机器人,确认到期仍收到提醒。若因权限不足显示等待,开好权限并再次验证;旧版已自动取消的任务需先 `/tx retry 编号` 恢复。 5. `@机器人 /tx 6分钟 主动提醒测试`,期间不再 @机器人,确认到期仍收到提醒。若因权限不足显示等待,开好权限并再次验证;旧版已自动取消的任务需先 `/tx retry 编号` 恢复。
## 来源 ## 来源
+2
View File
@@ -1,5 +1,7 @@
{ {
"proactive_reminders": {"type": "bool", "description": "QQ 官方到点主动提醒", "hint": "默认开启;首次入群/使用提示管理员允许主动消息。关闭后使用有时效和额度限制的被动回复。v1.2 起替代旧 official_delivery_mode 配置。", "default": true}, "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"}, "timezone": {"type": "string", "description": "提醒时区", "hint": "IANA 时区名称,默认北京时间;修改只影响新建提醒。", "default": "Asia/Shanghai"},
"max_per_user": {"type": "int", "description": "每人在每个群/私聊最多活跃提醒数", "default": 10}, "max_per_user": {"type": "int", "description": "每人在每个群/私聊最多活跃提醒数", "default": 10},
"check_interval_seconds": {"type": "int", "description": "到期扫描间隔(秒)", "default": 30}, "check_interval_seconds": {"type": "int", "description": "到期扫描间隔(秒)", "default": 30},
+30 -1
View File
@@ -14,6 +14,7 @@ from astrbot.api.star import Context, Star, StarTools
from .services.delivery import ( from .services.delivery import (
OFFICIAL, OFFICIAL,
MentionDeliveryError,
available, available,
deliver, deliver,
field, field,
@@ -72,6 +73,10 @@ class ReminderPlugin(Star):
self.max_content = max(1, min(1500, int(config.get("max_content_length", 1000)))) 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. # 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.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._wake = asyncio.Event()
self.store = ReminderStore(StarTools.get_data_dir("astrbot_plugin_tixing") / "reminders.db") self.store = ReminderStore(StarTools.get_data_dir("astrbot_plugin_tixing") / "reminders.db")
self.owner = uuid.uuid4().hex self.owner = uuid.uuid4().hex
@@ -250,8 +255,28 @@ class ReminderPlugin(Star):
async def _fire(self, platform, rem, reply=None): async def _fire(self, platform, rem, reply=None):
try: 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: 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 reply is None and rem["platform_name"] in OFFICIAL and proactive_denied(exc):
if rem["scene"] == "group": if rem["scene"] == "group":
await self.store.set_permission( await self.store.set_permission(
@@ -451,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}" message = f"⏰ 提醒已设置 #{reminder_id}\n时间:{describe(record['remind_at'], parsed.repeat, self.timezone)}\n时区:{self.timezone}\n内容:{parsed.content}"
if target != user: if target != user:
message += f"\n提醒对象:{target_name or target}" message += f"\n提醒对象:{target_name or target}"
else:
message += "\n提醒对象:你自己"
if event.get_platform_name() in OFFICIAL: if event.get_platform_name() in OFFICIAL:
if self.delivery_mode == "passive": if self.delivery_mode == "passive":
message += "\n使用被动回复:到期有有效回复窗口时发送,否则等待下次 @机器人 补发。" message += "\n使用被动回复:到期有有效回复窗口时发送,否则等待下次 @机器人 补发。"
@@ -466,6 +493,8 @@ class ReminderPlugin(Star):
if rem["waiting_reason"].startswith("主动消息权限") if rem["waiting_reason"].startswith("主动消息权限")
else "等待可回复消息" else "等待可回复消息"
) )
if rem["waiting_reason"].startswith("Markdown @"):
status = "等待 Markdown 配置"
content = ( content = (
rem["content"] rem["content"]
if detail if detail
+1 -1
View File
@@ -1,7 +1,7 @@
name: astrbot_plugin_tixing name: astrbot_plugin_tixing
display_name: 栗子提醒 display_name: 栗子提醒
desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。 desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。
version: v1.2.0 version: v1.2.2
author: itxiaohui author: itxiaohui
repo: https://github.com/itxiaohui66/astrbot_plugin_tixing repo: https://github.com/itxiaohui66/astrbot_plugin_tixing
support_platforms: support_platforms:
+65 -6
View File
@@ -1,5 +1,6 @@
"""Deliver through the current adapter using a validated incoming reply context.""" """Deliver through the current adapter using a validated incoming reply context."""
import re
import time import time
from datetime import datetime from datetime import datetime
from html import escape from html import escape
@@ -7,6 +8,27 @@ from html import escape
OFFICIAL = {"qq_official", "qq_official_webhook"} 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): def proactive_denied(exc):
text = str(exc).lower() text = str(exc).lower()
return any( return any(
@@ -100,12 +122,30 @@ def available(platform):
def reminder_text(rem): 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 "" prefix = f"来自 {creator} 的提醒:\n" if rem["target_id"] != rem["creator_id"] else ""
return f"{prefix}⏰ {rem['content']}\n(提醒 #{rem['id']})" 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.""" """Official SDK return value must contain a message ID to count as sent."""
client = platform.get_client() client = platform.get_client()
text = reminder_text(rem) text = reminder_text(rem)
@@ -116,17 +156,36 @@ async def deliver(platform, rem, reply=None):
if scene not in {"group", "c2c"}: if scene not in {"group", "c2c"}:
kwargs.pop("msg_seq", None) kwargs.pop("msg_seq", None)
if scene == "group": if scene == "group":
mention = f'<qqbot-at-user id="{escape(rem["target_id"], quote=True)}" />' body = reminder_markdown(rem)
result = await api.post_group_message( markdown = (
group_openid=rem["destination"], msg_type=0, content=f"{mention}\n{text}", **kwargs {
"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": elif scene == "c2c":
result = await api.post_c2c_message( result = await api.post_c2c_message(
openid=rem["destination"], msg_type=0, content=text, **kwargs openid=rem["destination"], msg_type=0, content=text, **kwargs
) )
elif scene == "channel": elif scene == "channel":
result = await api.post_message( 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": elif scene == "guild_dm":
result = await api.post_dms(guild_id=rem["destination"], content=text, **kwargs) result = await api.post_dms(guild_id=rem["destination"], content=text, **kwargs)
+73 -9
View File
@@ -16,22 +16,58 @@ async def resolve_target(event, args, store, scope):
bot_ids = {str(event.message_obj.self_id)} bot_ids = {str(event.message_obj.self_id)}
raw = event.message_obj.raw_message raw = event.message_obj.raw_message
raw_data = field(raw, "raw_data", raw) 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 = {} 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: 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 "")
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)
user = aliases.get(user, user)
if field(mention, "is_you", False) or field(mention, "bot", False): 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: elif user and user not in bot_ids:
trusted[user] = str(field(mention, "username", "") or "") 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(): for component in event.get_messages():
if field(component, "type") in {"At", "at"} or type(component).__name__ == "At": 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: 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) candidates = list(trusted)
for match in MARKUP.finditer(args): 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: if user not in bot_ids:
candidates.append(user) candidates.append(user)
args = MARKUP.sub(" ", args) args = MARKUP.sub(" ", args)
@@ -45,9 +81,37 @@ async def resolve_target(event, args, store, scope):
if len(names) > 1: if len(names) > 1:
raise ValueError("被 @ 成员重名,请使用用户标识。") raise ValueError("被 @ 成员重名,请使用用户标识。")
member = await store.member(scope, value) 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() args = TEXT_AT.sub(" ", args).strip()
candidates = list(dict.fromkeys(candidates)) 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: if len(candidates) > 1:
raise ValueError("一次提醒只能指定一个成员。") raise ValueError("一次提醒只能指定一个成员。")
target = candidates[0] if candidates else sender target = candidates[0] if candidates else sender
+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"
+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]
+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 kwargs[destination_key] == "group_1"
assert "msg_id" not in kwargs assert "msg_id" not in kwargs
if scene == "group": 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): async def test_empty_official_result_is_failure(platform_factory):