Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
800f267b66 | ||
|
|
9c5b87772f | ||
|
|
f89aadb5da | ||
|
|
61ed965d38 | ||
|
|
d4a8177acf | ||
|
|
88cadbac0b |
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.1.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.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` 查看帮助。
|
||||
|
||||
@@ -27,7 +27,7 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
|
||||
| 每人最多 10 条 | 按平台 + 群/私聊 + 创建者计算,仅统计活跃任务;支持配置 |
|
||||
| 30 秒轮询 | 可配置;通常在到期后一个扫描周期内发送,拥塞时可能更晚 |
|
||||
| 数据库存储、重启恢复 | SQLite 位于 AstrBot `data/plugin_data/astrbot_plugin_tixing/reminders.db` |
|
||||
| 投递失败重试、达到阈值取消 | 普通投递错误默认重试间隔 60 秒,连续 3 次失败自动取消;回复窗口/额度受限则等待新消息,不增加失败次数 |
|
||||
| 投递失败重试、达到阈值取消 | 普通投递错误默认重试间隔 60 秒,连续 3 次失败自动取消;主动消息无权限时保留任务,不增加失败次数 |
|
||||
| `/cxzd` 重启提醒调度器 | 保留;使用 AstrBot 管理员或插件授权管理员,不丢任务 |
|
||||
| 旧帮助中的 `/提醒`、`/remind` | 实现为 `/tx` 别名 |
|
||||
| 旧帮助中的今天、明天、指定日期 | 原代码未实现的格式已补齐,并支持后天 |
|
||||
@@ -49,19 +49,24 @@ 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。
|
||||
|
||||
到期后在创建时的群或私聊发送提醒。QQ 官方默认使用被动回复:只有存在有效的近期用户消息和回复额度时才投递,否则保留任务,在下一条机器人收到的同会话消息到来后尝试补发。因此,没有主动消息能力时,长时间后的提醒不能保证准点发出;群内可 `@机器人 /tx list` 打开新的回复窗口。
|
||||
到期后在创建时的群或私聊发送提醒。QQ 官方默认使用**主动发送**,无需等待群成员再次 @机器人。群主或管理员需在本群的机器人权限设置中开启“允许机器人主动发送消息”;入群或首次使用提醒命令时会提示检查该开关。
|
||||
|
||||
循环任务按创建时的时区续期,修改配置时区只影响新任务。离线或等待期间错过多次循环,会在有效窗口中补发一次并续到下一次未来时刻,避免刷屏。一次性逾期提醒同样等待有效窗口补发;如果适配器还未加载或运行,不增加失败次数。OneBot 的发送方式保持原样。
|
||||
循环任务按创建时的时区续期,修改配置时区只影响新任务。离线或等待权限期间错过多次循环,恢复投递时补发一次并续到下一次未来时刻,避免刷屏。一次性逾期提醒也会保留并补发;如果适配器还未加载或运行,不增加失败次数。OneBot 的发送方式保持原样。
|
||||
|
||||
## 管理命令
|
||||
|
||||
| 命令 | 行为 |
|
||||
| --- | --- |
|
||||
| `/tx help` | 全部帮助 |
|
||||
| `/tx to 昵称 时间 内容` / `/tx 给 昵称 时间 内容` | 按名字提醒本群已识别的成员;不用 @ 对方或填写 ID |
|
||||
| `/tx name 昵称` / `/tx 昵称 昵称` / `/tx 登记 昵称` | 给自己登记一个本群唯一的提醒昵称,每人一个,可再次登记修改 |
|
||||
| `/tx name` | 查看自己登记的提醒昵称 |
|
||||
| `/tx list [页码]` / `/cktx` / `/提醒列表` | 当前会话中自己创建的活跃提醒 |
|
||||
| `/tx history [页码]` | 自己的全部记录,包括完成、取消、失败 |
|
||||
| `/tx detail 编号` | 查看全文、时间、状态、失败次数和最近错误 |
|
||||
@@ -70,33 +75,75 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
|
||||
| `/tx retry 编号` | 恢复投递失败后自动取消的任务,或重试待投递任务;仍检查当前会话、创建者和数量限制 |
|
||||
| `/tx identity` | 当前平台、群、用户标识和本群授权管理员标识 |
|
||||
| `/tx status` | 调度器状态、当前会话活跃数量、时区、扫描间隔和最近错误 |
|
||||
| `/tx permission` / `/tx 权限` | 当前官方群的权限记录和开启说明 |
|
||||
| `/tx permission check` | 实际发送一条主动测试消息;成功后立即唤醒等待权限的到期提醒 |
|
||||
| `/cxzd` / `/重启提醒` | 管理员重启提醒调度器 |
|
||||
| `/tx list all [页码]` | 管理员查看当前会话所有人的活跃任务 |
|
||||
| `/tx history all [页码]` | 管理员查看当前会话所有人的历史 |
|
||||
|
||||
管理员可以取消当前会话其他人的单条任务、查看详情。按编号操作也受平台和群隔离限制。群管理员并不会自动获得机器人管理权限;使用 AstrBot 管理员配置,或在插件配置中加入 `admin_ids`、`group_admin_ids`。`group_admin_ids` 的格式为 `平台ID|群OpenID|用户OpenID`,可从 `/tx identity` 复制。
|
||||
|
||||
列表每页 2 条,长内容显示预览,可用 `detail` 查看全文。缺少回复窗口、额度用完或 QQ 拒绝该回复上下文时,状态显示“等待可回复消息”,不会因此自动取消。普通投递错误超过失败阈值后仍会自动取消,可以在 `history` 中查到原因。
|
||||
列表每页 2 条,长内容显示预览,可用 `detail` 查看全文。主动发送无权限时,状态显示“等待主动消息权限”,不会因此自动取消。普通投递错误超过失败阈值后仍会自动取消,可以在 `history` 中查到原因。
|
||||
|
||||
从 v1.0.0 更新后,数据库自动升级并保留原提醒。已经因“主动消息失败,无权限”自动取消的任务不会被擅自恢复;在原群中发送 `/tx retry 2`、`/tx retry 3` 等对应编号即可恢复。等待中的提醒、未到期提醒仍占用活跃任务额度。
|
||||
从 v1.0.0 / v1.1.0 更新后,数据库自动升级并保留原提醒。v1.2.0 默认恢复主动发送,旧 `official_delivery_mode` 配置由 `proactive_reminders` 替代。已经因“主动消息失败,无权限”自动取消的任务不会被擅自恢复;先开启权限并验证,再在原群中发送 `/tx retry 2`、`/tx retry 3` 等对应编号恢复。等待中的提醒、未到期提醒仍占用活跃任务额度。
|
||||
|
||||
## 官方 QQ 的对象和发送权限
|
||||
|
||||
官方 QQ 下发 `group_openid`、`member_openid`、`user_openid`;普通 QQ 号、群号不能直接代替它们。提醒他人优先解析真实 @ 消息段或平台提供的 mentions。若官方事件没有提供被 @ 成员的标识,让对方先在本群 `@机器人 /tx identity`,再使用:
|
||||
**官方 QQ 不保证在“@机器人”事件中提供被 @ 的其他成员信息。** 已确认的部署事件中,用户发送 `@xh` 后,QQ 原始 `mentions` 和 SDK `mentions` 都为空;实际 @ 还可能从正文中被删除,插件无法恢复没有下发的目标名字或 ID。此前说明中“从 QQ 列表选中对方就一定能识别”的说法不准确。
|
||||
|
||||
v1.4.0 增加不需要复制长串 ID 的可靠路径。若机器人已经收到过该成员带昵称的群消息,可以直接按已知昵称提醒;否则让被提醒的成员在**同一个群**登记一次,例如 **xh 本人**发送:
|
||||
|
||||
```text
|
||||
/tx 30分钟 开会 @对方的用户标识
|
||||
@机器人 /tx name xh
|
||||
```
|
||||
|
||||
插件会记住本群里机器人实际收到的成员消息,名字唯一且官方提供昵称时也支持 `@昵称`。不同群里的成员记录不会混用,重名时要求明确标识。OneBot 模式会查询目标是否是本群成员。私聊只能提醒自己。
|
||||
机器人从**登记者这条消息的发送者 ID** 自动绑定名字,发起提醒的人无需填写 ID。之后其他人发送:
|
||||
|
||||
v1.1.0 默认采用 **被动回复**:使用真正收到的用户消息 `msg_id`,群、频道、频道私信保守采用 4 分钟窗口,C2C 保守采用 59 分钟窗口,给网络发送留出安全余量。官方文档规定群回复有效期 5 分钟、C2C 60 分钟,每条消息最多回复 5 次;插件每个上下文最多投递 3 条提醒,留出回复次数给命令响应和其他插件。若其他插件已经用完回复额度,QQ 拒绝该上下文后会等待下一条消息。
|
||||
```text
|
||||
@机器人 /tx to xh 1分钟 测试
|
||||
```
|
||||
|
||||
回复上下文按平台、场景和投递目标隔离,保存消息原始时间及已用次数;重复事件不会延长有效期或补充额度。群/C2C 的提醒采用与 AstrBot 当前回复发送范围分开的独立 `msg_seq`。新消息到来会唤醒扫描器,不必等到下一轮轮询。只有接口返回消息 ID 后才标记成功或续期;被动发送失败时不降级为无权限的主动发送。
|
||||
`to` 后直接写名字,不从 QQ 的 @ 列表选择对方,这样名字不会被 QQ 删除。带空格的名字用双引号,例如 `/tx name "小 明"`、`/tx to "小 明" 1分钟 测试`。昵称登记仅能登记自己,不能用自己的消息登记别人的 ID。已被其他已识别成员使用的名字会拒绝登记;重名时选择不同提醒昵称。登记按平台、群保存,重载或收到新的 QQ 昵称后仍保留。更改登记不会改变已有任务保存的接收者 ID。
|
||||
|
||||
`official_delivery_mode=proactive` 仅保留给已确认具备该能力的环境使用。QQ 官方文档对主动推送有停止提供能力的公告,普通账号不能靠换 API 或旧消息 ID 绕过限制。详见 [腾讯官方消息收发文档](https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/server-inter/message/send-receive/send.md)。
|
||||
显式 `to` 的对象未识别、与真实 @ 冲突或无法解析时会拒绝创建,绝不改成提醒自己。原来的 `/tx 时间 内容` 仍用于提醒自己;若 QQ 已完全删除另一个 @,插件无法区分这条命令原本是否要提醒他人,所以确认回复会明确警示“未识别到其他成员”,并提示取消后用 `to` 重建。
|
||||
|
||||
QQ 普通群使用 `<qqbot-at-user id="OpenID" />` 实现真正 @,频道使用频道成员 ID。群、C2C、频道、频道私信分别走对应 SDK 接口。插件自己的到期提醒使用普通文本,不要求 Markdown 模板;命令回复仍由 AstrBot 当前事件的配置发送。
|
||||
腾讯公开文档中的 [群成员列表接口](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 @ 列表选择,避免被删除);带空格的名字支持 `@"小 明"` 或 `@小 明`(后者需名字已被识别)。平台下发真实 @ 的 ID 时,实际选择优先于昵称缓存。收到新名字时更新观察记录,不继续按旧昵称匹配;v1.4.0 的自定义登记昵称独立保留。
|
||||
|
||||
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;请按上述流程让对方 `/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 模式会查询目标是否是本群成员。私聊只能提醒自己。
|
||||
|
||||
v1.2.0 默认采用 **主动发送**。新群的 `GROUP_ADD_ROBOT` 事件到来时,插件使用该真实事件的 `event_id` 回复管理员开启说明;若事件缺失、发送失败或插件是后来才安装的,则在首次提醒命令回复中附加说明。提示按平台和群持久化,成功提示后不会在每次命令中重复。
|
||||
|
||||
插件接收官方 SDK 的 `GROUP_MSG_RECEIVE` / `GROUP_MSG_REJECT` 事件,分别记录允许和关闭状态。已收到允许事件或实际发送成功的群不会被误报为未开启;没有证据时仅提示“确认已开启”。退群及重新入群事件也会更新记录。生命周期监听支持 WebSocket 和 Webhook,保留其他组件已有的回调,重载时移除本插件监听。
|
||||
|
||||
管理员开启后,在原群发送 `@机器人 /tx permission check`。验证消息不带 `msg_id` 或 `event_id`,接口返回消息 ID 后才确认主动投递成功,并唤醒等待权限的到期任务。群开关允许后仍以 QQ 接口实际返回为准;应用本身的权限、发送额度等限制会显示在验证结果或提醒记录中。官方事件依据 [腾讯 botpy 群管理事件](https://github.com/tencent-connect/botpy/blob/master/botpy/manage.py) 和 [事件解析器](https://github.com/tencent-connect/botpy/blob/master/botpy/connection.py),消息接口依据 [腾讯官方消息收发文档](https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/server-inter/message/send-receive/send.md)。
|
||||
|
||||
主动消息被 QQ 拒绝且错误指向权限时,插件保留任务、不增加失败次数,并每 5 分钟重试。若明确收到管理员拒绝消息或退群事件,则暂停主动投递,等待允许事件或主动验证成功。允许事件和验证成功会使等待权限的到期任务立即进入扫描;接口仍失败时继续保留。命令回复使用当前消息进行被动回复,因此也能在权限未开时显示设置说明。
|
||||
|
||||
如需使用被动回复,可关闭 `proactive_reminders`。这时只有存在有效的近期用户消息和回复额度才投递,超出窗口则等待下一条同会话消息。群、频道、频道私信保守采用 4 分钟窗口,C2C 59 分钟;每条消息最多投递 3 条提醒,给命令回复和其他插件预留额度。回复上下文按平台、场景和目标隔离;重复事件不会刷新有效期或额度,受限时不会切换为主动发送。被动模式无法保证长时间后准点提醒。
|
||||
|
||||
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/`。
|
||||
|
||||
@@ -106,7 +153,9 @@ QQ 普通群使用 `<qqbot-at-user id="OpenID" />` 实现真正 @,频道使用
|
||||
|
||||
| 字段 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `official_delivery_mode` | `passive` | 默认被动回复,等待有效窗口;可显式选 `proactive` 保留原发送方式 |
|
||||
| `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 秒 |
|
||||
@@ -128,15 +177,15 @@ ruff format --check .
|
||||
python tools/package.py
|
||||
```
|
||||
|
||||
自动化测试使用真实 SQLite 和时间解析;AstrBot 主机边界和 QQ 发送接口使用测试替身,覆盖时间格式、上限、群隔离、成员识别、失败重试、循环补发、权限、热重载,以及回复时效、额度、序号、重复事件、即时唤醒和数据库升级。GitHub Actions 会在 Linux(Python 3.10、3.12)和 Windows(Python 3.12)上运行测试、代码检查和打包。真实 QQ 投递仍需在实际部署的 AstrBot 和账号中验证。
|
||||
自动化测试使用真实 SQLite 和时间解析;AstrBot 主机边界和 QQ 发送接口使用测试替身,覆盖时间格式、上限、群隔离、成员识别、失败重试、循环补发、权限、入群提示、首次使用去重、允许/拒绝事件、回调恢复、重载,以及回复时效、额度、序号、重复事件、即时唤醒和数据库升级。GitHub Actions 会在 Linux(Python 3.10、3.12)和 Windows(Python 3.12)上运行测试、代码检查和打包。真实 QQ 投递仍需在实际部署的 AstrBot 和账号中验证。
|
||||
|
||||
安装后可用以下流程确认部署环境:
|
||||
|
||||
1. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,并在有效回复窗口内收到真正 @ 的通知。
|
||||
2. `/tx history` 检查该任务状态;失败时检查记录里的原因和 AstrBot 日志。
|
||||
1. 首次命令或入群时确认收到权限开启提示;管理员开启“允许机器人主动发送消息”后,`@机器人 /tx permission check` 确认主动验证成功。
|
||||
2. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,到期收到真正 @ 的通知;`/tx history` 检查状态,失败时查看原因和日志。
|
||||
3. `/tx 5分钟 重启测试`,重载插件后用 `/tx list` 确认仍在,再 `/tx cancel 编号` 确认取消。
|
||||
4. 让另一成员先发送 `/tx identity`,测试本群的他人提醒。
|
||||
5. 超过群回复窗口后,确认 `/tx list` 显示待补发原因;在群里再次 @机器人 时应唤醒投递。若已因旧版错误自动取消,先 `/tx retry 编号` 恢复。
|
||||
4. 让另一成员发送 `@机器人 /tx name xh`,你发送 `@机器人 /tx to xh 1分钟 他人提醒测试`,确认创建回复中的提醒对象是 xh;到期只 @ 对方,不 @ 发起人。再验证重载后仍可按登记昵称提醒。若平台确实下发真实 @ 的成员 ID,再验证从 QQ 列表选择成员的旧语法。
|
||||
5. `@机器人 /tx 6分钟 主动提醒测试`,期间不再 @机器人,确认到期仍收到提醒。若因权限不足显示等待,开好权限并再次验证;旧版已自动取消的任务需先 `/tx retry 编号` 恢复。
|
||||
|
||||
## 来源
|
||||
|
||||
|
||||
+3
-1
@@ -1,5 +1,7 @@
|
||||
{
|
||||
"official_delivery_mode": {"type": "string", "description": "QQ 官方发送方式", "options": ["passive", "proactive"], "hint": "默认 passive 被动回复;没有有效回复窗口时保留任务等待下次消息。仅已确认支持主动消息的账号选择 proactive。", "default": "passive"},
|
||||
"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},
|
||||
|
||||
@@ -14,20 +14,33 @@ from astrbot.api.star import Context, Star, StarTools
|
||||
|
||||
from .services.delivery import (
|
||||
OFFICIAL,
|
||||
MentionDeliveryError,
|
||||
available,
|
||||
deliver,
|
||||
field,
|
||||
find_platform,
|
||||
incoming_reply,
|
||||
proactive_denied,
|
||||
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, 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 跨年
|
||||
@@ -41,11 +54,17 @@ HELP = """⏰ 栗子提醒
|
||||
/tx retry 编号 恢复投递失败的提醒
|
||||
/tx identity 查看当前平台、群和用户标识
|
||||
/tx status 查看提醒调度器状态
|
||||
/tx diagnose 时间 内容 @对方 检查成员识别(不创建提醒)
|
||||
/tx diagnose 编号 核对提醒保存的成员 ID
|
||||
/tx permission 查看主动消息权限说明
|
||||
/tx permission check 发送主动消息验证权限
|
||||
/cxzd 管理员重启提醒调度器
|
||||
命令别名:/提醒、/remind
|
||||
群内官方 QQ 需要 @机器人;时间按配置时区计算。
|
||||
官方 QQ 提醒他人须使用本群 OpenID 或真实 @;普通 QQ 号不可转换。
|
||||
默认使用被动回复;没有有效回复窗口时等待下次 @机器人 补发。
|
||||
QQ 有时不下发被 @ 成员的 ID,请优先 /tx to 昵称 时间 内容。
|
||||
机器人从成员发言学习 ID;未认识的成员可自己 /tx name 昵称 登记,无需复制 ID。
|
||||
平台提供完整真实 @ 时也支持;昵称带空格可用 /tx to "小 明" 1分钟 测试。
|
||||
默认到点主动提醒;群主/管理员需开启“允许机器人主动发送消息”。
|
||||
管理员可 /tx list all 和 /tx cancel 编号 管理当前群提醒。"""
|
||||
|
||||
|
||||
@@ -65,9 +84,12 @@ class ReminderPlugin(Star):
|
||||
self.max_failures = max(1, int(config.get("max_delivery_failures", 3)))
|
||||
self.retry_seconds = max(1, int(config.get("retry_interval_seconds", 60)))
|
||||
self.max_content = max(1, min(1500, int(config.get("max_content_length", 1000))))
|
||||
self.delivery_mode = config.get("official_delivery_mode", "passive")
|
||||
if self.delivery_mode not in {"passive", "proactive"}:
|
||||
raise ValueError("official_delivery_mode 必须为 passive 或 proactive")
|
||||
# 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
|
||||
@@ -76,6 +98,8 @@ class ReminderPlugin(Star):
|
||||
self._init_lock = asyncio.Lock()
|
||||
self._scan_lock = asyncio.Lock()
|
||||
self._scheduler = None
|
||||
self._permission_watcher = None
|
||||
self._bridges = {}
|
||||
self.last_scan = 0
|
||||
self.last_scan_error = ""
|
||||
|
||||
@@ -86,6 +110,9 @@ class ReminderPlugin(Star):
|
||||
if not self._ready:
|
||||
await self.store.initialize()
|
||||
self._ready = True
|
||||
await self._attach_platforms()
|
||||
if self._permission_watcher is None or self._permission_watcher.done():
|
||||
self._permission_watcher = asyncio.create_task(self._watch_platforms())
|
||||
if self._scheduler is None or self._scheduler.done():
|
||||
self._scheduler = asyncio.create_task(self._poll(), name="lizi-reminders")
|
||||
|
||||
@@ -93,6 +120,90 @@ class ReminderPlugin(Star):
|
||||
async def on_loaded(self):
|
||||
await self.initialize()
|
||||
|
||||
async def _attach_platforms(self):
|
||||
live = set()
|
||||
for platform in self.context.platform_manager.platform_insts:
|
||||
if platform.meta().name not in OFFICIAL:
|
||||
continue
|
||||
client = platform.get_client()
|
||||
if client is None:
|
||||
continue
|
||||
key = id(client)
|
||||
live.add(key)
|
||||
if key not in self._bridges:
|
||||
bridge = PermissionBridge(platform, self._permission_event)
|
||||
bridge.install()
|
||||
self._bridges[key] = bridge
|
||||
for key in set(self._bridges) - live:
|
||||
await self._bridges.pop(key).close()
|
||||
|
||||
async def _watch_platforms(self):
|
||||
while True:
|
||||
await asyncio.sleep(5)
|
||||
try:
|
||||
await self._attach_platforms()
|
||||
except Exception:
|
||||
logger.exception("[Reminder] 连接 QQ 群权限事件失败,将继续重试")
|
||||
|
||||
async def _permission_event(self, platform, kind, event):
|
||||
if self._closed:
|
||||
return
|
||||
destination = str(field(event, "group_openid") or "")
|
||||
if not destination:
|
||||
return
|
||||
platform_id = str(platform.meta().id)
|
||||
event_id = str(field(event, "event_id") or "")
|
||||
stamp = field(event, "timestamp")
|
||||
try:
|
||||
event_at = float(stamp)
|
||||
except (ValueError, TypeError):
|
||||
try:
|
||||
event_at = datetime.fromisoformat(str(stamp).replace("Z", "+00:00")).timestamp()
|
||||
except (ValueError, TypeError):
|
||||
event_at = time.time()
|
||||
states = {
|
||||
"group_add_robot": "unknown",
|
||||
"group_del_robot": "removed",
|
||||
"group_msg_receive": "granted",
|
||||
"group_msg_reject": "denied",
|
||||
}
|
||||
changed = await self.store.set_permission(
|
||||
platform_id,
|
||||
destination,
|
||||
states[kind],
|
||||
event_at,
|
||||
event_id,
|
||||
reset=kind in {"group_add_robot", "group_del_robot", "group_msg_reject"},
|
||||
)
|
||||
if not changed:
|
||||
return
|
||||
if kind == "group_msg_receive":
|
||||
self._wake.set()
|
||||
if kind != "group_add_robot" or not event_id or self.delivery_mode != "proactive":
|
||||
return
|
||||
if not await self.store.claim_notice(platform_id, destination):
|
||||
return
|
||||
sent = False
|
||||
try:
|
||||
# A real join event can be replied to even before proactive permission is enabled.
|
||||
result = await asyncio.wait_for(
|
||||
platform.get_client().api.post_group_message(
|
||||
group_openid=destination,
|
||||
msg_type=0,
|
||||
content=NOTICE,
|
||||
event_id=event_id,
|
||||
msg_seq=20001,
|
||||
),
|
||||
timeout=30,
|
||||
)
|
||||
sent = bool(field(result, "id"))
|
||||
if not sent:
|
||||
logger.warning("[Reminder] 入群权限提示没有返回消息 ID,将在首次命令时提示")
|
||||
except Exception as exc:
|
||||
logger.warning("[Reminder] 入群权限提示失败,将在首次命令时提示:%s", exc)
|
||||
finally:
|
||||
await self.store.finish_notice(platform_id, destination, sent)
|
||||
|
||||
async def _poll(self):
|
||||
while True:
|
||||
try:
|
||||
@@ -117,6 +228,20 @@ class ReminderPlugin(Star):
|
||||
if not await self.store.claim(rem["id"], self.owner, time.time()):
|
||||
continue
|
||||
reply = None
|
||||
if (
|
||||
rem["platform_name"] in OFFICIAL
|
||||
and self.delivery_mode == "proactive"
|
||||
and rem["scene"] == "group"
|
||||
):
|
||||
permission = await self.store.permission(rem["platform_id"], rem["destination"])
|
||||
if permission["state"] in {"denied", "removed"}:
|
||||
await self.store.wait_for_permission(
|
||||
rem["id"],
|
||||
self.owner,
|
||||
"主动消息权限未开启或机器人已退群;请管理员开启后 /tx permission check 验证",
|
||||
time.time() + 300,
|
||||
)
|
||||
continue
|
||||
if rem["platform_name"] in OFFICIAL and self.delivery_mode == "passive":
|
||||
# QQ documents group/channel/DM windows of 5 min, C2C 60 min.
|
||||
# Leave a margin for the 30 s send timeout.
|
||||
@@ -142,9 +267,52 @@ 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(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(
|
||||
rem["platform_id"], rem["destination"], "error", reset=True
|
||||
)
|
||||
await self.store.wait_for_permission(
|
||||
rem["id"],
|
||||
self.owner,
|
||||
f"主动消息权限受限:{exc};请管理员开启后 /tx permission check 验证,任务保留并每 5 分钟重试",
|
||||
time.time() + 300,
|
||||
)
|
||||
logger.warning(
|
||||
"[Reminder] 提醒 #%s 等待主动消息权限,任务已保留:%s", rem["id"], exc
|
||||
)
|
||||
return
|
||||
if reply is not None and reply_unavailable(exc):
|
||||
await self.store.block_reply(
|
||||
rem["platform_id"], rem["scene"], rem["destination"], reply["msg_id"]
|
||||
@@ -173,6 +341,8 @@ class ReminderPlugin(Star):
|
||||
rem["remind_at"], rem["repeat_type"], rem["timezone"], time.time()
|
||||
)
|
||||
await self.store.success(rem["id"], self.owner, next_time)
|
||||
if reply is None and rem["platform_name"] in OFFICIAL and rem["scene"] == "group":
|
||||
await self.store.set_permission(rem["platform_id"], rem["destination"], "granted")
|
||||
logger.info("[Reminder] 提醒 #%s 已投递,平台=%s", rem["id"], rem["platform_id"])
|
||||
|
||||
def _admin(self, event):
|
||||
@@ -194,7 +364,25 @@ class ReminderPlugin(Star):
|
||||
|
||||
async def _reply(self, event, text):
|
||||
# Passive command responses are sent by AstrBot using the current event.
|
||||
destination = ""
|
||||
if event.get_platform_name() in OFFICIAL and self.delivery_mode == "proactive":
|
||||
try:
|
||||
scene, dest = route(event)
|
||||
except ValueError:
|
||||
scene, dest = "", ""
|
||||
if scene == "group" and await self.store.claim_notice(
|
||||
str(event.get_platform_id()), dest
|
||||
):
|
||||
destination = dest
|
||||
if NOTICE not in text:
|
||||
text += "\n\n" + NOTICE
|
||||
sent = False
|
||||
try:
|
||||
await event.send(event.plain_result(text))
|
||||
sent = True
|
||||
finally:
|
||||
if destination:
|
||||
await self.store.finish_notice(str(event.get_platform_id()), destination, sent)
|
||||
|
||||
async def _guard(self, event, action):
|
||||
try:
|
||||
@@ -212,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", "帮助"}:
|
||||
@@ -231,10 +410,27 @@ class ReminderPlugin(Star):
|
||||
raise ValueError("当前插件支持 QQ 官方 WebSocket、Webhook 和 OneBot。")
|
||||
scope = self._scope(event)
|
||||
user = str(event.get_sender_id())
|
||||
await self.store.observe(scope, user, event.get_sender_name())
|
||||
await observe_members(event, self.store, scope)
|
||||
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
|
||||
@@ -249,7 +445,10 @@ class ReminderPlugin(Star):
|
||||
scope, None if self._admin(event) else user, int(tail), self.limit
|
||||
)
|
||||
self._wake.set()
|
||||
await self._reply(event, f"✅ 提醒 #{tail} 已恢复,等待有效回复窗口投递。")
|
||||
await self._reply(event, f"✅ 提醒 #{tail} 已恢复,将按当前发送方式重试投递。")
|
||||
return
|
||||
if action in {"permission", "权限"}:
|
||||
await self._permission_command(event, tail)
|
||||
return
|
||||
if action in {"detail", "详情"}:
|
||||
if not tail.isdecimal():
|
||||
@@ -265,6 +464,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()
|
||||
@@ -275,11 +494,16 @@ 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
|
||||
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} 个字符。")
|
||||
@@ -305,18 +529,38 @@ class ReminderPlugin(Star):
|
||||
reminder_id = await self.store.add(record, self.limit)
|
||||
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}"
|
||||
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使用主动投递;发送权限或额度受限时会记录失败。"
|
||||
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):
|
||||
status = {"active": "待提醒", "done": "已完成", "cancelled": "已取消"}[rem["status"]]
|
||||
if rem["status"] == "active" and rem.get("waiting_reason"):
|
||||
status = "等待可回复消息"
|
||||
status = (
|
||||
"等待主动消息权限"
|
||||
if rem["waiting_reason"].startswith("主动消息权限")
|
||||
else "等待可回复消息"
|
||||
)
|
||||
if rem["waiting_reason"].startswith("Markdown @"):
|
||||
status = "等待 Markdown 配置"
|
||||
content = (
|
||||
rem["content"]
|
||||
if detail
|
||||
@@ -325,7 +569,7 @@ class ReminderPlugin(Star):
|
||||
)
|
||||
text = f"#{rem['id']} [{status}] {describe(rem['remind_at'], rem['repeat_type'], rem['timezone'])}\n{content}"
|
||||
if rem["target_id"] != rem["creator_id"]:
|
||||
text += f"\n对象:{rem['target_name'] or rem['target_id']}"
|
||||
text += f"\n对象:{rem['target_name'] or '你选中的群成员'}"
|
||||
if detail:
|
||||
text += f"\n创建者:{rem['creator_name'] or rem['creator_id']}\n时区:{rem['timezone']}\n失败次数:{rem['failure_count']}"
|
||||
if rem["last_error"]:
|
||||
@@ -334,6 +578,46 @@ class ReminderPlugin(Star):
|
||||
text += f"\n等待原因:{rem['waiting_reason'][:150]}"
|
||||
return text
|
||||
|
||||
async def _permission_command(self, event, tail):
|
||||
if event.get_platform_name() not in OFFICIAL or route(event)[0] != "group":
|
||||
raise ValueError("主动消息群权限检查仅适用于 QQ 官方群聊。")
|
||||
platform_id = str(event.get_platform_id())
|
||||
destination = route(event)[1]
|
||||
if not tail:
|
||||
state = (await self.store.permission(platform_id, destination))["state"]
|
||||
labels = {
|
||||
"unknown": "尚未验证",
|
||||
"granted": "已收到允许事件或发送成功记录",
|
||||
"denied": "收到管理员关闭权限事件",
|
||||
"removed": "机器人已被移出群",
|
||||
"error": "最近一次主动发送被拒绝",
|
||||
}
|
||||
await self._reply(event, f"本群状态:{labels[state]}\n{NOTICE}")
|
||||
return
|
||||
if tail.lower() not in {"check", "检查", "验证"}:
|
||||
raise ValueError("用法:/tx permission 或 /tx permission check")
|
||||
platform = find_platform(self.context, platform_id)
|
||||
if not available(platform):
|
||||
raise ValueError("QQ 适配器尚未运行,请稍后再验证。")
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
platform.get_client().api.post_group_message(
|
||||
group_openid=destination,
|
||||
msg_type=0,
|
||||
content="✅ 主动消息权限验证成功。此消息为主动发送,等待权限的到期提醒将继续投递。",
|
||||
),
|
||||
timeout=30,
|
||||
)
|
||||
if not field(result, "id"):
|
||||
raise RuntimeError("QQ 接口未返回消息 ID")
|
||||
except Exception as exc:
|
||||
if proactive_denied(exc):
|
||||
await self.store.set_permission(platform_id, destination, "error", reset=True)
|
||||
await self._reply(event, f"❌ 主动消息验证失败:{str(exc)[:250]}\n{NOTICE}")
|
||||
return
|
||||
await self.store.set_permission(platform_id, destination, "granted")
|
||||
self._wake.set()
|
||||
|
||||
async def _list(self, event, scope, user, tail, history):
|
||||
all_users = tail.split()[:1] == ["all"]
|
||||
if all_users:
|
||||
@@ -418,9 +702,7 @@ class ReminderPlugin(Star):
|
||||
await self.initialize()
|
||||
await self._remember_incoming(event)
|
||||
if event.get_group_id():
|
||||
await self.store.observe(
|
||||
self._scope(event), str(event.get_sender_id()), event.get_sender_name()
|
||||
)
|
||||
await observe_members(event, self.store, self._scope(event))
|
||||
except Exception:
|
||||
logger.exception("[Reminder] 记录本群成员标识失败")
|
||||
|
||||
@@ -441,8 +723,16 @@ class ReminderPlugin(Star):
|
||||
async def terminate(self):
|
||||
async with self._init_lock:
|
||||
self._closed = True
|
||||
if self._permission_watcher:
|
||||
self._permission_watcher.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await self._permission_watcher
|
||||
self._permission_watcher = None
|
||||
if self._scheduler:
|
||||
self._scheduler.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await self._scheduler
|
||||
self._scheduler = None
|
||||
for bridge in self._bridges.values():
|
||||
await bridge.close()
|
||||
self._bridges.clear()
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
name: astrbot_plugin_tixing
|
||||
display_name: 栗子提醒
|
||||
desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。
|
||||
version: v1.1.0
|
||||
version: v1.4.0
|
||||
author: itxiaohui
|
||||
repo: https://github.com/itxiaohui66/astrbot_plugin_tixing
|
||||
support_platforms:
|
||||
|
||||
+75
-6
@@ -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,35 @@ 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(
|
||||
token in text
|
||||
for token in ("主动消息失败", "无权限", "permission", "not allowed", "主动消息权限")
|
||||
)
|
||||
|
||||
|
||||
def incoming_reply(event):
|
||||
"""Read an inbound message ID and its original timestamp, never a sent ID."""
|
||||
raw = event.message_obj.raw_message
|
||||
@@ -92,12 +122,32 @@ 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 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)
|
||||
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)
|
||||
@@ -108,17 +158,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)
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"""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, named_recipient, resolve_target
|
||||
|
||||
VERSION = "v1.4.0"
|
||||
|
||||
|
||||
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:
|
||||
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,
|
||||
"提醒自己": target == str(event.get_sender_id()),
|
||||
}
|
||||
except ValueError as exc:
|
||||
report["解析失败"] = redact(str(exc))
|
||||
return json.dumps(report, ensure_ascii=False, indent=2)
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Observe the official SDK's group lifecycle events without replacing its parsers."""
|
||||
|
||||
import asyncio
|
||||
import inspect
|
||||
|
||||
from astrbot.api import logger
|
||||
|
||||
NOTICE = (
|
||||
"⏰ 定时提醒需要主动消息权限。请群主或管理员打开本群机器人的权限设置,"
|
||||
"确认已开启“允许机器人主动发送消息”(不同 QQ 版本名称可能略有不同)。"
|
||||
"开启后可 @机器人 /tx permission check 验证;随后按设置时间主动提醒。"
|
||||
)
|
||||
EVENTS = ("group_add_robot", "group_del_robot", "group_msg_receive", "group_msg_reject")
|
||||
|
||||
|
||||
class PermissionBridge:
|
||||
def __init__(self, platform, handler):
|
||||
self.platform = platform
|
||||
self.client = platform.get_client()
|
||||
self.handler = handler
|
||||
self.closed = False
|
||||
self.callbacks = {}
|
||||
self.tasks = set()
|
||||
|
||||
def install(self):
|
||||
for kind in EVENTS:
|
||||
name = "on_" + kind
|
||||
previous = getattr(self.client, name, None)
|
||||
|
||||
async def callback(event, kind=kind, previous=previous):
|
||||
task = asyncio.current_task()
|
||||
if not self.closed:
|
||||
self.tasks.add(task)
|
||||
try:
|
||||
await self.handler(self.platform, kind, event)
|
||||
except Exception:
|
||||
logger.exception("[Reminder] 处理 QQ 群权限事件失败:%s", kind)
|
||||
finally:
|
||||
self.tasks.discard(task)
|
||||
if previous:
|
||||
result = previous(event)
|
||||
if inspect.isawaitable(result):
|
||||
await result
|
||||
|
||||
callback._reminder_bridge = self
|
||||
callback._reminder_previous = previous
|
||||
setattr(self.client, name, callback)
|
||||
self.callbacks[name] = callback
|
||||
|
||||
async def close(self):
|
||||
self.closed = True
|
||||
# Finish any notification + persistence before the plugin is unloaded.
|
||||
if self.tasks:
|
||||
pending = asyncio.gather(*self.tasks, return_exceptions=True)
|
||||
try:
|
||||
await asyncio.shield(pending)
|
||||
except asyncio.CancelledError:
|
||||
await pending
|
||||
raise
|
||||
for name, callback in self.callbacks.items():
|
||||
if getattr(self.client, name, None) is not callback:
|
||||
continue
|
||||
previous = callback._reminder_previous
|
||||
while previous and isinstance(
|
||||
getattr(previous, "_reminder_bridge", None), PermissionBridge
|
||||
):
|
||||
if not previous._reminder_bridge.closed:
|
||||
break
|
||||
previous = previous._reminder_previous
|
||||
if previous is None:
|
||||
delattr(self.client, name)
|
||||
else:
|
||||
setattr(self.client, name, previous)
|
||||
+176
-6
@@ -64,12 +64,30 @@ class ReminderStore:
|
||||
nickname TEXT NOT NULL DEFAULT '', seen_at REAL NOT NULL,
|
||||
PRIMARY KEY(scope, user_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS member_names (
|
||||
scope TEXT NOT NULL, user_id TEXT NOT NULL, name TEXT NOT NULL,
|
||||
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 (
|
||||
platform_id TEXT NOT NULL, scene TEXT NOT NULL, destination TEXT NOT NULL,
|
||||
msg_id TEXT NOT NULL, received_at REAL NOT NULL,
|
||||
used INTEGER NOT NULL DEFAULT 0, blocked INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY(platform_id, scene, destination)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS group_permissions (
|
||||
platform_id TEXT NOT NULL, destination TEXT NOT NULL,
|
||||
state TEXT NOT NULL DEFAULT 'unknown', notified INTEGER NOT NULL DEFAULT 0,
|
||||
notice_until REAL NOT NULL DEFAULT 0, event_at REAL NOT NULL DEFAULT 0,
|
||||
event_id TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY(platform_id, destination)
|
||||
);
|
||||
""")
|
||||
columns = {row[1] for row in db.execute("PRAGMA table_info(reminders)")}
|
||||
if "waiting_reason" not in columns:
|
||||
@@ -79,33 +97,185 @@ class ReminderStore:
|
||||
|
||||
await self._run(create)
|
||||
|
||||
async def observe(self, scope, user_id, nickname=""):
|
||||
async def permission(self, platform_id, destination):
|
||||
return await self._run(
|
||||
lambda db: dict(
|
||||
db.execute(
|
||||
"SELECT * FROM group_permissions WHERE platform_id=? AND destination=?",
|
||||
(platform_id, destination),
|
||||
).fetchone()
|
||||
or {"state": "unknown", "notified": 0}
|
||||
)
|
||||
)
|
||||
|
||||
async def set_permission(
|
||||
self, platform_id, destination, state, event_at=None, event_id="", reset=False
|
||||
):
|
||||
def write(db):
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
db.execute(
|
||||
"INSERT OR IGNORE INTO group_permissions(platform_id,destination) VALUES (?,?)",
|
||||
(platform_id, destination),
|
||||
)
|
||||
row = db.execute(
|
||||
"SELECT * FROM group_permissions WHERE platform_id=? AND destination=?",
|
||||
(platform_id, destination),
|
||||
).fetchone()
|
||||
if event_at is not None and (
|
||||
event_at < row["event_at"] or (event_id and event_id == row["event_id"])
|
||||
):
|
||||
return False
|
||||
reset_notice = reset and (row["state"] != state or event_at is not None)
|
||||
db.execute(
|
||||
"UPDATE group_permissions SET state=?,event_at=COALESCE(?,event_at),"
|
||||
"event_id=CASE WHEN ?!='' THEN ? ELSE event_id END,"
|
||||
"notified=CASE WHEN ? THEN 0 ELSE notified END,"
|
||||
"notice_until=CASE WHEN ? THEN 0 ELSE notice_until END "
|
||||
"WHERE platform_id=? AND destination=?",
|
||||
(
|
||||
state,
|
||||
event_at,
|
||||
event_id,
|
||||
event_id,
|
||||
reset_notice,
|
||||
reset_notice,
|
||||
platform_id,
|
||||
destination,
|
||||
),
|
||||
)
|
||||
if state == "granted":
|
||||
db.execute(
|
||||
"UPDATE reminders SET retry_at=0,waiting_reason='' WHERE platform_id=? "
|
||||
"AND destination=? AND scene='group' AND status='active' "
|
||||
"AND waiting_reason LIKE '主动消息权限%'",
|
||||
(platform_id, destination),
|
||||
)
|
||||
return True
|
||||
|
||||
return await self._run(write)
|
||||
|
||||
async def claim_notice(self, platform_id, destination):
|
||||
def write(db):
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
db.execute(
|
||||
"INSERT OR IGNORE INTO group_permissions(platform_id,destination) VALUES (?,?)",
|
||||
(platform_id, destination),
|
||||
)
|
||||
return (
|
||||
db.execute(
|
||||
"UPDATE group_permissions SET notice_until=? WHERE platform_id=? "
|
||||
"AND destination=? AND state!='granted' AND notified=0 AND notice_until<=?",
|
||||
(time.time() + 60, platform_id, destination, time.time()),
|
||||
).rowcount
|
||||
== 1
|
||||
)
|
||||
|
||||
return await self._run(write)
|
||||
|
||||
async def finish_notice(self, platform_id, destination, sent):
|
||||
await self._run(
|
||||
lambda db: (
|
||||
lambda db: db.execute(
|
||||
"UPDATE group_permissions SET notified=MAX(notified,?),notice_until=0 WHERE platform_id=? AND destination=?",
|
||||
(int(sent), platform_id, destination),
|
||||
)
|
||||
)
|
||||
|
||||
async def wait_for_permission(self, reminder_id, owner, reason, retry_at):
|
||||
await self._run(
|
||||
lambda db: db.execute(
|
||||
"UPDATE reminders SET waiting_reason=?,retry_at=?,lease_owner='',lease_until=0 "
|
||||
"WHERE id=? AND lease_owner=? AND status='active'",
|
||||
(reason[:500], retry_at, reminder_id, owner),
|
||||
)
|
||||
)
|
||||
|
||||
async def observe(self, scope, user_id, nickname="", names=()):
|
||||
await self.observe_members(scope, [(user_id, nickname, names)])
|
||||
|
||||
async def observe_members(self, scope, members):
|
||||
def write(db):
|
||||
for user_id, nickname, names in members:
|
||||
if nickname == user_id:
|
||||
nickname = ""
|
||||
names = list(dict.fromkeys(n for n in (nickname, *names) if n and n != user_id))
|
||||
db.execute(
|
||||
"INSERT INTO members VALUES (?,?,?,?) ON CONFLICT(scope,user_id) DO UPDATE SET "
|
||||
"nickname=CASE WHEN excluded.nickname!='' THEN excluded.nickname ELSE members.nickname END, "
|
||||
"seen_at=excluded.seen_at",
|
||||
(scope, user_id, nickname or "", time.time()),
|
||||
).rowcount
|
||||
)
|
||||
if names:
|
||||
# Keep current names, rather than matching a nickname after a rename.
|
||||
db.execute(
|
||||
"DELETE FROM member_names WHERE scope=? AND user_id=?", (scope, user_id)
|
||||
)
|
||||
db.executemany(
|
||||
"INSERT INTO member_names VALUES (?,?,?)",
|
||||
[(scope, user_id, name) for name in names],
|
||||
)
|
||||
|
||||
await self._run(write)
|
||||
|
||||
async def member_names(self, scope):
|
||||
return await self._run(
|
||||
lambda db: [
|
||||
r[0]
|
||||
for r in db.execute(
|
||||
"SELECT name FROM member_names WHERE scope=? UNION "
|
||||
"SELECT name FROM member_aliases WHERE scope=?",
|
||||
(scope, scope),
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
async def member(self, scope, value):
|
||||
def read(db):
|
||||
rows = db.execute(
|
||||
"SELECT * FROM members WHERE scope=? AND (user_id=? OR nickname=?)",
|
||||
(scope, value, value),
|
||||
"SELECT DISTINCT m.* FROM members m LEFT JOIN member_names n "
|
||||
"ON m.scope=n.scope AND m.user_id=n.user_id "
|
||||
"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("本群有重名用户,请使用真实 @ 或 /tx identity 获取的用户标识。")
|
||||
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")
|
||||
|
||||
+216
-23
@@ -7,47 +7,240 @@ from .delivery import OFFICIAL, field
|
||||
MARKUP = re.compile(
|
||||
r"<qqbot-at-user\s+id=[\"\']([^\"\']+)[\"\']\s*/>|<@!?([^>]+)>|\[CQ:at,qq=([^,\]]+)[^\]]*\]"
|
||||
)
|
||||
TEXT_AT = re.compile(r"(?<![\w@])@([^\s@]+)")
|
||||
VALID_ID = re.compile(r"[A-Za-z0-9_-]{1,128}\Z")
|
||||
COMMAND = re.compile(r"(?:^|\s)/?(?:tx|提醒|remind)(?=\s|$)", re.I)
|
||||
|
||||
|
||||
async def resolve_target(event, args, store, scope):
|
||||
sender = str(event.get_sender_id())
|
||||
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):
|
||||
return list(
|
||||
dict.fromkeys(
|
||||
str(field(member, key, "") or "").strip()
|
||||
for key in ("card", "nick", "nickname", "username", "name")
|
||||
if field(member, key)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def mention_data(event):
|
||||
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 = {}
|
||||
names = {}
|
||||
bot_names = set()
|
||||
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:
|
||||
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):
|
||||
bot_ids.add(user)
|
||||
elif user:
|
||||
trusted[user] = str(field(mention, "username", "") or "")
|
||||
bot_ids.update({user, generic_id, member_id} - {""})
|
||||
bot_names.update(member_names(mention))
|
||||
elif user and user not in bot_ids:
|
||||
values = member_names(mention)
|
||||
names.setdefault(user, []).extend(values)
|
||||
trusted[user] = trusted.get(user) or next(iter(values), "")
|
||||
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":
|
||||
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 "")
|
||||
names.setdefault(user, []).extend(member_names(component))
|
||||
elif user in bot_ids:
|
||||
bot_names.update(member_names(component))
|
||||
return trusted, names, aliases, bot_ids, bot_names, payload_mentions, sdk_mentions
|
||||
|
||||
|
||||
async def observe_members(event, store, scope):
|
||||
"""Learn names only from the sender and native mentions supplied by QQ."""
|
||||
trusted, names, *_ = mention_data(event)
|
||||
raw = event.message_obj.raw_message
|
||||
raw_data = field(raw, "raw_data", raw)
|
||||
sender = str(event.get_sender_id())
|
||||
sender_names = []
|
||||
for source in (raw_data, raw):
|
||||
sender_names.extend(member_names(field(source, "member", {})))
|
||||
sender_names.extend(member_names(field(source, "sender", {})))
|
||||
sender_names.extend(member_names(field(source, "author", {})))
|
||||
display = str(event.get_sender_name() or "")
|
||||
if display and display != sender:
|
||||
sender_names.append(display)
|
||||
rows = [(user, name, names.get(user, [])) for user, name in trusted.items() if user != sender]
|
||||
rows.append((sender, next(iter(sender_names), ""), sender_names))
|
||||
await store.observe_members(scope, rows)
|
||||
|
||||
|
||||
def text_mentions(names):
|
||||
# Longest known name first supports spaces in nicknames without consuming
|
||||
# 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'(?<![A-Za-z0-9_.@@])[@@](?:"([^"\n]+)"|“([^”\n]+)”|'
|
||||
+ (rf"({known})(?=\s|$)|" if known else "")
|
||||
+ r"([^\s@]+))"
|
||||
)
|
||||
return pattern
|
||||
|
||||
|
||||
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
|
||||
)
|
||||
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)
|
||||
textual = list(TEXT_AT.finditer(args))
|
||||
for match in textual:
|
||||
value = match.group(1)
|
||||
known_names = await store.member_names(scope)
|
||||
pattern = text_mentions(
|
||||
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.
|
||||
text = message_text(event)
|
||||
command = COMMAND.search(text)
|
||||
if command:
|
||||
prefix = MARKUP.sub(" ", text[: command.start()])
|
||||
textual.extend(pattern.finditer(prefix))
|
||||
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", "全体成员"}:
|
||||
raise ValueError("一次提醒只能指定一个成员,不能 @ 全体成员。")
|
||||
names = [user for user, name in trusted.items() if name and name == value]
|
||||
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)
|
||||
args = TEXT_AT.sub(" ", args).strip()
|
||||
matching = [user for user in trusted if value in names.get(user, [])]
|
||||
if len(matching) > 1:
|
||||
raise ValueError("被 @ 成员重名,请在 QQ 的 @ 群成员列表中只选中一个人。")
|
||||
# A real QQ selection identifies the member even when cached names collide.
|
||||
member = None if matching else await store.member(scope, value)
|
||||
if (
|
||||
not matching
|
||||
and not member
|
||||
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}”,未创建提醒。"
|
||||
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:
|
||||
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(
|
||||
"收到 @ 成员信息,但无法识别提醒对象,未创建提醒。"
|
||||
"QQ 没有提供完整成员标识。可让对方 /tx name 昵称 登记自己,再 /tx to 昵称 时间 内容。"
|
||||
)
|
||||
if len(candidates) > 1:
|
||||
raise ValueError("一次提醒只能指定一个成员。")
|
||||
target = candidates[0] if candidates else sender
|
||||
@@ -60,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(
|
||||
"无法确认该用户的本群 OpenID。请真实 @ 对方;若官方未提供成员标识,"
|
||||
"让对方先在本群 @ 机器人发送 /tx identity,再用 @用户标识。普通 QQ 号不能转换成 OpenID。"
|
||||
"无法识别本群提醒对象,未创建提醒。请让对方 /tx name 昵称 登记自己,"
|
||||
"再使用 /tx to 昵称 时间 内容。无需复制 ID。"
|
||||
)
|
||||
elif event.get_platform_name() == "aiocqhttp":
|
||||
try:
|
||||
@@ -70,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
|
||||
@@ -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]
|
||||
@@ -0,0 +1,211 @@
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from test_reminders import plugin as plugin
|
||||
from test_reminders import record
|
||||
|
||||
from services.storage import ReminderStore
|
||||
from services.targets import observe_members, resolve_target
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform_name", ["qq_official", "qq_official_webhook"])
|
||||
@pytest.mark.parametrize("name", ["小明", "群名片", "小 明", '"小 明"', "“小 明”"])
|
||||
async def test_nickname_creation_persists_and_mentions_other_on_delivery(
|
||||
plugin, plugin_class, event_factory, platform_name, name
|
||||
):
|
||||
instance, platform = plugin
|
||||
platform.meta = lambda: SimpleNamespace(id="platform_1", name=platform_name)
|
||||
# Learn a member's actual group name and username from a received message.
|
||||
member_event = event_factory(
|
||||
"你好",
|
||||
user="target_member",
|
||||
platform=platform_name,
|
||||
raw=SimpleNamespace(
|
||||
group_openid="group_1",
|
||||
author=SimpleNamespace(member_openid="target_member"),
|
||||
raw_data={
|
||||
"author": {"member_openid": "target_member", "username": "小明"},
|
||||
"member": {"nick": "群名片", "card": "小 明"},
|
||||
},
|
||||
),
|
||||
)
|
||||
await instance.observe_member(member_event)
|
||||
# The directory must survive plugin updates/restarts before creation too.
|
||||
await instance.store.initialize()
|
||||
event = event_factory(f"/tx 1分钟 开会 @{name}", platform=platform_name)
|
||||
await instance.tx(event)
|
||||
rows = await instance.store.list(record()["scope"])
|
||||
assert len(rows) == 1
|
||||
rem = rows[0]
|
||||
assert rem["target_id"] == "target_member" and rem["creator_id"] == "user_1"
|
||||
assert rem["content"] == "开会"
|
||||
assert "target_member" not in event.replies[0]
|
||||
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()
|
||||
body = platform.get_client().api.post_group_message.call_args.kwargs["markdown"]["content"]
|
||||
assert body.startswith('<qqbot-at-user id="target_member" />')
|
||||
assert body.count("qqbot-at-user") == 1 and 'id="user_1"' not in body
|
||||
finally:
|
||||
await restored.terminate()
|
||||
|
||||
|
||||
async def test_native_selection_wins_over_duplicate_cached_nickname(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
scope = record()["scope"]
|
||||
await instance.store.observe(scope, "another_member", "小明")
|
||||
event = event_factory(
|
||||
"/tx 1分钟 开会 @小明",
|
||||
raw={
|
||||
"group_openid": "group_1",
|
||||
"mentions": [
|
||||
{"id": "generic_target", "member_openid": "target_member", "username": "小明"}
|
||||
],
|
||||
},
|
||||
)
|
||||
await instance.tx(event)
|
||||
assert (await instance.store.list(scope))[0]["target_id"] == "target_member"
|
||||
|
||||
|
||||
async def test_mentions_are_learned_even_if_member_has_never_spoken(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
event = event_factory(
|
||||
"普通消息",
|
||||
raw=SimpleNamespace(
|
||||
group_openid="group_1",
|
||||
mentions=[SimpleNamespace(member_openid=None)],
|
||||
raw_data={
|
||||
"mentions": [
|
||||
{
|
||||
"id": "generic_target",
|
||||
"member_openid": "target_member",
|
||||
"username": "小明",
|
||||
"nickname": "群名片",
|
||||
}
|
||||
]
|
||||
},
|
||||
),
|
||||
)
|
||||
await instance.observe_member(event)
|
||||
assert not event.stopped
|
||||
for name in ("小明", "群名片"):
|
||||
_, target, _ = await resolve_target(
|
||||
event_factory(), f"1分钟 开会 @{name}", instance.store, record()["scope"]
|
||||
)
|
||||
assert target == "target_member"
|
||||
|
||||
|
||||
async def test_unknown_or_cross_group_nickname_never_creates_self_reminder(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
await instance.store.observe("another_scope", "target_member", "小明")
|
||||
event = event_factory("/tx 1分钟 开会 @小明")
|
||||
await instance.tx(event)
|
||||
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"])
|
||||
|
||||
|
||||
async def test_rename_removes_old_alias_and_empty_payload_keeps_current_names(
|
||||
tmp_path, event_factory
|
||||
):
|
||||
store = ReminderStore(tmp_path / "members.db")
|
||||
await store.initialize()
|
||||
scope = record()["scope"]
|
||||
await store.observe(scope, "target_member", "旧名", ["旧名片"])
|
||||
await store.observe(scope, "target_member", "新名", ["新名片"])
|
||||
await store.observe(scope, "target_member", "")
|
||||
await store.initialize()
|
||||
assert await store.member(scope, "旧名") is None
|
||||
assert await store.member(scope, "旧名片") is None
|
||||
assert (await store.member(scope, "新名片"))["user_id"] == "target_member"
|
||||
|
||||
|
||||
async def test_existing_database_nicknames_upgrade_without_losing_tasks(tmp_path):
|
||||
store = ReminderStore(tmp_path / "members.db")
|
||||
await store.initialize()
|
||||
reminder_id = await store.add(record(), 10)
|
||||
await store._run(
|
||||
lambda db: db.execute(
|
||||
"INSERT INTO members VALUES (?,?,?,?)",
|
||||
(record()["scope"], "target_member", "原昵称", time.time()),
|
||||
)
|
||||
)
|
||||
await store.initialize()
|
||||
assert (await store.member(record()["scope"], "原昵称"))["user_id"] == "target_member"
|
||||
assert (await store.get(reminder_id, record()["scope"]))["content"] == "吃饭"
|
||||
|
||||
|
||||
async def test_bot_display_name_is_not_a_recipient(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
event = event_factory(
|
||||
"/tx 1分钟 开会 @小明 @栗子",
|
||||
raw={
|
||||
"group_openid": "group_1",
|
||||
"mentions": [
|
||||
{"id": "bot_id", "is_you": True, "username": "栗子"},
|
||||
{"id": "target_member", "username": "小明"},
|
||||
],
|
||||
},
|
||||
)
|
||||
await instance.tx(event)
|
||||
assert (await instance.store.list(record()["scope"]))[0]["target_id"] == "target_member"
|
||||
|
||||
|
||||
async def test_at_component_name_is_learned(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
event = 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 发邮件"
|
||||
@@ -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('<qqbot-at-user id="target_member" />')
|
||||
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")
|
||||
@@ -0,0 +1,193 @@
|
||||
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 "<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):
|
||||
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"
|
||||
@@ -15,7 +15,7 @@ from services.storage import ReminderStore
|
||||
async def passive_plugin(plugin_class, platform_factory):
|
||||
platform = platform_factory()
|
||||
context = SimpleNamespace(platform_manager=SimpleNamespace(platform_insts=[platform]))
|
||||
instance = plugin_class(context, {"check_interval_seconds": 999})
|
||||
instance = plugin_class(context, {"check_interval_seconds": 999, "proactive_reminders": False})
|
||||
await instance.store.initialize()
|
||||
instance._ready = True
|
||||
assert instance.delivery_mode == "passive"
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
import asyncio
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
from test_reminders import record
|
||||
|
||||
from services.storage import ReminderStore
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def official_plugin(plugin_class, platform_factory):
|
||||
platform = platform_factory()
|
||||
instance = plugin_class(
|
||||
SimpleNamespace(platform_manager=SimpleNamespace(platform_insts=[platform])),
|
||||
{"check_interval_seconds": 999, "official_delivery_mode": "passive"},
|
||||
)
|
||||
await instance.store.initialize()
|
||||
instance._ready = True
|
||||
await instance._attach_platforms()
|
||||
instance.initialize = AsyncMock()
|
||||
yield instance, platform
|
||||
await instance.terminate()
|
||||
|
||||
|
||||
def lifecycle(event_id="join_1", timestamp=None, destination="group_1"):
|
||||
return SimpleNamespace(
|
||||
group_openid=destination,
|
||||
event_id=event_id,
|
||||
timestamp=time.time() if timestamp is None else timestamp,
|
||||
)
|
||||
|
||||
|
||||
async def test_default_and_upgrade_use_proactive_without_reply_context(official_plugin):
|
||||
instance, platform = official_plugin
|
||||
assert instance.delivery_mode == "proactive"
|
||||
rem_id = await instance.store.add(record(), 10)
|
||||
await instance._check_due()
|
||||
sent = platform.get_client().api.post_group_message.call_args.kwargs
|
||||
assert "msg_id" not in sent and "event_id" not in sent
|
||||
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "done"
|
||||
|
||||
|
||||
async def test_first_command_guidance_once_per_group_persisted(official_plugin, event_factory):
|
||||
instance, _ = official_plugin
|
||||
events = [event_factory("/tx help"), event_factory("/tx list", user="other")]
|
||||
for event in events:
|
||||
await instance.tx(event)
|
||||
assert "确认已开启" in events[0].replies[0]
|
||||
assert "确认已开启" not in events[1].replies[0]
|
||||
other = event_factory("/tx list", group="other")
|
||||
await instance.tx(other)
|
||||
assert "确认已开启" in other.replies[0]
|
||||
reopened = ReminderStore(instance.store.path)
|
||||
assert not await reopened.claim_notice("platform_1", "group_1")
|
||||
assert await reopened.claim_notice("platform_2", "group_1")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["qq_official", "qq_official_webhook"])
|
||||
async def test_join_uses_event_reply_and_deduplicates(official_plugin, event_factory, name):
|
||||
instance, platform = official_plugin
|
||||
platform.meta = lambda: SimpleNamespace(id="platform_1", name=name)
|
||||
client = platform.get_client()
|
||||
event = lifecycle()
|
||||
await client.on_group_add_robot(event)
|
||||
await client.on_group_add_robot(event)
|
||||
assert client.api.post_group_message.await_count == 1
|
||||
sent = client.api.post_group_message.call_args.kwargs
|
||||
assert sent["event_id"] == "join_1" and "msg_id" not in sent
|
||||
assert "群主或管理员" in sent["content"]
|
||||
command = event_factory("/tx list")
|
||||
await instance.tx(command)
|
||||
assert "确认已开启" not in command.replies[0]
|
||||
|
||||
|
||||
async def test_failed_join_falls_back_to_first_command(official_plugin, event_factory):
|
||||
instance, platform = official_plugin
|
||||
platform.get_client().api.post_group_message.side_effect = RuntimeError("event expired")
|
||||
await platform.get_client().on_group_add_robot(lifecycle())
|
||||
command = event_factory("/tx list")
|
||||
await instance.tx(command)
|
||||
assert "确认已开启" in command.replies[0]
|
||||
|
||||
|
||||
async def test_failed_command_notice_is_not_marked_sent(official_plugin, event_factory):
|
||||
instance, _ = official_plugin
|
||||
command = event_factory()
|
||||
command.send = AsyncMock(side_effect=RuntimeError("network error"))
|
||||
with pytest.raises(RuntimeError):
|
||||
await instance._reply(command, "test")
|
||||
assert (await instance.store.permission("platform_1", "group_1"))["notified"] == 0
|
||||
retry = event_factory("/tx list")
|
||||
await instance.tx(retry)
|
||||
assert "确认已开启" in retry.replies[0]
|
||||
|
||||
|
||||
async def test_granted_state_skips_first_use_notice_and_stale_join(official_plugin, event_factory):
|
||||
instance, platform = official_plugin
|
||||
now = time.time()
|
||||
await platform.get_client().on_group_msg_receive(lifecycle("receive", now))
|
||||
await platform.get_client().on_group_add_robot(lifecycle("old_join", now - 10))
|
||||
command = event_factory("/tx list")
|
||||
await instance.tx(command)
|
||||
assert "确认已开启" not in command.replies[0]
|
||||
platform.get_client().api.post_group_message.assert_not_awaited()
|
||||
assert (await instance.store.permission("platform_1", "group_1"))["state"] == "granted"
|
||||
|
||||
|
||||
async def test_permission_error_preserved_then_receive_event_wakes_delivery(official_plugin):
|
||||
instance, platform = official_plugin
|
||||
api = platform.get_client().api
|
||||
api.post_group_message.side_effect = RuntimeError("主动消息失败, 无权限")
|
||||
rem_id = await instance.store.add(record(), 10)
|
||||
await instance._check_due()
|
||||
for _ in range(4):
|
||||
await instance._check_due()
|
||||
rem = await instance.store.get(rem_id, record()["scope"])
|
||||
assert rem["status"] == "active" and rem["failure_count"] == 0
|
||||
assert "等待主动消息权限" in instance._format(rem)
|
||||
assert rem["retry_at"] > time.time() + 290
|
||||
assert api.post_group_message.await_count == 1
|
||||
api.post_group_message.side_effect = None
|
||||
await platform.get_client().on_group_msg_receive(lifecycle("allow"))
|
||||
assert instance._wake.is_set()
|
||||
await instance._check_due()
|
||||
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "done"
|
||||
|
||||
|
||||
async def test_reject_holds_tasks_and_permission_check_releases(official_plugin, event_factory):
|
||||
instance, platform = official_plugin
|
||||
await platform.get_client().on_group_msg_reject(lifecycle("reject"))
|
||||
rem_id = await instance.store.add(record(), 10)
|
||||
await instance._check_due()
|
||||
platform.get_client().api.post_group_message.assert_not_awaited()
|
||||
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "active"
|
||||
command = event_factory("/tx permission check")
|
||||
await instance.tx(command)
|
||||
assert command.stopped
|
||||
assert (await instance.store.permission("platform_1", "group_1"))["state"] == "granted"
|
||||
sent = platform.get_client().api.post_group_message.call_args.kwargs
|
||||
assert "msg_id" not in sent and "event_id" not in sent
|
||||
await instance._check_due()
|
||||
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "done"
|
||||
|
||||
|
||||
async def test_permission_check_failure_is_a_passive_reply(official_plugin, event_factory):
|
||||
instance, platform = official_plugin
|
||||
platform.get_client().api.post_group_message.side_effect = RuntimeError("主动消息失败, 无权限")
|
||||
command = event_factory("/tx permission check")
|
||||
await instance.tx(command)
|
||||
assert "验证失败" in command.replies[0]
|
||||
assert command.replies[0].count("确认已开启") == 1
|
||||
assert (await instance.store.permission("platform_1", "group_1"))["state"] == "error"
|
||||
|
||||
|
||||
async def test_check_without_message_id_is_not_success(official_plugin, event_factory):
|
||||
instance, platform = official_plugin
|
||||
platform.get_client().api.post_group_message.return_value = {}
|
||||
command = event_factory("/tx permission check")
|
||||
await instance.tx(command)
|
||||
assert "未返回消息 ID" in command.replies[0]
|
||||
assert (await instance.store.permission("platform_1", "group_1"))["state"] != "granted"
|
||||
|
||||
|
||||
async def test_member_cannot_set_authorized_state_by_text(official_plugin, event_factory):
|
||||
instance, _ = official_plugin
|
||||
command = event_factory("/tx permission 已开启")
|
||||
await instance.tx(command)
|
||||
assert "用法" in command.replies[0]
|
||||
assert (await instance.store.permission("platform_1", "group_1"))["state"] == "unknown"
|
||||
|
||||
|
||||
async def test_bridge_preserves_callbacks_and_overlapping_unload(official_plugin):
|
||||
instance, platform = official_plugin
|
||||
from reminder_plugin_test.services.permissions import PermissionBridge
|
||||
|
||||
await instance.terminate()
|
||||
client = platform.get_client()
|
||||
original = AsyncMock()
|
||||
client.on_group_add_robot = original
|
||||
handlers = [AsyncMock(), AsyncMock()]
|
||||
first = PermissionBridge(platform, handlers[0])
|
||||
second = PermissionBridge(platform, handlers[1])
|
||||
first.install()
|
||||
second.install()
|
||||
await first.close()
|
||||
await client.on_group_add_robot(lifecycle())
|
||||
handlers[0].assert_not_awaited()
|
||||
handlers[1].assert_awaited_once()
|
||||
original.assert_awaited_once()
|
||||
await second.close()
|
||||
assert client.on_group_add_robot is original
|
||||
assert not hasattr(client, "on_group_msg_receive")
|
||||
|
||||
|
||||
async def test_bridge_close_finishes_pending_event(official_plugin):
|
||||
instance, platform = official_plugin
|
||||
client = platform.get_client()
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def send(**kwargs):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return {"id": "sent"}
|
||||
|
||||
client.api.post_group_message.side_effect = send
|
||||
event_task = asyncio.create_task(client.on_group_add_robot(lifecycle()))
|
||||
await asyncio.wait_for(entered.wait(), 1)
|
||||
closing = asyncio.create_task(instance.terminate())
|
||||
await asyncio.sleep(0)
|
||||
assert not closing.done()
|
||||
release.set()
|
||||
await asyncio.wait_for(asyncio.gather(closing, event_task), 1)
|
||||
assert (await instance.store.permission("platform_1", "group_1"))["notified"] == 1
|
||||
|
||||
|
||||
async def test_concurrent_first_commands_emit_one_notice(official_plugin, event_factory):
|
||||
instance, _ = official_plugin
|
||||
commands = [event_factory("/tx list", user=f"user_{i}") for i in range(8)]
|
||||
await asyncio.gather(*(instance.tx(event) for event in commands))
|
||||
assert sum("确认已开启" in event.replies[0] for event in commands) == 1
|
||||
|
||||
|
||||
async def test_repeated_permission_failure_does_not_repeat_notice(official_plugin, event_factory):
|
||||
instance, platform = official_plugin
|
||||
platform.get_client().api.post_group_message.side_effect = RuntimeError("主动消息失败, 无权限")
|
||||
rem_id = await instance.store.add(record(), 10)
|
||||
await instance._check_due()
|
||||
first = event_factory("/tx list")
|
||||
await instance.tx(first)
|
||||
assert "确认已开启" in first.replies[0]
|
||||
await instance.store.resume(record()["scope"], "user_1", rem_id, 10)
|
||||
await instance._check_due()
|
||||
second = event_factory("/tx list")
|
||||
await instance.tx(second)
|
||||
assert "确认已开启" not in second.replies[0]
|
||||
rem = await instance.store.get(rem_id, record()["scope"])
|
||||
assert rem["status"] == "active" and rem["failure_count"] == 0
|
||||
|
||||
|
||||
async def test_del_and_rejoin_reset_guidance(official_plugin, event_factory):
|
||||
instance, platform = official_plugin
|
||||
client = platform.get_client()
|
||||
stamp = time.time()
|
||||
await client.on_group_add_robot(lifecycle("join", stamp))
|
||||
await client.on_group_del_robot(lifecycle("del", stamp + 1))
|
||||
rem_id = await instance.store.add(record(), 10)
|
||||
await instance._check_due()
|
||||
assert client.api.post_group_message.await_count == 1
|
||||
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "active"
|
||||
await client.on_group_add_robot(lifecycle("rejoin", stamp + 2))
|
||||
assert client.api.post_group_message.await_count == 2
|
||||
|
||||
|
||||
async def test_new_and_removed_platforms_attach_and_restore(official_plugin, platform_factory):
|
||||
instance, _ = official_plugin
|
||||
newcomer = platform_factory("qq_official_webhook")
|
||||
original = AsyncMock()
|
||||
newcomer.get_client().on_group_msg_receive = original
|
||||
instance.context.platform_manager.platform_insts.append(newcomer)
|
||||
await instance._attach_platforms()
|
||||
await newcomer.get_client().on_group_msg_receive(lifecycle("receive"))
|
||||
original.assert_awaited_once()
|
||||
instance.context.platform_manager.platform_insts.remove(newcomer)
|
||||
await instance._attach_platforms()
|
||||
assert newcomer.get_client().on_group_msg_receive is original
|
||||
assert not hasattr(newcomer.get_client(), "on_group_add_robot")
|
||||
@@ -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]
|
||||
@@ -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):
|
||||
@@ -127,7 +128,7 @@ async def test_member_and_mentions(tmp_path, event_factory):
|
||||
await resolve_target(event, '1小时 <qqbot-at-user id="opaque_new" /> 开会', 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):
|
||||
@@ -151,9 +152,7 @@ async def test_ambiguous_multiple_all_and_private(tmp_path, event_factory):
|
||||
async def plugin(plugin_class, platform_factory):
|
||||
platform = platform_factory()
|
||||
context = SimpleNamespace(platform_manager=SimpleNamespace(platform_insts=[platform]))
|
||||
instance = plugin_class(
|
||||
context, {"check_interval_seconds": 999, "official_delivery_mode": "proactive"}
|
||||
)
|
||||
instance = plugin_class(context, {"check_interval_seconds": 999})
|
||||
await instance.store.initialize()
|
||||
# Control scans explicitly in integration tests; lifecycle is tested separately.
|
||||
instance._ready = True
|
||||
@@ -179,7 +178,7 @@ async def test_due_success_once_and_recurring(plugin):
|
||||
async def test_failures_retry_then_cancel_and_history(plugin, event_factory):
|
||||
instance, platform = plugin
|
||||
instance.retry_seconds = 0
|
||||
platform.get_client().api.post_group_message.side_effect = RuntimeError("没有主动消息权限")
|
||||
platform.get_client().api.post_group_message.side_effect = RuntimeError("服务暂时不可用")
|
||||
rem_id = await instance.store.add(record(), 10)
|
||||
for count in range(1, 4):
|
||||
await instance._check_due()
|
||||
@@ -188,7 +187,7 @@ async def test_failures_retry_then_cancel_and_history(plugin, event_factory):
|
||||
assert rem["status"] == ("cancelled" if count == 3 else "active")
|
||||
event = event_factory("/tx history")
|
||||
await instance.tx(event)
|
||||
assert "没有主动消息权限" in event.replies[0]
|
||||
assert "服务暂时不可用" in event.replies[0]
|
||||
assert "已取消" in event.replies[0]
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user