From 58d6807ed0e8772a7bf28259511a13d9f28b7c6c Mon Sep 17 00:00:00 2001 From: itxiaohui <177289791+itxiaohui66@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:37:29 +0800 Subject: [PATCH] Use passive QQ replies and preserve reminders while waiting for a reply window --- .github/workflows/test.yml | 8 +- README.md | 25 ++-- _conf_schema.json | 1 + main.py | 99 +++++++++++++-- metadata.yaml | 2 +- services/delivery.py | 68 ++++++++++- services/storage.py | 104 +++++++++++++++- tests/test_passive_delivery.py | 216 +++++++++++++++++++++++++++++++++ tests/test_reminders.py | 7 +- 9 files changed, 495 insertions(+), 35 deletions(-) create mode 100644 tests/test_passive_delivery.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7e455c5..c914b6b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,16 +13,16 @@ jobs: fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-24.04 python: "3.10" - - os: ubuntu-latest + - os: ubuntu-24.04 python: "3.12" - os: windows-latest python: "3.12" runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: ${{ matrix.python }} cache: pip diff --git a/README.md b/README.md index 74d493d..82f81a8 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing ``` -也可以从 [GitHub Releases](https://github.com/itxiaohui66/astrbot_plugin_tixing/releases/latest) 下载 `astrbot_plugin_tixing-v1.0.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.1.0.zip`,在插件页上传安装。手动安装时,把 ZIP 中的 `astrbot_plugin_tixing` 文件夹解压到 AstrBot 的 `data/plugins/` 下,然后重启或重载插件。运行文件 `main.py`、`metadata.yaml` 和 `_conf_schema.json` 必须直接位于该插件文件夹中。 安装时 AstrBot 会读取 `requirements.txt` 安装 `tzdata`。配置默认采用北京时间 `Asia/Shanghai`;每人在每个群或私聊最多 10 个活跃提醒,每 30 秒扫描一次。确认机器人已经接入 QQ 官方适配器,群内使用 `@机器人 /tx help` 查看帮助。 @@ -27,7 +27,7 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing | 每人最多 10 条 | 按平台 + 群/私聊 + 创建者计算,仅统计活跃任务;支持配置 | | 30 秒轮询 | 可配置;通常在到期后一个扫描周期内发送,拥塞时可能更晚 | | 数据库存储、重启恢复 | SQLite 位于 AstrBot `data/plugin_data/astrbot_plugin_tixing/reminders.db` | -| 投递失败重试、达到阈值取消 | 默认重试间隔 60 秒,连续 3 次失败自动取消;保留错误原因 | +| 投递失败重试、达到阈值取消 | 普通投递错误默认重试间隔 60 秒,连续 3 次失败自动取消;回复窗口/额度受限则等待新消息,不增加失败次数 | | `/cxzd` 重启提醒调度器 | 保留;使用 AstrBot 管理员或插件授权管理员,不丢任务 | | 旧帮助中的 `/提醒`、`/remind` | 实现为 `/tx` 别名 | | 旧帮助中的今天、明天、指定日期 | 原代码未实现的格式已补齐,并支持后天 | @@ -53,7 +53,9 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing 时间和内容之间要有空格。内容可以包含空格、换行,默认最多 1000 个字符。单次 `HH:MM` 表示今天该时刻,已经过去则提示改用未来时间;每天和每周自动计算下一次。提醒间隔必须大于 0,小时范围 0–23,分钟范围 0–59。 -到期后在创建时的群或私聊发送提醒。循环任务按创建时的时区续期,修改配置时区只影响新任务。离线时错过多次循环,会在恢复后补发一次并续到下一次未来时刻,避免刷屏。一次性逾期提醒在恢复后补发;如果适配器还未加载或运行,不增加失败次数。 +到期后在创建时的群或私聊发送提醒。QQ 官方默认使用被动回复:只有存在有效的近期用户消息和回复额度时才投递,否则保留任务,在下一条机器人收到的同会话消息到来后尝试补发。因此,没有主动消息能力时,长时间后的提醒不能保证准点发出;群内可 `@机器人 /tx list` 打开新的回复窗口。 + +循环任务按创建时的时区续期,修改配置时区只影响新任务。离线或等待期间错过多次循环,会在有效窗口中补发一次并续到下一次未来时刻,避免刷屏。一次性逾期提醒同样等待有效窗口补发;如果适配器还未加载或运行,不增加失败次数。OneBot 的发送方式保持原样。 ## 管理命令 @@ -65,6 +67,7 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing | `/tx detail 编号` | 查看全文、时间、状态、失败次数和最近错误 | | `/tx cancel 编号` / `/qxtx 编号` / `/取消提醒 编号` | 取消自己创建的任务 | | `/tx cancel all` | 仅取消自己在当前会话创建的所有活跃任务 | +| `/tx retry 编号` | 恢复投递失败后自动取消的任务,或重试待投递任务;仍检查当前会话、创建者和数量限制 | | `/tx identity` | 当前平台、群、用户标识和本群授权管理员标识 | | `/tx status` | 调度器状态、当前会话活跃数量、时区、扫描间隔和最近错误 | | `/cxzd` / `/重启提醒` | 管理员重启提醒调度器 | @@ -73,7 +76,9 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing 管理员可以取消当前会话其他人的单条任务、查看详情。按编号操作也受平台和群隔离限制。群管理员并不会自动获得机器人管理权限;使用 AstrBot 管理员配置,或在插件配置中加入 `admin_ids`、`group_admin_ids`。`group_admin_ids` 的格式为 `平台ID|群OpenID|用户OpenID`,可从 `/tx identity` 复制。 -列表每页 2 条,长内容显示预览,可用 `detail` 查看全文。投递超过失败阈值后会自动取消,可以在 `history` 中查到原因;修复权限或网络后重新创建即可。 +列表每页 2 条,长内容显示预览,可用 `detail` 查看全文。缺少回复窗口、额度用完或 QQ 拒绝该回复上下文时,状态显示“等待可回复消息”,不会因此自动取消。普通投递错误超过失败阈值后仍会自动取消,可以在 `history` 中查到原因。 + +从 v1.0.0 更新后,数据库自动升级并保留原提醒。已经因“主动消息失败,无权限”自动取消的任务不会被擅自恢复;在原群中发送 `/tx retry 2`、`/tx retry 3` 等对应编号即可恢复。等待中的提醒、未到期提醒仍占用活跃任务额度。 ## 官方 QQ 的对象和发送权限 @@ -85,7 +90,11 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing 插件会记住本群里机器人实际收到的成员消息,名字唯一且官方提供昵称时也支持 `@昵称`。不同群里的成员记录不会混用,重名时要求明确标识。OneBot 模式会查询目标是否是本群成员。私聊只能提醒自己。 -定时提醒属于主动消息,插件直接使用当前官方适配器的客户端发送,不保存旧 `msg_id`、不复用过期回复窗口。QQ 官方的主动消息权限、额度、风控和目标可达性仍适用。平台拒绝或未返回消息 ID 时记录为失败,只有获得消息 ID 后才标记成功或计算下一次时间。相关依据见 [腾讯官方 SDK 使用说明](https://github.com/tencent-connect/qqbot-nodejs/blob/main/USAGE.md)。 +v1.1.0 默认采用 **被动回复**:使用真正收到的用户消息 `msg_id`,群、频道、频道私信保守采用 4 分钟窗口,C2C 保守采用 59 分钟窗口,给网络发送留出安全余量。官方文档规定群回复有效期 5 分钟、C2C 60 分钟,每条消息最多回复 5 次;插件每个上下文最多投递 3 条提醒,留出回复次数给命令响应和其他插件。若其他插件已经用完回复额度,QQ 拒绝该上下文后会等待下一条消息。 + +回复上下文按平台、场景和投递目标隔离,保存消息原始时间及已用次数;重复事件不会延长有效期或补充额度。群/C2C 的提醒采用与 AstrBot 当前回复发送范围分开的独立 `msg_seq`。新消息到来会唤醒扫描器,不必等到下一轮轮询。只有接口返回消息 ID 后才标记成功或续期;被动发送失败时不降级为无权限的主动发送。 + +`official_delivery_mode=proactive` 仅保留给已确认具备该能力的环境使用。QQ 官方文档对主动推送有停止提供能力的公告,普通账号不能靠换 API 或旧消息 ID 绕过限制。详见 [腾讯官方消息收发文档](https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/server-inter/message/send-receive/send.md)。 QQ 普通群使用 `` 实现真正 @,频道使用频道成员 ID。群、C2C、频道、频道私信分别走对应 SDK 接口。插件自己的到期提醒使用普通文本,不要求 Markdown 模板;命令回复仍由 AstrBot 当前事件的配置发送。 @@ -97,6 +106,7 @@ QQ 普通群使用 `` 实现真正 @,频道使用 | 字段 | 默认值 | 说明 | | --- | --- | --- | +| `official_delivery_mode` | `passive` | 默认被动回复,等待有效窗口;可显式选 `proactive` 保留原发送方式 | | `timezone` | `Asia/Shanghai` | IANA 时区 | | `max_per_user` | `10` | 当前会话每人最多活跃任务 | | `check_interval_seconds` | `30` | 扫描周期,最小 1 秒 | @@ -118,14 +128,15 @@ ruff format --check . python tools/package.py ``` -自动化测试使用真实 SQLite 和时间解析;AstrBot 主机边界和 QQ 发送接口使用测试替身,覆盖时间格式、上限、群隔离、成员识别、失败重试、循环补发、权限和热重载。GitHub Actions 会在 Linux(Python 3.10、3.12)和 Windows(Python 3.12)上运行测试、代码检查和打包。真实 QQ 投递仍需在实际部署的 AstrBot 和账号中验证。 +自动化测试使用真实 SQLite 和时间解析;AstrBot 主机边界和 QQ 发送接口使用测试替身,覆盖时间格式、上限、群隔离、成员识别、失败重试、循环补发、权限、热重载,以及回复时效、额度、序号、重复事件、即时唤醒和数据库升级。GitHub Actions 会在 Linux(Python 3.10、3.12)和 Windows(Python 3.12)上运行测试、代码检查和打包。真实 QQ 投递仍需在实际部署的 AstrBot 和账号中验证。 安装后可用以下流程确认部署环境: -1. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,并在一分钟后加一个扫描周期内收到真正 @ 的通知。 +1. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,并在有效回复窗口内收到真正 @ 的通知。 2. `/tx history` 检查该任务状态;失败时检查记录里的原因和 AstrBot 日志。 3. `/tx 5分钟 重启测试`,重载插件后用 `/tx list` 确认仍在,再 `/tx cancel 编号` 确认取消。 4. 让另一成员先发送 `/tx identity`,测试本群的他人提醒。 +5. 超过群回复窗口后,确认 `/tx list` 显示待补发原因;在群里再次 @机器人 时应唤醒投递。若已因旧版错误自动取消,先 `/tx retry 编号` 恢复。 ## 来源 diff --git a/_conf_schema.json b/_conf_schema.json index 70a773a..5def212 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -1,4 +1,5 @@ { + "official_delivery_mode": {"type": "string", "description": "QQ 官方发送方式", "options": ["passive", "proactive"], "hint": "默认 passive 被动回复;没有有效回复窗口时保留任务等待下次消息。仅已确认支持主动消息的账号选择 proactive。", "default": "passive"}, "timezone": {"type": "string", "description": "提醒时区", "hint": "IANA 时区名称,默认北京时间;修改只影响新建提醒。", "default": "Asia/Shanghai"}, "max_per_user": {"type": "int", "description": "每人在每个群/私聊最多活跃提醒数", "default": 10}, "check_interval_seconds": {"type": "int", "description": "到期扫描间隔(秒)", "default": 30}, diff --git a/main.py b/main.py index 283c9e7..dfff32a 100644 --- a/main.py +++ b/main.py @@ -12,7 +12,15 @@ from astrbot.api import AstrBotConfig, logger from astrbot.api.event import AstrMessageEvent, filter from astrbot.api.star import Context, Star, StarTools -from .services.delivery import OFFICIAL, available, deliver, find_platform, route +from .services.delivery import ( + OFFICIAL, + available, + deliver, + find_platform, + incoming_reply, + reply_unavailable, + route, +) from .services.storage import ReminderStore, scope_key from .services.targets import MARKUP, resolve_target from .services.time_parser import describe, next_occurrence, parse_time @@ -30,12 +38,14 @@ HELP = """⏰ 栗子提醒 /tx detail 编号 查看一条提醒 /tx cancel 编号 取消自己的一条提醒 /tx cancel all 取消自己当前会话的全部提醒 +/tx retry 编号 恢复投递失败的提醒 /tx identity 查看当前平台、群和用户标识 /tx status 查看提醒调度器状态 /cxzd 管理员重启提醒调度器 命令别名:/提醒、/remind 群内官方 QQ 需要 @机器人;时间按配置时区计算。 官方 QQ 提醒他人须使用本群 OpenID 或真实 @;普通 QQ 号不可转换。 +默认使用被动回复;没有有效回复窗口时等待下次 @机器人 补发。 管理员可 /tx list all 和 /tx cancel 编号 管理当前群提醒。""" @@ -55,6 +65,10 @@ class ReminderPlugin(Star): self.max_failures = max(1, int(config.get("max_delivery_failures", 3))) self.retry_seconds = max(1, int(config.get("retry_interval_seconds", 60))) self.max_content = max(1, min(1500, int(config.get("max_content_length", 1000)))) + self.delivery_mode = config.get("official_delivery_mode", "passive") + if self.delivery_mode not in {"passive", "proactive"}: + raise ValueError("official_delivery_mode 必须为 passive 或 proactive") + self._wake = asyncio.Event() self.store = ReminderStore(StarTools.get_data_dir("astrbot_plugin_tixing") / "reminders.db") self.owner = uuid.uuid4().hex self._ready = False @@ -87,7 +101,11 @@ class ReminderPlugin(Star): except Exception as exc: self.last_scan_error = str(exc)[:300] logger.exception("[Reminder] 扫描提醒失败,将在下一轮继续") - await asyncio.sleep(self.interval) + try: + await asyncio.wait_for(self._wake.wait(), timeout=self.interval) + except asyncio.TimeoutError: + pass + self._wake.clear() async def _check_due(self): async with self._scan_lock: @@ -98,19 +116,44 @@ class ReminderPlugin(Star): continue if not await self.store.claim(rem["id"], self.owner, time.time()): continue + reply = None + if rem["platform_name"] in OFFICIAL and self.delivery_mode == "passive": + # QQ documents group/channel/DM windows of 5 min, C2C 60 min. + # Leave a margin for the 30 s send timeout. + window = 3540 if rem["scene"] == "c2c" else 240 + reply = await self.store.reserve_reply( + rem["platform_id"], rem["scene"], rem["destination"], time.time(), window + ) + if reply is None: + await self.store.wait_for_reply( + rem["id"], + self.owner, + rem.get("waiting_reason") + or "没有有效回复窗口或本条消息回复额度已用完,等待下次 @机器人 补发", + ) + continue # On unload, finish the current send + persistence before exiting. # A send has a 30 s timeout, shorter than the 120 s DB lease. - task = asyncio.create_task(self._fire(platform, rem)) + task = asyncio.create_task(self._fire(platform, rem, reply)) try: await asyncio.shield(task) except asyncio.CancelledError: await task raise - async def _fire(self, platform, rem): + async def _fire(self, platform, rem, reply=None): try: - await asyncio.wait_for(deliver(platform, rem), timeout=30) + await asyncio.wait_for(deliver(platform, rem, reply), timeout=30) except Exception as exc: + if reply is not None and reply_unavailable(exc): + await self.store.block_reply( + rem["platform_id"], rem["scene"], rem["destination"], reply["msg_id"] + ) + await self.store.wait_for_reply( + rem["id"], self.owner, f"被动回复受限:{exc};等待下次 @机器人 补发" + ) + logger.info("[Reminder] 提醒 #%s 等待新的可回复消息:%s", rem["id"], exc) + return await self.store.failure( rem["id"], self.owner, exc, self.max_failures, time.time() + self.retry_seconds ) @@ -156,6 +199,7 @@ class ReminderPlugin(Star): async def _guard(self, event, action): try: await self.initialize() + await self._remember_incoming(event) await action() except ValueError as exc: await self._reply(event, f"❌ {exc}") @@ -197,6 +241,16 @@ class ReminderPlugin(Star): if action in {"cancel", "取消"}: await self._cancel(event, scope, user, tail) return + if action in {"retry", "重试"}: + if not tail.isdecimal(): + raise ValueError("用法:/tx retry 编号") + async with self._scan_lock: + await self.store.resume( + scope, None if self._admin(event) else user, int(tail), self.limit + ) + self._wake.set() + await self._reply(event, f"✅ 提醒 #{tail} 已恢复,等待有效回复窗口投递。") + return if action in {"detail", "详情"}: if not tail.isdecimal(): raise ValueError("用法:/tx detail 编号") @@ -221,7 +275,7 @@ class ReminderPlugin(Star): ) await self._reply( event, - f"调度器:{'运行中' if running else '停止'}\n当前会话活跃提醒:{len(reminders)}\n扫描间隔:{self.interval} 秒\n时区:{self.timezone}\n最近扫描:{last}" + f"调度器:{'运行中' if running else '停止'}\n当前会话活跃提醒:{len(reminders)}\n扫描间隔:{self.interval} 秒\n时区:{self.timezone}\n最近扫描:{last}\n官方发送方式:{self.delivery_mode}" + (f"\n扫描错误:{self.last_scan_error}" if self.last_scan_error else ""), ) return @@ -253,11 +307,16 @@ class ReminderPlugin(Star): if target != user: message += f"\n提醒对象:{target_name or target}" if event.get_platform_name() in OFFICIAL: - message += "\n到期由 QQ 官方主动投递;发送权限或额度受限时会记录失败。" + if self.delivery_mode == "passive": + message += "\n使用被动回复:到期有有效回复窗口时发送,否则等待下次 @机器人 补发。" + else: + message += "\n使用主动投递;发送权限或额度受限时会记录失败。" await self._reply(event, message) def _format(self, rem, detail=False): status = {"active": "待提醒", "done": "已完成", "cancelled": "已取消"}[rem["status"]] + if rem["status"] == "active" and rem.get("waiting_reason"): + status = "等待可回复消息" content = ( rem["content"] if detail @@ -271,6 +330,8 @@ class ReminderPlugin(Star): text += f"\n创建者:{rem['creator_name'] or rem['creator_id']}\n时区:{rem['timezone']}\n失败次数:{rem['failure_count']}" if rem["last_error"]: text += f"\n最近投递失败:{rem['last_error'][:150]}" + if rem.get("waiting_reason"): + text += f"\n等待原因:{rem['waiting_reason'][:150]}" return text async def _list(self, event, scope, user, tail, history): @@ -351,16 +412,32 @@ class ReminderPlugin(Star): @filter.event_message_type(filter.EventMessageType.ALL) async def observe_member(self, event: AstrMessageEvent): """Remember group participants for OpenID/name resolution without intercepting chat.""" - if event.get_platform_name() not in OFFICIAL | {"aiocqhttp"} or not event.get_group_id(): + if event.get_platform_name() not in OFFICIAL | {"aiocqhttp"}: return try: await self.initialize() - await self.store.observe( - self._scope(event), str(event.get_sender_id()), event.get_sender_name() - ) + await self._remember_incoming(event) + if event.get_group_id(): + await self.store.observe( + self._scope(event), str(event.get_sender_id()), event.get_sender_name() + ) except Exception: logger.exception("[Reminder] 记录本群成员标识失败") + async def _remember_incoming(self, event): + if event.get_platform_name() not in OFFICIAL: + return + incoming = incoming_reply(event) + if incoming is None: + return + scene, destination = route(event) + if not destination: + return + await self.store.remember_reply( + str(event.get_platform_id()), scene, destination, **incoming + ) + self._wake.set() + async def terminate(self): async with self._init_lock: self._closed = True diff --git a/metadata.yaml b/metadata.yaml index 2d7039f..61c3e74 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -1,7 +1,7 @@ name: astrbot_plugin_tixing display_name: 栗子提醒 desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。 -version: v1.0.0 +version: v1.1.0 author: itxiaohui repo: https://github.com/itxiaohui66/astrbot_plugin_tixing support_platforms: diff --git a/services/delivery.py b/services/delivery.py index 60043fb..32710bb 100644 --- a/services/delivery.py +++ b/services/delivery.py @@ -1,10 +1,61 @@ -"""Deliver through the current adapter; never persist a live event or old msg_id.""" +"""Deliver through the current adapter using a validated incoming reply context.""" +import time +from datetime import datetime from html import escape OFFICIAL = {"qq_official", "qq_official_webhook"} +def incoming_reply(event): + """Read an inbound message ID and its original timestamp, never a sent ID.""" + raw = event.message_obj.raw_message + data = field(raw, "raw_data", raw) + msg_id = str( + field(raw, "id") or field(data, "id") or field(event.message_obj, "message_id", "") or "" + ) + if not msg_id: + return None + timestamp = ( + field(raw, "timestamp") or field(data, "timestamp") or field(event.message_obj, "timestamp") + ) + try: + received_at = float(timestamp) + except (TypeError, ValueError): + try: + parsed = datetime.fromisoformat(str(timestamp).replace("Z", "+00:00")) + if parsed.tzinfo is None: + return None + received_at = parsed.timestamp() + except (TypeError, ValueError): + return None + return {"msg_id": msg_id, "received_at": min(received_at, time.time())} + + +def reply_unavailable(exc): + text = str(exc).lower() + return any( + token in text + for token in ( + "22009", + "msg limit exceed", + "msg_id", + "msg id", + "msg_seq", + "message expired", + "message is expired", + "消息过期", + "消息已过期", + "被动消息", + "回复超", + "超频", + "无权限", + "permission", + "主动消息失败", + ) + ) + + def field(value, name, default=None): return value.get(name, default) if isinstance(value, dict) else getattr(value, name, default) @@ -46,26 +97,31 @@ def reminder_text(rem): return f"{prefix}⏰ {rem['content']}\n(提醒 #{rem['id']})" -async def deliver(platform, rem): +async def deliver(platform, rem, reply=None): """Official SDK return value must contain a message ID to count as sent.""" client = platform.get_client() text = reminder_text(rem) if rem["platform_name"] in OFFICIAL: api = client.api scene = rem["scene"] + kwargs = dict(reply or {}) + if scene not in {"group", "c2c"}: + kwargs.pop("msg_seq", None) if scene == "group": mention = f'' result = await api.post_group_message( - group_openid=rem["destination"], msg_type=0, content=f"{mention}\n{text}" + group_openid=rem["destination"], msg_type=0, content=f"{mention}\n{text}", **kwargs ) elif scene == "c2c": - result = await api.post_c2c_message(openid=rem["destination"], msg_type=0, content=text) + result = await api.post_c2c_message( + openid=rem["destination"], msg_type=0, content=text, **kwargs + ) elif scene == "channel": result = await api.post_message( - channel_id=rem["destination"], content=f"<@{rem['target_id']}>\n{text}" + channel_id=rem["destination"], content=f"<@{rem['target_id']}>\n{text}", **kwargs ) elif scene == "guild_dm": - result = await api.post_dms(guild_id=rem["destination"], content=text) + result = await api.post_dms(guild_id=rem["destination"], content=text, **kwargs) else: raise ValueError(f"未知官方 QQ 投递场景:{scene}") if not field(result, "id"): diff --git a/services/storage.py b/services/storage.py index 41a735a..6d0a406 100644 --- a/services/storage.py +++ b/services/storage.py @@ -64,7 +64,18 @@ class ReminderStore: nickname TEXT NOT NULL DEFAULT '', seen_at REAL NOT NULL, PRIMARY KEY(scope, user_id) ); + CREATE TABLE IF NOT EXISTS reply_contexts ( + platform_id TEXT NOT NULL, scene TEXT NOT NULL, destination TEXT NOT NULL, + msg_id TEXT NOT NULL, received_at REAL NOT NULL, + used INTEGER NOT NULL DEFAULT 0, blocked INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(platform_id, scene, destination) + ); """) + columns = {row[1] for row in db.execute("PRAGMA table_info(reminders)")} + if "waiting_reason" not in columns: + db.execute( + "ALTER TABLE reminders ADD COLUMN waiting_reason TEXT NOT NULL DEFAULT ''" + ) await self._run(create) @@ -153,7 +164,7 @@ class ReminderStore: async def cancel(self, scope, creator_id, reminder_id=None): def write(db): - sql = "UPDATE reminders SET status='cancelled', lease_owner='', lease_until=0 WHERE scope=? AND status='active'" + sql = "UPDATE reminders SET status='cancelled', waiting_reason='', lease_owner='', lease_until=0 WHERE scope=? AND status='active'" params = [scope] if creator_id is not None: sql += " AND creator_id=?" @@ -171,7 +182,7 @@ class ReminderStore: dict(r) for r in db.execute( "SELECT * FROM reminders WHERE status='active' AND remind_at<=? " - "AND retry_at<=? AND lease_until<=? ORDER BY remind_at,id LIMIT 100", + "AND retry_at<=? AND lease_until<=? ORDER BY remind_at,id", (now, now, now), ) ] @@ -195,7 +206,7 @@ class ReminderStore: lambda db: ( db.execute( "UPDATE reminders SET status=?,remind_at=COALESCE(?,remind_at),failure_count=0," - "last_error='',retry_at=0,lease_owner='',lease_until=0 WHERE id=? AND lease_owner=? AND status='active'", + "last_error='',waiting_reason='',retry_at=0,lease_owner='',lease_until=0 WHERE id=? AND lease_owner=? AND status='active'", ("active" if next_time is not None else "done", next_time, reminder_id, owner), ).rowcount ) @@ -204,7 +215,7 @@ class ReminderStore: async def failure(self, reminder_id, owner, error, maximum, retry_at): def write(db): db.execute( - "UPDATE reminders SET failure_count=failure_count+1,last_error=?,retry_at=?," + "UPDATE reminders SET failure_count=failure_count+1,last_error=?,retry_at=?,waiting_reason=''," "status=CASE WHEN failure_count+1>=? THEN 'cancelled' ELSE 'active' END," "lease_owner='',lease_until=0 WHERE id=? AND lease_owner=? AND status='active'", (str(error)[:500], retry_at, maximum, reminder_id, owner), @@ -221,3 +232,88 @@ class ReminderStore: ).rowcount ) ) + + async def remember_reply(self, platform_id, scene, destination, msg_id, received_at): + # Duplicate/replayed events must not renew expiry or refill reply quota. + await self._run( + lambda db: ( + db.execute( + "INSERT INTO reply_contexts(platform_id,scene,destination,msg_id,received_at) VALUES (?,?,?,?,?) " + "ON CONFLICT(platform_id,scene,destination) DO UPDATE SET " + "msg_id=excluded.msg_id,received_at=excluded.received_at,used=0,blocked=0 " + "WHERE reply_contexts.msg_id!=excluded.msg_id AND excluded.received_at>=reply_contexts.received_at", + (platform_id, scene, destination, msg_id, received_at), + ).rowcount + ) + ) + + async def reserve_reply(self, platform_id, scene, destination, now, window): + def reserve(db): + db.execute("BEGIN IMMEDIATE") + row = db.execute( + "SELECT * FROM reply_contexts WHERE platform_id=? AND scene=? AND destination=?", + (platform_id, scene, destination), + ).fetchone() + # Reserve two of QQ's five replies for command responses/other plugins. + if ( + not row + or row["blocked"] + or row["used"] >= 3 + or not 0 <= now - row["received_at"] < window + ): + return None + db.execute( + "UPDATE reply_contexts SET used=used+1 WHERE platform_id=? AND scene=? AND destination=?", + (platform_id, scene, destination), + ) + # AstrBot's official event sender uses random sequences in 1..10000. + return {"msg_id": row["msg_id"], "msg_seq": 20001 + row["used"]} + + return await self._run(reserve) + + async def block_reply(self, platform_id, scene, destination, msg_id): + await self._run( + lambda db: ( + db.execute( + "UPDATE reply_contexts SET blocked=1 WHERE platform_id=? AND scene=? AND destination=? AND msg_id=?", + (platform_id, scene, destination, msg_id), + ).rowcount + ) + ) + + async def wait_for_reply(self, reminder_id, owner, reason): + await self._run( + lambda db: ( + db.execute( + "UPDATE reminders SET waiting_reason=?,retry_at=0,lease_owner='',lease_until=0 " + "WHERE id=? AND lease_owner=? AND status='active'", + (reason[:500], reminder_id, owner), + ).rowcount + ) + ) + + async def resume(self, scope, creator_id, reminder_id, limit): + def write(db): + db.execute("BEGIN IMMEDIATE") + row = db.execute( + "SELECT * FROM reminders WHERE scope=? AND id=?", (scope, reminder_id) + ).fetchone() + if not row or (creator_id is not None and row["creator_id"] != creator_id): + raise ValueError("当前会话中找不到该提醒,或你没有操作权限。") + if row["status"] == "done" or (row["status"] == "cancelled" and not row["last_error"]): + raise ValueError("只能重试投递失败或正在等待的提醒。") + if row["lease_until"] > time.time(): + raise ValueError("该提醒正在投递,请稍后重试。") + count = db.execute( + "SELECT COUNT(*) FROM reminders WHERE scope=? AND creator_id=? AND status='active' AND id!=?", + (scope, row["creator_id"], reminder_id), + ).fetchone()[0] + if count >= limit: + raise ValueError(f"最多只能设置 {limit} 个活跃提醒,请先取消一些。") + db.execute( + "UPDATE reminders SET status='active',failure_count=0,last_error='',waiting_reason=''," + "retry_at=0,lease_owner='',lease_until=0 WHERE id=?", + (reminder_id,), + ) + + await self._run(write) diff --git a/tests/test_passive_delivery.py b/tests/test_passive_delivery.py new file mode 100644 index 0000000..5babd5c --- /dev/null +++ b/tests/test_passive_delivery.py @@ -0,0 +1,216 @@ +import asyncio +import sqlite3 +import time +from datetime import datetime, timezone +from types import SimpleNamespace + +import pytest +from test_reminders import record + +from services.delivery import deliver, incoming_reply +from services.storage import ReminderStore + + +@pytest.fixture +async def passive_plugin(plugin_class, platform_factory): + platform = platform_factory() + context = SimpleNamespace(platform_manager=SimpleNamespace(platform_insts=[platform])) + instance = plugin_class(context, {"check_interval_seconds": 999}) + await instance.store.initialize() + instance._ready = True + assert instance.delivery_mode == "passive" + yield instance, platform + await instance.terminate() + + +def inbound( + event_factory, *, message="incoming_1", group="group_1", user="user_1", age=0, text="/tx list" +): + raw = { + "id": message, + "timestamp": datetime.fromtimestamp(time.time() - age, timezone.utc).isoformat(), + } + if group: + raw["group_openid"] = group + return event_factory(text, group=group, user=user, raw=raw) + + +async def test_no_window_waits_without_sending_or_cancelling(passive_plugin): + instance, platform = passive_plugin + rem_id = await instance.store.add(record(), 10) + for _ in range(4): + await instance._check_due() + rem = await instance.store.get(rem_id, record()["scope"]) + assert rem["status"] == "active" and rem["failure_count"] == 0 and rem["waiting_reason"] + platform.get_client().api.post_group_message.assert_not_awaited() + assert "等待可回复消息" in instance._format(rem) + + +@pytest.mark.parametrize("name", ["qq_official", "qq_official_webhook"]) +async def test_fresh_message_delivers_pending_with_msg_id(passive_plugin, event_factory, name): + instance, platform = passive_plugin + rem_id = await instance.store.add(record(platform_name=name), 10) + await instance._check_due() + event = inbound(event_factory) + event.platform = name + await instance.observe_member(event) + assert instance._wake.is_set() and not event.stopped + await instance._check_due() + sent = platform.get_client().api.post_group_message.call_args.kwargs + assert sent["msg_id"] == "incoming_1" and sent["msg_seq"] > 10000 + assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "done" + + +async def test_expired_reply_not_reused_and_group_isolated(passive_plugin, event_factory): + instance, platform = passive_plugin + rem_id = await instance.store.add(record(), 10) + await instance.observe_member(inbound(event_factory, age=301)) + await instance.observe_member(inbound(event_factory, group="another_group")) + await instance._check_due() + platform.get_client().api.post_group_message.assert_not_awaited() + assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "active" + await instance.observe_member(inbound(event_factory, message="fresh")) + await instance._check_due() + assert platform.get_client().api.post_group_message.call_args.kwargs["msg_id"] == "fresh" + + +async def test_reply_quota_unique_sequences_and_replay(passive_plugin, event_factory): + instance, platform = passive_plugin + ids = [await instance.store.add(record(), 10) for _ in range(4)] + event = inbound(event_factory) + await instance.observe_member(event) + await instance._check_due() + assert platform.get_client().api.post_group_message.await_count == 3 + sequences = [ + call.kwargs["msg_seq"] + for call in platform.get_client().api.post_group_message.call_args_list + ] + assert len(set(sequences)) == 3 + await instance.observe_member(event) + await instance._check_due() + assert platform.get_client().api.post_group_message.await_count == 3 + assert (await instance.store.get(ids[-1], record()["scope"]))["waiting_reason"] + await instance.observe_member(inbound(event_factory, message="new_id")) + await instance._check_due() + assert (await instance.store.get(ids[-1], record()["scope"]))["status"] == "done" + + +@pytest.mark.parametrize( + "error", ["msg limit exceed 22009", "msg_id expired", "主动消息失败, 无权限"] +) +async def test_platform_reply_rejection_waits_for_new_message(passive_plugin, event_factory, error): + instance, platform = passive_plugin + api = platform.get_client().api.post_group_message + api.side_effect = RuntimeError(error) + rem_id = await instance.store.add(record(), 10) + await instance.observe_member(inbound(event_factory)) + await instance._check_due() + rem = await instance.store.get(rem_id, record()["scope"]) + assert rem["failure_count"] == 0 and rem["status"] == "active" + assert error in rem["waiting_reason"] + await instance._check_due() + assert api.await_count == 1 + api.side_effect = None + await instance.observe_member(inbound(event_factory, message="new_id")) + await instance._check_due() + assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "done" + + +async def test_c2c_longer_window_and_same_user_destination(passive_plugin, event_factory): + instance, platform = passive_plugin + event = inbound(event_factory, group="", age=1800) + rem_id = await instance.store.add( + record(scene="c2c", destination="user_1", scope=instance._scope(event)), 10 + ) + await instance.observe_member(event) + await instance._check_due() + kwargs = platform.get_client().api.post_c2c_message.call_args.kwargs + assert kwargs["openid"] == "user_1" and kwargs["msg_id"] == "incoming_1" + assert (await instance.store.get(rem_id, instance._scope(event)))["status"] == "done" + + +async def test_retry_cancelled_legacy_failure_and_permission(passive_plugin, event_factory): + instance, platform = passive_plugin + rem_id = await instance.store.add(record(), 10) + await instance.store.claim(rem_id, instance.owner, time.time()) + await instance.store.failure(rem_id, instance.owner, "主动消息失败, 无权限", 1, 0) + denied = inbound(event_factory, user="other", text=f"/tx retry {rem_id}") + await instance.tx(denied) + assert "没有操作权限" in denied.replies[0] + event = inbound(event_factory, message="retry_msg", text=f"/tx retry {rem_id}") + await instance.tx(event) + assert "已恢复" in event.replies[0] + await instance._check_due() + rem = await instance.store.get(rem_id, record()["scope"]) + assert rem["status"] == "done" and rem["failure_count"] == 0 + assert platform.get_client().api.post_group_message.call_args.kwargs["msg_id"] == "retry_msg" + + +async def test_context_persistence_quota_transaction_and_late_replay(tmp_path): + first = ReminderStore(tmp_path / "db") + await first.initialize() + now = time.time() + await first.remember_reply("p", "group", "g", "new", now) + second = ReminderStore(first.path) + await second.initialize() + results = await asyncio.gather( + *(s.reserve_reply("p", "group", "g", now, 240) for s in [first, second, first, second]) + ) + assert sum(r is not None for r in results) == 3 + await second.remember_reply("p", "group", "g", "old", now - 100) + await second.remember_reply("p", "group", "g", "new", now + 100) + assert await second.reserve_reply("p", "group", "g", now, 240) is None + assert await second.reserve_reply("p", "group", "different_group", now, 240) is None + assert await second.reserve_reply("different_platform", "group", "g", now, 240) is None + + +def test_incoming_time_validation(event_factory): + event = inbound(event_factory, age=600) + assert time.time() - incoming_reply(event)["received_at"] >= 599 + event.message_obj.raw_message = {"id": "x", "timestamp": "bad"} + assert incoming_reply(event) is None + event.message_obj.raw_message = {"id": "x", "timestamp": "2026-10-05T00:00:00"} + assert incoming_reply(event) is None + event.message_obj.raw_message = {"timestamp": time.time()} + assert incoming_reply(event) is None + + +@pytest.mark.parametrize("scene,method", [("channel", "post_message"), ("guild_dm", "post_dms")]) +async def test_guild_passive_omits_unsupported_sequence(platform_factory, scene, method): + platform = platform_factory() + await deliver( + platform, {**record(scene=scene), "id": 1}, {"msg_id": "incoming", "msg_seq": 20001} + ) + kwargs = getattr(platform.get_client().api, method).call_args.kwargs + assert kwargs["msg_id"] == "incoming" and "msg_seq" not in kwargs + + +async def test_migration_from_v1_database_preserves_tasks(tmp_path): + store = ReminderStore(tmp_path / "legacy.db") + await store.initialize() + rem_id = await store.add(record(), 10) + # Remove only the added column to emulate the previously released schema. + with sqlite3.connect(store.path) as db: + db.execute("ALTER TABLE reminders DROP COLUMN waiting_reason") + db.execute("DROP TABLE reply_contexts") + upgraded = ReminderStore(store.path) + await upgraded.initialize() + restored = await upgraded.get(rem_id, record()["scope"]) + assert restored["content"] == "吃饭" and restored["status"] == "active" + assert restored["waiting_reason"] == "" + + +async def test_poll_wakes_on_incoming_instead_of_waiting_999_seconds(passive_plugin, event_factory): + instance, platform = passive_plugin + rem_id = await instance.store.add(record(), 10) + await instance.initialize() + try: + await instance.observe_member(inbound(event_factory)) + for _ in range(100): + if (await instance.store.get(rem_id, record()["scope"]))["status"] == "done": + break + await asyncio.sleep(0.01) + assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "done" + assert platform.get_client().api.post_group_message.await_count == 1 + finally: + await instance.terminate() diff --git a/tests/test_reminders.py b/tests/test_reminders.py index 0ead300..c3b1f9f 100644 --- a/tests/test_reminders.py +++ b/tests/test_reminders.py @@ -151,7 +151,9 @@ async def test_ambiguous_multiple_all_and_private(tmp_path, event_factory): async def plugin(plugin_class, platform_factory): platform = platform_factory() context = SimpleNamespace(platform_manager=SimpleNamespace(platform_insts=[platform])) - instance = plugin_class(context, {"check_interval_seconds": 999}) + instance = plugin_class( + context, {"check_interval_seconds": 999, "official_delivery_mode": "proactive"} + ) await instance.store.initialize() # Control scans explicitly in integration tests; lifecycle is tested separately. instance._ready = True @@ -261,6 +263,7 @@ async def test_unload_waits_for_delivery_persistence(plugin_class, platform_fact context = SimpleNamespace(platform_manager=SimpleNamespace(platform_insts=[platform])) instance = plugin_class(context, {"check_interval_seconds": 999}) await instance.store.initialize() + await instance.store.remember_reply("platform_1", "group", "group_1", "incoming", time.time()) rem_id = await instance.store.add(record(), 10) entered, release = asyncio.Event(), asyncio.Event() @@ -271,7 +274,7 @@ async def test_unload_waits_for_delivery_persistence(plugin_class, platform_fact platform.get_client().api.post_group_message.side_effect = delayed_send await instance.initialize() - await entered.wait() + await asyncio.wait_for(entered.wait(), timeout=2) unload = asyncio.create_task(instance.terminate()) await asyncio.sleep(0) assert not unload.done()