Initial release of AstrBot reminder plugin
This commit is contained in:
commit
cf10c43e61
20 files changed
+1692
No files matched your search
@@ -0,0 +1,41 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
python: "3.10"
|
||||
- os: ubuntu-latest
|
||||
python: "3.12"
|
||||
- os: windows-latest
|
||||
python: "3.12"
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python }}
|
||||
cache: pip
|
||||
cache-dependency-path: |
|
||||
requirements.txt
|
||||
requirements-dev.txt
|
||||
- name: Install dependencies
|
||||
run: python -m pip install -r requirements.txt -r requirements-dev.txt
|
||||
- name: Lint
|
||||
run: ruff check .
|
||||
- name: Check formatting
|
||||
run: ruff format --check .
|
||||
- name: Test
|
||||
run: python -m pytest -q
|
||||
- name: Build plugin ZIP
|
||||
run: python tools/package.py
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
.venv/
|
||||
venv/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
dist/
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 itxiaohui
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,138 @@
|
||||
# 栗子提醒 · AstrBot
|
||||
|
||||
把栗子 QQ 机器人项目 `liziqqbotpy` 的提醒功能迁移为 AstrBot 插件,适配 QQ 官方 WebSocket、QQ 官方 Webhook 和 OneBot v11。插件要求 AstrBot `>=4.16,<5`,Python 3.10 及以上。
|
||||
|
||||
[开源仓库](https://github.com/itxiaohui66/astrbot_plugin_tixing) · [下载安装包](https://github.com/itxiaohui66/astrbot_plugin_tixing/releases/latest) · [报告问题](https://github.com/itxiaohui66/astrbot_plugin_tixing/issues)
|
||||
|
||||
## 安装
|
||||
|
||||
推荐在 AstrBot WebUI 的插件页选择通过仓库链接安装,填入:
|
||||
|
||||
```text
|
||||
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` 必须直接位于该插件文件夹中。
|
||||
|
||||
安装时 AstrBot 会读取 `requirements.txt` 安装 `tzdata`。配置默认采用北京时间 `Asia/Shanghai`;每人在每个群或私聊最多 10 个活跃提醒,每 30 秒扫描一次。确认机器人已经接入 QQ 官方适配器,群内使用 `@机器人 /tx help` 查看帮助。
|
||||
|
||||
## 完整功能对照
|
||||
|
||||
| 旧项目功能 | 本插件行为 |
|
||||
| --- | --- |
|
||||
| `/tx X分钟/X小时/X天 内容` | 全部保留,支持原来的 `minute/hour/day/min/h/d`,另支持复数和“后” |
|
||||
| 每天提醒 | `每天9:00`、`每天 9:00` 均支持 |
|
||||
| 每周提醒 | 支持一到六、日、天、1–7;修正同一天未来时刻错误跳到下周的问题 |
|
||||
| 提醒自己 / @ 他人 | 到期真正 @ 对象;官方 QQ 保存成员 OpenID,OneBot 保存 QQ 号 |
|
||||
| 每人最多 10 条 | 按平台 + 群/私聊 + 创建者计算,仅统计活跃任务;支持配置 |
|
||||
| 30 秒轮询 | 可配置;通常在到期后一个扫描周期内发送,拥塞时可能更晚 |
|
||||
| 数据库存储、重启恢复 | SQLite 位于 AstrBot `data/plugin_data/astrbot_plugin_tixing/reminders.db` |
|
||||
| 投递失败重试、达到阈值取消 | 默认重试间隔 60 秒,连续 3 次失败自动取消;保留错误原因 |
|
||||
| `/cxzd` 重启提醒调度器 | 保留;使用 AstrBot 管理员或插件授权管理员,不丢任务 |
|
||||
| 旧帮助中的 `/提醒`、`/remind` | 实现为 `/tx` 别名 |
|
||||
| 旧帮助中的今天、明天、指定日期 | 原代码未实现的格式已补齐,并支持后天 |
|
||||
| 旧代码提示“先取消一些”但没有取消入口 | 新增列表、详情、历史、按编号取消和取消自己的全部任务 |
|
||||
|
||||
## 创建提醒
|
||||
|
||||
```text
|
||||
/tx 30分钟 开会
|
||||
/tx 1小时后 开会
|
||||
/tx 2天 检查服务器
|
||||
/tx 30min 吃饭
|
||||
/tx 10:00 今天的会议
|
||||
/tx 今天 10:00 今天的会议
|
||||
/tx 明天10:00 明天的会议
|
||||
/tx 后天 10:00 后天的会议
|
||||
/tx 2026-12-31 20:00 跨年
|
||||
/tx 每天9:00 早起打卡
|
||||
/tx 每周一 9:00 周报
|
||||
/tx 每周7 20:00 总结
|
||||
/tx 1小时 开会 @某人
|
||||
```
|
||||
|
||||
时间和内容之间要有空格。内容可以包含空格、换行,默认最多 1000 个字符。单次 `HH:MM` 表示今天该时刻,已经过去则提示改用未来时间;每天和每周自动计算下一次。提醒间隔必须大于 0,小时范围 0–23,分钟范围 0–59。
|
||||
|
||||
到期后在创建时的群或私聊发送提醒。循环任务按创建时的时区续期,修改配置时区只影响新任务。离线时错过多次循环,会在恢复后补发一次并续到下一次未来时刻,避免刷屏。一次性逾期提醒在恢复后补发;如果适配器还未加载或运行,不增加失败次数。
|
||||
|
||||
## 管理命令
|
||||
|
||||
| 命令 | 行为 |
|
||||
| --- | --- |
|
||||
| `/tx help` | 全部帮助 |
|
||||
| `/tx list [页码]` / `/cktx` / `/提醒列表` | 当前会话中自己创建的活跃提醒 |
|
||||
| `/tx history [页码]` | 自己的全部记录,包括完成、取消、失败 |
|
||||
| `/tx detail 编号` | 查看全文、时间、状态、失败次数和最近错误 |
|
||||
| `/tx cancel 编号` / `/qxtx 编号` / `/取消提醒 编号` | 取消自己创建的任务 |
|
||||
| `/tx cancel all` | 仅取消自己在当前会话创建的所有活跃任务 |
|
||||
| `/tx identity` | 当前平台、群、用户标识和本群授权管理员标识 |
|
||||
| `/tx status` | 调度器状态、当前会话活跃数量、时区、扫描间隔和最近错误 |
|
||||
| `/cxzd` / `/重启提醒` | 管理员重启提醒调度器 |
|
||||
| `/tx list all [页码]` | 管理员查看当前会话所有人的活跃任务 |
|
||||
| `/tx history all [页码]` | 管理员查看当前会话所有人的历史 |
|
||||
|
||||
管理员可以取消当前会话其他人的单条任务、查看详情。按编号操作也受平台和群隔离限制。群管理员并不会自动获得机器人管理权限;使用 AstrBot 管理员配置,或在插件配置中加入 `admin_ids`、`group_admin_ids`。`group_admin_ids` 的格式为 `平台ID|群OpenID|用户OpenID`,可从 `/tx identity` 复制。
|
||||
|
||||
列表每页 2 条,长内容显示预览,可用 `detail` 查看全文。投递超过失败阈值后会自动取消,可以在 `history` 中查到原因;修复权限或网络后重新创建即可。
|
||||
|
||||
## 官方 QQ 的对象和发送权限
|
||||
|
||||
官方 QQ 下发 `group_openid`、`member_openid`、`user_openid`;普通 QQ 号、群号不能直接代替它们。提醒他人优先解析真实 @ 消息段或平台提供的 mentions。若官方事件没有提供被 @ 成员的标识,让对方先在本群 `@机器人 /tx identity`,再使用:
|
||||
|
||||
```text
|
||||
/tx 30分钟 开会 @对方的用户标识
|
||||
```
|
||||
|
||||
插件会记住本群里机器人实际收到的成员消息,名字唯一且官方提供昵称时也支持 `@昵称`。不同群里的成员记录不会混用,重名时要求明确标识。OneBot 模式会查询目标是否是本群成员。私聊只能提醒自己。
|
||||
|
||||
定时提醒属于主动消息,插件直接使用当前官方适配器的客户端发送,不保存旧 `msg_id`、不复用过期回复窗口。QQ 官方的主动消息权限、额度、风控和目标可达性仍适用。平台拒绝或未返回消息 ID 时记录为失败,只有获得消息 ID 后才标记成功或计算下一次时间。相关依据见 [腾讯官方 SDK 使用说明](https://github.com/tencent-connect/qqbot-nodejs/blob/main/USAGE.md)。
|
||||
|
||||
QQ 普通群使用 `<qqbot-at-user id="OpenID" />` 实现真正 @,频道使用频道成员 ID。群、C2C、频道、频道私信分别走对应 SDK 接口。插件自己的到期提醒使用普通文本,不要求 Markdown 模板;命令回复仍由 AstrBot 当前事件的配置发送。
|
||||
|
||||
旧数据库里的数字 QQ 号/群号无法自动换算为官方 OpenID,所以本次迁移的是功能,没有修改或直接导入旧数据库。更换 QQ 应用或 AstrBot 平台 ID 时,原 OpenID/路由可能失效,需要重建对应提醒。备份时停止 AstrBot 后复制整个 `data/plugin_data/astrbot_plugin_tixing/`。
|
||||
|
||||
正常重载和并发扫描由数据库租约避免重复发送,卸载时会等待正在发送的任务完成并保存结果。数据库和 QQ 网络接口无法组成同一事务;如果进程在“QQ 已收消息但本地尚未保存”时被强制结束,或服务器收消息后响应超时,恢复重试仍可能重复。建议只在一个 AstrBot 实例里运行该插件。
|
||||
|
||||
## 配置
|
||||
|
||||
| 字段 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `timezone` | `Asia/Shanghai` | IANA 时区 |
|
||||
| `max_per_user` | `10` | 当前会话每人最多活跃任务 |
|
||||
| `check_interval_seconds` | `30` | 扫描周期,最小 1 秒 |
|
||||
| `max_delivery_failures` | `3` | 失败取消阈值,最小 1 |
|
||||
| `retry_interval_seconds` | `60` | 失败重试间隔,最小 1 秒 |
|
||||
| `max_content_length` | `1000` | 内容长度,最大配置值 1500 |
|
||||
| `admin_ids` | `[]` | 额外机器人管理员用户标识 |
|
||||
| `group_admin_ids` | `[]` | 当前群的授权管理员标识 |
|
||||
|
||||
配置保存后重载插件生效,任务保留。
|
||||
|
||||
## 验证和打包
|
||||
|
||||
```text
|
||||
python -m pip install -r requirements.txt -r requirements-dev.txt
|
||||
python -m pytest -q
|
||||
ruff check .
|
||||
ruff format --check .
|
||||
python tools/package.py
|
||||
```
|
||||
|
||||
自动化测试使用真实 SQLite 和时间解析;AstrBot 主机边界和 QQ 发送接口使用测试替身,覆盖时间格式、上限、群隔离、成员识别、失败重试、循环补发、权限和热重载。GitHub Actions 会在 Linux(Python 3.10、3.12)和 Windows(Python 3.12)上运行测试、代码检查和打包。真实 QQ 投递仍需在实际部署的 AstrBot 和账号中验证。
|
||||
|
||||
安装后可用以下流程确认部署环境:
|
||||
|
||||
1. `@机器人 /tx 1分钟 测试提醒`,确认返回任务编号,并在一分钟后加一个扫描周期内收到真正 @ 的通知。
|
||||
2. `/tx history` 检查该任务状态;失败时检查记录里的原因和 AstrBot 日志。
|
||||
3. `/tx 5分钟 重启测试`,重载插件后用 `/tx list` 确认仍在,再 `/tx cancel 编号` 确认取消。
|
||||
4. 让另一成员先发送 `/tx identity`,测试本群的他人提醒。
|
||||
|
||||
## 来源
|
||||
|
||||
功能参考作者的原项目 `liziqqbotpy`,主要为 `plugins/reminder.py`、`core/event.py`、`core/scheduler.py`、`database/models.py`、`database/sqlite.py` 和 `plugins/help.py`。原项目未提供公开仓库链接。本插件保留提醒行为,重写 AstrBot 入口、存储和平台适配,不依赖旧项目的 NoneBot、NapCat 或全局调度器。
|
||||
|
||||
接口依据 [AstrBot 插件开发文档](https://docs.astrbot.app/dev/star/plugin-new.html)、[QQ 官方 WebSocket 适配器源码](https://github.com/AstrBotDevs/AstrBot/blob/master/astrbot/core/platform/sources/qqofficial/qqofficial_platform_adapter.py)、[Webhook 适配器源码](https://github.com/AstrBotDevs/AstrBot/blob/master/astrbot/core/platform/sources/qqofficial_webhook/qo_webhook_adapter.py) 和 [腾讯 botpy SDK](https://github.com/tencent-connect/botpy/blob/master/botpy/api.py)。
|
||||
|
||||
## 开源与贡献
|
||||
|
||||
本项目采用 [MIT License](LICENSE)。欢迎提交 Issue 和 Pull Request;修改代码后请运行上面的测试、格式检查和打包命令。请在报告问题时说明 AstrBot 版本、QQ 适配器类型、触发命令和经过脱敏的错误日志。
|
||||
@@ -0,0 +1 @@
|
||||
"""栗子提醒 AstrBot 插件。"""
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"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},
|
||||
"max_delivery_failures": {"type": "int", "description": "连续投递失败多少次后自动取消", "default": 3},
|
||||
"retry_interval_seconds": {"type": "int", "description": "投递失败重试间隔(秒)", "default": 60},
|
||||
"max_content_length": {"type": "int", "description": "提醒内容最大字符数(上限 1500)", "default": 1000},
|
||||
"admin_ids": {"type": "list", "description": "额外机器人管理员用户标识", "hint": "官方 QQ 使用 OpenID,使用 /tx identity 查看;无需复制旧 QQ 号管理员配置。", "default": []},
|
||||
"group_admin_ids": {"type": "list", "description": "本群授权管理员标识", "hint": "格式:平台ID|群OpenID|用户OpenID,使用 /tx identity 查看。", "default": []}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
"""Complete reminder migration from liziqqbotpy to AstrBot."""
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
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.storage import ReminderStore, scope_key
|
||||
from .services.targets import MARKUP, resolve_target
|
||||
from .services.time_parser import describe, next_occurrence, parse_time
|
||||
|
||||
HELP = """⏰ 栗子提醒
|
||||
/tx 30分钟 开会(也支持分钟后、小时、天、min/h/d)
|
||||
/tx 1小时 开会 @某人
|
||||
/tx 10:00 开会(今天)
|
||||
/tx 明天10:00 开会
|
||||
/tx 2026-12-31 20:00 跨年
|
||||
/tx 每天9:00 早起打卡
|
||||
/tx 每周一 9:00 周报(也支持周日、周天、1-7)
|
||||
/tx list [页码] 查看自己当前会话的提醒
|
||||
/tx history [页码] 查看历史和失败原因
|
||||
/tx detail 编号 查看一条提醒
|
||||
/tx cancel 编号 取消自己的一条提醒
|
||||
/tx cancel all 取消自己当前会话的全部提醒
|
||||
/tx identity 查看当前平台、群和用户标识
|
||||
/tx status 查看提醒调度器状态
|
||||
/cxzd 管理员重启提醒调度器
|
||||
命令别名:/提醒、/remind
|
||||
群内官方 QQ 需要 @机器人;时间按配置时区计算。
|
||||
官方 QQ 提醒他人须使用本群 OpenID 或真实 @;普通 QQ 号不可转换。
|
||||
管理员可 /tx list all 和 /tx cancel 编号 管理当前群提醒。"""
|
||||
|
||||
|
||||
class ReminderPlugin(Star):
|
||||
def __init__(self, context: Context, config: AstrBotConfig):
|
||||
super().__init__(context)
|
||||
self.config = config
|
||||
self.timezone = str(config.get("timezone", "Asia/Shanghai"))
|
||||
try:
|
||||
self.tz = ZoneInfo(self.timezone)
|
||||
except ZoneInfoNotFoundError as exc:
|
||||
raise ValueError(
|
||||
f"无效提醒时区:{self.timezone},请使用 Asia/Shanghai 等 IANA 时区"
|
||||
) from exc
|
||||
self.limit = max(1, int(config.get("max_per_user", 10)))
|
||||
self.interval = max(1, int(config.get("check_interval_seconds", 30)))
|
||||
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.store = ReminderStore(StarTools.get_data_dir("astrbot_plugin_tixing") / "reminders.db")
|
||||
self.owner = uuid.uuid4().hex
|
||||
self._ready = False
|
||||
self._closed = False
|
||||
self._init_lock = asyncio.Lock()
|
||||
self._scan_lock = asyncio.Lock()
|
||||
self._scheduler = None
|
||||
self.last_scan = 0
|
||||
self.last_scan_error = ""
|
||||
|
||||
async def initialize(self):
|
||||
async with self._init_lock:
|
||||
if self._closed:
|
||||
return
|
||||
if not self._ready:
|
||||
await self.store.initialize()
|
||||
self._ready = True
|
||||
if self._scheduler is None or self._scheduler.done():
|
||||
self._scheduler = asyncio.create_task(self._poll(), name="lizi-reminders")
|
||||
|
||||
@filter.on_astrbot_loaded()
|
||||
async def on_loaded(self):
|
||||
await self.initialize()
|
||||
|
||||
async def _poll(self):
|
||||
while True:
|
||||
try:
|
||||
await self._check_due()
|
||||
self.last_scan_error = ""
|
||||
except Exception as exc:
|
||||
self.last_scan_error = str(exc)[:300]
|
||||
logger.exception("[Reminder] 扫描提醒失败,将在下一轮继续")
|
||||
await asyncio.sleep(self.interval)
|
||||
|
||||
async def _check_due(self):
|
||||
async with self._scan_lock:
|
||||
self.last_scan = time.time()
|
||||
for rem in await self.store.due(self.last_scan):
|
||||
platform = find_platform(self.context, rem["platform_id"])
|
||||
if not available(platform):
|
||||
continue
|
||||
if not await self.store.claim(rem["id"], self.owner, time.time()):
|
||||
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))
|
||||
try:
|
||||
await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
await task
|
||||
raise
|
||||
|
||||
async def _fire(self, platform, rem):
|
||||
try:
|
||||
await asyncio.wait_for(deliver(platform, rem), timeout=30)
|
||||
except Exception as exc:
|
||||
await self.store.failure(
|
||||
rem["id"], self.owner, exc, self.max_failures, time.time() + self.retry_seconds
|
||||
)
|
||||
logger.warning(
|
||||
"[Reminder] 提醒 #%s 投递失败(%s/%s):%s",
|
||||
rem["id"],
|
||||
rem["failure_count"] + 1,
|
||||
self.max_failures,
|
||||
exc,
|
||||
)
|
||||
return
|
||||
# A DB write failure after successful delivery is a distinct failure.
|
||||
# Keep the lease rather than incrementing the delivery-failure count.
|
||||
next_time = None
|
||||
if rem["repeat_type"] in {"daily", "weekly"}:
|
||||
next_time = next_occurrence(
|
||||
rem["remind_at"], rem["repeat_type"], rem["timezone"], time.time()
|
||||
)
|
||||
await self.store.success(rem["id"], self.owner, next_time)
|
||||
logger.info("[Reminder] 提醒 #%s 已投递,平台=%s", rem["id"], rem["platform_id"])
|
||||
|
||||
def _admin(self, event):
|
||||
return (
|
||||
event.is_admin()
|
||||
or str(event.get_sender_id())
|
||||
in {str(user) for user in self.config.get("admin_ids", [])}
|
||||
or f"{event.get_platform_id()}|{event.get_group_id()}|{event.get_sender_id()}"
|
||||
in self.config.get("group_admin_ids", [])
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _scope(event):
|
||||
return scope_key(
|
||||
str(event.get_platform_id()),
|
||||
str(event.get_group_id() or ""),
|
||||
str(event.get_sender_id()),
|
||||
)
|
||||
|
||||
async def _reply(self, event, text):
|
||||
# Passive command responses are sent by AstrBot using the current event.
|
||||
await event.send(event.plain_result(text))
|
||||
|
||||
async def _guard(self, event, action):
|
||||
try:
|
||||
await self.initialize()
|
||||
await action()
|
||||
except ValueError as exc:
|
||||
await self._reply(event, f"❌ {exc}")
|
||||
except Exception:
|
||||
logger.exception("[Reminder] 处理提醒命令失败")
|
||||
await self._reply(event, "❌ 处理失败,请稍后重试或查看 AstrBot 日志。")
|
||||
finally:
|
||||
event.stop_event()
|
||||
|
||||
@filter.command("tx", alias={"提醒", "remind"})
|
||||
async def tx(self, event: AstrMessageEvent):
|
||||
"""设置、查看、取消单次或循环提醒。"""
|
||||
# Raw text preserves spaces/newlines in reminder content. Remove only the bot mention.
|
||||
text = event.message_str
|
||||
bot_id = str(event.message_obj.self_id)
|
||||
text = MARKUP.sub(
|
||||
lambda m: " " if next(g for g in m.groups() if g is not None) == bot_id else m.group(0),
|
||||
text,
|
||||
)
|
||||
match = re.search(r"(?:^|\s)/?(?:tx|提醒|remind)(?=\s|$)", text, re.I)
|
||||
args = text[match.end() :].strip() if match else ""
|
||||
await self._guard(event, lambda: self._command(event, args))
|
||||
|
||||
async def _command(self, event, args):
|
||||
if not args or args.lower() in {"help", "帮助"}:
|
||||
await self._reply(event, HELP)
|
||||
return
|
||||
if event.get_platform_name() not in OFFICIAL | {"aiocqhttp"}:
|
||||
raise ValueError("当前插件支持 QQ 官方 WebSocket、Webhook 和 OneBot。")
|
||||
scope = self._scope(event)
|
||||
user = str(event.get_sender_id())
|
||||
await self.store.observe(scope, user, event.get_sender_name())
|
||||
parts = args.split(maxsplit=1)
|
||||
action = parts[0].lower()
|
||||
tail = parts[1].strip() if len(parts) == 2 else ""
|
||||
if action in {"list", "列表", "查看", "history", "历史"}:
|
||||
await self._list(event, scope, user, tail, action in {"history", "历史"})
|
||||
return
|
||||
if action in {"cancel", "取消"}:
|
||||
await self._cancel(event, scope, user, tail)
|
||||
return
|
||||
if action in {"detail", "详情"}:
|
||||
if not tail.isdecimal():
|
||||
raise ValueError("用法:/tx detail 编号")
|
||||
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, self._format(rem, detail=True))
|
||||
return
|
||||
if action in {"identity", "身份"}:
|
||||
await self._reply(
|
||||
event,
|
||||
f"平台:{event.get_platform_id()}\n群标识:{event.get_group_id() or '私聊'}\n用户标识:{user}\n本群管理员授权标识:{event.get_platform_id()}|{event.get_group_id()}|{user}",
|
||||
)
|
||||
return
|
||||
if action in {"status", "状态"}:
|
||||
reminders = await self.store.list(scope, None if self._admin(event) else user)
|
||||
running = self._scheduler is not None and not self._scheduler.done()
|
||||
last = (
|
||||
datetime.fromtimestamp(self.last_scan, self.tz).strftime("%Y-%m-%d %H:%M:%S")
|
||||
if self.last_scan
|
||||
else "尚未扫描"
|
||||
)
|
||||
await self._reply(
|
||||
event,
|
||||
f"调度器:{'运行中' if running else '停止'}\n当前会话活跃提醒:{len(reminders)}\n扫描间隔:{self.interval} 秒\n时区:{self.timezone}\n最近扫描:{last}"
|
||||
+ (f"\n扫描错误:{self.last_scan_error}" if self.last_scan_error else ""),
|
||||
)
|
||||
return
|
||||
args, target, target_name = await resolve_target(event, args, self.store, scope)
|
||||
parsed = parse_time(args, datetime.now(self.tz))
|
||||
if len(parsed.content) > self.max_content:
|
||||
raise ValueError(f"提醒内容最多 {self.max_content} 个字符。")
|
||||
scene, destination = route(event)
|
||||
if not destination:
|
||||
raise ValueError("无法获取当前会话的投递目标。")
|
||||
record = {
|
||||
"scope": scope,
|
||||
"platform_id": str(event.get_platform_id()),
|
||||
"platform_name": event.get_platform_name(),
|
||||
"destination": destination,
|
||||
"scene": scene,
|
||||
"umo": event.unified_msg_origin,
|
||||
"creator_id": user,
|
||||
"creator_name": event.get_sender_name() or "",
|
||||
"target_id": target,
|
||||
"target_name": target_name,
|
||||
"content": parsed.content,
|
||||
"remind_at": parsed.when.timestamp(),
|
||||
"timezone": self.timezone,
|
||||
"repeat_type": parsed.repeat,
|
||||
}
|
||||
reminder_id = await self.store.add(record, self.limit)
|
||||
message = f"⏰ 提醒已设置 #{reminder_id}\n时间:{describe(record['remind_at'], parsed.repeat, self.timezone)}\n时区:{self.timezone}\n内容:{parsed.content}"
|
||||
if target != user:
|
||||
message += f"\n提醒对象:{target_name or target}"
|
||||
if event.get_platform_name() in OFFICIAL:
|
||||
message += "\n到期由 QQ 官方主动投递;发送权限或额度受限时会记录失败。"
|
||||
await self._reply(event, message)
|
||||
|
||||
def _format(self, rem, detail=False):
|
||||
status = {"active": "待提醒", "done": "已完成", "cancelled": "已取消"}[rem["status"]]
|
||||
content = (
|
||||
rem["content"]
|
||||
if detail
|
||||
else rem["content"][:200]
|
||||
+ ("…(/tx detail 查看全文)" if len(rem["content"]) > 200 else "")
|
||||
)
|
||||
text = f"#{rem['id']} [{status}] {describe(rem['remind_at'], rem['repeat_type'], rem['timezone'])}\n{content}"
|
||||
if rem["target_id"] != rem["creator_id"]:
|
||||
text += f"\n对象:{rem['target_name'] or rem['target_id']}"
|
||||
if detail:
|
||||
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]}"
|
||||
return text
|
||||
|
||||
async def _list(self, event, scope, user, tail, history):
|
||||
all_users = tail.split()[:1] == ["all"]
|
||||
if all_users:
|
||||
if not self._admin(event):
|
||||
raise ValueError("仅管理员可以查看当前会话全部用户的提醒。")
|
||||
tail = tail[3:].strip()
|
||||
if tail and not tail.isdecimal():
|
||||
raise ValueError("用法:/tx list [页码] 或 /tx history [页码]")
|
||||
page = int(tail or "1")
|
||||
if page < 1:
|
||||
raise ValueError("页码必须大于 0。")
|
||||
rows = await self.store.list(scope, None if all_users else user, history=history)
|
||||
if not rows:
|
||||
await self._reply(
|
||||
event, "当前会话没有提醒记录。" if history else "当前会话没有待提醒任务。"
|
||||
)
|
||||
return
|
||||
# List previews are truncated; detail shows the entire reminder.
|
||||
pages = (len(rows) + 1) // 2
|
||||
if page > pages:
|
||||
raise ValueError(f"总共 {pages} 页。")
|
||||
await self._reply(
|
||||
event,
|
||||
f"📋 提醒{'历史' if history else '列表'}({page}/{pages})\n"
|
||||
+ "\n\n".join(self._format(r) for r in rows[(page - 1) * 2 : page * 2]),
|
||||
)
|
||||
|
||||
async def _cancel(self, event, scope, user, tail):
|
||||
if tail.lower() in {"all", "全部"}:
|
||||
reminder_id = None
|
||||
creator = user
|
||||
elif tail.isdecimal():
|
||||
reminder_id = int(tail)
|
||||
creator = None if self._admin(event) else user
|
||||
else:
|
||||
raise ValueError("用法:/tx cancel 编号 或 /tx cancel all")
|
||||
# A confirmed cancellation cannot race a local in-flight delivery.
|
||||
async with self._scan_lock:
|
||||
count = await self.store.cancel(scope, creator, reminder_id)
|
||||
await self._reply(
|
||||
event,
|
||||
f"✅ 已取消 {count} 条提醒。" if count else "未找到可取消的提醒,或你没有操作权限。",
|
||||
)
|
||||
|
||||
@filter.command("cktx", alias={"提醒列表"})
|
||||
async def list_reminders(self, event: AstrMessageEvent):
|
||||
"""查看自己当前会话的待提醒任务。"""
|
||||
await self._guard(event, lambda: self._command(event, "list"))
|
||||
|
||||
@filter.command("qxtx", alias={"取消提醒"})
|
||||
async def cancel_reminder(self, event: AstrMessageEvent):
|
||||
"""通过编号取消提醒。"""
|
||||
match = re.search(r"(?:^|\s)/?(?:qxtx|取消提醒)(?=\s|$)", event.message_str)
|
||||
tail = event.message_str[match.end() :].strip() if match else ""
|
||||
await self._guard(event, lambda: self._command(event, "cancel " + tail))
|
||||
|
||||
@filter.command("cxzd", alias={"重启提醒"})
|
||||
async def restart_scheduler(self, event: AstrMessageEvent):
|
||||
"""管理员重启提醒调度器,保留数据库内所有任务。"""
|
||||
|
||||
async def restart():
|
||||
if not self._admin(event):
|
||||
raise ValueError("只有机器人管理员或配置授权的管理员可以重启提醒调度器。")
|
||||
async with self._init_lock:
|
||||
if self._scheduler:
|
||||
self._scheduler.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await self._scheduler
|
||||
self._scheduler = asyncio.create_task(self._poll(), name="lizi-reminders")
|
||||
await self._reply(
|
||||
event, f"✅ 提醒调度器已重启\n时区:{self.timezone}\n扫描间隔:{self.interval} 秒"
|
||||
)
|
||||
|
||||
await self._guard(event, restart)
|
||||
|
||||
@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():
|
||||
return
|
||||
try:
|
||||
await self.initialize()
|
||||
await self.store.observe(
|
||||
self._scope(event), str(event.get_sender_id()), event.get_sender_name()
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("[Reminder] 记录本群成员标识失败")
|
||||
|
||||
async def terminate(self):
|
||||
async with self._init_lock:
|
||||
self._closed = True
|
||||
if self._scheduler:
|
||||
self._scheduler.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await self._scheduler
|
||||
self._scheduler = None
|
||||
@@ -0,0 +1,11 @@
|
||||
name: astrbot_plugin_tixing
|
||||
display_name: 栗子提醒
|
||||
desc: 完整移植栗子 QQ 机器人的单次、每日、每周和他人提醒,支持列表、取消、持久化恢复及投递失败重试。
|
||||
version: v1.0.0
|
||||
author: itxiaohui
|
||||
repo: https://github.com/itxiaohui66/astrbot_plugin_tixing
|
||||
support_platforms:
|
||||
- qq_official
|
||||
- qq_official_webhook
|
||||
- aiocqhttp
|
||||
astrbot_version: ">=4.16,<5"
|
||||
@@ -0,0 +1,12 @@
|
||||
[tool.ruff]
|
||||
target-version = "py310"
|
||||
line-length = 100
|
||||
extend-exclude = ["dist"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E4", "E7", "E9", "F", "I"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["."]
|
||||
@@ -0,0 +1,3 @@
|
||||
pytest>=8
|
||||
pytest-asyncio>=0.23
|
||||
ruff>=0.9
|
||||
@@ -0,0 +1,2 @@
|
||||
# Windows needs the IANA timezone database used by zoneinfo.
|
||||
tzdata>=2024.1
|
||||
@@ -0,0 +1 @@
|
||||
"""Time parsing, storage and platform delivery services."""
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Deliver through the current adapter; never persist a live event or old msg_id."""
|
||||
|
||||
from html import escape
|
||||
|
||||
OFFICIAL = {"qq_official", "qq_official_webhook"}
|
||||
|
||||
|
||||
def field(value, name, default=None):
|
||||
return value.get(name, default) if isinstance(value, dict) else getattr(value, name, default)
|
||||
|
||||
|
||||
def route(event):
|
||||
group = str(event.get_group_id() or "")
|
||||
raw = event.message_obj.raw_message
|
||||
data = field(raw, "raw_data", raw)
|
||||
if event.get_platform_name() in OFFICIAL:
|
||||
if field(raw, "group_openid") or field(data, "group_openid"):
|
||||
return "group", str(field(raw, "group_openid") or field(data, "group_openid"))
|
||||
if field(raw, "channel_id") or field(data, "channel_id"):
|
||||
# Guild DMs need a separate guild ID, not the user's OpenID.
|
||||
if not group:
|
||||
return "guild_dm", str(field(raw, "guild_id") or field(data, "guild_id") or "")
|
||||
return "channel", str(field(raw, "channel_id") or field(data, "channel_id"))
|
||||
if not group:
|
||||
return "c2c", str(event.get_sender_id())
|
||||
raise ValueError("无法识别官方 QQ 群消息来源,请检查 AstrBot 适配器版本。")
|
||||
return ("group", group) if group else ("private", str(event.get_sender_id()))
|
||||
|
||||
|
||||
def find_platform(context, platform_id):
|
||||
manager = context.platform_manager
|
||||
return next((p for p in manager.platform_insts if str(p.meta().id) == platform_id), None)
|
||||
|
||||
|
||||
def available(platform):
|
||||
if platform is None:
|
||||
return False
|
||||
status = field(field(platform, "status"), "value", "running")
|
||||
# An absent/starting/disconnected platform does not count as a failed delivery.
|
||||
return str(status).lower() == "running"
|
||||
|
||||
|
||||
def reminder_text(rem):
|
||||
creator = rem["creator_name"] or rem["creator_id"]
|
||||
prefix = f"来自 {creator} 的提醒:\n" if rem["target_id"] != rem["creator_id"] else ""
|
||||
return f"{prefix}⏰ {rem['content']}\n(提醒 #{rem['id']})"
|
||||
|
||||
|
||||
async def deliver(platform, rem):
|
||||
"""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"]
|
||||
if scene == "group":
|
||||
mention = f'<qqbot-at-user id="{escape(rem["target_id"], quote=True)}" />'
|
||||
result = await api.post_group_message(
|
||||
group_openid=rem["destination"], msg_type=0, content=f"{mention}\n{text}"
|
||||
)
|
||||
elif scene == "c2c":
|
||||
result = await api.post_c2c_message(openid=rem["destination"], msg_type=0, content=text)
|
||||
elif scene == "channel":
|
||||
result = await api.post_message(
|
||||
channel_id=rem["destination"], content=f"<@{rem['target_id']}>\n{text}"
|
||||
)
|
||||
elif scene == "guild_dm":
|
||||
result = await api.post_dms(guild_id=rem["destination"], content=text)
|
||||
else:
|
||||
raise ValueError(f"未知官方 QQ 投递场景:{scene}")
|
||||
if not field(result, "id"):
|
||||
raise RuntimeError(
|
||||
"QQ 官方发送接口未返回消息 ID,请检查主动消息权限、额度和适配器版本。"
|
||||
)
|
||||
return
|
||||
# Preserve old OneBot behavior, including a real @ and member validation.
|
||||
if rem["platform_name"] == "aiocqhttp":
|
||||
message = [{"type": "text", "data": {"text": text}}]
|
||||
if rem["scene"] == "group":
|
||||
message.insert(0, {"type": "at", "data": {"qq": rem["target_id"]}})
|
||||
result = await client.send_group_msg(group_id=int(rem["destination"]), message=message)
|
||||
else:
|
||||
result = await client.send_private_msg(user_id=int(rem["destination"]), message=message)
|
||||
if not field(result, "message_id"):
|
||||
raise RuntimeError("OneBot 发送接口未返回消息 ID。")
|
||||
return
|
||||
raise ValueError(f"不支持的提醒平台:{rem['platform_name']}")
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Transactional SQLite persistence outside the installed plugin directory."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def scope_key(platform_id, group_id, user_id):
|
||||
# Group UMO may include the sender when unique-session is enabled.
|
||||
return json.dumps([platform_id, "group" if group_id else "private", group_id or user_id])
|
||||
|
||||
|
||||
class ReminderStore:
|
||||
def __init__(self, path):
|
||||
self.path = Path(path)
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
async def _run(self, operation):
|
||||
def run():
|
||||
with closing(sqlite3.connect(self.path, timeout=10)) as db, db:
|
||||
db.row_factory = sqlite3.Row
|
||||
return operation(db)
|
||||
|
||||
async with self._lock:
|
||||
# Wait for the worker before releasing the lock even during unload.
|
||||
worker = asyncio.create_task(asyncio.to_thread(run))
|
||||
try:
|
||||
return await asyncio.shield(worker)
|
||||
except asyncio.CancelledError:
|
||||
await worker
|
||||
raise
|
||||
|
||||
async def initialize(self):
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def create(db):
|
||||
db.executescript("""
|
||||
PRAGMA journal_mode=WAL;
|
||||
CREATE TABLE IF NOT EXISTS reminders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
scope TEXT NOT NULL, platform_id TEXT NOT NULL,
|
||||
platform_name TEXT NOT NULL, destination TEXT NOT NULL,
|
||||
scene TEXT NOT NULL, umo TEXT NOT NULL,
|
||||
creator_id TEXT NOT NULL, creator_name TEXT NOT NULL DEFAULT '',
|
||||
target_id TEXT NOT NULL, target_name TEXT NOT NULL DEFAULT '',
|
||||
content TEXT NOT NULL, remind_at REAL NOT NULL,
|
||||
timezone TEXT NOT NULL, repeat_type TEXT NOT NULL
|
||||
CHECK(repeat_type IN ('none','daily','weekly')),
|
||||
status TEXT NOT NULL DEFAULT 'active'
|
||||
CHECK(status IN ('active','done','cancelled')),
|
||||
failure_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_error TEXT NOT NULL DEFAULT '',
|
||||
retry_at REAL NOT NULL DEFAULT 0,
|
||||
lease_owner TEXT NOT NULL DEFAULT '', lease_until REAL NOT NULL DEFAULT 0,
|
||||
created_at REAL NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS reminders_due ON reminders(status, remind_at);
|
||||
CREATE INDEX IF NOT EXISTS reminders_scope ON reminders(scope, creator_id);
|
||||
CREATE TABLE IF NOT EXISTS members (
|
||||
scope TEXT NOT NULL, user_id TEXT NOT NULL,
|
||||
nickname TEXT NOT NULL DEFAULT '', seen_at REAL NOT NULL,
|
||||
PRIMARY KEY(scope, user_id)
|
||||
);
|
||||
""")
|
||||
|
||||
await self._run(create)
|
||||
|
||||
async def observe(self, scope, user_id, nickname=""):
|
||||
await self._run(
|
||||
lambda db: (
|
||||
db.execute(
|
||||
"INSERT INTO members VALUES (?,?,?,?) ON CONFLICT(scope,user_id) DO UPDATE SET "
|
||||
"nickname=CASE WHEN excluded.nickname!='' THEN excluded.nickname ELSE members.nickname END, "
|
||||
"seen_at=excluded.seen_at",
|
||||
(scope, user_id, nickname or "", time.time()),
|
||||
).rowcount
|
||||
)
|
||||
)
|
||||
|
||||
async def member(self, scope, value):
|
||||
def read(db):
|
||||
rows = db.execute(
|
||||
"SELECT * FROM members WHERE scope=? AND (user_id=? OR nickname=?)",
|
||||
(scope, value, value),
|
||||
).fetchall()
|
||||
exact = [r for r in rows if r["user_id"] == value]
|
||||
if exact:
|
||||
return dict(exact[0])
|
||||
if len(rows) > 1:
|
||||
raise ValueError("本群有重名用户,请使用真实 @ 或 /tx identity 获取的用户标识。")
|
||||
return dict(rows[0]) if rows else None
|
||||
|
||||
return await self._run(read)
|
||||
|
||||
async def add(self, record, limit):
|
||||
def insert(db):
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
count = db.execute(
|
||||
"SELECT COUNT(*) FROM reminders WHERE scope=? AND creator_id=? AND status='active'",
|
||||
(record["scope"], record["creator_id"]),
|
||||
).fetchone()[0]
|
||||
if count >= limit:
|
||||
raise ValueError(f"你在当前会话最多只能设置 {limit} 个提醒,请先取消一些。")
|
||||
columns = (
|
||||
"scope",
|
||||
"platform_id",
|
||||
"platform_name",
|
||||
"destination",
|
||||
"scene",
|
||||
"umo",
|
||||
"creator_id",
|
||||
"creator_name",
|
||||
"target_id",
|
||||
"target_name",
|
||||
"content",
|
||||
"remind_at",
|
||||
"timezone",
|
||||
"repeat_type",
|
||||
)
|
||||
cursor = db.execute(
|
||||
f"INSERT INTO reminders ({','.join(columns)},created_at) "
|
||||
f"VALUES ({','.join('?' for _ in range(len(columns) + 1))})",
|
||||
tuple(record[c] for c in columns) + (time.time(),),
|
||||
)
|
||||
return cursor.lastrowid
|
||||
|
||||
return await self._run(insert)
|
||||
|
||||
async def list(self, scope, creator_id=None, history=False):
|
||||
def read(db):
|
||||
sql, params = "SELECT * FROM reminders WHERE scope=?", [scope]
|
||||
if creator_id is not None:
|
||||
sql += " AND creator_id=?"
|
||||
params.append(creator_id)
|
||||
if not history:
|
||||
sql += " AND status='active'"
|
||||
sql += " ORDER BY remind_at,id"
|
||||
return [dict(r) for r in db.execute(sql, params).fetchall()]
|
||||
|
||||
return await self._run(read)
|
||||
|
||||
async def get(self, reminder_id, scope):
|
||||
def read(db):
|
||||
row = db.execute(
|
||||
"SELECT * FROM reminders WHERE id=? AND scope=?", (reminder_id, scope)
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
return await self._run(read)
|
||||
|
||||
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'"
|
||||
params = [scope]
|
||||
if creator_id is not None:
|
||||
sql += " AND creator_id=?"
|
||||
params.append(creator_id)
|
||||
if reminder_id is not None:
|
||||
sql += " AND id=?"
|
||||
params.append(reminder_id)
|
||||
return db.execute(sql, params).rowcount
|
||||
|
||||
return await self._run(write)
|
||||
|
||||
async def due(self, now):
|
||||
return await self._run(
|
||||
lambda db: [
|
||||
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",
|
||||
(now, now, now),
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
async def claim(self, reminder_id, owner, now):
|
||||
# One lease per send prevents overlapping hot reloads from sending twice.
|
||||
return await self._run(
|
||||
lambda db: (
|
||||
db.execute(
|
||||
"UPDATE reminders SET lease_owner=?,lease_until=? WHERE id=? AND status='active' "
|
||||
"AND lease_until<=? AND remind_at<=? AND retry_at<=?",
|
||||
(owner, now + 120, reminder_id, now, now, now),
|
||||
).rowcount
|
||||
== 1
|
||||
)
|
||||
)
|
||||
|
||||
async def success(self, reminder_id, owner, next_time=None):
|
||||
return await self._run(
|
||||
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'",
|
||||
("active" if next_time is not None else "done", next_time, reminder_id, owner),
|
||||
).rowcount
|
||||
)
|
||||
)
|
||||
|
||||
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=?,"
|
||||
"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),
|
||||
)
|
||||
|
||||
await self._run(write)
|
||||
|
||||
async def release(self, reminder_id, owner):
|
||||
await self._run(
|
||||
lambda db: (
|
||||
db.execute(
|
||||
"UPDATE reminders SET lease_owner='',lease_until=0 WHERE id=? AND lease_owner=?",
|
||||
(reminder_id, owner),
|
||||
).rowcount
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Resolve real mention components, QQ official markup and observed member names."""
|
||||
|
||||
import re
|
||||
|
||||
from .delivery import OFFICIAL, field
|
||||
|
||||
MARKUP = re.compile(
|
||||
r"<qqbot-at-user\s+id=[\"\']([^\"\']+)[\"\']\s*/>|<@!?([^>]+)>|\[CQ:at,qq=([^,\]]+)[^\]]*\]"
|
||||
)
|
||||
TEXT_AT = re.compile(r"(?<![\w@])@([^\s@]+)")
|
||||
VALID_ID = re.compile(r"[A-Za-z0-9_-]{1,128}\Z")
|
||||
|
||||
|
||||
async def resolve_target(event, args, store, scope):
|
||||
sender = str(event.get_sender_id())
|
||||
bot_ids = {str(event.message_obj.self_id)}
|
||||
raw = event.message_obj.raw_message
|
||||
raw_data = field(raw, "raw_data", raw)
|
||||
mentions = field(raw, "mentions", None) or field(raw_data, "mentions", []) or []
|
||||
trusted = {}
|
||||
for mention in mentions:
|
||||
user = str(field(mention, "id", None) or field(mention, "member_openid", ""))
|
||||
if field(mention, "is_you", False) or field(mention, "bot", False):
|
||||
bot_ids.add(user)
|
||||
elif user:
|
||||
trusted[user] = str(field(mention, "username", "") or "")
|
||||
for component in event.get_messages():
|
||||
if field(component, "type") in {"At", "at"} or type(component).__name__ == "At":
|
||||
user = str(field(component, "qq", ""))
|
||||
if user and user not in bot_ids:
|
||||
trusted[user] = str(field(component, "name", "") or "")
|
||||
candidates = list(trusted)
|
||||
for match in MARKUP.finditer(args):
|
||||
user = next(g for g in match.groups() if g is not None)
|
||||
if user not in bot_ids:
|
||||
candidates.append(user)
|
||||
args = MARKUP.sub(" ", args)
|
||||
textual = list(TEXT_AT.finditer(args))
|
||||
for match in textual:
|
||||
value = match.group(1)
|
||||
# @all must not be allowed as a recipient.
|
||||
if value in {"all", "everyone", "全体成员"}:
|
||||
raise ValueError("一次提醒只能指定一个成员,不能 @ 全体成员。")
|
||||
names = [user for user, name in trusted.items() if name and name == value]
|
||||
if len(names) > 1:
|
||||
raise ValueError("被 @ 成员重名,请使用用户标识。")
|
||||
member = await store.member(scope, value)
|
||||
candidates.append(names[0] if names else member["user_id"] if member else value)
|
||||
args = TEXT_AT.sub(" ", args).strip()
|
||||
candidates = list(dict.fromkeys(candidates))
|
||||
if len(candidates) > 1:
|
||||
raise ValueError("一次提醒只能指定一个成员。")
|
||||
target = candidates[0] if candidates else sender
|
||||
if not VALID_ID.fullmatch(target) or target == "all":
|
||||
raise ValueError("提醒对象标识无效,请使用真实 @。")
|
||||
if not event.get_group_id() and target != sender:
|
||||
raise ValueError("私聊只能提醒自己;提醒他人请在群内使用。")
|
||||
member = await store.member(scope, target)
|
||||
if target != sender:
|
||||
if event.get_platform_name() in OFFICIAL:
|
||||
if target not in trusted and not member:
|
||||
raise ValueError(
|
||||
"无法确认该用户的本群 OpenID。请真实 @ 对方;若官方未提供成员标识,"
|
||||
"让对方先在本群 @ 机器人发送 /tx identity,再用 @用户标识。普通 QQ 号不能转换成 OpenID。"
|
||||
)
|
||||
elif event.get_platform_name() == "aiocqhttp":
|
||||
try:
|
||||
await event.bot.get_group_member_info(
|
||||
group_id=int(event.get_group_id()), user_id=int(target), no_cache=True
|
||||
)
|
||||
except Exception as exc:
|
||||
raise ValueError("无法在本群找到该成员,请重新 @ 群成员。") from exc
|
||||
name = trusted.get(target) or (member["nickname"] if member else "")
|
||||
if target == sender:
|
||||
name = event.get_sender_name() or ""
|
||||
return args, target, name
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Parse the old reminder syntax and the formats advertised by its help."""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
WEEKDAYS = {s: i for i, s in enumerate("一二三四五六日")}
|
||||
WEEKDAYS.update({str(i + 1): i for i in range(7)})
|
||||
WEEKDAYS["天"] = 6
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ParsedReminder:
|
||||
when: datetime
|
||||
content: str
|
||||
repeat: str = "none"
|
||||
|
||||
|
||||
def parse_time(text: str, now: datetime) -> ParsedReminder:
|
||||
"""Always use an explicit timezone; reject past/invalid/zero times."""
|
||||
text = text.strip()
|
||||
flags = re.I | re.S
|
||||
try:
|
||||
match = re.fullmatch(r"每天\s*(\d{1,2})[::](\d{2})\s+(.+)", text, flags)
|
||||
if match:
|
||||
hour, minute, content = match.groups()
|
||||
when = now.replace(hour=int(hour), minute=int(minute), second=0, microsecond=0)
|
||||
if when <= now:
|
||||
when += timedelta(days=1)
|
||||
return _result(when, content, "daily")
|
||||
match = re.fullmatch(
|
||||
r"每周([一二三四五六日天1-7])\s*(\d{1,2})[::](\d{2})\s+(.+)", text, flags
|
||||
)
|
||||
if match:
|
||||
weekday, hour, minute, content = match.groups()
|
||||
when = now.replace(hour=int(hour), minute=int(minute), second=0, microsecond=0)
|
||||
when += timedelta(days=(WEEKDAYS[weekday] - now.weekday()) % 7)
|
||||
# The old code incorrectly skipped later times on the same weekday.
|
||||
if when <= now:
|
||||
when += timedelta(weeks=1)
|
||||
return _result(when, content, "weekly")
|
||||
match = re.fullmatch(
|
||||
r"(\d+)\s*(分钟|小时|天|minutes?|hours?|days?|min|h|d)(?:后)?\s+(.+)", text, flags
|
||||
)
|
||||
if match:
|
||||
amount, unit, content = match.groups()
|
||||
amount = int(amount)
|
||||
if amount <= 0:
|
||||
raise ValueError("提醒间隔必须大于 0。")
|
||||
unit = unit.lower()
|
||||
seconds = (
|
||||
60
|
||||
if unit in {"分钟", "minute", "minutes", "min"}
|
||||
else (3600 if unit in {"小时", "hour", "hours", "h"} else 86400)
|
||||
)
|
||||
return _result(now + timedelta(seconds=amount * seconds), content)
|
||||
match = re.fullmatch(r"(\d{4}-\d{2}-\d{2})\s+(\d{1,2})[::](\d{2})\s+(.+)", text, flags)
|
||||
if match:
|
||||
date, hour, minute, content = match.groups()
|
||||
when = datetime.strptime(f"{date} {hour}:{minute}", "%Y-%m-%d %H:%M").replace(
|
||||
tzinfo=now.tzinfo
|
||||
)
|
||||
else:
|
||||
match = re.fullmatch(r"(今天|明天|后天)?\s*(\d{1,2})[::](\d{2})\s+(.+)", text, flags)
|
||||
if not match:
|
||||
raise ValueError("时间格式错误,发送 /tx help 查看全部格式。")
|
||||
day, hour, minute, content = match.groups()
|
||||
when = now.replace(hour=int(hour), minute=int(minute), second=0, microsecond=0)
|
||||
when += timedelta(days={None: 0, "今天": 0, "明天": 1, "后天": 2}[day])
|
||||
if when <= now:
|
||||
raise ValueError("单次提醒时间已经过去,请指定未来时间。")
|
||||
return _result(when, content)
|
||||
except (OverflowError, ValueError) as exc:
|
||||
if isinstance(exc, OverflowError) or str(exc).startswith(
|
||||
("hour must", "minute must", "day is", "time data")
|
||||
):
|
||||
raise ValueError("日期或时间无效,请检查日期、小时和分钟。") from exc
|
||||
raise
|
||||
|
||||
|
||||
def _result(when, content, repeat="none"):
|
||||
content = content.strip()
|
||||
if not content:
|
||||
raise ValueError("提醒内容不能为空。")
|
||||
return ParsedReminder(when, content, repeat)
|
||||
|
||||
|
||||
def next_occurrence(timestamp: float, repeat: str, timezone: str, now: float) -> float:
|
||||
"""Skip missed cycles after downtime instead of flooding a group."""
|
||||
previous = datetime.fromtimestamp(timestamp, ZoneInfo(timezone))
|
||||
current = datetime.fromtimestamp(now, previous.tzinfo)
|
||||
step = 1 if repeat == "daily" else 7
|
||||
days = max(step, ((current.date() - previous.date()).days // step) * step)
|
||||
target = previous + timedelta(days=days)
|
||||
if target.timestamp() <= now:
|
||||
target += timedelta(days=step)
|
||||
return target.timestamp()
|
||||
|
||||
|
||||
def describe(timestamp: float, repeat: str, timezone: str) -> str:
|
||||
when = datetime.fromtimestamp(timestamp, ZoneInfo(timezone))
|
||||
if repeat == "daily":
|
||||
return f"每天 {when:%H:%M}(下次 {when:%Y-%m-%d %H:%M})"
|
||||
if repeat == "weekly":
|
||||
return f"每周{'一二三四五六日'[when.weekday()]} {when:%H:%M}(下次 {when:%Y-%m-%d %H:%M})"
|
||||
return when.strftime("%Y-%m-%d %H:%M")
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Small host boundary doubles; real time parsing and SQLite are never mocked."""
|
||||
|
||||
import importlib.util
|
||||
import logging
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class Event:
|
||||
def __init__(
|
||||
self,
|
||||
text="/tx 1分钟 开会",
|
||||
user="user_1",
|
||||
group="group_1",
|
||||
platform="qq_official",
|
||||
raw=None,
|
||||
):
|
||||
self.message_str = text
|
||||
self.user = user
|
||||
self.group = group
|
||||
self.platform = platform
|
||||
self.message_obj = SimpleNamespace(
|
||||
self_id="bot_id",
|
||||
raw_message=raw if raw is not None else {"group_openid": group} if group else {},
|
||||
)
|
||||
self.messages = []
|
||||
self.replies = []
|
||||
self.stopped = False
|
||||
self.admin = False
|
||||
self.unified_msg_origin = f"platform_1:GroupMessage:{user}_{group}"
|
||||
self.bot = SimpleNamespace(get_group_member_info=AsyncMock(return_value={"user_id": user}))
|
||||
|
||||
def get_platform_id(self):
|
||||
return "platform_1"
|
||||
|
||||
def get_platform_name(self):
|
||||
return self.platform
|
||||
|
||||
def get_group_id(self):
|
||||
return self.group
|
||||
|
||||
def get_sender_id(self):
|
||||
return self.user
|
||||
|
||||
def get_sender_name(self):
|
||||
return "名字_" + self.user
|
||||
|
||||
def get_messages(self):
|
||||
return self.messages
|
||||
|
||||
def is_admin(self):
|
||||
return self.admin
|
||||
|
||||
def plain_result(self, text):
|
||||
return text
|
||||
|
||||
async def send(self, result):
|
||||
self.replies.append(result)
|
||||
|
||||
def stop_event(self):
|
||||
self.stopped = True
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def event_factory():
|
||||
return Event
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def plugin_class(monkeypatch, tmp_path):
|
||||
api = types.ModuleType("astrbot.api")
|
||||
api.AstrBotConfig = dict
|
||||
api.logger = logging.getLogger("reminder-tests")
|
||||
events = types.ModuleType("astrbot.api.event")
|
||||
events.AstrMessageEvent = Event
|
||||
|
||||
def decorator(*args, **kwargs):
|
||||
return lambda func: func
|
||||
|
||||
events.filter = SimpleNamespace(
|
||||
command=decorator,
|
||||
on_astrbot_loaded=decorator,
|
||||
event_message_type=decorator,
|
||||
EventMessageType=SimpleNamespace(ALL="all"),
|
||||
)
|
||||
stars = types.ModuleType("astrbot.api.star")
|
||||
|
||||
class Star:
|
||||
def __init__(self, context):
|
||||
self.context = context
|
||||
|
||||
stars.Star = Star
|
||||
stars.Context = object
|
||||
stars.StarTools = SimpleNamespace(get_data_dir=lambda name: tmp_path)
|
||||
for name, module in {
|
||||
"astrbot": types.ModuleType("astrbot"),
|
||||
"astrbot.api": api,
|
||||
"astrbot.api.event": events,
|
||||
"astrbot.api.star": stars,
|
||||
}.items():
|
||||
monkeypatch.setitem(sys.modules, name, module)
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"reminder_plugin_test", root / "__init__.py", submodule_search_locations=[str(root)]
|
||||
)
|
||||
package = importlib.util.module_from_spec(spec)
|
||||
monkeypatch.setitem(sys.modules, spec.name, package)
|
||||
spec.loader.exec_module(package)
|
||||
main_spec = importlib.util.spec_from_file_location(
|
||||
"reminder_plugin_test.main", root / "main.py"
|
||||
)
|
||||
module = importlib.util.module_from_spec(main_spec)
|
||||
main_spec.loader.exec_module(module)
|
||||
return module.ReminderPlugin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def platform_factory():
|
||||
def factory(name="qq_official", result=None):
|
||||
result = {"id": "sent_1"} if result is None else result
|
||||
api = SimpleNamespace(
|
||||
**{
|
||||
method: AsyncMock(return_value=result)
|
||||
for method in (
|
||||
"post_group_message",
|
||||
"post_c2c_message",
|
||||
"post_message",
|
||||
"post_dms",
|
||||
)
|
||||
}
|
||||
)
|
||||
client = SimpleNamespace(
|
||||
api=api,
|
||||
send_group_msg=AsyncMock(return_value={"message_id": 1}),
|
||||
send_private_msg=AsyncMock(return_value={"message_id": 1}),
|
||||
)
|
||||
return SimpleNamespace(
|
||||
meta=lambda: SimpleNamespace(id="platform_1", name=name),
|
||||
status=SimpleNamespace(value="running"),
|
||||
get_client=lambda: client,
|
||||
)
|
||||
|
||||
return factory
|
||||
@@ -0,0 +1,293 @@
|
||||
import asyncio
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from services.delivery import deliver, route
|
||||
from services.storage import ReminderStore, scope_key
|
||||
from services.targets import resolve_target
|
||||
|
||||
|
||||
def record(**changes):
|
||||
rem = dict(
|
||||
scope=scope_key("platform_1", "group_1", "user_1"),
|
||||
platform_id="platform_1",
|
||||
platform_name="qq_official",
|
||||
destination="group_1",
|
||||
scene="group",
|
||||
umo="old_umo",
|
||||
creator_id="user_1",
|
||||
creator_name="甲",
|
||||
target_id="user_1",
|
||||
target_name="甲",
|
||||
content="吃饭",
|
||||
remind_at=time.time() - 10,
|
||||
timezone="Asia/Shanghai",
|
||||
repeat_type="none",
|
||||
)
|
||||
rem.update(changes)
|
||||
return rem
|
||||
|
||||
|
||||
async def test_atomic_limit_and_scope(tmp_path):
|
||||
store = ReminderStore(tmp_path / "test.db")
|
||||
await store.initialize()
|
||||
results = await asyncio.gather(
|
||||
*(store.add(record(), 1) for _ in range(2)), return_exceptions=True
|
||||
)
|
||||
assert sum(isinstance(r, ValueError) for r in results) == 1
|
||||
await store.add(record(scope=scope_key("platform_2", "group_1", "user_1")), 1)
|
||||
await store.add(record(scope=scope_key("platform_1", "group_2", "user_1")), 1)
|
||||
assert len(await store.list(record()["scope"])) == 1
|
||||
|
||||
|
||||
async def test_leases_across_instances_and_restore(tmp_path):
|
||||
first = ReminderStore(tmp_path / "test.db")
|
||||
await first.initialize()
|
||||
rem_id = await first.add(record(), 10)
|
||||
second = ReminderStore(first.path)
|
||||
await second.initialize()
|
||||
now = time.time()
|
||||
claims = await asyncio.gather(first.claim(rem_id, "one", now), second.claim(rem_id, "two", now))
|
||||
assert sum(claims) == 1
|
||||
assert not await second.due(now)
|
||||
assert len(await second.due(now + 121)) == 1
|
||||
assert (await second.list(record()["scope"]))[0]["content"] == "吃饭"
|
||||
|
||||
|
||||
async def test_cancel_authorization_and_lease(tmp_path):
|
||||
store = ReminderStore(tmp_path / "test.db")
|
||||
await store.initialize()
|
||||
rem_id = await store.add(record(), 10)
|
||||
assert not await store.cancel(record()["scope"], "other", rem_id)
|
||||
assert not await store.cancel("other_group", None, rem_id)
|
||||
assert await store.cancel(record()["scope"], "user_1", rem_id) == 1
|
||||
assert not await store.claim(rem_id, "owner", time.time())
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"scene,method,destination_key",
|
||||
[
|
||||
("group", "post_group_message", "group_openid"),
|
||||
("c2c", "post_c2c_message", "openid"),
|
||||
("channel", "post_message", "channel_id"),
|
||||
("guild_dm", "post_dms", "guild_id"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("platform_name", ["qq_official", "qq_official_webhook"])
|
||||
async def test_official_routes(platform_factory, scene, method, destination_key, platform_name):
|
||||
platform = platform_factory(platform_name)
|
||||
await deliver(platform, {**record(scene=scene, platform_name=platform_name), "id": 1})
|
||||
kwargs = getattr(platform.get_client().api, method).call_args.kwargs
|
||||
assert kwargs[destination_key] == "group_1"
|
||||
assert "msg_id" not in kwargs
|
||||
if scene == "group":
|
||||
assert '<qqbot-at-user id="user_1" />' in kwargs["content"]
|
||||
|
||||
|
||||
async def test_empty_official_result_is_failure(platform_factory):
|
||||
platform = platform_factory()
|
||||
platform.get_client().api.post_group_message.return_value = None
|
||||
with pytest.raises(RuntimeError):
|
||||
await deliver(platform, {**record(), "id": 1})
|
||||
|
||||
|
||||
async def test_onebot_delivery(platform_factory):
|
||||
platform = platform_factory("aiocqhttp")
|
||||
await deliver(
|
||||
platform,
|
||||
{**record(platform_name="aiocqhttp", destination="12345", target_id="67890"), "id": 1},
|
||||
)
|
||||
kwargs = platform.get_client().send_group_msg.call_args.kwargs
|
||||
assert kwargs["group_id"] == 12345
|
||||
assert kwargs["message"][0]["data"]["qq"] == "67890"
|
||||
|
||||
|
||||
async def test_member_and_mentions(tmp_path, event_factory):
|
||||
store = ReminderStore(tmp_path / "test.db")
|
||||
await store.initialize()
|
||||
event = event_factory()
|
||||
scope = record()["scope"]
|
||||
await store.observe(scope, "opaque_OpenID", "小明")
|
||||
text, target, name = await resolve_target(event, "1小时 开会 @小明", store, scope)
|
||||
assert target == "opaque_OpenID" and name == "小明" and text == "1小时 开会"
|
||||
event.messages = [
|
||||
SimpleNamespace(qq="bot_id", name="", type="At"),
|
||||
SimpleNamespace(qq="opaque_new", name="新用户", type="At"),
|
||||
]
|
||||
assert (await resolve_target(event, "1小时 开会", store, scope))[1] == "opaque_new"
|
||||
event.messages = []
|
||||
event.message_obj.raw_message = {
|
||||
"group_openid": "group_1",
|
||||
"mentions": [{"id": "opaque_new", "username": "新用户"}, {"id": "bot_id", "is_you": True}],
|
||||
}
|
||||
assert (
|
||||
await resolve_target(event, '1小时 <qqbot-at-user id="opaque_new" /> 开会', store, scope)
|
||||
)[1] == "opaque_new"
|
||||
event.message_obj.raw_message = {"group_openid": "group_1"}
|
||||
with pytest.raises(ValueError, match="OpenID"):
|
||||
await resolve_target(event, "1小时 开会 @123456789", store, scope)
|
||||
await store.observe("other_scope", "unknown", "跨群用户")
|
||||
with pytest.raises(ValueError):
|
||||
await resolve_target(event, "1小时 开会 @unknown", store, scope)
|
||||
|
||||
|
||||
async def test_ambiguous_multiple_all_and_private(tmp_path, event_factory):
|
||||
store = ReminderStore(tmp_path / "test.db")
|
||||
await store.initialize()
|
||||
scope = record()["scope"]
|
||||
await store.observe(scope, "u1", "小明")
|
||||
await store.observe(scope, "u2", "小明")
|
||||
for args in ["1小时 开会 @小明", "1小时 开会 @u1 @u2", "1小时 开会 @all"]:
|
||||
with pytest.raises(ValueError):
|
||||
await resolve_target(event_factory(), args, store, scope)
|
||||
with pytest.raises(ValueError, match="私聊"):
|
||||
await resolve_target(event_factory(group=""), "1小时 开会 @u1", store, scope)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
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})
|
||||
await instance.store.initialize()
|
||||
# Control scans explicitly in integration tests; lifecycle is tested separately.
|
||||
instance._ready = True
|
||||
instance.initialize = AsyncMock()
|
||||
yield instance, platform
|
||||
await instance.terminate()
|
||||
|
||||
|
||||
async def test_due_success_once_and_recurring(plugin):
|
||||
instance, platform = plugin
|
||||
one_id = await instance.store.add(record(), 10)
|
||||
daily_id = await instance.store.add(
|
||||
record(repeat_type="daily", remind_at=time.time() - 86400 * 5), 10
|
||||
)
|
||||
await instance._check_due()
|
||||
assert (await instance.store.get(one_id, record()["scope"]))["status"] == "done"
|
||||
daily = await instance.store.get(daily_id, record()["scope"])
|
||||
assert daily["status"] == "active" and daily["remind_at"] > time.time()
|
||||
await instance._check_due()
|
||||
assert platform.get_client().api.post_group_message.await_count == 2
|
||||
|
||||
|
||||
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("没有主动消息权限")
|
||||
rem_id = await instance.store.add(record(), 10)
|
||||
for count in range(1, 4):
|
||||
await instance._check_due()
|
||||
rem = await instance.store.get(rem_id, record()["scope"])
|
||||
assert rem["failure_count"] == count
|
||||
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]
|
||||
|
||||
|
||||
async def test_platform_unavailable_does_not_cancel(plugin):
|
||||
instance, platform = plugin
|
||||
rem_id = await instance.store.add(record(), 10)
|
||||
platform.status.value = "pending"
|
||||
await instance._check_due()
|
||||
assert (await instance.store.get(rem_id, record()["scope"]))["failure_count"] == 0
|
||||
platform.status.value = "running"
|
||||
await instance._check_due()
|
||||
assert (await instance.store.get(rem_id, record()["scope"]))["status"] == "done"
|
||||
|
||||
|
||||
async def test_commands_scope_cancel_and_admin(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
for alias in ["tx", "提醒", "remind"]:
|
||||
event = event_factory(f"/{alias} 1小时 提醒:内容\n第二行")
|
||||
await instance.tx(event)
|
||||
assert "提醒已设置" in event.replies[0] and event.stopped
|
||||
assert len(await instance.store.list(record()["scope"])) == 3
|
||||
other = event_factory("/tx list", user="user_2")
|
||||
await instance.tx(other)
|
||||
assert "没有待提醒" in other.replies[0]
|
||||
denied = event_factory("/tx cancel 1", user="user_2")
|
||||
await instance.tx(denied)
|
||||
assert "未找到" in denied.replies[0]
|
||||
denied.admin = True
|
||||
await instance.tx(denied)
|
||||
assert "已取消 1" in denied.replies[-1]
|
||||
cross = event_factory("/tx cancel 2", group="other_group")
|
||||
cross.admin = True
|
||||
await instance.tx(cross)
|
||||
assert "未找到" in cross.replies[0]
|
||||
mine = event_factory("/tx cancel all")
|
||||
await instance.tx(mine)
|
||||
assert "已取消 2" in mine.replies[0]
|
||||
|
||||
|
||||
async def test_private_and_member_observation(plugin, event_factory):
|
||||
instance, _ = plugin
|
||||
event = event_factory("/tx 1小时 私聊提醒", group="")
|
||||
await instance.tx(event)
|
||||
rows = await instance.store.list(instance._scope(event))
|
||||
assert rows[0]["scene"] == "c2c" and rows[0]["destination"] == "user_1"
|
||||
observe = event_factory("普通消息", user="user_2")
|
||||
await instance.observe_member(observe)
|
||||
assert not observe.stopped
|
||||
assert (await instance.store.member(record()["scope"], "user_2"))["user_id"] == "user_2"
|
||||
|
||||
|
||||
async def test_lifecycle_restart_does_not_duplicate(plugin_class, platform_factory, event_factory):
|
||||
context = SimpleNamespace(platform_manager=SimpleNamespace(platform_insts=[platform_factory()]))
|
||||
instance = plugin_class(context, {"check_interval_seconds": 999})
|
||||
await instance.initialize()
|
||||
original = instance._scheduler
|
||||
await instance.initialize()
|
||||
await instance.on_loaded()
|
||||
assert instance._scheduler is original
|
||||
event = event_factory("/cxzd")
|
||||
await instance.restart_scheduler(event)
|
||||
assert "管理员" in event.replies[0] and instance._scheduler is original
|
||||
event.admin = True
|
||||
await instance.restart_scheduler(event)
|
||||
assert original.done() and instance._scheduler is not original
|
||||
await instance.terminate()
|
||||
assert instance._scheduler is None
|
||||
|
||||
|
||||
async def test_unload_waits_for_delivery_persistence(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()
|
||||
rem_id = await instance.store.add(record(), 10)
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def delayed_send(**kwargs):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return {"id": "sent"}
|
||||
|
||||
platform.get_client().api.post_group_message.side_effect = delayed_send
|
||||
await instance.initialize()
|
||||
await entered.wait()
|
||||
unload = asyncio.create_task(instance.terminate())
|
||||
await asyncio.sleep(0)
|
||||
assert not unload.done()
|
||||
release.set()
|
||||
await unload
|
||||
restored = ReminderStore(instance.store.path)
|
||||
assert (await restored.get(rem_id, record()["scope"]))["status"] == "done"
|
||||
|
||||
|
||||
def test_route_raw_object_and_channel(event_factory):
|
||||
assert route(event_factory(raw=SimpleNamespace(group_openid="opaque_group"))) == (
|
||||
"group",
|
||||
"opaque_group",
|
||||
)
|
||||
assert route(event_factory(group="chan", raw={"channel_id": "chan"})) == ("channel", "chan")
|
||||
assert route(event_factory(group="", raw={"channel_id": "dm", "guild_id": "guild"})) == (
|
||||
"guild_dm",
|
||||
"guild",
|
||||
)
|
||||
@@ -0,0 +1,93 @@
|
||||
from datetime import datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from services.time_parser import next_occurrence, parse_time
|
||||
|
||||
NOW = datetime(2026, 10, 5, 8, 0, tzinfo=ZoneInfo("Asia/Shanghai")) # Monday
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text,delta",
|
||||
[
|
||||
("30分钟 内容", timedelta(minutes=30)),
|
||||
("2小时后 内容", timedelta(hours=2)),
|
||||
("3天 内容", timedelta(days=3)),
|
||||
("30min 内容", timedelta(minutes=30)),
|
||||
("2H 内容", timedelta(hours=2)),
|
||||
("1day 内容", timedelta(days=1)),
|
||||
("1minutes 内容", timedelta(minutes=1)),
|
||||
("2 hours 内容", timedelta(hours=2)),
|
||||
("1d 内容", timedelta(days=1)),
|
||||
],
|
||||
)
|
||||
def test_relative(text, delta):
|
||||
parsed = parse_time(text, NOW)
|
||||
assert parsed.when == NOW + delta
|
||||
assert parsed.content == "内容"
|
||||
assert parsed.repeat == "none"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text,expected,repeat",
|
||||
[
|
||||
("每天9:00 内容", "2026-10-05 09:00", "daily"),
|
||||
("每天 8:00 内容", "2026-10-06 08:00", "daily"),
|
||||
("每周一 9:00 内容", "2026-10-05 09:00", "weekly"),
|
||||
("每周1 7:00 内容", "2026-10-12 07:00", "weekly"),
|
||||
("每周日 9:00 内容", "2026-10-11 09:00", "weekly"),
|
||||
("每周天9:00 内容", "2026-10-11 09:00", "weekly"),
|
||||
("每周7 9:00 内容", "2026-10-11 09:00", "weekly"),
|
||||
("明天10:00 内容", "2026-10-06 10:00", "none"),
|
||||
("后天 10:00 内容", "2026-10-07 10:00", "none"),
|
||||
("今天 10:00 内容", "2026-10-05 10:00", "none"),
|
||||
("10:00 内容", "2026-10-05 10:00", "none"),
|
||||
("2026-12-31 20:00 内容", "2026-12-31 20:00", "none"),
|
||||
],
|
||||
)
|
||||
def test_clock(text, expected, repeat):
|
||||
parsed = parse_time(text, NOW)
|
||||
assert parsed.when.strftime("%Y-%m-%d %H:%M") == expected
|
||||
assert parsed.repeat == repeat
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
[
|
||||
"0分钟 内容",
|
||||
"-1小时 内容",
|
||||
"每天25:00 内容",
|
||||
"每周一9:60 内容",
|
||||
"每周八9:00 内容",
|
||||
"7:00 过去",
|
||||
"今天8:00 过去",
|
||||
"2026-02-30 9:00 无效",
|
||||
"1分钟",
|
||||
"1分钟 ",
|
||||
"999999999999999999天 内容",
|
||||
],
|
||||
)
|
||||
def test_reject_invalid(text):
|
||||
with pytest.raises(ValueError):
|
||||
parse_time(text, NOW)
|
||||
|
||||
|
||||
def test_content_keeps_newlines_and_colons():
|
||||
assert parse_time("每天9:00 提醒:吃饭\n第二行", NOW).content == "提醒:吃饭\n第二行"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"repeat,old,now,expected",
|
||||
[
|
||||
("daily", "2026-10-01 09:00", "2026-10-05 12:00", "2026-10-06 09:00"),
|
||||
("daily", "2026-10-01 09:00", "2026-10-05 08:00", "2026-10-05 09:00"),
|
||||
("weekly", "2026-09-07 09:00", "2026-10-05 12:00", "2026-10-12 09:00"),
|
||||
("weekly", "2026-09-07 09:00", "2026-10-05 08:00", "2026-10-05 09:00"),
|
||||
],
|
||||
)
|
||||
def test_skip_missed_cycles(repeat, old, now, expected):
|
||||
def stamp(value):
|
||||
return datetime.strptime(value, "%Y-%m-%d %H:%M").replace(tzinfo=NOW.tzinfo).timestamp()
|
||||
|
||||
assert next_occurrence(stamp(old), repeat, "Asia/Shanghai", stamp(now)) == stamp(expected)
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Build an AstrBot upload ZIP from an explicit list of runtime files."""
|
||||
|
||||
from pathlib import Path
|
||||
from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
version = next(
|
||||
line.split(":", 1)[1].strip()
|
||||
for line in (ROOT / "metadata.yaml").read_text(encoding="utf-8").splitlines()
|
||||
if line.startswith("version:")
|
||||
)
|
||||
files = [
|
||||
ROOT / name
|
||||
for name in (
|
||||
"__init__.py",
|
||||
"main.py",
|
||||
"metadata.yaml",
|
||||
"_conf_schema.json",
|
||||
"requirements.txt",
|
||||
"README.md",
|
||||
"LICENSE",
|
||||
)
|
||||
]
|
||||
files += sorted((ROOT / "services").glob("*.py"))
|
||||
destination = ROOT / "dist" / f"astrbot_plugin_tixing-{version}.zip"
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
with ZipFile(destination, "w", ZIP_DEFLATED) as archive:
|
||||
for path in files:
|
||||
archive.write(path, "astrbot_plugin_tixing/" + path.relative_to(ROOT).as_posix())
|
||||
with ZipFile(destination) as archive:
|
||||
assert archive.testzip() is None
|
||||
assert "astrbot_plugin_tixing/main.py" in archive.namelist()
|
||||
assert "astrbot_plugin_tixing/metadata.yaml" in archive.namelist()
|
||||
print(destination)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user