diff --git a/README.md b/README.md index 44f27b7..061c287 100644 --- a/README.md +++ b/README.md @@ -8,57 +8,57 @@ AstrBot 原生《断箭》(Broken Arrow)战绩查询插件。支持玩家概 ## 快速开始 -1. **安装插件**:在 AstrBot 插件管理中导入 `astrbot_plugin_ba_stats_v0.1.0.zip`(或将插件目录放入 `data/plugins/` 并使用 AstrBot 的 Python 环境安装 `requirements.txt`)。 +1. **安装插件**:在 AstrBot 插件管理中导入 `astrbot_plugin_ba_stats_v0.1.1.zip`(或将插件目录放入 `data/plugins/` 并使用 AstrBot 的 Python 环境安装 `requirements.txt`)。 2. **配置接入**:打开插件设置中的「数据源接入」,填入获准客户端标识(若运营方要求则填写 Bearer 令牌),开启「启用在线查询」。 3. **保存重载**:保存配置并重载插件使其生效。 4. **绑定与查询**: - - 发送 `/ba search 昵称` 搜索玩家 - - 发送 `/ba bind stb:玩家ID` 并按提示发送 `/ba select 请求码 序号` 确认绑定 - - 发送 `/ba me` 或 `/ba recent` 查看战报 + - 发送 `ba search 昵称` 搜索玩家 + - 发送 `ba bind stb:玩家ID` 并按提示发送 `ba select 请求码 序号` 确认绑定 + - 发送 `ba me` 或 `ba recent` 查看战报 接入说明见 [API 说明](docs/API_NOTES.md)。 ## 命令列表 -默认前缀为 `/`(以实际 AstrBot 配置为准),英文子命令不区分大小写,开启中文别名后也可直接使用中文指令(如 `/ba 帮助`、`/ba 我`、`/ba 战绩`、`/ba 近期`、`/ba 上一场`、`/ba 单局`、`/ba 搜索`、`/ba 绑定`、`/ba 当前绑定`、`/ba 解绑`、`/ba 选择`、`/ba 取消`、`/ba 额度`)。 +下表为命令正文。群聊请先通过聊天软件的提及功能 @ 机器人,再输入 `ba …`;私聊通常直接发送,若宿主要求唤醒词则加在命令前。英文子命令不区分大小写,开启中文别名后也可直接使用中文指令(如 `ba 帮助`、`ba 我`、`ba 战绩`、`ba 近期`、`ba 上一场`、`ba 单局`、`ba 搜索`、`ba 绑定`、`ba 当前绑定`、`ba 解绑`、`ba 选择`、`ba 取消`、`ba 额度`)。 | 命令 | 用途 | | --- | --- | -| `/ba help` | 查看使用帮助与示例 | -| `/ba me` | 查看自己默认绑定账号的玩家概览 | -| `/ba stats ` | 查看指定玩家概览 | -| `/ba recent [count]` | 查看自己近期战绩(默认 5 场,上限 20 场) | -| `/ba me recent [count]` | 与 `/ba recent [count]` 等价 | -| `/ba recent --limit N` | 查看指定玩家近期最多 `N` 场战绩 | -| `/ba last [target]` | 查看自己或指定玩家最近一场可用单局战报 | -| `/ba me last` | 与 `/ba last` 等价 | -| `/ba match ` | 查看指定对局 ID 的单局战报 | -| `/ba search ` | 搜索玩家候选,选择后查看概览 | -| `/ba bind ` | 设置默认查询账号(不验证账号归属) | -| `/ba binding` | 查看当前绑定(纯本地,不耗额度) | -| `/ba unbind` | 解除当前绑定(纯本地,不耗额度) | -| `/ba select ` | 确认候选编号(120 秒内有效,单次有效) | -| `/ba cancel ` | 取消当前待确认选择 | -| `/ba quota` | 查看个人、本群与全插件今日已用和剩余额度 | -| `/ba status` | 管理员查看接入配置、请求与缓存状态 | -| `/ba cache clear` | 管理员清理 API 与图片缓存(不影响绑定与额度) | +| `ba help` | 查看使用帮助与示例 | +| `ba me` | 查看自己默认绑定账号的玩家概览 | +| `ba stats ` | 查看指定玩家概览 | +| `ba recent [count]` | 查看自己近期战绩(默认 5 场,上限 20 场) | +| `ba me recent [count]` | 与 `ba recent [count]` 等价 | +| `ba recent --limit N` | 查看指定玩家近期最多 `N` 场战绩 | +| `ba last [target]` | 查看自己或指定玩家最近一场可用单局战报 | +| `ba me last` | 与 `ba last` 等价 | +| `ba match ` | 查看指定对局 ID 的单局战报 | +| `ba search ` | 搜索玩家候选,选择后查看概览 | +| `ba bind ` | 设置默认查询账号(不验证账号归属) | +| `ba binding` | 查看当前绑定(纯本地,不耗额度) | +| `ba unbind` | 解除当前绑定(纯本地,不耗额度) | +| `ba select ` | 确认候选编号(120 秒内有效,单次有效) | +| `ba cancel ` | 取消当前待确认选择 | +| `ba quota` | 查看个人、本群与全插件今日已用和剩余额度 | +| `ba status` | 管理员查看接入配置、请求与缓存状态 | +| `ba cache clear` | 管理员清理 API 与图片缓存(不影响绑定与额度) | ### 目标玩家(`target`)写法 支持 `me`、`@群友`、`stb:规范ID`、`name:完整昵称` 或普通非数字昵称: ```text -/ba stats "Player 2" -/ba bind name:"Player 2" -/ba recent name:"Player 2" --limit 10 -/ba recent 10 -/ba stats name:12345 -/ba stats name:me -/ba stats @群友 +ba stats "Player 2" +ba bind name:"Player 2" +ba recent name:"Player 2" --limit 10 +ba recent 10 +ba stats name:12345 +ba stats name:me +ba stats @群友 ``` - `@群友` 需使用聊天软件的真实提及功能,查询对方已绑定的账号。 -- 纯数字请加 `stb:`、`steam:` 或 `name:` 前缀(`/ba recent 10` 除外,该写法专指查询自己近期 10 场)。 +- 纯数字请加 `stb:`、`steam:` 或 `name:` 前缀(`ba recent 10` 除外,该写法专指查询自己近期 10 场)。 - `steam:SteamID64` 当前因映射尚未确认暂不可直接查询,请改用昵称搜索后选择 STB ID。 ## 主要配置 @@ -68,21 +68,21 @@ AstrBot 原生《断箭》(Broken Arrow)战绩查询插件。支持玩家概 - **数据源接入**:在线查询开关、获准客户端标识、访问令牌(可选)、API 地址。 - **查询与命令**:默认/最大近期场数(5 / 20)、用户冷却(3 秒)、中文子命令别名开关。 - **每日请求额度**:每用户默认 20 次、每群默认 100 次(可在 `0–100` 间调整,`0` 表示不单独限制);**全插件每日总上限固定为 100 次不可调整**。所有额度于北京时间每天 0 点重置,按上游 HTTP 请求计数,失败与重试也计入;命中缓存及本地命令不扣额。 -- **战报显示**:图片战报开关(渲染失败自动回退为同内容文字)、深浅主题(默认深色)、显示时区(默认 `Asia/Shanghai`)。 +- **战报显示**:图片战报开关(渲染或发送未成功时回复同内容文字)、深浅主题(默认深色)、显示时区(默认 `Asia/Shanghai`)。 - **维护与缓存**:请求间隔、并发、超时、重试及缓存容量/旧缓存回退时间。 ## 数据与常见问题 - **为什么有字段显示「暂无」?**:当数据源未提供、未收录地图/单位名称,或胜负/模式语义尚未确认时,插件会显示「暂无」或来源 ID,不以猜测数据替代。 -- **为什么没查满 20 次就提示额度用完?**:额度按上游 HTTP 请求次数计算,单条战报命令可能触发多次接口请求(如未命中缓存的概览需请求搜索、分析与近期列表),个人额度跨群及私聊累计,可用 `/ba quota` 查看用量;重载或清缓存不会重置额度。 +- **为什么没查满 20 次就提示额度用完?**:额度按上游 HTTP 请求次数计算,单条战报命令可能触发多次接口请求(如未命中缓存的概览需请求搜索、分析与近期列表),个人额度跨群及私聊累计,可用 `ba quota` 查看用量;重载或清缓存不会重置额度。 - **只收到文字没有图片?**:请检查「发送图片战报」是否开启及 AstrBot HTML 渲染服务是否正常。 -- **同名玩家怎么区分?**:请核对候选列表中的规范 STB ID 与来源链接后再发送 `/ba select` 确认。 +- **同名玩家怎么区分?**:绑定候选不超过 3 人时,核对 STB ID 与来源链接后按提示确认;超过 3 人请前往 [BATrace](https://dash.batrace.top/) 搜索,在玩家主页链接末尾取得 ID,再发送 `ba bind stb:玩家ID`。 ## 开发与许可 - 运行要求:AstrBot **4.29.4 及以上**,QQ(OneBot v11);详细测试与验证记录见 [验证记录](docs/VALIDATION.md)。 - 开源协议:**Apache-2.0**。 -- 致谢与参考:[BATrace](https://dash.batrace.top/)(战绩数据源)、[AlexanderHYu/ba-dragon](https://github.com/AlexanderHYu/ba-dragon)、[benx1n/wows-stats-bot](https://github.com/benx1n/wows-stats-bot)、[timeance/astrbot_plugin_openai_native](https://github.com/timeance/astrbot_plugin_openai_native)、AstrBot(第三方边界说明见 [第三方说明](docs/THIRD_PARTY.md))。 +- 致谢与参考:[BATrace](https://dash.batrace.top/)(战绩数据源)、[AlexanderHYuba-dragon](https://github.com/AlexanderHYu/ba-dragon)、[benx1n/wows-stats-bot](https://github.com/benx1n/wows-stats-bot)、[timeance/astrbot_plugin_openai_native](https://github.com/timeance/astrbot_plugin_openai_native)、AstrBot(第三方边界说明见 [第三方说明](docs/THIRD_PARTY.md))。 ```sh python -m pip install -r requirements-dev.txt diff --git a/_conf_schema.json b/_conf_schema.json index dbf4eca..2a9e3a8 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -58,7 +58,7 @@ "description": "启用中文子命令别名", "type": "bool", "default": true, - "hint": "如 /ba 帮助;英文主命令始终可用。" + "hint": "如 ba 帮助;群聊先 @ 机器人,英文主命令始终可用。" } } }, @@ -90,7 +90,7 @@ "description": "发送图片战报", "type": "bool", "default": true, - "hint": "调用 AstrBot 图文渲染服务生成战报图;渲染失败时自动回退为同内容文字。" + "hint": "调用 AstrBot 图文渲染服务生成战报图;渲染或图片发送未成功时,使用同一查询结果回复文字,不重复查询。" }, "theme": { "description": "图片主题", diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 271c7af..1961765 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,21 +1,32 @@ -# 首版验证记录 +# 验证记录 -验证日期:2026-11-17(Asia/Hong_Kong)。版本:v0.1.0。 +验证日期:2026-11-17(Asia/Hong_Kong)。版本:v0.1.1。 + +## v0.1.1 命令提示与发送修复 + +用户提供的实际群聊记录复现了 `wake_prefix=zar` 被直接拼成 `zarba` 的帮助和候选提示,同时提供了 QQ/OneBot 图片发送阶段 `retcode=1200`、`sendMsg` 确认超时日志。该日志不能单独确定 QQ 发送超时的底层原因。 + +- 命令正文统一为 `ba …`,唤醒信息只由平台适配层添加;群聊确认、取消和后续操作使用真实 At 组件,显示名由 QQ 解析。帮助与候选提示保留为可复制文字,不再自动转图。 +- 私聊通常显示裸命令;宿主要求唤醒词时,在操作示例中单独加上唤醒词和空格。输入解析同时支持 `zar ba …`、既有符号前缀和真实 @。 +- 昵称绑定按去重后的规范 ID 计数,超过 3 人时不发布可确认的绑定候选,提示去 BATrace 网站搜索并使用 `ba bind stb:玩家ID`。1–3 人和明确 ID 仍只需确认一次,既有绑定不受未确认操作影响。 +- 图片通过 `await event.send(...)` 发送并等待平台返回;渲染或发送异常时,本次剩余分页改用相同数据的文字,关闭文字自动转图,不重发图片或重新查询。发送超时表述为“未获成功确认”,不宣称远端一定未送达;取消继续传播。 +- 完整离线测试 **453 passed,25.95 秒**。新增测试覆盖 1/3/4/20 人、重复 ID、旧候选失效、真实 At 确认往返、私聊唤醒词、首张/中途图片发送失败及取消。 +- 核对 AstrBot v4.29.4 的 `chain_result`、`use_t2i(False)`、OneBot `send` 与唤醒流程;这些测试使用事件桩和合成数据,修复后的真实 QQ 收发仍待部署验收。三类战报模板未修改,复用已有卡片渲染结果。 ## 结果边界 | 项目 | 结果 | | --- | --- | | 首版代码与文档 | 已实现;按项目框架、插件实现两个 PR 审阅 | -| 离线业务与契约测试 | **435 passed,24.70 秒**(含文案导入及 PR 审查回归) | +| 离线业务与契约测试 | **453 passed,25.95 秒**(含 v0.1.1 回归) | | 本地卡片渲染 | 18 组 HTML/文字、36 张 PNG;布局与外部请求检查全通过 | | 成品目视检查 | 主代理查看 4 张代表图;渲染子代理另查看 9 张 | | Python 语法检查 | 全部通过 | | 两张 Logo 原样核对 | SHA-256 与交接包一致 | | AstrBot API 兼容性研究 | 核对 v4.29.4 固定源码,插件适配器用本地桩测试 | | 完整 AstrBot 服务启动/真实 html_render | **尚未执行** | -| BATrace 真实接口联调 | **尚未执行,缺本插件独立获准接入** | -| QQ OneBot v11 群聊与私聊 | **尚未执行,未发送真实消息** | +| BATrace 真实接口联调 | 用户已提供玩家候选结果;开发环境未执行完整真实接口联调 | +| QQ OneBot v11 群聊与私聊 | 用户提供群聊提示和图片发送超时日志;v0.1.1 修复后的实际收发待验收 | | GitHub PR / 发布 / 部署 | 远端检查以对应 PR 为准;本记录不代表发布或部署验收 | API 与模型 fixture、渲染预览均为合成数据。HTTP 测试使用 `httpx.MockTransport`,不调用 BATrace。`tests/test_main.py` 在测试作用域注入 AstrBot 桩并恢复,不代表真实框架启动成功。 diff --git a/main.py b/main.py index b49d6b6..dc4aae6 100644 --- a/main.py +++ b/main.py @@ -43,7 +43,7 @@ def extract_arguments(event, prefixes): raw = "".join(parts).strip() choices = sorted({str(p) for p in prefixes if p}, key=len, reverse=True) for prefix in choices + [""]: - match = re.match(r"^" + re.escape(prefix) + r"ba(?:\s+|$)", raw, re.IGNORECASE) + match = re.match(r"^" + re.escape(prefix) + r"\s*ba(?:\s+|$)", raw, re.IGNORECASE) if match: return raw[match.end():], mentions # Some adapters expose normalized text with command prefixes already removed. @@ -134,7 +134,7 @@ async def _status(self): "schema": "响应结构变化", "identity_mismatch": "身份校验失败", "no_data": "暂无收录", "upstream": "上游暂不可用", "queue_full": "队列已满", "not_configured": "接入未配置", "closed": "客户端已关闭", "daily_quota": "每日额度已用完"} - return (f"断箭战报 v0.1.0\n接入配置:{'已填写(不代表联调通过)' if status['configured'] else '未配置'}\n" + return (f"断箭战报 v0.1.1\n接入配置:{'已填写(不代表联调通过)' if status['configured'] else '未配置'}\n" f"今日总请求:{usage['global']}/{GLOBAL_DAILY_LIMIT}(固定上限);北京时间 0 点重置\n" f"本次运行请求:{status['requests']};进行中:{status['inflight']}\n" f"API 缓存:{await self.storage.cache_count()} 条;命中:{status['cache_hits']};旧缓存:{status['stale_hits']}\n" @@ -157,20 +157,35 @@ def line(label, used, limit): "按实际发出的上游 HTTP 请求计数(含重试与失败);命中缓存、本地命令及图片渲染不计入。"]) return "\n".join(lines) + def _response_result(self, event, response, config): + parts = [Plain(response.text)] if response.text else [] + private_prefix = "" + if not event.get_group_id() and config.get("platform_settings", {}).get("friend_message_needs_wake_prefix", False): + prefixes = config.get("wake_prefix", []) + private_prefix = str(prefixes[0]) if prefixes else "" + for label, command in response.instructions: + parts.append(Plain("\n" + label)) + if event.get_group_id(): + # QQ resolves this real mention to the bot's current group card/name. + parts.extend([At(qq=event.get_self_id()), Plain(" " + command)]) + else: + parts.append(Plain((private_prefix + " " if private_prefix else "") + command)) + # Instructions must remain copyable, and At components must stay interactive. + return event.chain_result(parts).use_t2i(False) + @filter.command("ba", alias={"BA", "Ba", "bA"}) async def ba(self, event: AstrMessageEvent): if self._closed: return event.stop_event() - config = self.context.get_config(event.unified_msg_origin) - prefixes = config.get("wake_prefix", ["/"]) if config is not None else ["/"] - prefix = str(prefixes[0]) if prefixes else "" + config = self.context.get_config(event.unified_msg_origin) or {} + prefixes = config.get("wake_prefix", ["/"]) try: text, mentions = extract_arguments(event, prefixes) request = parse_command(text, mentions, self.settings.default_limit, self.settings.max_limit, self.settings.chinese_aliases) caller = Caller(str(event.get_platform_id()), event.unified_msg_origin, - str(event.get_sender_id()), prefix + "ba") + str(event.get_sender_id())) if request.action == "quota": yield event.plain_result(await self._quota(quota_actor(event))) return @@ -191,18 +206,33 @@ async def ba(self, event: AstrMessageEvent): with self.client.request_scope(quota_actor(event)): response = await self._run(self.service.execute(request, caller)) if response.text: - yield event.plain_result(response.text) + yield self._response_result(event, response, config) if response.view is not None: + send_images = self.settings.image_enabled for view in self.renderer.views(response.view): - if self.settings.image_enabled: + send_uncertain = False + if send_images: try: path = await self._run(self._image(view, event.unified_msg_origin)) - except (Exception,): + except Exception: self.logger.warning("断箭战报图片渲染失败,已使用相同查询结果回复文字。") else: - yield event.image_result(path) - continue - yield event.plain_result(self.renderer.text(view)) + try: + # Await the transport here: errors from yielded results + # are otherwise swallowed later by AstrBot's pipeline. + await self._run(event.send(event.image_result(path))) + except Exception as exc: + self.logger.warning("断箭战报图片发送未获成功确认(%s),改发文字。", type(exc).__name__) + send_uncertain = True + else: + continue + send_images = False + text = self.renderer.text(view) + if send_uncertain: + text = "图片发送未获成功确认,以下为文字战报:\n" + text + # Prevent the host's global T2I setting from turning fallback + # text into another image sent through the same failing path. + yield event.plain_result(text).use_t2i(False) except (ClientError, ValueError) as exc: yield event.plain_result(str(exc)) except asyncio.TimeoutError: diff --git a/metadata.yaml b/metadata.yaml index 5d939b8..2ee20bc 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -2,7 +2,7 @@ name: astrbot_plugin_ba_stats display_name: 断箭战报 short_desc: "《断箭》玩家战绩查询,支持账号绑定与图片战报。" desc: "查询《断箭》(Broken Arrow)玩家概览、近期战绩和单局战报,支持账号绑定、群友查询及图片或文字展示。使用前需配置 BATrace 接入。" -version: "0.1.0" +version: "0.1.1" author: timeance repo: https://github.com/timeance/astrbot_plugin_BA_stats astrbot_version: ">=4.29.4" diff --git a/service.py b/service.py index 0dde3de..dd8391c 100644 --- a/service.py +++ b/service.py @@ -20,7 +20,6 @@ class Caller: platform: str session: str user: str - prefix: str = "/ba" @property def scope(self): @@ -31,6 +30,8 @@ def scope(self): class Response: text: str = "" view: dict | None = None + # Keep commands separate from player-provided text; the adapter adds wake/At. + instructions: tuple[tuple[str, str], ...] = () def ratio(numerator, denominator): @@ -105,7 +106,7 @@ def __init__(self, client, storage, settings): self._binding_lock = asyncio.Lock() def help(self, caller): - p = caller.prefix + p = "ba" return f"""【断箭战报】使用指南 首次使用:{p} search 昵称 → 找到目标后发送 {p} bind stb:玩家ID → 按提示发送 {p} select <请求码> <序号> 确认一次即可。 说明:绑定仅用于设定默认查询对象,不代表 Steam 账号所有权认证。 @@ -128,7 +129,8 @@ def help(self, caller): • steam:SteamID64 需等待权威映射确认,当前请先用昵称搜索再选择 STB ID。 • 管理员命令:{p} status(查看状态)、{p} cache clear(清理缓存)。 • 全插件每日固定上限 100 次(个人默认 20 次、每群默认 100 次),北京时间 0 点重置;按实际发出的上游 HTTP 请求计数(含重试与失败),命中缓存不计入。 -• 命令前缀遵循 AstrBot 配置;图片渲染失败时会自动回复同内容的文字战报。""" +• 群聊请先 @ 机器人再发送命令;绑定候选超过 3 人时,请到 https://dash.batrace.top/ 搜索并使用 STB ID 绑定。 +• 图片渲染或发送未成功时会回复同内容的文字战报。""" def _mutation(self, caller): key = (caller.platform, caller.user) @@ -173,17 +175,16 @@ async def execute(self, request: Request, caller: Caller): self.client.namespace, player.id, player.name, player.source_url or "")) return Response(f"""已绑定默认账号:{player.name or '未命名玩家'} STB ID:{player.id} -{player.source_url or ''} -现在可以发送 {caller.prefix} me 查看战报。""") +{player.source_url or ''}""", instructions=(("查看战报:", "ba me"),)) return await self._report(original, candidate.id) generation = self.pending.begin(caller.scope) if action == "help": - return Response(self.help(caller)) + return Response(self.help(caller), instructions=(("发送示例:", "ba me"),)) if action == "binding": binding = await self.storage.get_binding(caller.platform, caller.user) if binding is None: - return Response(f"""你还没有绑定默认账号,请发送 {caller.prefix} bind name:昵称 进行绑定。""") + return Response("你还没有绑定默认账号。", instructions=(("绑定请发送:", "ba bind name:昵称"),)) return Response(f"""当前默认账号:{binding.display_name or '未命名玩家'} STB ID:{binding.player_id} {binding.source_url} @@ -203,8 +204,9 @@ async def execute(self, request: Request, caller: Caller): user = caller.user if target.kind == "me" else target.value binding = await self.storage.get_binding(caller.platform, user) if binding is None: - raise ValueError("你尚未绑定默认账号,请先使用 bind name:昵称 进行绑定。" if target.kind == "me" - else "对方尚未绑定默认游戏账号。") + if target.kind == "me": + return Response("你尚未绑定默认账号。", instructions=(("绑定请发送:", "ba bind name:昵称"),)) + raise ValueError("对方尚未绑定默认游戏账号。") if binding.namespace != self.client.namespace: raise ValueError("当前绑定的账号属于其他数据源环境,与当前接入不一致,请重新绑定。") target = Target("stb", binding.player_id) @@ -223,23 +225,30 @@ async def execute(self, request: Request, caller: Caller): return await self._report(request, candidates[0].id) if action == "bind" and result.stale: raise ValueError("当前仅命中旧缓存,暂无法完成绑定核验,原绑定保持不变,请稍后重试。") + if action == "bind" and len(candidates) > 3: + if not self.pending.is_current(caller.scope, generation): + return Response("本次查询已被新操作覆盖,请使用最新的候选列表。") + return Response("匹配到超过 3 位玩家,请使用 STB ID 绑定。\n" + "请前往 https://dash.batrace.top/ 搜索昵称,打开目标玩家主页,复制链接末尾的数字 ID。", + instructions=(("取得 ID 后发送:", "ba bind stb:玩家ID"),)) operation = Request("stats", limit=request.limit) if action == "search" else request selected = candidates[:10] pending = self.pending.publish(caller.scope, generation, operation, selected) if pending is None: return Response("本次查询已被新操作覆盖,请使用最新的候选列表。") - lines = ["选择后绑定此账号(只需确认一次):" if action == "bind" else "请选择要查询的账号:", - "以下为当前接口返回的候选(不代表全库完整结果);如需缩小范围,请提供更准确的昵称。"] + lines = ["查询结果如下,请确认绑定账号:" if action == "bind" else "查询结果如下,请选择账号:"] if len(candidates) == 1 and candidates[0].name != target.value and target.kind == "name": lines.append("仅找到相似昵称结果,请仔细核对 STB ID 与来源链接后再确认。") if result.stale: lines.append(f"旧缓存 · 抓取于 {result.fetched_at.isoformat()}") for index, player in enumerate(selected, 1): lines.extend([f"{index}. {player.name or '未命名玩家'} · STB ID:{player.id}", - player.source_url or "来源链接暂无", - f"{caller.prefix} select {pending.code} {index}"]) - lines.append(f"""请在 120 秒内发送上方对应指令确认;取消请发送:{caller.prefix} cancel {pending.code}""") - return Response("\n".join(lines)) + player.source_url or "来源链接暂无"]) + lines.append("---") + instructions = tuple((f"请在 120 秒内发送指令确认{'第 ' + str(index) + ' 项' if len(selected) > 1 else ''}:", + f"ba select {pending.code} {index}") for index in range(1, len(selected) + 1)) + instructions += (("取消请发送:", f"ba cancel {pending.code}"),) + return Response("\n".join(lines), instructions=instructions) async def _report(self, request, player_id): player_result = await self.client.player(player_id) diff --git a/tests/test_main.py b/tests/test_main.py index f62f040..0ab9300 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -34,6 +34,18 @@ class At: qq: str | int +class Result(tuple): + def __new__(cls, kind, value, chain=()): + result = super().__new__(cls, (kind, value)) + result.chain = list(chain) + result.use_t2i_ = None + return result + + def use_t2i(self, value): + self.use_t2i_ = value + return self + + class Event: def __init__(self, messages, *, admin=False, normalized=None, session="onebot:test:group:1", user="10001", group="1", platform="onebot:test"): @@ -44,6 +56,7 @@ def __init__(self, messages, *, admin=False, normalized=None, session="onebot:te self.normalized = normalized self.message_obj.sender.user_id = user self.group, self.platform = group, platform + self.sent = [] def get_messages(self): return self.message_obj.message @@ -73,10 +86,17 @@ def stop_event(self): self.stopped = True def plain_result(self, text): - return "plain", text + return Result("plain", text, [Plain(text)]) def image_result(self, path): - return "image", path + return Result("image", path) + + def chain_result(self, chain): + text = "".join(p.text if isinstance(p, Plain) else f"@{p.qq}" for p in chain) + return Result("plain", text, chain) + + async def send(self, result): + self.sent.append(result) @pytest.fixture @@ -223,7 +243,7 @@ def test_plain_text_cannot_forge_component_position(app_modules): ]) async def test_handler_preserves_marker_text_for_nickname_targets(app, monkeypatch, command): plugin = await app.make() - execute = AsyncMock(return_value=SimpleNamespace(text="ok", view=None)) + execute = AsyncMock(return_value=SimpleNamespace(text="ok", view=None, instructions=())) monkeypatch.setattr(plugin.service, "execute", execute) assert await collect(plugin, Event([Plain("/ba " + command)])) == [("plain", "ok")] request, _ = execute.await_args.args @@ -252,7 +272,7 @@ async def test_unconfigured_plugin_help_works_and_online_command_explains_missin async def test_handler_passes_component_preserved_name_to_service(app, monkeypatch): plugin = await app.make(prefixes=["!!"]) - execute = AsyncMock(return_value=SimpleNamespace(text="ok", view=None)) + execute = AsyncMock(return_value=SimpleNamespace(text="ok", view=None, instructions=())) monkeypatch.setattr(plugin.service, "execute", execute) replies = await collect(plugin, Event( [Plain('!!ba stats name:"a '), Plain(' b"')], normalized='ba stats name:"a b"' @@ -260,7 +280,7 @@ async def test_handler_passes_component_preserved_name_to_service(app, monkeypat assert replies == [("plain", "ok")] request, caller = execute.await_args.args assert request.target.value == "a b" - assert caller.prefix == "!!ba" + assert caller.user == "10001" @pytest.mark.parametrize("command", ["status", "状态", "cache clear", "缓存 清理"]) @@ -336,12 +356,107 @@ async def execute(*args): assert len(responses) == 1 expected = plugin.renderer.text(plugin.renderer.views(responses[0].view)[0]) assert replies == [("plain", expected)] + assert replies[0].use_t2i_ is False assert "001" in expected and "Synthetic a b" in expected image.assert_awaited_once() client.player.assert_awaited_once_with("001") client.recent.assert_awaited_once_with("001", plugin.settings.max_limit) +@pytest.mark.parametrize("wake", ["zar", "zariba", "/", "!!"]) +async def test_help_uses_bare_ba_and_real_self_mention(app, wake): + plugin = await app.make(prefixes=[wake]) + result, = await collect(plugin, Event([At("999"), Plain(" ba help")])) + assert "• ba me:" in result[1] + assert wake + "ba" not in result[1] + assert "发送示例:@999 ba me" in result[1] + assert [part.qq for part in result.chain if isinstance(part, At)] == ["999"] + assert result.use_t2i_ is False + + +@pytest.mark.parametrize("choice", ["select", "cancel"]) +async def test_binding_hints_round_trip_real_mentions_and_do_not_rewrite_names(app, monkeypatch, choice): + plugin = await app.make(prefixes=["zar"]) + player = app.models.Player("152117", "zarba select stays literal", source_url="https://dash.batrace.top/player/152117") + result = app.models.FetchResult(player, datetime.now(timezone.utc)) + monkeypatch.setattr(plugin.client, "player", AsyncMock(return_value=result)) + offered, = await collect(plugin, Event([At("999"), Plain(" ba bind stb:152117")])) + assert player.name in offered[1] + assert [p.qq for p in offered.chain if isinstance(p, At)] == ["999", "999"] + commands = [p.text.strip() for p in offered.chain if isinstance(p, Plain) and p.text.startswith(" ba ")] + select, cancel = commands + assert select.startswith("ba select ") and cancel.startswith("ba cancel ") + assert select.split()[2] == cancel.split()[2] + confirmed, = await collect(plugin, Event([At("999"), Plain(" " + (select if choice == "select" else cancel))])) + if choice == "select": + assert "已绑定默认账号" in confirmed[1] and "@999 ba me" in confirmed[1] + assert (await plugin.storage.get_binding("onebot:test", "10001")).player_id == "152117" + else: + assert "已取消" in confirmed[1] + assert await plugin.storage.get_binding("onebot:test", "10001") is None + + +async def test_unbound_self_uses_same_structured_binding_hint(app): + plugin = await app.make(prefixes=["zar"]) + result, = await collect(plugin, Event([At("999"), Plain(" ba me")])) + assert "@999 ba bind name:昵称" in result[1] + assert [p.qq for p in result.chain if isinstance(p, At)] == ["999"] + + +@pytest.mark.parametrize("needs_prefix", [False, True]) +async def test_private_hint_uses_host_wake_requirement_without_at(app, needs_prefix): + plugin = await app.make() + plugin.context.get_config = lambda umo: {"wake_prefix": ["zar"], "platform_settings": { + "friend_message_needs_wake_prefix": needs_prefix}} + result, = await collect(plugin, Event([Plain("zar ba help")], group="")) + assert not any(isinstance(p, At) for p in result.chain) + expected = "zar ba me" if needs_prefix else "ba me" + assert result[1].endswith("发送示例:" + expected) + args, _ = app.main.extract_arguments(Event([Plain(expected)], group=""), ["zar"]) + assert app.main.parse_command(args).action == "stats" + + +@pytest.mark.parametrize("failed_page", [None, 0, 1]) +async def test_report_delivery_failure_switches_remaining_pages_to_plain_text(app, monkeypatch, failed_page): + plugin = await app.make(images=True) + execute = AsyncMock(return_value=SimpleNamespace(text="", view={}, instructions=())) + monkeypatch.setattr(plugin.service, "execute", execute) + monkeypatch.setattr(plugin.renderer, "views", lambda view: [0, 1, 2]) + monkeypatch.setattr(plugin.renderer, "text", lambda view: f"same data page {view}") + render = AsyncMock(side_effect=lambda view, umo: f"page-{view}.jpg") + monkeypatch.setattr(plugin, "_image", render) + event = Event([Plain("/ba stats stb:152117")]) + attempted = [] + async def send(result): + attempted.append(result) + if failed_page is not None and len(attempted) - 1 == failed_page: + raise RuntimeError("ActionFailed retcode=1200 synthetic transport timeout") + event.send = send + replies = await collect(plugin, event) + execute.assert_awaited_once() + if failed_page is None: + assert replies == [] and len(attempted) == render.await_count == 3 + else: + assert len(attempted) == render.await_count == failed_page + 1 + assert len(replies) == 3 - failed_page + assert "图片发送未获成功确认" in replies[0][1] + for index, reply in enumerate(replies, failed_page): + assert reply[1].endswith(f"same data page {index}") + assert reply.use_t2i_ is False + + +async def test_cancelled_image_send_is_not_converted_to_fallback(app, monkeypatch): + plugin = await app.make(images=True) + monkeypatch.setattr(plugin.service, "execute", AsyncMock(return_value=SimpleNamespace(text="", view={}, instructions=()))) + monkeypatch.setattr(plugin.renderer, "views", lambda view: [view]) + monkeypatch.setattr(plugin, "_image", AsyncMock(return_value="synthetic.jpg")) + event = Event([Plain("/ba stats stb:001")]) + event.send = AsyncMock(side_effect=asyncio.CancelledError) + with pytest.raises(asyncio.CancelledError): + await collect(plugin, event) + event.send.assert_awaited_once() + + async def test_image_render_uses_mobile_jpeg_contract_and_fixed_outer_template(app, monkeypatch, tmp_path): plugin = await app.make(images=True) # Only exercise local file handoff/caching, not image validity or appearance. @@ -468,7 +583,7 @@ async def search(query, user, group, admin=False): assert len(calls) == 4 # A fresh cached response consumes no upstream request, even at the cap. cached = await search("one", "u1", "g1") - assert "请选择" in cached[0][1] + assert "请选择账号" in cached[0][1] assert len(calls) == 4 actor = app.main.QuotaActor("onebot:test", "u1", "g1") usage = await plugin.storage.quota_usage(actor) diff --git a/tests/test_service.py b/tests/test_service.py index 6644ceb..221319d 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -82,7 +82,7 @@ def spawn(coro): def select_command(response): - match = re.search(r"/ba select ([^\s]+) ([0-9]+)", response.text) + match = re.search(r"ba select ([^\s]+) ([0-9]+)", "\n".join(command for _, command in response.instructions)) assert match, response.text return f"select {match[1]} {match[2]}" @@ -107,7 +107,7 @@ def forbidden_network(request): h.service.client = real_client try: await seed(h, namespace=real_client.namespace) - assert "/ba help" in (await h.run("help")).text + assert "ba help" in (await h.run("help")).text assert "old" in (await h.run("binding")).text assert "解除" in (await h.run("unbind")).text assert await binding(h) is None @@ -123,7 +123,7 @@ async def test_single_bind_requires_one_choice_and_forces_identity_revalidation( renamed = h.m.Player("001", "Renamed", source_url=h.player.source_url) h.client.player.side_effect = [h.result(h.player), h.result(renamed)] offered = await h.run("bind stb:001") - assert "选择后绑定" in offered.text + assert "请确认绑定账号" in offered.text assert h.player.source_url in offered.text assert await binding(h) == old command = select_command(offered) @@ -161,7 +161,7 @@ async def test_read_only_search_and_select_never_change_binding(h, monkeypatch): write = AsyncMock(wraps=h.storage.set_binding) monkeypatch.setattr(h.storage, "set_binding", write) offered = await h.run("search Synthetic Player") - assert "请选择要查询" in offered.text + assert "请选择账号" in offered.text assert await binding(h) == old response = await h.run(select_command(offered)) assert response.view["kind"] == "overview" @@ -172,6 +172,37 @@ async def test_read_only_search_and_select_never_change_binding(h, monkeypatch): h.client.recent.assert_awaited_once_with("001", h.service.settings.max_limit) +@pytest.mark.parametrize("count", [1, 3, 4, 20]) +async def test_bind_candidate_limit_and_explicit_id_recovery(h, count): + old = await seed(h) + previous = await h.run("bind stb:001") + players = [h.m.Player(str(i), f"Synthetic {i}") for i in range(count)] + h.client.search.return_value = h.result(players) + offered = await h.run("bind name:Synthetic") + assert await binding(h) == old + with pytest.raises(ValueError, match="过期"): + await h.run(select_command(previous)) + if count <= 3: + choices = [cmd for _, cmd in offered.instructions if cmd.startswith("ba select ")] + assert len(choices) == count + assert offered.instructions[-1][1].startswith("ba cancel ") + else: + assert "https://dash.batrace.top/" in offered.text and "超过 3" in offered.text + assert offered.instructions == (("取得 ID 后发送:", "ba bind stb:玩家ID"),) + # The user can still bind a known player ID using the single confirmation. + explicit = await h.run("bind stb:001") + await h.run(select_command(explicit)) + assert (await binding(h)).player_id == "001" + + +async def test_bind_threshold_counts_distinct_ids(h): + h.client.search.return_value = h.result([h.player] * 4) + offered = await h.run("bind name:Synthetic Player") + assert "超过 3" not in offered.text + await h.run(select_command(offered)) + assert (await binding(h)).player_id == "001" + + async def test_late_search_cannot_publish_over_newer_candidates(h): started, release = asyncio.Event(), asyncio.Event() newer = h.m.Player("002", "New", source_url="https://example.invalid/players/002") diff --git a/tools/build_delivery.py b/tools/build_delivery.py index 79b4db8..e6dc0fa 100644 --- a/tools/build_delivery.py +++ b/tools/build_delivery.py @@ -18,7 +18,7 @@ import yaml ROOT = Path(__file__).resolve().parents[1] -VERSION = "0.1.0" +VERSION = "0.1.1" CHINESE = re.compile(r"[\u3400-\u9fff]") @@ -133,7 +133,7 @@ def walk(value, pointer=""): PROMPT = """# 交给 Gemini 的文案优化任务 -你将润色 AstrBot 插件「断箭战报」v0.1.0 的中文提示、配置说明、图片战报文字和 README。只提出文案修改,不执行代码、不调用服务、不改变功能或统计逻辑。 +你将润色 AstrBot 插件「断箭战报」v0.1.1 的中文提示、配置说明、图片战报文字和 README。只提出文案修改,不执行代码、不调用服务、不改变功能或统计逻辑。 ## 先读这些材料 1. `事实与约束.md`:哪些能力已实现、哪些尚未验证。 @@ -146,8 +146,8 @@ def walk(value, pointer=""): 自然、准确、简洁的中文,像成熟工具的帮助信息;先告诉用户发生了什么及下一步。删重复说明和生硬技术用语,但保留影响操作的条件、范围、单位和后果。不要营销腔,不添加未经证实的能力、性能、兼容性或成功承诺。管理员诊断与普通玩家提示分别处理。 ## 不可改动 -- `/ba`、英文子命令、现有中文别名、`stb:`、`steam:`、`name:`、`--limit`、示例 ID 的类型和参数顺序。 -- Python f-string 的所有占位符及格式说明,如 `{caller.prefix}`、`{remaining:.0f}`;JSON 键、枚举值、路径、URL、版本、默认值与数字边界。 +- `ba`、英文子命令、现有中文别名、`stb:`、`steam:`、`name:`、`--limit`、示例 ID 的类型和参数顺序。 +- Python f-string 的所有占位符及格式说明,如 `{pending.code}`、`{remaining:.0f}`;JSON 键、枚举值、路径、URL、版本、默认值与数字边界。 - Jinja 的 `{{ ... }}`、`{% ... %}`、HTML 标签属性、CSS、自动转义及安全规则。 - STB ID 与 Steam ID 的区分;绑定不是所有权认证;一次选择即确认;查询不修改绑定;原绑定在失败时保留。 - 缺失与零、未知胜负、近期样本与生涯、数量与价值、抓取时间与来源时间的区分。 @@ -174,7 +174,7 @@ def walk(value, pointer=""): - 配置保存后需重载。本地默认值不是上游许可额度。 - 每用户默认 20 次、每群默认 100 次,均可在设置调整为 0–100;0 不单独限制。全插件每日 100 次为固定上限,不提供调整项或管理员豁免。所有额度北京时间每天 0 点重置,与显示时区无关。 - 用户额度按同平台实例的实际发送者跨群及私聊累计,群额度由群内用户共享。按实际提交 HTTP 的尝试计数,重试、失败计入;一条战报命令可能耗多次。命中缓存、本地命令、图片渲染不计入。并发原子记账、重载/清缓存/改凭据不清零;发送前已记账的中断保守保留。 -- `/ba quota` 或 `/ba 额度` 可查看个人、本群、全插件用量;总额度固定 100,不得描述为可配置。达到额度仍可读取新鲜缓存,需要刷新则提示额度已用完,不使用旧缓存隐藏提示。 +- `ba quota` 或 `ba 额度` 可查看个人、本群、全插件用量;总额度固定 100,不得描述为可配置。达到额度仍可读取新鲜缓存,需要刷新则提示额度已用完,不使用旧缓存隐藏提示。 - 用户偏好:界面简洁、主次清晰、必要解释靠近字段,普通小数两位、计数整数、精简冗余但保留口径和操作后果。 - 交付源码保持 Apache-2.0;既有 Logo 原样保留。来源资料见原文件/docs。 - 文案清单覆盖根目录 Python 中中文字符串及英文异常提示、配置展示字段、插件展示信息和含中文模板行;README 与文档全文随包。测试、工具、注释不作为用户文案润色目标。 @@ -239,7 +239,7 @@ def main(): 3. 「文案优化/{copy_name}」可单独交给 Gemini。先让 Gemini 阅读「给Gemini的任务说明.md」,润色提示、配置文字、卡片和 README;回填前仍需核对占位符及功能语义。 4. 「验证」包含真实执行记录及标注为合成样本的预览。离线通过不代表真实 API 或 QQ 平台验收。 5. 完整源码、测试和重建工具位于「源码/astrbot_plugin_ba_stats」。仓库审阅状态以 GitHub PR 为准;此包不表示已发布市场或部署生产。 -6. 每日默认额度:个人 20 次、每群 100 次可调,全插件固定 100 次。北京时间 0 点重置;发送 `/ba quota` 查看用量。按上游 HTTP 请求计数,重试及失败计入,命中缓存不计入。 +6. 每日默认额度:个人 20 次、每群 100 次可调,全插件固定 100 次。北京时间 0 点重置;发送 `ba quota` 查看用量。按上游 HTTP 请求计数,重试及失败计入,命中缓存不计入。 """.encode() bundle["SHA256.json"] = json.dumps({name: digest(data) for name, data in bundle.items()}, ensure_ascii=False, indent=2).encode() final_name = f"断箭战报_v{VERSION}_交付包.zip"