Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
800f267b66 | ||
|
|
9c5b87772f | ||
|
|
f89aadb5da | ||
|
|
61ed965d38 | ||
|
|
d4a8177acf |
No files matched your search
@@ -12,7 +12,7 @@
|
|||||||
https://github.com/itxiaohui66/astrbot_plugin_tixing
|
https://github.com/itxiaohui66/astrbot_plugin_tixing
|
||||||
```
|
```
|
||||||
|
|
||||||
也可以从 [GitHub Releases](https://github.com/itxiaohui66/astrbot_plugin_tixing/releases/latest) 下载 `astrbot_plugin_tixing-v1.2.0.zip`,在插件页上传安装。手动安装时,把 ZIP 中的 `astrbot_plugin_tixing` 文件夹解压到 AstrBot 的 `data/plugins/` 下,然后重启或重载插件。运行文件 `main.py`、`metadata.yaml` 和 `_conf_schema.json` 必须直接位于该插件文件夹中。
|
也可以从 [GitHub Releases](https://github.com/itxiaohui66/astrbot_plugin_tixing/releases/latest) 下载 `astrbot_plugin_tixing-v1.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` 查看帮助。
|
安装时 AstrBot 会读取 `requirements.txt` 安装 `tzdata`。配置默认采用北京时间 `Asia/Shanghai`;每人在每个群或私聊最多 10 个活跃提醒,每 30 秒扫描一次。确认机器人已经接入 QQ 官方适配器,群内使用 `@机器人 /tx help` 查看帮助。
|
||||||
|
|
||||||
@@ -49,6 +49,8 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
|
|||||||
/tx 每周一 9:00 周报
|
/tx 每周一 9:00 周报
|
||||||
/tx 每周7 20:00 总结
|
/tx 每周7 20:00 总结
|
||||||
/tx 1小时 开会 @某人
|
/tx 1小时 开会 @某人
|
||||||
|
/tx to xh 1分钟 测试
|
||||||
|
/tx to "小 明" 每天9:00 打卡
|
||||||
```
|
```
|
||||||
|
|
||||||
时间和内容之间要有空格。内容可以包含空格、换行,默认最多 1000 个字符。单次 `HH:MM` 表示今天该时刻,已经过去则提示改用未来时间;每天和每周自动计算下一次。提醒间隔必须大于 0,小时范围 0–23,分钟范围 0–59。
|
时间和内容之间要有空格。内容可以包含空格、换行,默认最多 1000 个字符。单次 `HH:MM` 表示今天该时刻,已经过去则提示改用未来时间;每天和每周自动计算下一次。提醒间隔必须大于 0,小时范围 0–23,分钟范围 0–59。
|
||||||
@@ -62,6 +64,9 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
|
|||||||
| 命令 | 行为 |
|
| 命令 | 行为 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `/tx help` | 全部帮助 |
|
| `/tx help` | 全部帮助 |
|
||||||
|
| `/tx to 昵称 时间 内容` / `/tx 给 昵称 时间 内容` | 按名字提醒本群已识别的成员;不用 @ 对方或填写 ID |
|
||||||
|
| `/tx name 昵称` / `/tx 昵称 昵称` / `/tx 登记 昵称` | 给自己登记一个本群唯一的提醒昵称,每人一个,可再次登记修改 |
|
||||||
|
| `/tx name` | 查看自己登记的提醒昵称 |
|
||||||
| `/tx list [页码]` / `/cktx` / `/提醒列表` | 当前会话中自己创建的活跃提醒 |
|
| `/tx list [页码]` / `/cktx` / `/提醒列表` | 当前会话中自己创建的活跃提醒 |
|
||||||
| `/tx history [页码]` | 自己的全部记录,包括完成、取消、失败 |
|
| `/tx history [页码]` | 自己的全部记录,包括完成、取消、失败 |
|
||||||
| `/tx detail 编号` | 查看全文、时间、状态、失败次数和最近错误 |
|
| `/tx detail 编号` | 查看全文、时间、状态、失败次数和最近错误 |
|
||||||
@@ -84,13 +89,41 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
|
|||||||
|
|
||||||
## 官方 QQ 的对象和发送权限
|
## 官方 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
|
```text
|
||||||
/tx 30分钟 开会 @对方的用户标识
|
@机器人 /tx name xh
|
||||||
```
|
```
|
||||||
|
|
||||||
插件会记住本群里机器人实际收到的成员消息,名字唯一且官方提供昵称时也支持 `@昵称`。不同群里的成员记录不会混用,重名时要求明确标识。OneBot 模式会查询目标是否是本群成员。私聊只能提醒自己。
|
机器人从**登记者这条消息的发送者 ID** 自动绑定名字,发起提醒的人无需填写 ID。之后其他人发送:
|
||||||
|
|
||||||
|
```text
|
||||||
|
@机器人 /tx to xh 1分钟 测试
|
||||||
|
```
|
||||||
|
|
||||||
|
`to` 后直接写名字,不从 QQ 的 @ 列表选择对方,这样名字不会被 QQ 删除。带空格的名字用双引号,例如 `/tx name "小 明"`、`/tx to "小 明" 1分钟 测试`。昵称登记仅能登记自己,不能用自己的消息登记别人的 ID。已被其他已识别成员使用的名字会拒绝登记;重名时选择不同提醒昵称。登记按平台、群保存,重载或收到新的 QQ 昵称后仍保留。更改登记不会改变已有任务保存的接收者 ID。
|
||||||
|
|
||||||
|
显式 `to` 的对象未识别、与真实 @ 冲突或无法解析时会拒绝创建,绝不改成提醒自己。原来的 `/tx 时间 内容` 仍用于提醒自己;若 QQ 已完全删除另一个 @,插件无法区分这条命令原本是否要提醒他人,所以确认回复会明确警示“未识别到其他成员”,并提示取消后用 `to` 重建。
|
||||||
|
|
||||||
|
腾讯公开文档中的 [群成员列表接口](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` 回复管理员开启说明;若事件缺失、发送失败或插件是后来才安装的,则在首次提醒命令回复中附加说明。提示按平台和群持久化,成功提示后不会在每次命令中重复。
|
v1.2.0 默认采用 **主动发送**。新群的 `GROUP_ADD_ROBOT` 事件到来时,插件使用该真实事件的 `event_id` 回复管理员开启说明;若事件缺失、发送失败或插件是后来才安装的,则在首次提醒命令回复中附加说明。提示按平台和群持久化,成功提示后不会在每次命令中重复。
|
||||||
|
|
||||||
@@ -102,7 +135,15 @@ v1.2.0 默认采用 **主动发送**。新群的 `GROUP_ADD_ROBOT` 事件到来
|
|||||||
|
|
||||||
如需使用被动回复,可关闭 `proactive_reminders`。这时只有存在有效的近期用户消息和回复额度才投递,超出窗口则等待下一条同会话消息。群、频道、频道私信保守采用 4 分钟窗口,C2C 59 分钟;每条消息最多投递 3 条提醒,给命令回复和其他插件预留额度。回复上下文按平台、场景和目标隔离;重复事件不会刷新有效期或额度,受限时不会切换为主动发送。被动模式无法保证长时间后准点提醒。
|
如需使用被动回复,可关闭 `proactive_reminders`。这时只有存在有效的近期用户消息和回复额度才投递,超出窗口则等待下一条同会话消息。群、频道、频道私信保守采用 4 分钟窗口,C2C 59 分钟;每条消息最多投递 3 条提醒,给命令回复和其他插件预留额度。回复上下文按平台、场景和目标隔离;重复事件不会刷新有效期或额度,受限时不会切换为主动发送。被动模式无法保证长时间后准点提醒。
|
||||||
|
|
||||||
QQ 普通群使用 `<qqbot-at-user id="OpenID" />` 实现真正 @,频道使用频道成员 ID。群、C2C、频道、频道私信分别走对应 SDK 接口。插件自己的到期提醒使用普通文本,不要求 Markdown 模板;命令回复仍由 AstrBot 当前事件的配置发送。
|
v1.2.1 修复官方群到期提醒把 `<qqbot-at-user id="OpenID" />` 原样显示的问题:群提醒改用 `msg_type=2`,将原生 @ 标签放入 `markdown.content`,由 QQ 渲染为可点击的 @ 用户。主动和被动投递均使用该格式,仍保留原本的发送权限和回复上下文。提醒内容中的 Markdown 标点作为普通文字显示,@ 标签单独放在正文开头。
|
||||||
|
|
||||||
|
默认使用原生 Markdown。如果 QQ 返回“不允许发送原生 markdown”等错误,任务显示“等待 Markdown 配置”,保留并每 5 分钟重试,不会改回显示长串标签的普通文本消息。原生 Markdown 权限与群管理员的主动消息开关是两项不同设置;需在机器人应用中开通原生 Markdown,或配置已有的获批 Markdown 模板。
|
||||||
|
|
||||||
|
使用模板时,在插件配置填写 `official_markdown_template_id`;模板正文应包含 `{{.content}}`,并将 `official_markdown_parameter` 设置为 `content`。如果模板的变量名是 `body`,则正文使用 `{{.body}}`,参数设置为 `body`。插件向该变量填入完整的 @ 标签、提醒内容及编号。开通能力或配置模板后,可 `/tx retry 编号` 立即重试。
|
||||||
|
|
||||||
|
解析被 @ 成员时,官方群优先使用该成员的本群 `member_openid`,并统一消息段和原始标签里的别名;频道仍使用频道成员 ID。未提供昵称时,提醒正文不会把创建者 OpenID 当作昵称。群、C2C、频道、频道私信分别走对应 SDK 接口;私聊不发送 @ 标签,OneBot 继续发送原生 `at` 消息段。命令回复仍由 AstrBot 当前事件的配置发送。
|
||||||
|
|
||||||
|
格式依据 [腾讯官方文本交互与 @ 协议](https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/server-inter/message/trans/text-chain.md) 和 [Markdown 消息协议](https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/server-inter/message/type/markdown.md)。客户端最终显示需在实际 QQ 环境确认。
|
||||||
|
|
||||||
旧数据库里的数字 QQ 号/群号无法自动换算为官方 OpenID,所以本次迁移的是功能,没有修改或直接导入旧数据库。更换 QQ 应用或 AstrBot 平台 ID 时,原 OpenID/路由可能失效,需要重建对应提醒。备份时停止 AstrBot 后复制整个 `data/plugin_data/astrbot_plugin_tixing/`。
|
旧数据库里的数字 QQ 号/群号无法自动换算为官方 OpenID,所以本次迁移的是功能,没有修改或直接导入旧数据库。更换 QQ 应用或 AstrBot 平台 ID 时,原 OpenID/路由可能失效,需要重建对应提醒。备份时停止 AstrBot 后复制整个 `data/plugin_data/astrbot_plugin_tixing/`。
|
||||||
|
|
||||||
@@ -113,6 +154,8 @@ QQ 普通群使用 `<qqbot-at-user id="OpenID" />` 实现真正 @,频道使用
|
|||||||
| 字段 | 默认值 | 说明 |
|
| 字段 | 默认值 | 说明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `proactive_reminders` | `true` | 默认到点主动投递并提示群权限;关闭后使用被动回复 |
|
| `proactive_reminders` | `true` | 默认到点主动投递并提示群权限;关闭后使用被动回复 |
|
||||||
|
| `official_markdown_template_id` | 空 | 官方群提醒默认原生 Markdown;应用不支持时填写已获批的模板 ID |
|
||||||
|
| `official_markdown_parameter` | `content` | 模板中接收完整提醒正文的变量名,未填模板时忽略 |
|
||||||
| `timezone` | `Asia/Shanghai` | IANA 时区 |
|
| `timezone` | `Asia/Shanghai` | IANA 时区 |
|
||||||
| `max_per_user` | `10` | 当前会话每人最多活跃任务 |
|
| `max_per_user` | `10` | 当前会话每人最多活跃任务 |
|
||||||
| `check_interval_seconds` | `30` | 扫描周期,最小 1 秒 |
|
| `check_interval_seconds` | `30` | 扫描周期,最小 1 秒 |
|
||||||
@@ -141,7 +184,7 @@ python tools/package.py
|
|||||||
1. 首次命令或入群时确认收到权限开启提示;管理员开启“允许机器人主动发送消息”后,`@机器人 /tx permission check` 确认主动验证成功。
|
1. 首次命令或入群时确认收到权限开启提示;管理员开启“允许机器人主动发送消息”后,`@机器人 /tx permission check` 确认主动验证成功。
|
||||||
2. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,到期收到真正 @ 的通知;`/tx history` 检查状态,失败时查看原因和日志。
|
2. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,到期收到真正 @ 的通知;`/tx history` 检查状态,失败时查看原因和日志。
|
||||||
3. `/tx 5分钟 重启测试`,重载插件后用 `/tx list` 确认仍在,再 `/tx cancel 编号` 确认取消。
|
3. `/tx 5分钟 重启测试`,重载插件后用 `/tx list` 确认仍在,再 `/tx cancel 编号` 确认取消。
|
||||||
4. 让另一成员先发送 `/tx identity`,测试本群的他人提醒。
|
4. 让另一成员发送 `@机器人 /tx name xh`,你发送 `@机器人 /tx to xh 1分钟 他人提醒测试`,确认创建回复中的提醒对象是 xh;到期只 @ 对方,不 @ 发起人。再验证重载后仍可按登记昵称提醒。若平台确实下发真实 @ 的成员 ID,再验证从 QQ 列表选择成员的旧语法。
|
||||||
5. `@机器人 /tx 6分钟 主动提醒测试`,期间不再 @机器人,确认到期仍收到提醒。若因权限不足显示等待,开好权限并再次验证;旧版已自动取消的任务需先 `/tx retry 编号` 恢复。
|
5. `@机器人 /tx 6分钟 主动提醒测试`,期间不再 @机器人,确认到期仍收到提醒。若因权限不足显示等待,开好权限并再次验证;旧版已自动取消的任务需先 `/tx retry 编号` 恢复。
|
||||||
|
|
||||||
## 来源
|
## 来源
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
{
|
{
|
||||||
"proactive_reminders": {"type": "bool", "description": "QQ 官方到点主动提醒", "hint": "默认开启;首次入群/使用提示管理员允许主动消息。关闭后使用有时效和额度限制的被动回复。v1.2 起替代旧 official_delivery_mode 配置。", "default": true},
|
"proactive_reminders": {"type": "bool", "description": "QQ 官方到点主动提醒", "hint": "默认开启;首次入群/使用提示管理员允许主动消息。关闭后使用有时效和额度限制的被动回复。v1.2 起替代旧 official_delivery_mode 配置。", "default": true},
|
||||||
|
"official_markdown_template_id": {"type": "string", "description": "官方群提醒 Markdown 模板 ID(可选)", "hint": "默认留空使用原生 Markdown,让 QQ 正确渲染 @。若应用不允许原生 Markdown,填入已获批的模板 ID,模板需使用 {{.content}} 等正文变量。", "default": ""},
|
||||||
|
"official_markdown_parameter": {"type": "string", "description": "提醒模板正文变量名", "hint": "填写模板中用于接收完整提醒正文的变量名,例如模板 {{.content}} 对应 content;未配置模板时忽略。", "default": "content"},
|
||||||
"timezone": {"type": "string", "description": "提醒时区", "hint": "IANA 时区名称,默认北京时间;修改只影响新建提醒。", "default": "Asia/Shanghai"},
|
"timezone": {"type": "string", "description": "提醒时区", "hint": "IANA 时区名称,默认北京时间;修改只影响新建提醒。", "default": "Asia/Shanghai"},
|
||||||
"max_per_user": {"type": "int", "description": "每人在每个群/私聊最多活跃提醒数", "default": 10},
|
"max_per_user": {"type": "int", "description": "每人在每个群/私聊最多活跃提醒数", "default": 10},
|
||||||
"check_interval_seconds": {"type": "int", "description": "到期扫描间隔(秒)", "default": 30},
|
"check_interval_seconds": {"type": "int", "description": "到期扫描间隔(秒)", "default": 30},
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from astrbot.api.star import Context, Star, StarTools
|
|||||||
|
|
||||||
from .services.delivery import (
|
from .services.delivery import (
|
||||||
OFFICIAL,
|
OFFICIAL,
|
||||||
|
MentionDeliveryError,
|
||||||
available,
|
available,
|
||||||
deliver,
|
deliver,
|
||||||
field,
|
field,
|
||||||
@@ -23,14 +24,23 @@ from .services.delivery import (
|
|||||||
reply_unavailable,
|
reply_unavailable,
|
||||||
route,
|
route,
|
||||||
)
|
)
|
||||||
|
from .services.diagnostics import VERSION, diagnose, identity
|
||||||
from .services.permissions import NOTICE, PermissionBridge
|
from .services.permissions import NOTICE, PermissionBridge
|
||||||
from .services.storage import ReminderStore, scope_key
|
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
|
from .services.time_parser import describe, next_occurrence, parse_time
|
||||||
|
|
||||||
HELP = """⏰ 栗子提醒
|
HELP = """⏰ 栗子提醒
|
||||||
/tx 30分钟 开会(也支持分钟后、小时、天、min/h/d)
|
/tx 30分钟 开会(也支持分钟后、小时、天、min/h/d)
|
||||||
/tx 1小时 开会 @某人
|
/tx 1小时 开会 @某人
|
||||||
|
/tx to xh 1分钟 测试(直接写名字,不用 @ 对方或填写 ID)
|
||||||
|
/tx name xh 登记自己的提醒昵称(对方在本群登记一次即可)
|
||||||
/tx 10:00 开会(今天)
|
/tx 10:00 开会(今天)
|
||||||
/tx 明天10:00 开会
|
/tx 明天10:00 开会
|
||||||
/tx 2026-12-31 20:00 跨年
|
/tx 2026-12-31 20:00 跨年
|
||||||
@@ -44,12 +54,16 @@ HELP = """⏰ 栗子提醒
|
|||||||
/tx retry 编号 恢复投递失败的提醒
|
/tx retry 编号 恢复投递失败的提醒
|
||||||
/tx identity 查看当前平台、群和用户标识
|
/tx identity 查看当前平台、群和用户标识
|
||||||
/tx status 查看提醒调度器状态
|
/tx status 查看提醒调度器状态
|
||||||
|
/tx diagnose 时间 内容 @对方 检查成员识别(不创建提醒)
|
||||||
|
/tx diagnose 编号 核对提醒保存的成员 ID
|
||||||
/tx permission 查看主动消息权限说明
|
/tx permission 查看主动消息权限说明
|
||||||
/tx permission check 发送主动消息验证权限
|
/tx permission check 发送主动消息验证权限
|
||||||
/cxzd 管理员重启提醒调度器
|
/cxzd 管理员重启提醒调度器
|
||||||
命令别名:/提醒、/remind
|
命令别名:/提醒、/remind
|
||||||
群内官方 QQ 需要 @机器人;时间按配置时区计算。
|
群内官方 QQ 需要 @机器人;时间按配置时区计算。
|
||||||
官方 QQ 提醒他人须使用本群 OpenID 或真实 @;普通 QQ 号不可转换。
|
QQ 有时不下发被 @ 成员的 ID,请优先 /tx to 昵称 时间 内容。
|
||||||
|
机器人从成员发言学习 ID;未认识的成员可自己 /tx name 昵称 登记,无需复制 ID。
|
||||||
|
平台提供完整真实 @ 时也支持;昵称带空格可用 /tx to "小 明" 1分钟 测试。
|
||||||
默认到点主动提醒;群主/管理员需开启“允许机器人主动发送消息”。
|
默认到点主动提醒;群主/管理员需开启“允许机器人主动发送消息”。
|
||||||
管理员可 /tx list all 和 /tx cancel 编号 管理当前群提醒。"""
|
管理员可 /tx list all 和 /tx cancel 编号 管理当前群提醒。"""
|
||||||
|
|
||||||
@@ -72,6 +86,10 @@ class ReminderPlugin(Star):
|
|||||||
self.max_content = max(1, min(1500, int(config.get("max_content_length", 1000))))
|
self.max_content = max(1, min(1500, int(config.get("max_content_length", 1000))))
|
||||||
# v1.2 replaces the old v1.1 passive default with a new configuration key.
|
# v1.2 replaces the old v1.1 passive default with a new configuration key.
|
||||||
self.delivery_mode = "proactive" if config.get("proactive_reminders", True) else "passive"
|
self.delivery_mode = "proactive" if config.get("proactive_reminders", True) else "passive"
|
||||||
|
self.markdown_template_id = str(config.get("official_markdown_template_id", "")).strip()
|
||||||
|
self.markdown_parameter = (
|
||||||
|
str(config.get("official_markdown_parameter", "content")).strip() or "content"
|
||||||
|
)
|
||||||
self._wake = asyncio.Event()
|
self._wake = asyncio.Event()
|
||||||
self.store = ReminderStore(StarTools.get_data_dir("astrbot_plugin_tixing") / "reminders.db")
|
self.store = ReminderStore(StarTools.get_data_dir("astrbot_plugin_tixing") / "reminders.db")
|
||||||
self.owner = uuid.uuid4().hex
|
self.owner = uuid.uuid4().hex
|
||||||
@@ -249,9 +267,37 @@ class ReminderPlugin(Star):
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
async def _fire(self, platform, rem, reply=None):
|
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:
|
try:
|
||||||
await asyncio.wait_for(deliver(platform, rem, reply), timeout=30)
|
await asyncio.wait_for(
|
||||||
|
deliver(
|
||||||
|
platform,
|
||||||
|
rem,
|
||||||
|
reply,
|
||||||
|
markdown_template_id=self.markdown_template_id,
|
||||||
|
markdown_parameter=self.markdown_parameter,
|
||||||
|
),
|
||||||
|
timeout=30,
|
||||||
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
|
if isinstance(exc, MentionDeliveryError):
|
||||||
|
await self.store.wait_for_permission(
|
||||||
|
rem["id"],
|
||||||
|
self.owner,
|
||||||
|
f"Markdown @ 格式受限:{exc};任务保留,每 5 分钟重试",
|
||||||
|
time.time() + 300,
|
||||||
|
)
|
||||||
|
logger.warning(
|
||||||
|
"[Reminder] 提醒 #%s 等待 Markdown 配置,任务已保留:%s", rem["id"], exc
|
||||||
|
)
|
||||||
|
return
|
||||||
if reply is None and rem["platform_name"] in OFFICIAL and proactive_denied(exc):
|
if reply is None and rem["platform_name"] in OFFICIAL and proactive_denied(exc):
|
||||||
if rem["scene"] == "group":
|
if rem["scene"] == "group":
|
||||||
await self.store.set_permission(
|
await self.store.set_permission(
|
||||||
@@ -354,16 +400,7 @@ class ReminderPlugin(Star):
|
|||||||
@filter.command("tx", alias={"提醒", "remind"})
|
@filter.command("tx", alias={"提醒", "remind"})
|
||||||
async def tx(self, event: AstrMessageEvent):
|
async def tx(self, event: AstrMessageEvent):
|
||||||
"""设置、查看、取消单次或循环提醒。"""
|
"""设置、查看、取消单次或循环提醒。"""
|
||||||
# Raw text preserves spaces/newlines in reminder content. Remove only the bot mention.
|
await self._guard(event, lambda: self._command(event, command_args(event)))
|
||||||
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))
|
|
||||||
|
|
||||||
async def _command(self, event, args):
|
async def _command(self, event, args):
|
||||||
if not args or args.lower() in {"help", "帮助"}:
|
if not args or args.lower() in {"help", "帮助"}:
|
||||||
@@ -373,10 +410,27 @@ class ReminderPlugin(Star):
|
|||||||
raise ValueError("当前插件支持 QQ 官方 WebSocket、Webhook 和 OneBot。")
|
raise ValueError("当前插件支持 QQ 官方 WebSocket、Webhook 和 OneBot。")
|
||||||
scope = self._scope(event)
|
scope = self._scope(event)
|
||||||
user = str(event.get_sender_id())
|
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)
|
parts = args.split(maxsplit=1)
|
||||||
action = parts[0].lower()
|
action = parts[0].lower()
|
||||||
tail = parts[1].strip() if len(parts) == 2 else ""
|
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", "历史"}:
|
if action in {"list", "列表", "查看", "history", "历史"}:
|
||||||
await self._list(event, scope, user, tail, action in {"history", "历史"})
|
await self._list(event, scope, user, tail, action in {"history", "历史"})
|
||||||
return
|
return
|
||||||
@@ -410,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}",
|
f"平台:{event.get_platform_id()}\n群标识:{event.get_group_id() or '私聊'}\n用户标识:{user}\n本群管理员授权标识:{event.get_platform_id()}|{event.get_group_id()}|{user}",
|
||||||
)
|
)
|
||||||
return
|
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", "状态"}:
|
if action in {"status", "状态"}:
|
||||||
reminders = await self.store.list(scope, None if self._admin(event) else user)
|
reminders = await self.store.list(scope, None if self._admin(event) else user)
|
||||||
running = self._scheduler is not None and not self._scheduler.done()
|
running = self._scheduler is not None and not self._scheduler.done()
|
||||||
@@ -420,11 +494,16 @@ class ReminderPlugin(Star):
|
|||||||
)
|
)
|
||||||
await self._reply(
|
await self._reply(
|
||||||
event,
|
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 ""),
|
+ (f"\n扫描错误:{self.last_scan_error}" if self.last_scan_error else ""),
|
||||||
)
|
)
|
||||||
return
|
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))
|
parsed = parse_time(args, datetime.now(self.tz))
|
||||||
if len(parsed.content) > self.max_content:
|
if len(parsed.content) > self.max_content:
|
||||||
raise ValueError(f"提醒内容最多 {self.max_content} 个字符。")
|
raise ValueError(f"提醒内容最多 {self.max_content} 个字符。")
|
||||||
@@ -450,12 +529,26 @@ class ReminderPlugin(Star):
|
|||||||
reminder_id = await self.store.add(record, self.limit)
|
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}"
|
message = f"⏰ 提醒已设置 #{reminder_id}\n时间:{describe(record['remind_at'], parsed.repeat, self.timezone)}\n时区:{self.timezone}\n内容:{parsed.content}"
|
||||||
if target != user:
|
if target != user:
|
||||||
message += f"\n提醒对象:{target_name or target}"
|
message += f"\n提醒对象:{target_name or '你选中的群成员'}"
|
||||||
|
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 event.get_platform_name() in OFFICIAL:
|
||||||
if self.delivery_mode == "passive":
|
if self.delivery_mode == "passive":
|
||||||
message += "\n使用被动回复:到期有有效回复窗口时发送,否则等待下次 @机器人 补发。"
|
message += "\n使用被动回复:到期有有效回复窗口时发送,否则等待下次 @机器人 补发。"
|
||||||
else:
|
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)
|
await self._reply(event, message)
|
||||||
|
|
||||||
def _format(self, rem, detail=False):
|
def _format(self, rem, detail=False):
|
||||||
@@ -466,6 +559,8 @@ class ReminderPlugin(Star):
|
|||||||
if rem["waiting_reason"].startswith("主动消息权限")
|
if rem["waiting_reason"].startswith("主动消息权限")
|
||||||
else "等待可回复消息"
|
else "等待可回复消息"
|
||||||
)
|
)
|
||||||
|
if rem["waiting_reason"].startswith("Markdown @"):
|
||||||
|
status = "等待 Markdown 配置"
|
||||||
content = (
|
content = (
|
||||||
rem["content"]
|
rem["content"]
|
||||||
if detail
|
if detail
|
||||||
@@ -474,7 +569,7 @@ class ReminderPlugin(Star):
|
|||||||
)
|
)
|
||||||
text = f"#{rem['id']} [{status}] {describe(rem['remind_at'], rem['repeat_type'], rem['timezone'])}\n{content}"
|
text = f"#{rem['id']} [{status}] {describe(rem['remind_at'], rem['repeat_type'], rem['timezone'])}\n{content}"
|
||||||
if rem["target_id"] != rem["creator_id"]:
|
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:
|
if detail:
|
||||||
text += f"\n创建者:{rem['creator_name'] or rem['creator_id']}\n时区:{rem['timezone']}\n失败次数:{rem['failure_count']}"
|
text += f"\n创建者:{rem['creator_name'] or rem['creator_id']}\n时区:{rem['timezone']}\n失败次数:{rem['failure_count']}"
|
||||||
if rem["last_error"]:
|
if rem["last_error"]:
|
||||||
@@ -607,9 +702,7 @@ class ReminderPlugin(Star):
|
|||||||
await self.initialize()
|
await self.initialize()
|
||||||
await self._remember_incoming(event)
|
await self._remember_incoming(event)
|
||||||
if event.get_group_id():
|
if event.get_group_id():
|
||||||
await self.store.observe(
|
await observe_members(event, self.store, self._scope(event))
|
||||||
self._scope(event), str(event.get_sender_id()), event.get_sender_name()
|
|
||||||
)
|
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception("[Reminder] 记录本群成员标识失败")
|
logger.exception("[Reminder] 记录本群成员标识失败")
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
name: astrbot_plugin_tixing
|
name: astrbot_plugin_tixing
|
||||||
display_name: 栗子提醒
|
display_name: 栗子提醒
|
||||||
desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。
|
desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。
|
||||||
version: v1.2.0
|
version: v1.4.0
|
||||||
author: itxiaohui
|
author: itxiaohui
|
||||||
repo: https://github.com/itxiaohui66/astrbot_plugin_tixing
|
repo: https://github.com/itxiaohui66/astrbot_plugin_tixing
|
||||||
support_platforms:
|
support_platforms:
|
||||||
|
|||||||
+67
-6
@@ -1,5 +1,6 @@
|
|||||||
"""Deliver through the current adapter using a validated incoming reply context."""
|
"""Deliver through the current adapter using a validated incoming reply context."""
|
||||||
|
|
||||||
|
import re
|
||||||
import time
|
import time
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from html import escape
|
from html import escape
|
||||||
@@ -7,6 +8,27 @@ from html import escape
|
|||||||
OFFICIAL = {"qq_official", "qq_official_webhook"}
|
OFFICIAL = {"qq_official", "qq_official_webhook"}
|
||||||
|
|
||||||
|
|
||||||
|
class MentionDeliveryError(RuntimeError):
|
||||||
|
"""The app cannot send the Markdown format required by this delivery path."""
|
||||||
|
|
||||||
|
|
||||||
|
def markdown_unavailable(exc):
|
||||||
|
text = str(exc).lower()
|
||||||
|
return ("markdown" in text or "模板" in text) and any(
|
||||||
|
token in text
|
||||||
|
for token in (
|
||||||
|
"不允许",
|
||||||
|
"权限",
|
||||||
|
"无效",
|
||||||
|
"不合法",
|
||||||
|
"不存在",
|
||||||
|
"not allowed",
|
||||||
|
"permission",
|
||||||
|
"invalid",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def proactive_denied(exc):
|
def proactive_denied(exc):
|
||||||
text = str(exc).lower()
|
text = str(exc).lower()
|
||||||
return any(
|
return any(
|
||||||
@@ -100,12 +122,32 @@ def available(platform):
|
|||||||
|
|
||||||
|
|
||||||
def reminder_text(rem):
|
def reminder_text(rem):
|
||||||
creator = rem["creator_name"] or rem["creator_id"]
|
# AstrBot may use an OpenID as the display-name fallback. Keep IDs out of prose.
|
||||||
|
creator = rem["creator_name"]
|
||||||
|
if not creator or creator == rem["creator_id"]:
|
||||||
|
creator = "群成员" if rem["scene"] in {"group", "channel"} else "用户"
|
||||||
prefix = f"来自 {creator} 的提醒:\n" if rem["target_id"] != rem["creator_id"] else ""
|
prefix = f"来自 {creator} 的提醒:\n" if rem["target_id"] != rem["creator_id"] else ""
|
||||||
return f"{prefix}⏰ {rem['content']}\n(提醒 #{rem['id']})"
|
return f"{prefix}⏰ {rem['content']}\n(提醒 #{rem['id']})"
|
||||||
|
|
||||||
|
|
||||||
async def deliver(platform, rem, reply=None):
|
def official_mention(user_id):
|
||||||
|
"""QQ native mention token; do not replace it with visible @OpenID text."""
|
||||||
|
return f'<qqbot-at-user id="{escape(str(user_id), quote=True)}" />'
|
||||||
|
|
||||||
|
|
||||||
|
def reminder_markdown(rem):
|
||||||
|
# Keep the mention outside user-provided text/code blocks. Preserve reminder
|
||||||
|
# text literally instead of interpreting 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."""
|
"""Official SDK return value must contain a message ID to count as sent."""
|
||||||
client = platform.get_client()
|
client = platform.get_client()
|
||||||
text = reminder_text(rem)
|
text = reminder_text(rem)
|
||||||
@@ -116,17 +158,36 @@ async def deliver(platform, rem, reply=None):
|
|||||||
if scene not in {"group", "c2c"}:
|
if scene not in {"group", "c2c"}:
|
||||||
kwargs.pop("msg_seq", None)
|
kwargs.pop("msg_seq", None)
|
||||||
if scene == "group":
|
if scene == "group":
|
||||||
mention = f'<qqbot-at-user id="{escape(rem["target_id"], quote=True)}" />'
|
body = reminder_markdown(rem)
|
||||||
result = await api.post_group_message(
|
markdown = (
|
||||||
group_openid=rem["destination"], msg_type=0, content=f"{mention}\n{text}", **kwargs
|
{
|
||||||
|
"custom_template_id": markdown_template_id,
|
||||||
|
"params": [{"key": markdown_parameter, "values": [body]}],
|
||||||
|
}
|
||||||
|
if markdown_template_id
|
||||||
|
else {"content": body}
|
||||||
)
|
)
|
||||||
|
try:
|
||||||
|
result = await api.post_group_message(
|
||||||
|
group_openid=rem["destination"], msg_type=2, markdown=markdown, **kwargs
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
if markdown_unavailable(exc):
|
||||||
|
raise MentionDeliveryError(
|
||||||
|
"QQ 拒绝 Markdown @ 消息,请开通原生 Markdown,或配置已获批的 "
|
||||||
|
"official_markdown_template_id / official_markdown_parameter;"
|
||||||
|
f"原始错误:{exc}"
|
||||||
|
) from exc
|
||||||
|
raise
|
||||||
elif scene == "c2c":
|
elif scene == "c2c":
|
||||||
result = await api.post_c2c_message(
|
result = await api.post_c2c_message(
|
||||||
openid=rem["destination"], msg_type=0, content=text, **kwargs
|
openid=rem["destination"], msg_type=0, content=text, **kwargs
|
||||||
)
|
)
|
||||||
elif scene == "channel":
|
elif scene == "channel":
|
||||||
result = await api.post_message(
|
result = await api.post_message(
|
||||||
channel_id=rem["destination"], content=f"<@{rem['target_id']}>\n{text}", **kwargs
|
channel_id=rem["destination"],
|
||||||
|
content=f"{official_mention(rem['target_id'])}\n{text}",
|
||||||
|
**kwargs,
|
||||||
)
|
)
|
||||||
elif scene == "guild_dm":
|
elif scene == "guild_dm":
|
||||||
result = await api.post_dms(guild_id=rem["destination"], content=text, **kwargs)
|
result = await api.post_dms(guild_id=rem["destination"], content=text, **kwargs)
|
||||||
|
|||||||
@@ -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)
|
||||||
+79
-8
@@ -64,6 +64,17 @@ class ReminderStore:
|
|||||||
nickname TEXT NOT NULL DEFAULT '', seen_at REAL NOT NULL,
|
nickname TEXT NOT NULL DEFAULT '', seen_at REAL NOT NULL,
|
||||||
PRIMARY KEY(scope, user_id)
|
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 (
|
CREATE TABLE IF NOT EXISTS reply_contexts (
|
||||||
platform_id TEXT NOT NULL, scene TEXT NOT NULL, destination TEXT NOT NULL,
|
platform_id TEXT NOT NULL, scene TEXT NOT NULL, destination TEXT NOT NULL,
|
||||||
msg_id TEXT NOT NULL, received_at REAL NOT NULL,
|
msg_id TEXT NOT NULL, received_at REAL NOT NULL,
|
||||||
@@ -178,33 +189,93 @@ class ReminderStore:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
async def observe(self, scope, user_id, nickname=""):
|
async def observe(self, scope, user_id, nickname="", names=()):
|
||||||
await self._run(
|
await self.observe_members(scope, [(user_id, nickname, names)])
|
||||||
lambda db: (
|
|
||||||
|
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(
|
db.execute(
|
||||||
"INSERT INTO members VALUES (?,?,?,?) ON CONFLICT(scope,user_id) DO UPDATE SET "
|
"INSERT INTO members VALUES (?,?,?,?) ON CONFLICT(scope,user_id) DO UPDATE SET "
|
||||||
"nickname=CASE WHEN excluded.nickname!='' THEN excluded.nickname ELSE members.nickname END, "
|
"nickname=CASE WHEN excluded.nickname!='' THEN excluded.nickname ELSE members.nickname END, "
|
||||||
"seen_at=excluded.seen_at",
|
"seen_at=excluded.seen_at",
|
||||||
(scope, user_id, nickname or "", time.time()),
|
(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):
|
async def member(self, scope, value):
|
||||||
def read(db):
|
def read(db):
|
||||||
rows = db.execute(
|
rows = db.execute(
|
||||||
"SELECT * FROM members WHERE scope=? AND (user_id=? OR nickname=?)",
|
"SELECT DISTINCT m.* FROM members m LEFT JOIN member_names n "
|
||||||
(scope, value, value),
|
"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()
|
).fetchall()
|
||||||
exact = [r for r in rows if r["user_id"] == value]
|
exact = [r for r in rows if r["user_id"] == value]
|
||||||
if exact:
|
if exact:
|
||||||
return dict(exact[0])
|
return dict(exact[0])
|
||||||
if len(rows) > 1:
|
if len(rows) > 1:
|
||||||
raise ValueError("本群有重名用户,请使用真实 @ 或 /tx identity 获取的用户标识。")
|
raise ValueError(
|
||||||
|
"本群有重名用户,请让成员 /tx name 登记不同提醒昵称,或使用平台能识别的真实 @。"
|
||||||
|
)
|
||||||
return dict(rows[0]) if rows else None
|
return dict(rows[0]) if rows else None
|
||||||
|
|
||||||
return await self._run(read)
|
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):
|
async def add(self, record, limit):
|
||||||
def insert(db):
|
def insert(db):
|
||||||
db.execute("BEGIN IMMEDIATE")
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
|||||||
+216
-23
@@ -7,47 +7,240 @@ from .delivery import OFFICIAL, field
|
|||||||
MARKUP = re.compile(
|
MARKUP = re.compile(
|
||||||
r"<qqbot-at-user\s+id=[\"\']([^\"\']+)[\"\']\s*/>|<@!?([^>]+)>|\[CQ:at,qq=([^,\]]+)[^\]]*\]"
|
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")
|
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):
|
def message_text(event):
|
||||||
sender = str(event.get_sender_id())
|
"""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)}
|
bot_ids = {str(event.message_obj.self_id)}
|
||||||
raw = event.message_obj.raw_message
|
raw = event.message_obj.raw_message
|
||||||
raw_data = field(raw, "raw_data", raw)
|
raw_data = field(raw, "raw_data", raw)
|
||||||
mentions = field(raw, "mentions", None) or field(raw_data, "mentions", []) or []
|
# botpy may expose a nonempty mentions list whose objects have lost id,
|
||||||
|
# is_you or username. It must not hide the adapter's original QQ payload.
|
||||||
|
payload_mentions = field(raw_data, "mentions", []) or []
|
||||||
|
sdk_mentions = field(raw, "mentions", []) or []
|
||||||
|
mentions = list(payload_mentions)
|
||||||
|
if raw_data is not raw:
|
||||||
|
mentions.extend(sdk_mentions)
|
||||||
trusted = {}
|
trusted = {}
|
||||||
|
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:
|
for mention in mentions:
|
||||||
user = str(field(mention, "id", None) or field(mention, "member_openid", ""))
|
generic_id = str(field(mention, "id", "") or "")
|
||||||
|
member_id = str(field(mention, "member_openid", "") or "")
|
||||||
|
canonical = (member_id or generic_id) if official_group else (generic_id or member_id)
|
||||||
|
if canonical:
|
||||||
|
for value in (generic_id, member_id):
|
||||||
|
if value:
|
||||||
|
aliases.setdefault(value, canonical)
|
||||||
|
for mention in mentions:
|
||||||
|
generic_id = str(field(mention, "id", "") or "")
|
||||||
|
member_id = str(field(mention, "member_openid", "") or "")
|
||||||
|
user = (member_id or generic_id) if official_group else (generic_id or member_id)
|
||||||
|
user = aliases.get(user, user)
|
||||||
if field(mention, "is_you", False) or field(mention, "bot", False):
|
if field(mention, "is_you", False) or field(mention, "bot", False):
|
||||||
bot_ids.add(user)
|
bot_ids.update({user, generic_id, member_id} - {""})
|
||||||
elif user:
|
bot_names.update(member_names(mention))
|
||||||
trusted[user] = str(field(mention, "username", "") or "")
|
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():
|
for component in event.get_messages():
|
||||||
if field(component, "type") in {"At", "at"} or type(component).__name__ == "At":
|
if field(component, "type") in {"At", "at"} or type(component).__name__ == "At":
|
||||||
user = str(field(component, "qq", ""))
|
raw_user = str(field(component, "qq", ""))
|
||||||
|
user = aliases.get(raw_user, raw_user)
|
||||||
if user and user not in bot_ids:
|
if user and user not in bot_ids:
|
||||||
trusted[user] = str(field(component, "name", "") or "")
|
trusted[user] = trusted.get(user) or str(field(component, "name", "") or "")
|
||||||
|
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)
|
candidates = list(trusted)
|
||||||
for match in MARKUP.finditer(args):
|
for match in MARKUP.finditer(args):
|
||||||
user = next(g for g in match.groups() if g is not None)
|
raw_user = next(g for g in match.groups() if g is not None)
|
||||||
|
user = aliases.get(raw_user, raw_user)
|
||||||
if user not in bot_ids:
|
if user not in bot_ids:
|
||||||
candidates.append(user)
|
candidates.append(user)
|
||||||
args = MARKUP.sub(" ", args)
|
args = MARKUP.sub(" ", args)
|
||||||
textual = list(TEXT_AT.finditer(args))
|
known_names = await store.member_names(scope)
|
||||||
for match in textual:
|
pattern = text_mentions(
|
||||||
value = match.group(1)
|
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.
|
# @all must not be allowed as a recipient.
|
||||||
if value in {"all", "everyone", "全体成员"}:
|
if value in {"all", "everyone", "全体成员"}:
|
||||||
raise ValueError("一次提醒只能指定一个成员,不能 @ 全体成员。")
|
raise ValueError("一次提醒只能指定一个成员,不能 @ 全体成员。")
|
||||||
names = [user for user, name in trusted.items() if name and name == value]
|
matching = [user for user in trusted if value in names.get(user, [])]
|
||||||
if len(names) > 1:
|
if len(matching) > 1:
|
||||||
raise ValueError("被 @ 成员重名,请使用用户标识。")
|
raise ValueError("被 @ 成员重名,请在 QQ 的 @ 群成员列表中只选中一个人。")
|
||||||
member = await store.member(scope, value)
|
# A real QQ selection identifies the member even when cached names collide.
|
||||||
candidates.append(names[0] if names else member["user_id"] if member else value)
|
member = None if matching else await store.member(scope, value)
|
||||||
args = TEXT_AT.sub(" ", args).strip()
|
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))
|
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:
|
if len(candidates) > 1:
|
||||||
raise ValueError("一次提醒只能指定一个成员。")
|
raise ValueError("一次提醒只能指定一个成员。")
|
||||||
target = candidates[0] if candidates else sender
|
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 event.get_platform_name() in OFFICIAL:
|
||||||
if target not in trusted and not member:
|
if target not in trusted and not member:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"无法确认该用户的本群 OpenID。请真实 @ 对方;若官方未提供成员标识,"
|
"无法识别本群提醒对象,未创建提醒。请让对方 /tx name 昵称 登记自己,"
|
||||||
"让对方先在本群 @ 机器人发送 /tx identity,再用 @用户标识。普通 QQ 号不能转换成 OpenID。"
|
"再使用 /tx to 昵称 时间 内容。无需复制 ID。"
|
||||||
)
|
)
|
||||||
elif event.get_platform_name() == "aiocqhttp":
|
elif event.get_platform_name() == "aiocqhttp":
|
||||||
try:
|
try:
|
||||||
@@ -70,7 +263,7 @@ async def resolve_target(event, args, store, scope):
|
|||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise ValueError("无法在本群找到该成员,请重新 @ 群成员。") from 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:
|
if target == sender:
|
||||||
name = event.get_sender_name() or ""
|
name = event.get_sender_name() or ""
|
||||||
return args, target, name
|
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"
|
||||||
@@ -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 kwargs[destination_key] == "group_1"
|
||||||
assert "msg_id" not in kwargs
|
assert "msg_id" not in kwargs
|
||||||
if scene == "group":
|
if scene == "group":
|
||||||
assert '<qqbot-at-user id="user_1" />' in kwargs["content"]
|
assert kwargs["msg_type"] == 2
|
||||||
|
assert '<qqbot-at-user id="user_1" />' in kwargs["markdown"]["content"]
|
||||||
|
|
||||||
|
|
||||||
async def test_empty_official_result_is_failure(platform_factory):
|
async def test_empty_official_result_is_failure(platform_factory):
|
||||||
@@ -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)
|
await resolve_target(event, '1小时 <qqbot-at-user id="opaque_new" /> 开会', store, scope)
|
||||||
)[1] == "opaque_new"
|
)[1] == "opaque_new"
|
||||||
event.message_obj.raw_message = {"group_openid": "group_1"}
|
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 resolve_target(event, "1小时 开会 @123456789", store, scope)
|
||||||
await store.observe("other_scope", "unknown", "跨群用户")
|
await store.observe("other_scope", "unknown", "跨群用户")
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
|
|||||||
Reference in new issue
Block a user