Restore proactive reminders with group permission guidance and verification

This commit is contained in:
itxiaohui committed 2026-10-05 19:58:27 +08:00
1 parent 58d6807ed0
commit 88cadbac0b
10 files changed
+679 -30

No files matched your search

+20 -14
View File
@@ -12,7 +12,7 @@
https://github.com/itxiaohui66/astrbot_plugin_tixing
```
也可以从 [GitHub Releases](https://github.com/itxiaohui66/astrbot_plugin_tixing/releases/latest) 下载 `astrbot_plugin_tixing-v1.1.0.zip`,在插件页上传安装。手动安装时,把 ZIP 中的 `astrbot_plugin_tixing` 文件夹解压到 AstrBot 的 `data/plugins/` 下,然后重启或重载插件。运行文件 `main.py`、`metadata.yaml` 和 `_conf_schema.json` 必须直接位于该插件文件夹中。
也可以从 [GitHub Releases](https://github.com/itxiaohui66/astrbot_plugin_tixing/releases/latest) 下载 `astrbot_plugin_tixing-v1.2.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,9 +53,9 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
时间和内容之间要有空格。内容可以包含空格、换行,默认最多 1000 个字符。单次 `HH:MM` 表示今天该时刻,已经过去则提示改用未来时间;每天和每周自动计算下一次。提醒间隔必须大于 0,小时范围 0–23,分钟范围 0–59。
到期后在创建时的群或私聊发送提醒。QQ 官方默认使用被动回复:只有存在有效的近期用户消息和回复额度时才投递,否则保留任务,在下一条机器人收到的同会话消息到来后尝试补发。因此,没有主动消息能力时,长时间后的提醒不能保证准点发出;群内可 `@机器人 /tx list` 打开新的回复窗口。
到期后在创建时的群或私聊发送提醒。QQ 官方默认使用**主动发送**,无需等待群成员再次 @机器人。群主或管理员需在本群的机器人权限设置中开启“允许机器人主动发送消息”;入群或首次使用提醒命令时会提示检查该开关。
循环任务按创建时的时区续期,修改配置时区只影响新任务。离线或等待期间错过多次循环,会在有效窗口中补发一次并续到下一次未来时刻,避免刷屏。一次性逾期提醒同样等待有效窗口补发;如果适配器还未加载或运行,不增加失败次数。OneBot 的发送方式保持原样。
循环任务按创建时的时区续期,修改配置时区只影响新任务。离线或等待权限期间错过多次循环,恢复投递时补发一次并续到下一次未来时刻,避免刷屏。一次性逾期提醒也会保留并补发;如果适配器还未加载或运行,不增加失败次数。OneBot 的发送方式保持原样。
## 管理命令
@@ -70,15 +70,17 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
| `/tx retry 编号` | 恢复投递失败后自动取消的任务,或重试待投递任务;仍检查当前会话、创建者和数量限制 |
| `/tx identity` | 当前平台、群、用户标识和本群授权管理员标识 |
| `/tx status` | 调度器状态、当前会话活跃数量、时区、扫描间隔和最近错误 |
| `/tx permission` / `/tx 权限` | 当前官方群的权限记录和开启说明 |
| `/tx permission check` | 实际发送一条主动测试消息;成功后立即唤醒等待权限的到期提醒 |
| `/cxzd` / `/重启提醒` | 管理员重启提醒调度器 |
| `/tx list all [页码]` | 管理员查看当前会话所有人的活跃任务 |
| `/tx history all [页码]` | 管理员查看当前会话所有人的历史 |
管理员可以取消当前会话其他人的单条任务、查看详情。按编号操作也受平台和群隔离限制。群管理员并不会自动获得机器人管理权限;使用 AstrBot 管理员配置,或在插件配置中加入 `admin_ids`、`group_admin_ids`。`group_admin_ids` 的格式为 `平台ID|群OpenID|用户OpenID`,可从 `/tx identity` 复制。
列表每页 2 条,长内容显示预览,可用 `detail` 查看全文。缺少回复窗口、额度用完或 QQ 拒绝该回复上下文时,状态显示“等待可回复消息”,不会因此自动取消。普通投递错误超过失败阈值后仍会自动取消,可以在 `history` 中查到原因。
列表每页 2 条,长内容显示预览,可用 `detail` 查看全文。主动发送无权限时,状态显示“等待主动消息权限”,不会因此自动取消。普通投递错误超过失败阈值后仍会自动取消,可以在 `history` 中查到原因。
从 v1.0.0 更新后,数据库自动升级并保留原提醒。已经因“主动消息失败,无权限”自动取消的任务不会被擅自恢复;在原群中发送 `/tx retry 2`、`/tx retry 3` 等对应编号即可恢复。等待中的提醒、未到期提醒仍占用活跃任务额度。
从 v1.0.0 / v1.1.0 更新后,数据库自动升级并保留原提醒。v1.2.0 默认恢复主动发送,旧 `official_delivery_mode` 配置由 `proactive_reminders` 替代。已经因“主动消息失败,无权限”自动取消的任务不会被擅自恢复;先开启权限并验证,再在原群中发送 `/tx retry 2`、`/tx retry 3` 等对应编号恢复。等待中的提醒、未到期提醒仍占用活跃任务额度。
## 官方 QQ 的对象和发送权限
@@ -90,11 +92,15 @@ https://github.com/itxiaohui66/astrbot_plugin_tixing
插件会记住本群里机器人实际收到的成员消息,名字唯一且官方提供昵称时也支持 `@昵称`。不同群里的成员记录不会混用,重名时要求明确标识。OneBot 模式会查询目标是否是本群成员。私聊只能提醒自己。
v1.1.0 默认采用 **被动回复**:使用真正收到的用户消息 `msg_id`,群、频道、频道私信保守采用 4 分钟窗口,C2C 保守采用 59 分钟窗口,给网络发送留出安全余量。官方文档规定群回复有效期 5 分钟、C2C 60 分钟,每条消息最多回复 5 次;插件每个上下文最多投递 3 条提醒,留出回复次数给命令响应和其他插件。若其他插件已经用完回复额度,QQ 拒绝该上下文后会等待下一条消息。
v1.2.0 默认采用 **主动发送**。新群的 `GROUP_ADD_ROBOT` 事件到来时,插件使用该真实事件的 `event_id` 回复管理员开启说明;若事件缺失、发送失败或插件是后来才安装的,则在首次提醒命令回复中附加说明。提示按平台和群持久化,成功提示后不会在每次命令中重复。
回复上下文按平台、场景和投递目标隔离,保存消息原始时间及已用次数;重复事件不会延长有效期或补充额度。群/C2C 的提醒采用与 AstrBot 当前回复发送范围分开的独立 `msg_seq`。新消息到来会唤醒扫描器,不必等到下一轮轮询。只有接口返回消息 ID 后才标记成功或续期;被动发送失败时不降级为无权限的主动发送。
插件接收官方 SDK 的 `GROUP_MSG_RECEIVE` / `GROUP_MSG_REJECT` 事件,分别记录允许和关闭状态。已收到允许事件或实际发送成功的群不会被误报为未开启;没有证据时仅提示“确认已开启”。退群及重新入群事件也会更新记录。生命周期监听支持 WebSocket 和 Webhook,保留其他组件已有的回调,重载时移除本插件监听。
`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)。
管理员开启后,在原群发送 `@机器人 /tx permission check`。验证消息不带 `msg_id` 或 `event_id`,接口返回消息 ID 后才确认主动投递成功,并唤醒等待权限的到期任务。群开关允许后仍以 QQ 接口实际返回为准;应用本身的权限、发送额度等限制会显示在验证结果或提醒记录中。官方事件依据 [腾讯 botpy 群管理事件](https://github.com/tencent-connect/botpy/blob/master/botpy/manage.py) 和 [事件解析器](https://github.com/tencent-connect/botpy/blob/master/botpy/connection.py),消息接口依据 [腾讯官方消息收发文档](https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/server-inter/message/send-receive/send.md)。
主动消息被 QQ 拒绝且错误指向权限时,插件保留任务、不增加失败次数,并每 5 分钟重试。若明确收到管理员拒绝消息或退群事件,则暂停主动投递,等待允许事件或主动验证成功。允许事件和验证成功会使等待权限的到期任务立即进入扫描;接口仍失败时继续保留。命令回复使用当前消息进行被动回复,因此也能在权限未开时显示设置说明。
如需使用被动回复,可关闭 `proactive_reminders`。这时只有存在有效的近期用户消息和回复额度才投递,超出窗口则等待下一条同会话消息。群、频道、频道私信保守采用 4 分钟窗口,C2C 59 分钟;每条消息最多投递 3 条提醒,给命令回复和其他插件预留额度。回复上下文按平台、场景和目标隔离;重复事件不会刷新有效期或额度,受限时不会切换为主动发送。被动模式无法保证长时间后准点提醒。
QQ 普通群使用 `<qqbot-at-user id="OpenID" />` 实现真正 @,频道使用频道成员 ID。群、C2C、频道、频道私信分别走对应 SDK 接口。插件自己的到期提醒使用普通文本,不要求 Markdown 模板;命令回复仍由 AstrBot 当前事件的配置发送。
@@ -106,7 +112,7 @@ QQ 普通群使用 `<qqbot-at-user id="OpenID" />` 实现真正 @,频道使用
| 字段 | 默认值 | 说明 |
| --- | --- | --- |
| `official_delivery_mode` | `passive` | 默认被动回复,等待有效窗口;可显式选 `proactive` 保留原发送方式 |
| `proactive_reminders` | `true` | 默认到点主动投递并提示群权限;关闭后使用被动回复 |
| `timezone` | `Asia/Shanghai` | IANA 时区 |
| `max_per_user` | `10` | 当前会话每人最多活跃任务 |
| `check_interval_seconds` | `30` | 扫描周期,最小 1 秒 |
@@ -128,15 +134,15 @@ ruff format --check .
python tools/package.py
```
自动化测试使用真实 SQLite 和时间解析;AstrBot 主机边界和 QQ 发送接口使用测试替身,覆盖时间格式、上限、群隔离、成员识别、失败重试、循环补发、权限、热重载,以及回复时效、额度、序号、重复事件、即时唤醒和数据库升级。GitHub Actions 会在 Linux(Python 3.10、3.12)和 Windows(Python 3.12)上运行测试、代码检查和打包。真实 QQ 投递仍需在实际部署的 AstrBot 和账号中验证。
自动化测试使用真实 SQLite 和时间解析;AstrBot 主机边界和 QQ 发送接口使用测试替身,覆盖时间格式、上限、群隔离、成员识别、失败重试、循环补发、权限、入群提示、首次使用去重、允许/拒绝事件、回调恢复、重载,以及回复时效、额度、序号、重复事件、即时唤醒和数据库升级。GitHub Actions 会在 Linux(Python 3.10、3.12)和 Windows(Python 3.12)上运行测试、代码检查和打包。真实 QQ 投递仍需在实际部署的 AstrBot 和账号中验证。
安装后可用以下流程确认部署环境:
1. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,并在有效回复窗口内收到真正 @ 的通知。
2. `/tx history` 检查该任务状态;失败时检查记录里的原因和 AstrBot 日志。
1. 首次命令或入群时确认收到权限开启提示;管理员开启“允许机器人主动发送消息”后,`@机器人 /tx permission check` 确认主动验证成功。
2. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,到期收到真正 @ 的通知;`/tx history` 检查状态,失败时查看原因和日志。
3. `/tx 5分钟 重启测试`,重载插件后用 `/tx list` 确认仍在,再 `/tx cancel 编号` 确认取消。
4. 让另一成员先发送 `/tx identity`,测试本群的他人提醒。
5. 超过群回复窗口后,确认 `/tx list` 显示待补发原因;在群里再次 @机器人 时应唤醒投递。若已因旧版错误自动取消,先 `/tx retry 编号` 恢复。
5. `@机器人 /tx 6分钟 主动提醒测试`,期间不再 @机器人,确认到期仍收到提醒。若因权限不足显示等待,开好权限并再次验证;旧版已自动取消的任务需先 `/tx retry 编号` 恢复。
## 来源
+1 -1
View File
@@ -1,5 +1,5 @@
{
"official_delivery_mode": {"type": "string", "description": "QQ 官方发送方式", "options": ["passive", "proactive"], "hint": "默认 passive 被动回复;没有有效回复窗口时保留任务等待下次消息。仅已确认支持主动消息的账号选择 proactive。", "default": "passive"},
"proactive_reminders": {"type": "bool", "description": "QQ 官方到点主动提醒", "hint": "默认开启;首次入群/使用提示管理员允许主动消息。关闭后使用有时效和额度限制的被动回复。v1.2 起替代旧 official_delivery_mode 配置。", "default": true},
"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},
+205 -8
View File
@@ -16,11 +16,14 @@ from .services.delivery import (
OFFICIAL,
available,
deliver,
field,
find_platform,
incoming_reply,
proactive_denied,
reply_unavailable,
route,
)
from .services.permissions import NOTICE, PermissionBridge
from .services.storage import ReminderStore, scope_key
from .services.targets import MARKUP, resolve_target
from .services.time_parser import describe, next_occurrence, parse_time
@@ -41,11 +44,13 @@ HELP = """⏰ 栗子提醒
/tx retry 编号 恢复投递失败的提醒
/tx identity 查看当前平台、群和用户标识
/tx status 查看提醒调度器状态
/tx permission 查看主动消息权限说明
/tx permission check 发送主动消息验证权限
/cxzd 管理员重启提醒调度器
命令别名:/提醒、/remind
群内官方 QQ 需要 @机器人;时间按配置时区计算。
官方 QQ 提醒他人须使用本群 OpenID 或真实 @;普通 QQ 号不可转换。
默认使用被动回复;没有有效回复窗口时等待下次 @机器人 补发。
默认到点主动提醒;群主/管理员需开启“允许机器人主动发送消息”。
管理员可 /tx list all 和 /tx cancel 编号 管理当前群提醒。"""
@@ -65,9 +70,8 @@ class ReminderPlugin(Star):
self.max_failures = max(1, int(config.get("max_delivery_failures", 3)))
self.retry_seconds = max(1, int(config.get("retry_interval_seconds", 60)))
self.max_content = max(1, min(1500, int(config.get("max_content_length", 1000))))
self.delivery_mode = config.get("official_delivery_mode", "passive")
if self.delivery_mode not in {"passive", "proactive"}:
raise ValueError("official_delivery_mode 必须为 passive 或 proactive")
# v1.2 replaces the old v1.1 passive default with a new configuration key.
self.delivery_mode = "proactive" if config.get("proactive_reminders", True) else "passive"
self._wake = asyncio.Event()
self.store = ReminderStore(StarTools.get_data_dir("astrbot_plugin_tixing") / "reminders.db")
self.owner = uuid.uuid4().hex
@@ -76,6 +80,8 @@ class ReminderPlugin(Star):
self._init_lock = asyncio.Lock()
self._scan_lock = asyncio.Lock()
self._scheduler = None
self._permission_watcher = None
self._bridges = {}
self.last_scan = 0
self.last_scan_error = ""
@@ -86,6 +92,9 @@ class ReminderPlugin(Star):
if not self._ready:
await self.store.initialize()
self._ready = True
await self._attach_platforms()
if self._permission_watcher is None or self._permission_watcher.done():
self._permission_watcher = asyncio.create_task(self._watch_platforms())
if self._scheduler is None or self._scheduler.done():
self._scheduler = asyncio.create_task(self._poll(), name="lizi-reminders")
@@ -93,6 +102,90 @@ class ReminderPlugin(Star):
async def on_loaded(self):
await self.initialize()
async def _attach_platforms(self):
live = set()
for platform in self.context.platform_manager.platform_insts:
if platform.meta().name not in OFFICIAL:
continue
client = platform.get_client()
if client is None:
continue
key = id(client)
live.add(key)
if key not in self._bridges:
bridge = PermissionBridge(platform, self._permission_event)
bridge.install()
self._bridges[key] = bridge
for key in set(self._bridges) - live:
await self._bridges.pop(key).close()
async def _watch_platforms(self):
while True:
await asyncio.sleep(5)
try:
await self._attach_platforms()
except Exception:
logger.exception("[Reminder] 连接 QQ 群权限事件失败,将继续重试")
async def _permission_event(self, platform, kind, event):
if self._closed:
return
destination = str(field(event, "group_openid") or "")
if not destination:
return
platform_id = str(platform.meta().id)
event_id = str(field(event, "event_id") or "")
stamp = field(event, "timestamp")
try:
event_at = float(stamp)
except (ValueError, TypeError):
try:
event_at = datetime.fromisoformat(str(stamp).replace("Z", "+00:00")).timestamp()
except (ValueError, TypeError):
event_at = time.time()
states = {
"group_add_robot": "unknown",
"group_del_robot": "removed",
"group_msg_receive": "granted",
"group_msg_reject": "denied",
}
changed = await self.store.set_permission(
platform_id,
destination,
states[kind],
event_at,
event_id,
reset=kind in {"group_add_robot", "group_del_robot", "group_msg_reject"},
)
if not changed:
return
if kind == "group_msg_receive":
self._wake.set()
if kind != "group_add_robot" or not event_id or self.delivery_mode != "proactive":
return
if not await self.store.claim_notice(platform_id, destination):
return
sent = False
try:
# A real join event can be replied to even before proactive permission is enabled.
result = await asyncio.wait_for(
platform.get_client().api.post_group_message(
group_openid=destination,
msg_type=0,
content=NOTICE,
event_id=event_id,
msg_seq=20001,
),
timeout=30,
)
sent = bool(field(result, "id"))
if not sent:
logger.warning("[Reminder] 入群权限提示没有返回消息 ID,将在首次命令时提示")
except Exception as exc:
logger.warning("[Reminder] 入群权限提示失败,将在首次命令时提示:%s", exc)
finally:
await self.store.finish_notice(platform_id, destination, sent)
async def _poll(self):
while True:
try:
@@ -117,6 +210,20 @@ class ReminderPlugin(Star):
if not await self.store.claim(rem["id"], self.owner, time.time()):
continue
reply = None
if (
rem["platform_name"] in OFFICIAL
and self.delivery_mode == "proactive"
and rem["scene"] == "group"
):
permission = await self.store.permission(rem["platform_id"], rem["destination"])
if permission["state"] in {"denied", "removed"}:
await self.store.wait_for_permission(
rem["id"],
self.owner,
"主动消息权限未开启或机器人已退群;请管理员开启后 /tx permission check 验证",
time.time() + 300,
)
continue
if rem["platform_name"] in OFFICIAL and self.delivery_mode == "passive":
# QQ documents group/channel/DM windows of 5 min, C2C 60 min.
# Leave a margin for the 30 s send timeout.
@@ -145,6 +252,21 @@ class ReminderPlugin(Star):
try:
await asyncio.wait_for(deliver(platform, rem, reply), timeout=30)
except Exception as exc:
if reply is None and rem["platform_name"] in OFFICIAL and proactive_denied(exc):
if rem["scene"] == "group":
await self.store.set_permission(
rem["platform_id"], rem["destination"], "error", reset=True
)
await self.store.wait_for_permission(
rem["id"],
self.owner,
f"主动消息权限受限:{exc};请管理员开启后 /tx permission check 验证,任务保留并每 5 分钟重试",
time.time() + 300,
)
logger.warning(
"[Reminder] 提醒 #%s 等待主动消息权限,任务已保留:%s", rem["id"], exc
)
return
if reply is not None and reply_unavailable(exc):
await self.store.block_reply(
rem["platform_id"], rem["scene"], rem["destination"], reply["msg_id"]
@@ -173,6 +295,8 @@ class ReminderPlugin(Star):
rem["remind_at"], rem["repeat_type"], rem["timezone"], time.time()
)
await self.store.success(rem["id"], self.owner, next_time)
if reply is None and rem["platform_name"] in OFFICIAL and rem["scene"] == "group":
await self.store.set_permission(rem["platform_id"], rem["destination"], "granted")
logger.info("[Reminder] 提醒 #%s 已投递,平台=%s", rem["id"], rem["platform_id"])
def _admin(self, event):
@@ -194,7 +318,25 @@ class ReminderPlugin(Star):
async def _reply(self, event, text):
# Passive command responses are sent by AstrBot using the current event.
await event.send(event.plain_result(text))
destination = ""
if event.get_platform_name() in OFFICIAL and self.delivery_mode == "proactive":
try:
scene, dest = route(event)
except ValueError:
scene, dest = "", ""
if scene == "group" and await self.store.claim_notice(
str(event.get_platform_id()), dest
):
destination = dest
if NOTICE not in text:
text += "\n\n" + NOTICE
sent = False
try:
await event.send(event.plain_result(text))
sent = True
finally:
if destination:
await self.store.finish_notice(str(event.get_platform_id()), destination, sent)
async def _guard(self, event, action):
try:
@@ -249,7 +391,10 @@ class ReminderPlugin(Star):
scope, None if self._admin(event) else user, int(tail), self.limit
)
self._wake.set()
await self._reply(event, f"✅ 提醒 #{tail} 已恢复,等待有效回复窗口投递。")
await self._reply(event, f"✅ 提醒 #{tail} 已恢复,将按当前发送方式重试投递。")
return
if action in {"permission", "权限"}:
await self._permission_command(event, tail)
return
if action in {"detail", "详情"}:
if not tail.isdecimal():
@@ -310,13 +455,17 @@ class ReminderPlugin(Star):
if self.delivery_mode == "passive":
message += "\n使用被动回复:到期有有效回复窗口时发送,否则等待下次 @机器人 补发。"
else:
message += "\n使用主动投递;发送权限或额度受限时会记录失败。"
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 = "等待可回复消息"
status = (
"等待主动消息权限"
if rem["waiting_reason"].startswith("主动消息权限")
else "等待可回复消息"
)
content = (
rem["content"]
if detail
@@ -334,6 +483,46 @@ class ReminderPlugin(Star):
text += f"\n等待原因:{rem['waiting_reason'][:150]}"
return text
async def _permission_command(self, event, tail):
if event.get_platform_name() not in OFFICIAL or route(event)[0] != "group":
raise ValueError("主动消息群权限检查仅适用于 QQ 官方群聊。")
platform_id = str(event.get_platform_id())
destination = route(event)[1]
if not tail:
state = (await self.store.permission(platform_id, destination))["state"]
labels = {
"unknown": "尚未验证",
"granted": "已收到允许事件或发送成功记录",
"denied": "收到管理员关闭权限事件",
"removed": "机器人已被移出群",
"error": "最近一次主动发送被拒绝",
}
await self._reply(event, f"本群状态:{labels[state]}\n{NOTICE}")
return
if tail.lower() not in {"check", "检查", "验证"}:
raise ValueError("用法:/tx permission 或 /tx permission check")
platform = find_platform(self.context, platform_id)
if not available(platform):
raise ValueError("QQ 适配器尚未运行,请稍后再验证。")
try:
result = await asyncio.wait_for(
platform.get_client().api.post_group_message(
group_openid=destination,
msg_type=0,
content="✅ 主动消息权限验证成功。此消息为主动发送,等待权限的到期提醒将继续投递。",
),
timeout=30,
)
if not field(result, "id"):
raise RuntimeError("QQ 接口未返回消息 ID")
except Exception as exc:
if proactive_denied(exc):
await self.store.set_permission(platform_id, destination, "error", reset=True)
await self._reply(event, f"❌ 主动消息验证失败:{str(exc)[:250]}\n{NOTICE}")
return
await self.store.set_permission(platform_id, destination, "granted")
self._wake.set()
async def _list(self, event, scope, user, tail, history):
all_users = tail.split()[:1] == ["all"]
if all_users:
@@ -441,8 +630,16 @@ class ReminderPlugin(Star):
async def terminate(self):
async with self._init_lock:
self._closed = True
if self._permission_watcher:
self._permission_watcher.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self._permission_watcher
self._permission_watcher = None
if self._scheduler:
self._scheduler.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self._scheduler
self._scheduler = None
for bridge in self._bridges.values():
await bridge.close()
self._bridges.clear()
+1 -1
View File
@@ -1,7 +1,7 @@
name: astrbot_plugin_tixing
display_name: 栗子提醒
desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。
version: v1.1.0
version: v1.2.0
author: itxiaohui
repo: https://github.com/itxiaohui66/astrbot_plugin_tixing
support_platforms:
+8
View File
@@ -7,6 +7,14 @@ from html import escape
OFFICIAL = {"qq_official", "qq_official_webhook"}
def proactive_denied(exc):
text = str(exc).lower()
return any(
token in text
for token in ("主动消息失败", "无权限", "permission", "not allowed", "主动消息权限")
)
def incoming_reply(event):
"""Read an inbound message ID and its original timestamp, never a sent ID."""
raw = event.message_obj.raw_message
+73
View File
@@ -0,0 +1,73 @@
"""Observe the official SDK's group lifecycle events without replacing its parsers."""
import asyncio
import inspect
from astrbot.api import logger
NOTICE = (
"⏰ 定时提醒需要主动消息权限。请群主或管理员打开本群机器人的权限设置,"
"确认已开启“允许机器人主动发送消息”(不同 QQ 版本名称可能略有不同)。"
"开启后可 @机器人 /tx permission check 验证;随后按设置时间主动提醒。"
)
EVENTS = ("group_add_robot", "group_del_robot", "group_msg_receive", "group_msg_reject")
class PermissionBridge:
def __init__(self, platform, handler):
self.platform = platform
self.client = platform.get_client()
self.handler = handler
self.closed = False
self.callbacks = {}
self.tasks = set()
def install(self):
for kind in EVENTS:
name = "on_" + kind
previous = getattr(self.client, name, None)
async def callback(event, kind=kind, previous=previous):
task = asyncio.current_task()
if not self.closed:
self.tasks.add(task)
try:
await self.handler(self.platform, kind, event)
except Exception:
logger.exception("[Reminder] 处理 QQ 群权限事件失败:%s", kind)
finally:
self.tasks.discard(task)
if previous:
result = previous(event)
if inspect.isawaitable(result):
await result
callback._reminder_bridge = self
callback._reminder_previous = previous
setattr(self.client, name, callback)
self.callbacks[name] = callback
async def close(self):
self.closed = True
# Finish any notification + persistence before the plugin is unloaded.
if self.tasks:
pending = asyncio.gather(*self.tasks, return_exceptions=True)
try:
await asyncio.shield(pending)
except asyncio.CancelledError:
await pending
raise
for name, callback in self.callbacks.items():
if getattr(self.client, name, None) is not callback:
continue
previous = callback._reminder_previous
while previous and isinstance(
getattr(previous, "_reminder_bridge", None), PermissionBridge
):
if not previous._reminder_bridge.closed:
break
previous = previous._reminder_previous
if previous is None:
delattr(self.client, name)
else:
setattr(self.client, name, previous)
+99
View File
@@ -70,6 +70,13 @@ class ReminderStore:
used INTEGER NOT NULL DEFAULT 0, blocked INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY(platform_id, scene, destination)
);
CREATE TABLE IF NOT EXISTS group_permissions (
platform_id TEXT NOT NULL, destination TEXT NOT NULL,
state TEXT NOT NULL DEFAULT 'unknown', notified INTEGER NOT NULL DEFAULT 0,
notice_until REAL NOT NULL DEFAULT 0, event_at REAL NOT NULL DEFAULT 0,
event_id TEXT NOT NULL DEFAULT '',
PRIMARY KEY(platform_id, destination)
);
""")
columns = {row[1] for row in db.execute("PRAGMA table_info(reminders)")}
if "waiting_reason" not in columns:
@@ -79,6 +86,98 @@ class ReminderStore:
await self._run(create)
async def permission(self, platform_id, destination):
return await self._run(
lambda db: dict(
db.execute(
"SELECT * FROM group_permissions WHERE platform_id=? AND destination=?",
(platform_id, destination),
).fetchone()
or {"state": "unknown", "notified": 0}
)
)
async def set_permission(
self, platform_id, destination, state, event_at=None, event_id="", reset=False
):
def write(db):
db.execute("BEGIN IMMEDIATE")
db.execute(
"INSERT OR IGNORE INTO group_permissions(platform_id,destination) VALUES (?,?)",
(platform_id, destination),
)
row = db.execute(
"SELECT * FROM group_permissions WHERE platform_id=? AND destination=?",
(platform_id, destination),
).fetchone()
if event_at is not None and (
event_at < row["event_at"] or (event_id and event_id == row["event_id"])
):
return False
reset_notice = reset and (row["state"] != state or event_at is not None)
db.execute(
"UPDATE group_permissions SET state=?,event_at=COALESCE(?,event_at),"
"event_id=CASE WHEN ?!='' THEN ? ELSE event_id END,"
"notified=CASE WHEN ? THEN 0 ELSE notified END,"
"notice_until=CASE WHEN ? THEN 0 ELSE notice_until END "
"WHERE platform_id=? AND destination=?",
(
state,
event_at,
event_id,
event_id,
reset_notice,
reset_notice,
platform_id,
destination,
),
)
if state == "granted":
db.execute(
"UPDATE reminders SET retry_at=0,waiting_reason='' WHERE platform_id=? "
"AND destination=? AND scene='group' AND status='active' "
"AND waiting_reason LIKE '主动消息权限%'",
(platform_id, destination),
)
return True
return await self._run(write)
async def claim_notice(self, platform_id, destination):
def write(db):
db.execute("BEGIN IMMEDIATE")
db.execute(
"INSERT OR IGNORE INTO group_permissions(platform_id,destination) VALUES (?,?)",
(platform_id, destination),
)
return (
db.execute(
"UPDATE group_permissions SET notice_until=? WHERE platform_id=? "
"AND destination=? AND state!='granted' AND notified=0 AND notice_until<=?",
(time.time() + 60, platform_id, destination, time.time()),
).rowcount
== 1
)
return await self._run(write)
async def finish_notice(self, platform_id, destination, sent):
await self._run(
lambda db: db.execute(
"UPDATE group_permissions SET notified=MAX(notified,?),notice_until=0 WHERE platform_id=? AND destination=?",
(int(sent), platform_id, destination),
)
)
async def wait_for_permission(self, reminder_id, owner, reason, retry_at):
await self._run(
lambda db: db.execute(
"UPDATE reminders SET waiting_reason=?,retry_at=?,lease_owner='',lease_until=0 "
"WHERE id=? AND lease_owner=? AND status='active'",
(reason[:500], retry_at, reminder_id, owner),
)
)
async def observe(self, scope, user_id, nickname=""):
await self._run(
lambda db: (
+1 -1
View File
@@ -15,7 +15,7 @@ from services.storage import ReminderStore
async def passive_plugin(plugin_class, platform_factory):
platform = platform_factory()
context = SimpleNamespace(platform_manager=SimpleNamespace(platform_insts=[platform]))
instance = plugin_class(context, {"check_interval_seconds": 999})
instance = plugin_class(context, {"check_interval_seconds": 999, "proactive_reminders": False})
await instance.store.initialize()
instance._ready = True
assert instance.delivery_mode == "passive"
+268
View File
@@ -0,0 +1,268 @@
import asyncio
import time
from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
from test_reminders import record
from services.storage import ReminderStore
@pytest.fixture
async def official_plugin(plugin_class, platform_factory):
platform = platform_factory()
instance = plugin_class(
SimpleNamespace(platform_manager=SimpleNamespace(platform_insts=[platform])),
{"check_interval_seconds": 999, "official_delivery_mode": "passive"},
)
await instance.store.initialize()
instance._ready = True
await instance._attach_platforms()
instance.initialize = AsyncMock()
yield instance, platform
await instance.terminate()
def lifecycle(event_id="join_1", timestamp=None, destination="group_1"):
return SimpleNamespace(
group_openid=destination,
event_id=event_id,
timestamp=time.time() if timestamp is None else timestamp,
)
async def test_default_and_upgrade_use_proactive_without_reply_context(official_plugin):
instance, platform = official_plugin
assert instance.delivery_mode == "proactive"
rem_id = await instance.store.add(record(), 10)
await instance._check_due()
sent = platform.get_client().api.post_group_message.call_args.kwargs
assert "msg_id" not in sent and "event_id" not in sent
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "done"
async def test_first_command_guidance_once_per_group_persisted(official_plugin, event_factory):
instance, _ = official_plugin
events = [event_factory("/tx help"), event_factory("/tx list", user="other")]
for event in events:
await instance.tx(event)
assert "确认已开启" in events[0].replies[0]
assert "确认已开启" not in events[1].replies[0]
other = event_factory("/tx list", group="other")
await instance.tx(other)
assert "确认已开启" in other.replies[0]
reopened = ReminderStore(instance.store.path)
assert not await reopened.claim_notice("platform_1", "group_1")
assert await reopened.claim_notice("platform_2", "group_1")
@pytest.mark.parametrize("name", ["qq_official", "qq_official_webhook"])
async def test_join_uses_event_reply_and_deduplicates(official_plugin, event_factory, name):
instance, platform = official_plugin
platform.meta = lambda: SimpleNamespace(id="platform_1", name=name)
client = platform.get_client()
event = lifecycle()
await client.on_group_add_robot(event)
await client.on_group_add_robot(event)
assert client.api.post_group_message.await_count == 1
sent = client.api.post_group_message.call_args.kwargs
assert sent["event_id"] == "join_1" and "msg_id" not in sent
assert "群主或管理员" in sent["content"]
command = event_factory("/tx list")
await instance.tx(command)
assert "确认已开启" not in command.replies[0]
async def test_failed_join_falls_back_to_first_command(official_plugin, event_factory):
instance, platform = official_plugin
platform.get_client().api.post_group_message.side_effect = RuntimeError("event expired")
await platform.get_client().on_group_add_robot(lifecycle())
command = event_factory("/tx list")
await instance.tx(command)
assert "确认已开启" in command.replies[0]
async def test_failed_command_notice_is_not_marked_sent(official_plugin, event_factory):
instance, _ = official_plugin
command = event_factory()
command.send = AsyncMock(side_effect=RuntimeError("network error"))
with pytest.raises(RuntimeError):
await instance._reply(command, "test")
assert (await instance.store.permission("platform_1", "group_1"))["notified"] == 0
retry = event_factory("/tx list")
await instance.tx(retry)
assert "确认已开启" in retry.replies[0]
async def test_granted_state_skips_first_use_notice_and_stale_join(official_plugin, event_factory):
instance, platform = official_plugin
now = time.time()
await platform.get_client().on_group_msg_receive(lifecycle("receive", now))
await platform.get_client().on_group_add_robot(lifecycle("old_join", now - 10))
command = event_factory("/tx list")
await instance.tx(command)
assert "确认已开启" not in command.replies[0]
platform.get_client().api.post_group_message.assert_not_awaited()
assert (await instance.store.permission("platform_1", "group_1"))["state"] == "granted"
async def test_permission_error_preserved_then_receive_event_wakes_delivery(official_plugin):
instance, platform = official_plugin
api = platform.get_client().api
api.post_group_message.side_effect = RuntimeError("主动消息失败, 无权限")
rem_id = await instance.store.add(record(), 10)
await instance._check_due()
for _ in range(4):
await instance._check_due()
rem = await instance.store.get(rem_id, record()["scope"])
assert rem["status"] == "active" and rem["failure_count"] == 0
assert "等待主动消息权限" in instance._format(rem)
assert rem["retry_at"] > time.time() + 290
assert api.post_group_message.await_count == 1
api.post_group_message.side_effect = None
await platform.get_client().on_group_msg_receive(lifecycle("allow"))
assert instance._wake.is_set()
await instance._check_due()
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "done"
async def test_reject_holds_tasks_and_permission_check_releases(official_plugin, event_factory):
instance, platform = official_plugin
await platform.get_client().on_group_msg_reject(lifecycle("reject"))
rem_id = await instance.store.add(record(), 10)
await instance._check_due()
platform.get_client().api.post_group_message.assert_not_awaited()
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "active"
command = event_factory("/tx permission check")
await instance.tx(command)
assert command.stopped
assert (await instance.store.permission("platform_1", "group_1"))["state"] == "granted"
sent = platform.get_client().api.post_group_message.call_args.kwargs
assert "msg_id" not in sent and "event_id" not in sent
await instance._check_due()
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "done"
async def test_permission_check_failure_is_a_passive_reply(official_plugin, event_factory):
instance, platform = official_plugin
platform.get_client().api.post_group_message.side_effect = RuntimeError("主动消息失败, 无权限")
command = event_factory("/tx permission check")
await instance.tx(command)
assert "验证失败" in command.replies[0]
assert command.replies[0].count("确认已开启") == 1
assert (await instance.store.permission("platform_1", "group_1"))["state"] == "error"
async def test_check_without_message_id_is_not_success(official_plugin, event_factory):
instance, platform = official_plugin
platform.get_client().api.post_group_message.return_value = {}
command = event_factory("/tx permission check")
await instance.tx(command)
assert "未返回消息 ID" in command.replies[0]
assert (await instance.store.permission("platform_1", "group_1"))["state"] != "granted"
async def test_member_cannot_set_authorized_state_by_text(official_plugin, event_factory):
instance, _ = official_plugin
command = event_factory("/tx permission 已开启")
await instance.tx(command)
assert "用法" in command.replies[0]
assert (await instance.store.permission("platform_1", "group_1"))["state"] == "unknown"
async def test_bridge_preserves_callbacks_and_overlapping_unload(official_plugin):
instance, platform = official_plugin
from reminder_plugin_test.services.permissions import PermissionBridge
await instance.terminate()
client = platform.get_client()
original = AsyncMock()
client.on_group_add_robot = original
handlers = [AsyncMock(), AsyncMock()]
first = PermissionBridge(platform, handlers[0])
second = PermissionBridge(platform, handlers[1])
first.install()
second.install()
await first.close()
await client.on_group_add_robot(lifecycle())
handlers[0].assert_not_awaited()
handlers[1].assert_awaited_once()
original.assert_awaited_once()
await second.close()
assert client.on_group_add_robot is original
assert not hasattr(client, "on_group_msg_receive")
async def test_bridge_close_finishes_pending_event(official_plugin):
instance, platform = official_plugin
client = platform.get_client()
entered, release = asyncio.Event(), asyncio.Event()
async def send(**kwargs):
entered.set()
await release.wait()
return {"id": "sent"}
client.api.post_group_message.side_effect = send
event_task = asyncio.create_task(client.on_group_add_robot(lifecycle()))
await asyncio.wait_for(entered.wait(), 1)
closing = asyncio.create_task(instance.terminate())
await asyncio.sleep(0)
assert not closing.done()
release.set()
await asyncio.wait_for(asyncio.gather(closing, event_task), 1)
assert (await instance.store.permission("platform_1", "group_1"))["notified"] == 1
async def test_concurrent_first_commands_emit_one_notice(official_plugin, event_factory):
instance, _ = official_plugin
commands = [event_factory("/tx list", user=f"user_{i}") for i in range(8)]
await asyncio.gather(*(instance.tx(event) for event in commands))
assert sum("确认已开启" in event.replies[0] for event in commands) == 1
async def test_repeated_permission_failure_does_not_repeat_notice(official_plugin, event_factory):
instance, platform = official_plugin
platform.get_client().api.post_group_message.side_effect = RuntimeError("主动消息失败, 无权限")
rem_id = await instance.store.add(record(), 10)
await instance._check_due()
first = event_factory("/tx list")
await instance.tx(first)
assert "确认已开启" in first.replies[0]
await instance.store.resume(record()["scope"], "user_1", rem_id, 10)
await instance._check_due()
second = event_factory("/tx list")
await instance.tx(second)
assert "确认已开启" not in second.replies[0]
rem = await instance.store.get(rem_id, record()["scope"])
assert rem["status"] == "active" and rem["failure_count"] == 0
async def test_del_and_rejoin_reset_guidance(official_plugin, event_factory):
instance, platform = official_plugin
client = platform.get_client()
stamp = time.time()
await client.on_group_add_robot(lifecycle("join", stamp))
await client.on_group_del_robot(lifecycle("del", stamp + 1))
rem_id = await instance.store.add(record(), 10)
await instance._check_due()
assert client.api.post_group_message.await_count == 1
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "active"
await client.on_group_add_robot(lifecycle("rejoin", stamp + 2))
assert client.api.post_group_message.await_count == 2
async def test_new_and_removed_platforms_attach_and_restore(official_plugin, platform_factory):
instance, _ = official_plugin
newcomer = platform_factory("qq_official_webhook")
original = AsyncMock()
newcomer.get_client().on_group_msg_receive = original
instance.context.platform_manager.platform_insts.append(newcomer)
await instance._attach_platforms()
await newcomer.get_client().on_group_msg_receive(lifecycle("receive"))
original.assert_awaited_once()
instance.context.platform_manager.platform_insts.remove(newcomer)
await instance._attach_platforms()
assert newcomer.get_client().on_group_msg_receive is original
assert not hasattr(newcomer.get_client(), "on_group_add_robot")
+3 -5
View File
@@ -151,9 +151,7 @@ async def test_ambiguous_multiple_all_and_private(tmp_path, event_factory):
async def plugin(plugin_class, platform_factory):
platform = platform_factory()
context = SimpleNamespace(platform_manager=SimpleNamespace(platform_insts=[platform]))
instance = plugin_class(
context, {"check_interval_seconds": 999, "official_delivery_mode": "proactive"}
)
instance = plugin_class(context, {"check_interval_seconds": 999})
await instance.store.initialize()
# Control scans explicitly in integration tests; lifecycle is tested separately.
instance._ready = True
@@ -179,7 +177,7 @@ async def test_due_success_once_and_recurring(plugin):
async def test_failures_retry_then_cancel_and_history(plugin, event_factory):
instance, platform = plugin
instance.retry_seconds = 0
platform.get_client().api.post_group_message.side_effect = RuntimeError("没有主动消息权限")
platform.get_client().api.post_group_message.side_effect = RuntimeError("服务暂时不可用")
rem_id = await instance.store.add(record(), 10)
for count in range(1, 4):
await instance._check_due()
@@ -188,7 +186,7 @@ async def test_failures_retry_then_cancel_and_history(plugin, event_factory):
assert rem["status"] == ("cancelled" if count == 3 else "active")
event = event_factory("/tx history")
await instance.tx(event)
assert "没有主动消息权限" in event.replies[0]
assert "服务暂时不可用" in event.replies[0]
assert "已取消" in event.replies[0]