diff --git a/.astrbot-plugin/i18n/zh-CN.json b/.astrbot-plugin/i18n/zh-CN.json new file mode 100644 index 0000000..336dea3 --- /dev/null +++ b/.astrbot-plugin/i18n/zh-CN.json @@ -0,0 +1,7 @@ +{ + "views": { + "settings": { + "title": "设置中心" + } + } +} diff --git a/.gitattributes b/.gitattributes index 31318e2..a062451 100644 --- a/.gitattributes +++ b/.gitattributes @@ -5,5 +5,6 @@ *.yaml text eol=lf *.json text eol=lf *.html text eol=lf +*.js text eol=lf *.txt text eol=lf *.png binary diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c4b4551 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,21 @@ +# 更新日志 + +## 0.1.2 · 2026-11-17 + +- 近期战绩新增基于 ba-dragon 模型的逐局「评分」,按分数着色,不附称号。 +- 单局战报新增赛前预测,双方对比与兵种构成左右排布,玩家数据集中展示。 +- 图片页脚统一展示 GitHub 头像、项目名称与「数据来源 BATracer」。 +- 简化数据源设置,移除客户端标识和访问令牌输入项。 +- 新增统一设置中心,集中管理常用设置、每日额度和维护选项。 +- 新增 30 MB 环形诊断日志,开关保存后即时生效;可在设置中心展开诊断日志,复现问题并下载 ZIP。 + +## 0.1.1 · 2026-11-17 + +- 修正帮助与绑定提示中的命令,群聊确认和取消会正确 @ 机器人。 +- 绑定候选超过 3 人时,引导到网站查找玩家 ID 后绑定。 +- 图片发送失败时改发文字战报,避免查询后没有回复。 + +## 0.1.0 · 2026-11-17 + +- 新增玩家查询、账号绑定、近期战绩和单局战报。 +- 支持图片与文字展示,以及每日请求额度管理。 diff --git a/README.md b/README.md index 061c287..3a06c00 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,17 @@ # 断箭战报 -AstrBot 原生《断箭》(Broken Arrow)战绩查询插件。支持玩家概览、近期战绩、单局战报图片生成与默认账号绑定,不依赖大模型。 +AstrBot 原生《断箭》(Broken Arrow)战绩查询插件。以简洁排版展示玩家概览、近期战绩与单局核心数据,支持图片战报和默认账号绑定,不依赖大模型。 -> 首次使用需配置获准的 BATrace 客户端标识,并开启在线查询。 +近期战绩提供彩色评分;单局战报包含赛前预测、双方对比、兵种构成和玩家数据。 + +> 数据来源 [BATrace](https://dash.batrace.top/),如有帮助请支持该平台。更新内容见 [更新日志](CHANGELOG.md)。 ## 快速开始 -1. **安装插件**:在 AstrBot 插件管理中导入 `astrbot_plugin_ba_stats_v0.1.1.zip`(或将插件目录放入 `data/plugins/` 并使用 AstrBot 的 Python 环境安装 `requirements.txt`)。 -2. **配置接入**:打开插件设置中的「数据源接入」,填入获准客户端标识(若运营方要求则填写 Bearer 令牌),开启「启用在线查询」。 -3. **保存重载**:保存配置并重载插件使其生效。 +1. **安装插件**:在 AstrBot 插件管理中导入 `astrbot_plugin_ba_stats_v0.1.2.zip`(或将插件目录放入 `data/plugins/` 并使用 AstrBot 的 Python 环境安装 `requirements.txt`)。 +2. **开启查询**:进入插件详情 → 可视化视图 → 设置中心,在「常用设置」中开启「启用在线查询」(默认关闭);API 地址通常保持默认即可。常用设置也可在 AstrBot 原生插件配置中调整。 +3. **保存重载**:保存设置后,在 AstrBot 插件页手动重载,使在线查询设置生效。 4. **绑定与查询**: - 发送 `ba search 昵称` 搜索玩家 - 发送 `ba bind stb:玩家ID` 并按提示发送 `ba select 请求码 序号` 确认绑定 @@ -63,13 +65,16 @@ ba stats @群友 ## 主要配置 -可在 AstrBot 插件管理页直接调整,修改后需重载插件: +设置中心和 AstrBot 原生插件配置共用同一份设置。诊断开关保存后即时生效;其他设置保存后,请在插件页手动重载。 -- **数据源接入**:在线查询开关、获准客户端标识、访问令牌(可选)、API 地址。 +- **数据源接入**:在线查询开关、API 地址,无需填写客户端标识或令牌。 - **查询与命令**:默认/最大近期场数(5 / 20)、用户冷却(3 秒)、中文子命令别名开关。 - **每日请求额度**:每用户默认 20 次、每群默认 100 次(可在 `0–100` 间调整,`0` 表示不单独限制);**全插件每日总上限固定为 100 次不可调整**。所有额度于北京时间每天 0 点重置,按上游 HTTP 请求计数,失败与重试也计入;命中缓存及本地命令不扣额。 - **战报显示**:图片战报开关(渲染或发送未成功时回复同内容文字)、深浅主题(默认深色)、显示时区(默认 `Asia/Shanghai`)。 -- **维护与缓存**:请求间隔、并发、超时、重试及缓存容量/旧缓存回退时间。 +- **维护与缓存**:请求间隔、并发、超时、重试及缓存容量/旧缓存回退时间,设置中心中默认折叠。 +- **诊断日志**:诊断开关、日志状态和 ZIP 下载集中显示,内容默认折叠;总容量上限 30 MB,旧日志自动轮换。 + +排查问题时,在设置中心选择「诊断日志」并展开,开启诊断并保存后复现问题,再点击「下载诊断日志(ZIP)」。下载由宿主登录鉴权。 ## 数据与常见问题 @@ -81,8 +86,8 @@ ba stats @群友 ## 开发与许可 - 运行要求:AstrBot **4.29.4 及以上**,QQ(OneBot v11);详细测试与验证记录见 [验证记录](docs/VALIDATION.md)。 -- 开源协议:**Apache-2.0**。 -- 致谢与参考:[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))。 +- 开源协议:项目采用 **Apache-2.0**;`scoring.py` 的 ba-dragon 移植部分及 `assets/scoring-model.json` 保留上游 **MIT** 许可,完整文本见 [ba-dragon 许可](docs/BA_DRAGON_LICENSE.txt)。 +- 致谢与参考:[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))。 ```sh python -m pip install -r requirements-dev.txt diff --git a/_conf_schema.json b/_conf_schema.json index 2a9e3a8..c9ee7f8 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -7,28 +7,14 @@ "description": "启用在线查询", "type": "bool", "default": false, - "hint": "请先取得 BATrace 对本插件的独立接入许可,填写获准客户端标识后再开启。", + "hint": "数据来源 BATrace ,如有帮助请支持该平台", "obvious_hint": true }, - "client_id": { - "description": "获准客户端标识", - "type": "string", - "default": "", - "hint": "由 BATrace 运营方为本插件单独分配,请勿借用其他项目的标识。", - "secret": true - }, - "api_token": { - "description": "访问令牌(如需要)", - "type": "string", - "default": "", - "hint": "仅在运营方要求 Bearer 令牌时填写。", - "secret": true - }, "base_url": { "description": "API 地址", "type": "string", "default": "https://bot.batrace.top", - "hint": "以运营方确认的 HTTPS 地址为准。" + "hint": "通常保持默认;更换时请填写不含路径、参数和账号信息的 HTTPS 地址。" } } }, @@ -113,6 +99,25 @@ } } }, + "diagnostics": { + "type": "object", + "description": "诊断日志", + "items": { + "show_options": { + "description": "显示诊断选项", + "type": "bool", + "default": false, + "hint": "完整设置与日志下载:插件详情 → 可视化视图 → 设置中心 → 诊断日志。" + }, + "enabled": { + "description": "启用诊断模式", + "type": "bool", + "default": false, + "condition": {"show_options": true}, + "hint": "启用后持续记录受控诊断信息,日志总量最多 30 MB,满后淘汰旧日志。关闭后停止记录,已有日志仍可下载。" + } + } + }, "maintenance": { "type": "object", "description": "维护与请求限制", @@ -121,7 +126,7 @@ "description": "上游请求最小间隔(秒)", "type": "float", "default": 1.0, - "hint": "根据获准接入频率调整,对所有在线查询全局生效。" + "hint": "对所有在线查询全局生效,避免频繁请求。" }, "concurrency": { "description": "上游并发上限", diff --git a/assets/github-avatar.png b/assets/github-avatar.png new file mode 100644 index 0000000..0d54e59 Binary files /dev/null and b/assets/github-avatar.png differ diff --git a/assets/scoring-model.json b/assets/scoring-model.json new file mode 100644 index 0000000..6f5a775 --- /dev/null +++ b/assets/scoring-model.json @@ -0,0 +1 @@ +{"version":2,"fittedAt":"2026-11-12","expect":{"scale":400,"afkPenalty":500},"catSplit":{"recon":{"recon":1},"infantry":{"inf":0.86,"aa":0.14},"vehicles":{"armor":1},"support":{"arty":0.365,"aa":0.435},"logistic":{},"helicopters":{"heli":0.557},"aircrafts":{"jet":0.973}},"avgRoles":{"armor":0.256,"inf":0.164,"recon":0.133,"arty":0.095,"aa":0.139,"heli":0.047,"jet":0.165},"weights":{"kd":0.5,"con":0.5,"obj":0,"out":0.5},"outSd":0.4541,"marks":{"dragon":0.8,"qu":0.2},"units":{"1":["armor",55],"2":["recon",260],"3":["armor",65],"4":["arty",140],"5":["arty",75],"6":["armor",45],"7":[null,70],"8":["heli",110],"9":["armor",130],"10":["aa",90],"11":["arty",200],"12":["aa",170],"13":["armor",390],"14":["armor",80],"15":["armor",55],"16":["armor",70],"17":[null,110],"19":["heli",90],"20":["aa",110],"21":["recon",70],"22":["armor",45],"23":["recon",35],"24":["armor",85],"25":["armor",70],"26":["armor",50],"27":["aa",110],"28":["recon",70],"29":["recon",50],"30":["armor",60],"31":["aa",150],"33":["armor",45],"34":["aa",140],"35":["recon",45],"37":["recon",90],"40":["arty",90],"41":["armor",50],"44":["jet",225],"46":["heli",135],"47":["armor",20],"48":["recon",40],"49":["recon",45],"50":["arty",80],"51":["recon",55],"52":[null,40],"53":["armor",205],"54":["armor",260],"57":["inf",60],"60":["inf",65],"61":["recon",70],"62":["inf",70],"63":["inf",80],"65":["recon",85],"66":["inf",125],"68":["recon",75],"69":["aa",90],"70":["inf",110],"72":["inf",90],"73":["aa",100],"74":["inf",60],"75":["inf",60],"76":["recon",90],"77":["recon",80],"78":["armor",60],"79":[null,30],"80":[null,100],"81":[null,80],"82":["armor",40],"84":[null,65],"86":["heli",110],"87":["heli",75],"89":["armor",65],"90":["armor",35],"91":["arty",80],"92":["arty",100],"93":["arty",275],"94":["aa",110],"95":[null,85],"96":["armor",45],"97":["arty",200],"98":["arty",140],"99":["recon",45],"100":["heli",95],"102":["heli",55],"103":["recon",100],"105":["heli",65],"106":["heli",25],"107":["heli",70],"108":["inf",60],"109":["aa",70],"110":["inf",90],"111":["inf",80],"112":["inf",50],"114":["recon",70],"115":["recon",85],"116":["recon",70],"117":["inf",70],"118":["inf",40],"119":["inf",45],"120":["aa",80],"121":["inf",50],"122":["inf",50],"123":["recon",65],"124":["recon",75],"125":["recon",100],"126":["inf",75],"127":["inf",70],"128":["inf",45],"129":["inf",60],"130":["inf",95],"131":["inf",115],"132":["inf",60],"133":["inf",75],"134":["aa",75],"135":["recon",30],"136":["recon",80],"137":["recon",100],"138":["recon",65],"139":[null,100],"140":[null,50],"141":["armor",35],"142":["armor",55],"143":[null,115],"144":["armor",80],"145":[null,90],"146":["inf",60],"147":["inf",100],"148":["inf",40],"149":["inf",50],"150":["inf",105],"151":["armor",100],"152":["recon",40],"153":[null,105],"154":["arty",60],"155":["arty",40],"156":["aa",175],"157":["armor",180],"158":["armor",155],"159":[null,80],"160":["jet",60],"162":["arty",270],"163":["aa",145],"164":[null,40],"166":[null,40],"167":["recon",40],"168":["jet",145],"169":["jet",155],"170":["recon",75],"171":[null,9],"172":["armor",50],"173":["recon",45],"176":["inf",40],"177":["recon",65],"180":["armor",55],"182":["armor",75],"183":["armor",90],"184":["recon",45],"185":["armor",30],"186":["recon",60],"187":["armor",50],"188":["aa",80],"189":["arty",75],"190":["arty",300],"191":["armor",280],"194":["armor",35],"195":["recon",45],"196":["aa",75],"197":["armor",95],"198":["arty",200],"199":[null,40],"200":["armor",40],"201":["armor",45],"202":["aa",80],"203":["arty",55],"204":["armor",35],"205":["arty",80],"206":["armor",50],"207":["arty",90],"208":["armor",65],"209":["recon",70],"210":["arty",100],"211":["aa",130],"212":["armor",55],"213":["armor",60],"214":["armor",50],"215":["recon",60],"216":["armor",50],"217":["recon",55],"218":["arty",65],"219":["armor",45],"220":["aa",90],"221":["aa",60],"222":["aa",45],"223":["arty",275],"224":["arty",300],"225":["aa",230],"226":["arty",250],"227":["aa",325],"228":[null,65],"229":[null,80],"230":["armor",30],"231":["aa",150],"232":["arty",260],"233":["aa",175],"234":["arty",80],"235":["armor",60],"236":["armor",170],"237":["recon",250],"238":["armor",250],"239":["armor",200],"240":["armor",160],"241":[null,40],"242":[null,75],"243":["armor",250],"244":["armor",240],"245":["armor",215],"246":[null,30],"247":["arty",130],"249":["recon",40],"250":["aa",80],"251":["aa",180],"252":["armor",55],"253":["armor",45],"254":["armor",45],"255":["armor",250],"256":["heli",85],"257":[null,65],"258":[null,30],"259":[null,100],"260":[null,110],"261":[null,110],"262":[null,105],"263":["heli",75],"264":["recon",150],"266":[null,70],"267":["heli",55],"268":[null,90],"269":["heli",85],"270":["heli",115],"271":["heli",135],"272":["heli",115],"273":[null,80],"274":[null,120],"275":[null,120],"276":["recon",70],"277":["recon",60],"278":["recon",85],"280":["jet",200],"281":[null,140],"282":["jet",95],"283":["jet",145],"284":["jet",135],"285":["jet",110],"286":["jet",205],"287":["jet",160],"288":["jet",60],"289":["jet",170],"291":["jet",175],"292":["jet",165],"293":["jet",200],"294":["jet",240],"295":["jet",240],"297":["jet",275],"298":["jet",140],"299":["jet",200],"300":["jet",100],"301":["jet",150],"302":[null,100],"303":[null,100],"304":[null,140],"305":[null,150],"306":["jet",150],"307":["jet",75],"308":["jet",185],"309":["jet",165],"310":["jet",150],"311":["jet",150],"312":["jet",130],"313":["jet",60],"314":["jet",60],"315":["jet",180],"316":[null,70],"317":["jet",200],"318":["jet",400],"319":["jet",130],"320":["inf",100],"321":[null,9],"322":[null,150],"323":[null,150],"324":[null,200],"325":[null,150],"326":[null,150],"327":[null,200],"328":["recon",50],"329":["recon",50],"330":[null,9],"331":["jet",100],"350":["recon",65],"351":["inf",80],"353":["inf",50],"360":[null,9],"361":[null,9],"362":["recon",75],"363":["recon",90],"364":["heli",150],"365":["armor",35],"366":["recon",70],"367":["recon",80],"369":["inf",50],"370":["inf",65],"371":["aa",70],"372":["inf",110],"373":["arty",150],"374":["jet",65],"375":[null,25],"376":["arty",250],"377":["jet",100],"379":["jet",100],"380":["heli",115],"381":[null,50],"382":["arty",140],"383":["recon",70],"384":["recon",45],"386":["armor",45],"387":["recon",75],"388":["arty",200],"389":["aa",100],"390":[null,55],"391":["arty",125],"392":["armor",40],"393":["aa",110],"394":["aa",200],"395":["recon",200],"396":["armor",50],"397":[null,100],"398":["inf",60],"399":["inf",65],"401":["inf",50],"402":["inf",70],"403":["recon",80],"404":["aa",70],"407":["inf",80],"413":["aa",75],"414":["inf",65],"419":["inf",65],"420":[null,9],"421":["armor",35],"422":["arty",220],"423":[null,45],"425":["armor",45],"426":["arty",200],"427":[null,50],"428":[null,80],"429":["arty",140],"430":["armor",30],"431":["arty",100],"432":["armor",35],"433":["armor",40],"434":["inf",70],"435":["inf",75],"436":["inf",50],"437":["recon",60],"438":["inf",75],"439":["inf",75],"440":["aa",75],"441":["inf",40],"442":["inf",75],"443":["armor",70],"444":["armor",75],"445":["armor",70],"447":["recon",50],"448":["aa",160],"449":["inf",80],"450":["armor",40],"451":[null,9],"452":["arty",110],"453":["armor",140],"455":["recon",45],"456":[null,9],"457":["armor",200],"458":["recon",50],"459":["inf",70],"461":[null,5],"462":[null,200],"463":[null,125],"465":["jet",130],"466":["aa",225],"467":["recon",50],"468":["recon",80],"469":["inf",70],"471":["armor",90],"472":[null,200],"473":["inf",100],"474":["armor",5],"475":["heli",5],"476":[null,30],"477":[null,65],"478":[null,40],"479":[null,170],"480":[null,75],"481":["armor",210],"482":["inf",50],"483":["inf",50],"484":[null,5],"485":[null,45],"486":[null,200],"487":[null,50],"488":[null,210],"489":[null,9],"490":[null,40],"491":[null,40],"492":[null,40],"493":[null,40],"494":[null,40],"495":[null,40],"496":["inf",40],"497":["inf",40],"498":["armor",70],"499":["recon",40],"500":["armor",85],"501":["armor",40],"502":["armor",35],"503":["armor",260],"504":[null,45],"505":["recon",45],"508":["aa",110],"509":["recon",45],"510":["arty",80],"511":["arty",90],"512":["jet",60],"513":["inf",65],"515":["inf",35],"517":["inf",100],"519":["inf",80],"522":["aa",70],"525":["recon",70],"528":["recon",75],"531":[null,80],"532":[null,65],"533":["inf",40],"535":["armor",40],"536":[null,80],"537":[null,45],"538":["aa",45],"539":["arty",230],"540":["arty",250],"541":["armor",30],"542":["armor",50],"543":["recon",65],"545":["aa",110],"602":["armor",100],"604":["inf",35],"612":["inf",75],"615":["armor",110],"624":["inf",40],"627":["armor",40],"628":["armor",45],"632":["recon",50],"633":["recon",180],"635":["arty",90],"636":["arty",210],"702":["jet",1500],"703":["armor",240]},"norm":{"career":{"kd":{"mu":{"armor":-0.3196,"inf":-1.2321,"recon":-1.3268,"arty":1.4975,"aa":1.782,"heli":-1.2978,"jet":0.8931},"elo":-0.0095,"gap":0.51,"sigma":{"armor":0.6919,"inf":0.6862,"recon":0.6796,"arty":0.6946,"aa":0.6927,"heli":0.6936,"jet":0.682},"lambda":1,"q":[-4.036,-2.487,-2.032,-1.844,-1.715,-1.566,-1.475,-1.389,-1.324,-1.242,-1.181,-1.138,-1.078,-1.043,-1.004,-0.967,-0.924,-0.891,-0.858,-0.83,-0.791,-0.755,-0.72,-0.693,-0.666,-0.64,-0.61,-0.586,-0.561,-0.535,-0.505,-0.475,-0.448,-0.421,-0.391,-0.365,-0.337,-0.312,-0.288,-0.265,-0.242,-0.219,-0.192,-0.168,-0.146,-0.127,-0.108,-0.091,-0.06,-0.03,-0.009,0.013,0.033,0.054,0.081,0.104,0.12,0.147,0.177,0.202,0.224,0.242,0.269,0.294,0.317,0.343,0.37,0.391,0.416,0.441,0.466,0.494,0.522,0.55,0.577,0.608,0.637,0.665,0.697,0.729,0.767,0.797,0.836,0.873,0.912,0.947,0.992,1.049,1.104,1.15,1.205,1.249,1.322,1.413,1.507,1.629,1.757,1.909,2.14,2.619,6.665]},"con":{"mu":{"armor":0.2048,"inf":-0.6317,"recon":-0.6904,"arty":-0.5807,"aa":0.2152,"heli":-0.2517,"jet":0.7624},"elo":0.0173,"gap":0.1663,"sigma":{"armor":0.4764,"inf":0.4809,"recon":0.4639,"arty":0.4775,"aa":0.4669,"heli":0.4771,"jet":0.4459},"lambda":3,"q":[-7.407,-3.174,-2.469,-2.131,-1.843,-1.68,-1.544,-1.444,-1.334,-1.257,-1.171,-1.119,-1.063,-1.003,-0.959,-0.912,-0.866,-0.82,-0.775,-0.727,-0.691,-0.648,-0.615,-0.571,-0.535,-0.508,-0.474,-0.443,-0.413,-0.383,-0.361,-0.335,-0.311,-0.288,-0.268,-0.237,-0.218,-0.196,-0.174,-0.145,-0.122,-0.097,-0.073,-0.048,-0.025,-0.004,0.015,0.033,0.053,0.076,0.094,0.12,0.138,0.16,0.18,0.204,0.221,0.239,0.261,0.284,0.314,0.337,0.36,0.38,0.397,0.422,0.448,0.471,0.492,0.513,0.531,0.556,0.574,0.595,0.612,0.641,0.668,0.697,0.727,0.753,0.776,0.8,0.829,0.864,0.894,0.925,0.961,0.989,1.024,1.068,1.107,1.149,1.204,1.264,1.332,1.4,1.471,1.582,1.724,1.933,3.323]},"obj":{"mu":{"armor":0.2223,"inf":0.095,"recon":0.2026,"arty":-0.4083,"aa":-0.4643,"heli":-0.4827,"jet":-0.421},"elo":0.021,"gap":0.0535,"sigma":{"armor":0.5151,"inf":0.3268,"recon":0.3268,"arty":0.6746,"aa":0.772,"heli":1.0949,"jet":0.7373},"lambda":10,"q":[-3.628,-2.568,-2.36,-2.174,-2.002,-1.881,-1.774,-1.668,-1.565,-1.468,-1.362,-1.283,-1.179,-1.108,-1.045,-0.986,-0.928,-0.881,-0.838,-0.794,-0.755,-0.719,-0.681,-0.64,-0.589,-0.544,-0.512,-0.476,-0.444,-0.409,-0.383,-0.354,-0.331,-0.305,-0.264,-0.24,-0.213,-0.189,-0.161,-0.135,-0.115,-0.091,-0.065,-0.047,-0.026,0.002,0.029,0.047,0.072,0.093,0.118,0.139,0.163,0.181,0.201,0.226,0.245,0.275,0.295,0.323,0.343,0.361,0.384,0.408,0.43,0.452,0.475,0.494,0.519,0.539,0.56,0.586,0.615,0.639,0.661,0.685,0.71,0.733,0.759,0.784,0.82,0.848,0.869,0.896,0.927,0.959,0.989,1.037,1.071,1.109,1.144,1.193,1.239,1.302,1.36,1.4,1.459,1.556,1.662,1.824,2.573]}}},"matchPct":{"career":[-8.795,-3.102,-2.542,-2.258,-2.058,-1.92,-1.796,-1.693,-1.605,-1.528,-1.46,-1.395,-1.336,-1.28,-1.231,-1.179,-1.133,-1.085,-1.039,-0.992,-0.949,-0.909,-0.869,-0.83,-0.794,-0.758,-0.724,-0.691,-0.661,-0.63,-0.598,-0.568,-0.535,-0.505,-0.475,-0.449,-0.422,-0.395,-0.366,-0.334,-0.304,-0.275,-0.246,-0.216,-0.184,-0.153,-0.123,-0.097,-0.069,-0.042,-0.013,0.014,0.042,0.073,0.099,0.13,0.162,0.189,0.221,0.248,0.281,0.312,0.337,0.367,0.394,0.421,0.447,0.479,0.506,0.537,0.566,0.595,0.625,0.658,0.692,0.727,0.761,0.794,0.826,0.856,0.89,0.928,0.965,1.002,1.045,1.083,1.122,1.166,1.207,1.256,1.314,1.366,1.425,1.489,1.558,1.647,1.743,1.87,2.031,2.31,4.246]},"source":{"repository":"https://github.com/AlexanderHYu/ba-dragon","commit":"072dc9bc2d73ffc87000c1d3db4c0f9b4dcab549","files":["src/shared/dragon/score.ts","src/shared/dragon/roles.ts","src/shared/dragon/model.ts","src/shared/dragon/model.json","src/shared/types/batrace.ts"],"license":"MIT","licenseText":"MIT License\n\nCopyright (c) 2026 AlexanderHYu\nCopyright (c) 2025-2026 Zola (Zawinzala) — 从 https://github.com/Zawinzala/brokenarrow-log-maggot\n沿用的部分(录像、玩家追踪、卡组工具、日志解析规则)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","adaptation":"Python per-match career scoring and base-price composition; units retain role and base price only. No titles, Kalman aggregation, timeline or effective ELO."}} diff --git a/client.py b/client.py index ae57f40..2627947 100644 --- a/client.py +++ b/client.py @@ -1,7 +1,7 @@ """Independent BATrace adapter with bounded scheduling and persistent caching. Creating a client never probes the source. All network methods require explicit -access enablement and this plugin's own operator-approved client identity. +access enablement and use the plugin's fixed client identity. """ from __future__ import annotations @@ -9,7 +9,7 @@ import asyncio from contextlib import contextmanager from contextvars import ContextVar -from dataclasses import dataclass, field +from dataclasses import dataclass from datetime import datetime, timezone from email.utils import parsedate_to_datetime import hashlib @@ -17,17 +17,18 @@ import math import time from typing import Any, Awaitable, Callable, Protocol, TypeVar -from urllib.parse import urlsplit import httpx if __package__: + from .settings import valid_https_origin from .quota import AdmissionDeferred, GLOBAL_DAILY_LIMIT, QuotaActor, QuotaExceededError, quota_day from .models import ( FetchResult, Match, Participant, Player, canonical_id, parse_match, parse_player, parse_recent, parse_search, utc_datetime, ) else: # Direct module imports for framework-independent tests. + from settings import valid_https_origin from quota import AdmissionDeferred, GLOBAL_DAILY_LIMIT, QuotaActor, QuotaExceededError, quota_day from models import ( FetchResult, Match, Participant, Player, canonical_id, parse_match, parse_player, @@ -35,6 +36,7 @@ ) T = TypeVar("T") +CLIENT_ID = "Astrbot_BA_Stats" class CacheStorage(Protocol): @@ -52,8 +54,6 @@ async def quota_usage(self, actor: QuotaActor | None = None) -> dict: ... class ClientConfig: enabled: bool = False base_url: str = "https://bot.batrace.top" - client_id: str = "" - api_token: str = field(default="", repr=False) request_interval: float = 1.0 concurrency: int = 2 queue_size: int = 20 @@ -176,37 +176,26 @@ def __init__( self._cache_hits = 0 self._stale_hits = 0 self._last_error: str | None = None - # Includes origin AND identity, so a different deployment/credential can - # never accidentally read another source's cached identity response. - source = json.dumps([c.base_url.rstrip("/"), c.client_id, c.api_token]) + self.diagnostics: Callable[..., None] | None = None + # Cache identity follows the source and the fixed plugin client. + source = json.dumps([c.base_url.rstrip("/"), CLIENT_ID]) self._namespace = "batrace:v1:" + hashlib.sha256(source.encode()).hexdigest()[:24] @property def namespace(self) -> str: - """Stable binding identity: credential rotation must not change it.""" + """Binding identity follows the source, independently of cached responses.""" origin = self.config.base_url.rstrip("/") return "batrace:" + hashlib.sha256(origin.encode()).hexdigest()[:16] @property def configured(self) -> bool: - c = self.config - if not c.enabled or not c.client_id.strip() or "ba-dragon" in c.client_id.casefold(): - return False - if any(ch in c.client_id + c.api_token for ch in "\r\n"): - return False - try: - u = urlsplit(c.base_url) - _ = u.port - return bool(u.scheme == "https" and u.hostname and not u.username and not u.password - and not u.query and not u.fragment and u.path in {"", "/"}) - except ValueError: - return False + return self.config.enabled and valid_https_origin(self.config.base_url) def _check_ready(self) -> None: if self._closed: raise ClientClosedError("数据源客户端已关闭,请稍后重试。") if not self.configured: - raise NotConfiguredError("数据源接入未配置:需开启在线查询并填写本插件独立的获准客户端标识。") + raise NotConfiguredError("数据源接入未配置:请开启在线查询,并检查 API 地址是否为有效的 HTTPS 地址。") def status(self) -> dict[str, Any]: """Safe admin diagnostics: never return token, header, query or URL.""" @@ -381,9 +370,7 @@ async def _load( if isinstance(data, Match): # A structural complete flag is insufficient for a just-ended # match: keep it short until at least five minutes after end. - end = None - if data.started_at is not None and data.duration_seconds is not None: - end = data.started_at.timestamp() + data.duration_seconds + end = data.ended_at.timestamp() if data.ended_at is not None else None if not data.complete or end is None or time.time() - end < 300: ttl = 60 if self._storage is not None: @@ -460,11 +447,7 @@ async def _request(self, path: str, params: dict[str, Any]) -> Any: if self._http is None: self._http = httpx.AsyncClient() c = self.config - headers = {"Accept": "application/json", "User-Agent": "astrbot-plugin-ba-stats", "X-Client": c.client_id} - if c.api_token: - # Optional Bearer scheme is a deployment choice, NOT a verified - # BATrace requirement; configure only if operator-approved. - headers["Authorization"] = "Bearer " + c.api_token + headers = {"Accept": "application/json", "User-Agent": "astrbot-plugin-ba-stats", "X-Client": CLIENT_ID} for attempt in range(c.retries + 1): await self._check_daily_quota() async with self._start_lock: @@ -482,19 +465,28 @@ async def _request(self, path: str, params: dict[str, Any]) -> Any: # No suspension between releasing the gate and handing off to HTTP; # only request starts are serialized, never response processing. delay = 30.0 + started = time.monotonic() + if self.diagnostics: + self.diagnostics("http_start", route=path, attempt=attempt + 1) try: response = await self._http.get( c.base_url.rstrip("/") + path, params=params, headers=headers, timeout=c.request_timeout, follow_redirects=False, ) except httpx.TimeoutException: + if self.diagnostics: + self.diagnostics("http_error", route=path, error="timeout", duration_ms=round((time.monotonic() - started) * 1000)) error: ClientError = RequestTimeoutError("连接或读取数据源超时,请稍后重试。") except httpx.RequestError: + if self.diagnostics: + self.diagnostics("http_error", route=path, error="connection", duration_ms=round((time.monotonic() - started) * 1000)) error = UpstreamError("暂时无法连接到数据源,请稍后重试。") else: status = response.status_code + if self.diagnostics: + self.diagnostics("http_response", route=path, status=status, duration_ms=round((time.monotonic() - started) * 1000)) if status in {401, 403}: - raise AuthenticationError("数据源鉴权失败或拒绝访问,请管理员检查客户端标识与令牌配置。") + raise AuthenticationError("BATrace 拒绝了本次访问,请稍后重试或联系平台核实。") content_type = response.headers.get("content-type", "").split(";")[0].lower() is_json = content_type == "application/json" or content_type.endswith("+json") if not is_json and any(mark in response.text for mark in ( diff --git a/diagnostics.py b/diagnostics.py new file mode 100644 index 0000000..3ab4d06 --- /dev/null +++ b/diagnostics.py @@ -0,0 +1,273 @@ +"""Opt-in, metadata-only JSONL diagnostics; no AstrBot dependency. + +Create ONE DiagnosticLog per dedicated data directory. The directory must not +be shared with another writer/process. Managed JSONL files together never +exceed MAX_TOTAL_BYTES; ZIP exports are in memory and do not add disk files. +Unknown events/fields and invalid values are discarded, never stringified. +No free-form text, identifiers, URLs, exceptions, headers or payloads are kept. + +Integration: DiagnosticLog(data_dir / "diagnostics", enabled=settings_flag), +record("command", command=request.action, phase="finish", outcome="success", +duration_ms=elapsed_ms), then close() on plugin termination. Run export_zip() +in asyncio.to_thread from a host-authenticated download handler. Disabling +stops writes immediately but keeps previous logs available for export. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from io import BytesIO +import json +import math +from pathlib import Path +import re +from threading import RLock +from zipfile import ZIP_DEFLATED, ZipFile + + +MAX_TOTAL_BYTES = 30 * 1024 * 1024 +DEFAULT_FILE_BYTES = 1024 * 1024 +_FILENAME = re.compile(r"diagnostics-([0-9]{16,})\.jsonl\Z") +_EVENTS = frozenset({ + "lifecycle", "command", "query", "request", "cache", "render", "send", "fallback", "quota", "export", + "plugin_start", "plugin_stop", "command_start", "command_complete", "command_error", + "query_complete", "image_cache", "image_render_start", "image_render_complete", "image_render_error", + "image_send_start", "image_send_complete", "image_send_error", "text_report", + "text_send_start", "text_send_complete", "text_send_error", "http_start", "http_response", "http_error", +}) +_ACTIONS = frozenset({"help", "stats", "recent", "last", "match", "search", "bind", "binding", "unbind", "select", "cancel", "status", "quota", "cache_clear", "unknown"}) +_ERROR_CODES = frozenset({"client_error", "not_configured", "authentication", "rate_limited", "timeout", "connection", "upstream", "no_data", "schema", "identity_mismatch", "queue_full", "closed", "daily_quota", "invalid_command", "invalid_input", "permission_denied", "render_error", "storage_error", "action_failed", "unknown"}) +_ERROR_TYPES = frozenset({ + "ActionFailed", "TimeoutError", "CancelledError", "RuntimeError", "ValueError", "TypeError", "KeyError", + "OSError", "PermissionError", "FileNotFoundError", "ConnectionError", "ConnectError", "ConnectTimeout", + "ReadTimeout", "WriteTimeout", "PoolTimeout", "HTTPError", "HTTPStatusError", "RequestError", + "ClientError", "NotConfiguredError", "AuthenticationError", "RateLimitError", "RequestTimeoutError", + "UpstreamError", "NoDataError", "SchemaError", "IdentityMismatchError", "QueueFullError", "ClientClosedError", + "QuotaExceededError", +}) +_ROUTES = frozenset({"/api/players/search", "/api/analysis/player", "/api/players/matches", "/api/match"}) +_IMAGE_NAME = re.compile(r"(?:[0-9a-f]{64}|report|card|image)(?:-[0-9]{1,4})?\.(?:jpg|jpeg|png|webp|gif)\Z", re.IGNORECASE) +_MESSAGE_MARKERS = ( + ("Timeout", re.compile(r"\btimeout\b|\btimed?\s*out\b|超时", re.IGNORECASE)), + ("sendMsg", re.compile(r"\bsend(?:group|private)?msg\b", re.IGNORECASE)), + ("image", re.compile(r"\bimage\b|图片", re.IGNORECASE)), + ("upload", re.compile(r"\bupload\w*\b|上传", re.IGNORECASE)), + ("decode", re.compile(r"\bdecod\w*\b|解码", re.IGNORECASE)), + ("permission_denied", re.compile(r"permission|forbidden|权限", re.IGNORECASE)), + ("rate_limited", re.compile(r"rate.limit|限流", re.IGNORECASE)), + ("connection", re.compile(r"\bconnect\w*\b|连接", re.IGNORECASE)), + ("failed", re.compile(r"\bfail\w*\b|失败", re.IGNORECASE)), +) +_ENUMS = { + "phase": frozenset({"start", "finish", "error", "cancel", "initialize", "terminate", "enable", "disable"}), + "command": _ACTIONS, + "action": _ACTIONS, + "kind": frozenset({"text", "image", "overview", "recent", "match", "search", "binding", "help", "status", "quota", "error", "unknown"}), + "operation": frozenset({"search", "player", "recent", "match", "render", "export", "initialize", "terminate"}), + "outcome": frozenset({"success", "error", "cancelled", "rejected", "hit", "miss", "stale"}), + "error_code": _ERROR_CODES, + "error": _ERROR_CODES | _ERROR_TYPES, + "image_type": frozenset({"JPEG", "JPG", "PNG", "GIF", "WEBP", "UNKNOWN", "jpeg", "jpg", "png", "gif", "webp", "unknown", "未知"}), + "scope": frozenset({"global", "user", "group"}), +} +_COUNTERS = frozenset({"count", "inflight", "requests", "cache_hits", "stale_hits", "bytes", "retry", "limit", "used", "remaining", "page", "image_bytes", "attempt", "rows"}) +_BOOLEANS = frozenset({"configured", "closed", "force", "cached", "stale"}) + + +def _safe_fields(fields: dict) -> dict: + result = {} + for key, choices in _ENUMS.items(): + value = fields.get(key) + if type(value) is str and value in choices: + result[key] = value + for key in _COUNTERS: + value = fields.get(key) + if type(value) is int and 0 <= value <= 1_000_000_000: + result[key] = value + for key in _BOOLEANS: + value = fields.get(key) + if type(value) is bool: + result[key] = value + value = fields.get("status_code") + if type(value) is int and 100 <= value <= 599: + result["status_code"] = value + value = fields.get("status") + if type(value) is int and 100 <= value <= 599: + result["status"] = value + elif type(value) is str and value in _ERROR_CODES | {"ok", "success", "error", "failed", "fallback", "0.1.2"}: + result["status"] = value + value = fields.get("retcode") + if type(value) is int and -1_000_000_000 <= value <= 1_000_000_000: + result["retcode"] = value + value = fields.get("route") + if type(value) is str: + route = value.split("?", 1)[0].split("#", 1)[0] + if route in _ROUTES: + result["route"] = route + value = fields.get("path") + if type(value) is str: + name = value.replace("\\", "/").rsplit("/", 1)[-1] + if _IMAGE_NAME.fullmatch(name): + result["path"] = name + value = fields.get("message") + if type(value) is str: + # Extract fixed vocabulary only. Regex redaction of arbitrary exception + # strings cannot guarantee removal of bare tokens or response bodies. + markers = [label for label, pattern in _MESSAGE_MARKERS if pattern.search(value[:4096])] + result["message"] = ": ".join(markers) if markers else "details_omitted" + value = fields.get("duration_ms") + if type(value) in (int, float) and 0 <= value <= 1_000_000_000 and math.isfinite(value): + result["duration_ms"] = value + return result + + +class DiagnosticLog: + """Thread-safe bounded recorder with atomic ZIP snapshots. + + A smaller byte budget is accepted for tests/deployments, never a larger one. + record() returns False when disabled, closed, invalid, too large, or an OS + write fails. Export errors propagate to the download handler. close() is + permanent; set_enabled() is the reversible configuration switch. + """ + + def __init__(self, directory: str | Path, enabled: bool = False, *, + max_total_bytes: int = MAX_TOTAL_BYTES, + max_file_bytes: int = DEFAULT_FILE_BYTES): + if type(max_total_bytes) is not int or not 1 <= max_total_bytes <= MAX_TOTAL_BYTES: + raise ValueError("diagnostic total must be between 1 byte and 30 MiB") + if type(max_file_bytes) is not int or max_file_bytes < 1: + raise ValueError("diagnostic file size must be positive") + if type(enabled) is not bool: + raise ValueError("enabled must be a boolean") + self._directory = Path(directory) + self._max_total = max_total_bytes + self._max_file = min(max_file_bytes, max_total_bytes) + self._lock = RLock() + self._enabled = enabled + self._closed = False + self._files: list[tuple[Path, int]] = [] + self._total = 0 + self._next_id = 0 + # Read and enforce an existing ring after restart, even when disabled. + # A new disabled recorder does not create a directory or any file. + try: + self._scan() + self._trim() + except OSError: + self._enabled = False + + def _scan(self) -> None: + files = [] + for path in self._directory.glob("diagnostics-*.jsonl"): + match = _FILENAME.fullmatch(path.name) + if match and not path.is_symlink() and path.is_file(): + serial = int(match[1]) + files.append((serial, path, path.stat().st_size)) + files.sort(key=lambda item: item[0]) + self._files = [(path, size) for _, path, size in files] + self._total = sum(size for _, size in self._files) + if files: + self._next_id = max(self._next_id, files[-1][0] + 1) + + def _trim(self, reserve: int = 0) -> None: + while self._files and self._total + reserve > self._max_total: + path, size = self._files[0] + path.unlink(missing_ok=True) + self._files.pop(0) + self._total -= size + + @property + def enabled(self) -> bool: + with self._lock: + return self._enabled and not self._closed + + @property + def total_bytes(self) -> int: + with self._lock: + return self._total + + def stats(self) -> dict: + """Safe UI metadata, without file paths or arbitrary configuration.""" + with self._lock: + return {"enabled": self._enabled and not self._closed, + "bytes": self._total, "limit_bytes": self._max_total, + "files": len(self._files)} + + def set_enabled(self, enabled: bool) -> None: + if type(enabled) is not bool: + raise ValueError("enabled must be a boolean") + with self._lock: + self._enabled = enabled and not self._closed + + def close(self) -> None: + with self._lock: + self._closed = True + self._enabled = False + + def record(self, event: str, **fields) -> bool: + with self._lock: + if not self._enabled or self._closed or type(event) is not str or event not in _EVENTS: + return False + entry = { + "timestamp": datetime.now(timezone.utc).isoformat(timespec="milliseconds"), + "event": event, + **_safe_fields(fields), + } + line = (json.dumps(entry, ensure_ascii=True, allow_nan=False, separators=(",", ":")) + "\n").encode("utf-8") + if len(line) > self._max_file: + return False + path, size, opened = None, 0, False + try: + # Evict BEFORE append, including the active segment if needed. + self._trim(len(line)) + append = bool(self._files and self._files[-1][1] + len(line) <= self._max_file) + if append: + path, size = self._files[-1] + else: + self._directory.mkdir(parents=True, exist_ok=True) + path = self._directory / f"diagnostics-{self._next_id:016d}.jsonl" + self._next_id += 1 + size = 0 + with path.open("ab" if append else "xb") as stream: + opened = True + if stream.write(line) != len(line): + raise OSError("incomplete diagnostic write") + if append: + self._files[-1] = (path, size + len(line)) + else: + self._files.append((path, len(line))) + self._total += len(line) + return True + except OSError: + # Partial writes are still bounded by the pre-reserved bytes. + # Reconcile sizes so future attempts cannot overrun the budget. + try: + if opened and path is not None and path.exists(): + # Roll back a partial JSONL line after disk-full/flush + # errors; never append the next event onto broken JSON. + if size: + with path.open("r+b") as stream: + stream.truncate(size) + else: + path.unlink() + self._scan() + self._trim() + except OSError: + self._enabled = False + return False + + def export_zip(self) -> bytes: + """Snapshot all managed segments without rotating, clearing or logging. + + File reads share the writer lock; compression occurs after releasing it. + ZIP member names contain no absolute/user paths. Closed/disabled logs + remain downloadable. An empty recorder produces a valid empty ZIP. + The caller must authenticate the request; this module has no HTTP API. + """ + with self._lock: + snapshot = [(path.name, path.read_bytes()) for path, _ in self._files] + result = BytesIO() + with ZipFile(result, "w", compression=ZIP_DEFLATED) as archive: + for name, data in snapshot: + archive.writestr(name, data) + return result.getvalue() diff --git a/docs/API_NOTES.md b/docs/API_NOTES.md index 8af5164..75e703f 100644 --- a/docs/API_NOTES.md +++ b/docs/API_NOTES.md @@ -21,17 +21,15 @@ ## 接入与鉴权边界 参考源码的 API origin 是 `https://bot.batrace.top`,公开页面 origin 是 `https://dash.batrace.top`。 -源码使用 `X-Client` 标识,取值属于该项目自己的放行身份;README 的使用同意针对该工具,不延伸为其他插件的许可。 -本插件不会预置或发送该项目的标识,并拒绝包含 `ba-dragon` 的客户端标识。 +参考源码使用 `X-Client` 标识,取值属于该项目自己的身份;README 的使用同意针对该工具,不延伸为其他插件的许可。 +本插件独立使用固定标识 `X-Client: Astrbot_BA_Stats`,不复用参考项目标识,不提供客户端标识或令牌设置,也不发送 `Authorization`。 -配置由主代理统一读取:`access.enabled=false`、`base_url=https://bot.batrace.top`、`client_id=''`、`api_token=''`。 -`enabled=true`、合法 HTTPS origin 和本插件自己的获准 `client_id` 缺一不可;未配置时在缓存与网络操作之前抛出 `NotConfiguredError`。 -构造、状态查看、关闭均不探活。没有凭据时不发匿名探测,也不回退到网页抓取或验证码绕行。 +接入设置只有 `access.enabled=false` 和 `access.base_url=https://bot.batrace.top`;保存后重载生效。 +`enabled=true` 且 API 地址为合法 HTTPS origin 时才可查询;未开启或地址无效时,在缓存与网络操作之前抛出 `NotConfiguredError`。 +构造、状态查看、关闭均不探活,不回退到网页抓取或验证码绕行。 -本插件发送自己的 `User-Agent: astrbot-plugin-ba-stats` 和配置的 `X-Client`。 -`api_token` 非空时支持 `Authorization: Bearer `,**这只是配置支持,不是已核实的 BATrace 鉴权要求**;只能在运营方明确认可该方案后配置。 -若对方要求不同机制,应先核实并调整适配,不能尝试猜测凭据或身份。 -token 不出现在 `ClientConfig` 的 repr、status、异常消息或缓存明文 key 中。 +本插件同时发送 `User-Agent: astrbot-plugin-ba-stats` 与 `Accept: application/json`。固定客户端标识只描述请求行为,不代表真实接口已联调通过。 +设置中的在线查询提示固定为「数据来源 BATrace ,如有帮助请支持该平台」。 参考客户端文件头还保留“不发自定义 UA”的旧注释,但该提交的 `CLIENT_HEADERS()` 实际发送自定义 UA 和 `X-Client`;本说明以现行代码为准,未据旧注释模拟浏览器。 参考工具采用串行、约 1.2 秒间隔,网络/5xx 约 30 秒后重试一次。这些是该工具的本地策略,**不能宣传为本插件获准的上游限额或通用放行办法**。 @@ -61,39 +59,57 @@ SteamID64 与 STB ID 均保持字符串;**未找到可靠的 Steam→STB 映 | 模型 | 字段 | | --- | --- | -| `Player` | `id, name, steam_id?, elo?, source_url?, updated_at?, elo_observed_at?` | -| `Participant` | `player_id, name, team?, outcome, elo?, elo_delta?, kills?, losses?, destroyed_value?, lost_value?, units` | -| `Match` | `id, map_name?, mode, started_at?, duration_seconds?, winner_team?, players, complete, source_url?, updated_at?` | +| `Player` | `id, name, steam_id?, elo?, source_url?, updated_at?, elo_observed_at?, analysis` | +| `Participant` | `player_id, name, team?, outcome, elo?, elo_before?, elo_delta?, kills?, losses?, destroyed_value?, lost_value?, units, units_available, damage_dealt?, damage_received?, objectives?, spawned_value?, supply?` | +| `Match` | `id, map_id?, map_name?, mode, started_at?, ended_at?, duration_seconds?, winner_team?, players, complete, source_url?, updated_at?` | | `FetchResult[T]` | `data, fetched_at, stale=False, source_updated_at?, stale_reason?` | - 外部 ID 只接收字符串或整数,不接收布尔、浮点或按位数猜测的身份;转换不会丢掉字符串前导零。 -- 搜索 `rating` 是档案快照;`updated_at` 保留源时间。分析 `trend.points` 中显式 `ratingAfter` 配合 `endTime`,按实际时间选最新,不依赖数组顺序。已知更新时间更新的搜索评分优先。 -- `elo_observed_at` 表示评分观察对应的对局结束时间;它不是源记录更新时间。`source_updated_at` 不会用抓取时间或对局结束时间冒充。 +- 搜索 `rating` 是 ELO 档案快照;`updated_at` 保留源时间。分析 `trend.points` 中显式 `ratingAfter` 配合 `endTime`,按实际时间选最新,不依赖数组顺序。已知更新时间更新的搜索 ELO 优先。 +- `elo_observed_at` 表示 ELO 观察对应的对局结束时间;它不是源记录更新时间。`source_updated_at` 不会用抓取时间或对局结束时间冒充。 +- `analysis` 保留经过类型校验的来源分析数据:场数、带对局 ID 的 ELO/胜负与核心战绩记录、单位摘要、兵种占比和地图表现;逐局「评分」另由本地 ba-dragon 模型计算,缺失必要输入时保持未知。 - 只解析 Unix **秒**或带明确时区的 ISO 时间,内部为 aware UTC;不猜毫秒、不按机器本地时区解释无时区字符串。真实源若使用其他格式,须先核实其时区及单位再适配。 -- `MatchInfo` 已观察到 `MapId, Type, StartTime, EndTime, TotalPlayTimeInSec, Data`。列表可能只有结束时间,结束时间和时长都在时倒推开始时间;没有时间则保持未知。 +- `MatchInfo` 已观察到 `MapId, Type, StartTime, EndTime, TotalPlayTimeInSec, Data`。开始、结束时间分别保留;缺少开始时间时保持未知,不用结束时间和时长反推,以免改变评分中的时间判断。 - `Data` 为参与者对象字典,条目的 `Id` 为玩家规范 ID;不把对象键当 ID。重复参与者 ID、无 ID 或变更为其他集合结构均报结构错误。 -- `OldRating/NewRating` 仅用于 `elo/elo_delta`;**本版不将评分涨跌转换成胜负**。参考项目的推断没有权威胜负语义证据,故 `winner_team=None`、`outcome='unknown'`。 +- `OldRating/NewRating` 保留为赛前/赛后 ELO 与差值,**不将 ELO 涨跌转换成胜负**。单局适配缺少明确胜负字段时仍保留 `winner_team=None`、`outcome='unknown'`;展示层只在相同对局 ID 的分析记录中有明确布尔 `won` 时补充目标玩家结果。 - `Type` 枚举未得到可靠释义,故 `mode='unknown'`。缺评分或评分不变不能证明是自定义局;参考工具的“未计分”筛选也不能替代源模式。 - `Destruction/Losses` 对应单位数量,`DestructionScore/LossesScore` 对应摧毁/损失价值;两者不可混算。只在已识别的 protobuf 参与者 shape 中,对这四个省略字段和 `TeamId` 应用参考源码明确记载的零默认值;四个计数显式 null 保持未知,`TeamId` 显式 null 报结构错误。其他来源与 dataclass 默认不填零。 +- `DamageDealt/DamageReceived` 为造成/承受伤害,`ObjectivesCaptured` 为占点数,`TotalSpawnedUnitScore` 为出动价值,`SupplyPointsConsumed` 为补给消耗;这些可选核心字段缺失时保持未知,不填零。 - 名字缺失为空字符串;地图表未核实,已有 `MapId` 显示 `地图#`。不下载单位表或游戏资产。 -- `UnitData` 对象的每条记录只归一化为 `{id, name?, count:1}`;名称通常缺失。这里是**出场记录数**,飞机重复出动可能多条,不是独立单位数、击杀数、费用或兵种偏好。不会估算配装价或单位摧毁价值。 +- `UnitData` 每条记录保留 ID、名称、`count=1`,以及模型需要的出动/死亡时间、退款与击杀数。`count` 仍是**出场记录数**,飞机重复出动可能多条,不是独立单位数或实际花费。`units_available` 区分缺失的 `UnitData` 与明确提供的空对象;兵种构成的基础花费估算另行标注。 - `complete` 是保守的**本地缓存完整度标记**:单局详情有结束时间、参与者且每人显式含 `UnitData` 对象才为真;不代表源端声明“数据最终完成”。列表始终为 false。结束不足五分钟的详情仍仅缓存 60 秒。 -- 最近对局按稳定 ID 去重、按实际开始时间降序,未知时间放最后;相同 ID 优先保留参与者更多的记录。返回实际样本数,不冒称完整历史或完整排位样本。 +- 最近对局按稳定 ID 去重、按实际结束时间(缺少时用实际开始时间)降序,两者都缺少才放最后;相同 ID 优先保留参与者更多的记录。返回实际样本数,不冒称完整历史或完整排位样本。 - `players/matches` 必须显式返回数组。缺数组、错误对象、非 JSON/验证码响应不能当成“零搜索结果/零场对局”。 +## 评分、预测与战报展示 + +`scoring.py` 使用 `assets/scoring-model.json`,移植 ba-dragon 固定提交的逐局评分逻辑与参数。近期战绩首列统一命名「评分」,按分数段着色,不显示称号。缺少必要数据时返回 `None` 并显示「暂无」,不补零。它与来源 ELO 分别展示,不是完整生涯评价,也不引入时间线或 Kalman 聚合算法。 + +`ba last` 的单局图片顶部展示基于双方赛前 ELO 的赛前预测;中部左右排列双方数据对比与兵种构成;底部展示玩家数据。预测是模型估算,不表示实际赛果。兵种构成按模型的单位角色与基础价格估算出动花费,缺少单位价格或记录时保留不完整说明,不冒充实际结算。 + +所有战报图片页脚包含 `assets/github-avatar.png`、`timeance/astrbot_plugin_BA_stats` 与固定文字「数据来源 BATracer」。设置提示仍原样保留「数据来源 BATrace ,如有帮助请支持该平台」。 + +## 设置中心与诊断日志 + +入口为插件详情 → 可视化视图 → 设置中心,视图文件为 `views/settings/index.html`,脚本为同目录的 `settings.js`。表单与原生插件配置共用同一份设置,常用设置也可原生调整。诊断开关保存后即时生效;其他设置保存后需在插件页手动重载,页面不会自动重载或中断当前请求。 + +维护设置和诊断日志的内容默认折叠,诊断开关、日志状态和下载位于同一区域。排查时选择「诊断日志」并展开,开启诊断并保存后复现问题,再点击「下载诊断日志(ZIP)」。配置保存、状态查询与下载均通过宿主鉴权的插件 API 提供。 + +诊断记录总容量上限为 `30 * 1024 * 1024` 字节,面向用户显示为 30 MB,旧日志自动轮换。设置中心的 HTML/JS 由本插件独立编写,来源说明见 [THIRD_PARTY.md](THIRD_PARTY.md)。 + ## client 与 storage 契约 ```python client = BatraceClient( config=ClientConfig( - enabled=False, base_url="https://bot.batrace.top", client_id="", api_token="", + enabled=False, base_url="https://bot.batrace.top", request_interval=1, concurrency=2, queue_size=20, request_timeout=20, wait_timeout=45, retries=1, cache_max_entries=1000, stale_hours=24, user_daily_limit=20, group_daily_limit=100, ), storage=storage, # 已 open 的 Storage(data_dir) - http_client=async_client, # 可省略,首次获准请求时才内部创建 + http_client=async_client, # 可省略,首次在线请求时才内部创建 ) ``` @@ -103,7 +119,7 @@ client = BatraceClient( `match(id, *, force=False) -> FetchResult[Match]`、`clear_cache()`、`close()`。 `status()` 是同步安全摘要,返回 configured/closed/inflight/requests/cache_hits/stale_hits/last_error。 其中 `requests` 为本次运行的 HTTP 尝试数;每日持久用量由 `await storage.quota_usage(actor)` 提供。 -`namespace` 只由数据源 `base_url` 生成,供持久绑定使用;内部缓存命名空间另外包含客户端身份/token 的摘要,凭据轮换不改变绑定身份。 +`namespace` 只由数据源 `base_url` 生成,供持久绑定使用;内部缓存命名空间由 API 地址与固定客户端标识生成。更换 API 地址会隔离绑定与缓存,但不重置每日额度。 storage 为 duck type:`get_cache(key) -> (JSON payload, fetched_at, expires_at) | None`,过期但保留的记录也应返回; `put_cache(key,payload,ttl)`、`clear_cache()`、`prune_cache(max_entries=...,max_age_seconds=...)`、`cache_count()`。 @@ -135,13 +151,13 @@ AstrBot 适配器从事件的 `get_platform_id()/get_sender_id()/get_group_id()` 查询概览通常包含多个 HTTP,部分请求已发出后额度不足,会保留已用次数并中止剩余调用;绑定逻辑不会据不完整结果修改原绑定。额度不足时可读取新鲜缓存,但不会以 stale 回退隐藏该错误。网络合并仅限同一用户、同一群,防止其他调用者的强制刷新扣到原发起者。 -额度表独立于缓存及凭据命名空间;重开数据库、清缓存、改凭据、调整限制不清零。无 Storage 的独立适配器只有进程内全局计数,`request_scope` 拒绝该模式;生产插件始终使用持久 Storage。`/ba quota` 为无需接入许可的本地只读查询。 +额度表独立于数据源及缓存命名空间;重开数据库、清缓存、更换 API 地址、调整限制不清零。无 Storage 的独立适配器只有进程内全局计数,`request_scope` 拒绝该模式;生产插件始终使用持久 Storage。`ba quota` 为无需启用在线查询的本地只读查询。 ## 失败语义 | 异常/code | 含义 | 可用 stale | | --- | --- | --- | -| `NotConfiguredError / not_configured` | 缺自身接入配置,未发请求 | 否 | +| `NotConfiguredError / not_configured` | 在线查询未开启或 API 地址无效,未发请求 | 否 | | `AuthenticationError / authentication` | 401/403 或明确验证码页 | 否 | | `NoDataError / no_data` | 404 + JSON,暂无收录;不证明账号不存在 | 否 | | `IdentityMismatchError / identity_mismatch` | 规范 ID 未回显,或近期列表包含其他玩家对局 | 否 | @@ -164,7 +180,7 @@ AstrBot 适配器从事件的 `get_platform_id()/get_sender_id()/get_group_id()` 离线运行:`python -m pytest -q`。新增每日限额测试覆盖持久计数、北京时间日界、并发边界、失败/重试计数、缓存免费与身份传播;当前完整结果见 [验证记录](VALIDATION.md)。所有真实 SQLite 重开测试也使用临时目录,没有访问真实账号或 BATrace。 真实联调与实际平台验证均未执行。框架、service、render、平台与总验证详见主代理交付记录。 -最少还需补齐:本插件可使用的 API origin、自身获准身份/鉴权方式、允许接口与查询范围、实际并发/请求间隔/退避与缓存政策。 +真实联调仍需核对 API origin、固定客户端标识的响应、允许接口与查询范围、实际并发/请求间隔/退避与缓存政策。 随后在明确授权的最小调用量内依次核对: 1. 以已知玩家名搜索,确认规范 ID、updated_at 格式/时区和截断规则。 @@ -177,5 +193,5 @@ AstrBot 适配器从事件的 `get_platform_id()/get_sender_id()/get_group_id()` ## 许可与独立实现 该提交的 ba-dragon 主源码为 MIT,LICENSE 载明 AlexanderHYu 与沿用部分的 Zola 版权;其 README 另外说明可选录像使用 GPL FFmpeg。 -本插件只依据公开的路径、参数与字段事实独立编写 Python 调度、数据模型和测试,没有复制其评分模型、录像、游戏数据、FFmpeg 或其他 GPL 实质代码。 -本仓库原有 Apache-2.0 LICENSE 保持不变;来源致谢和全项目第三方说明由主代理统一维护。 +Python 请求调度、数据模型和业务适配由本插件实现;`scoring.py` 的移植部分与 `assets/scoring-model.json` 使用 ba-dragon 的 MIT 评分逻辑和模型参数,并保留其来源与版权。未引入录像工具或 FFmpeg。 +完整上游许可原样保留于 [BA_DRAGON_LICENSE.txt](BA_DRAGON_LICENSE.txt),安装、源码与 Gemini 包均随附。本仓库根 `LICENSE` 继续为 Apache-2.0;具体第三方来源与移植范围见 [THIRD_PARTY.md](THIRD_PARTY.md)。 diff --git a/docs/BA_DRAGON_LICENSE.txt b/docs/BA_DRAGON_LICENSE.txt new file mode 100644 index 0000000..70d64ad --- /dev/null +++ b/docs/BA_DRAGON_LICENSE.txt @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2026 AlexanderHYu +Copyright (c) 2025-2026 Zola (Zawinzala) — 从 https://github.com/Zawinzala/brokenarrow-log-maggot +沿用的部分(录像、玩家追踪、卡组工具、日志解析规则) + +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. diff --git a/docs/THIRD_PARTY.md b/docs/THIRD_PARTY.md index 447c834..aed33a5 100644 --- a/docs/THIRD_PARTY.md +++ b/docs/THIRD_PARTY.md @@ -1,18 +1,34 @@ # 来源与许可 -本项目既有许可证为 Apache-2.0,原始仓库基线为 `c4272e87413734ec317fe937faa868bbbf70eb08`。新增代码按该许可证提供;第三方服务数据、产品名称和交接图像不因本项目代码许可证而获得额外授权。 +本项目既有许可证为 Apache-2.0,原始仓库基线为 `c4272e87413734ec317fe937faa868bbbf70eb08`。项目自有代码按该许可证提供;ba-dragon 移植部分及模型保留上游 MIT 许可。第三方服务数据、产品名称和交接图像不因本项目代码许可证而获得额外授权。 | 来源 | 本次用途 | 固定版本 | | --- | --- | --- | | [AstrBot](https://github.com/astrbotdevs/astrbot) | 原生插件 API、ZIP 格式与配置 Schema 核对 | v4.29.4,`61335414433db721b3f7ecc93f90deafe0a59d78` | | [AstrBot T2I](https://github.com/AstrBotDevs/astrbot-t2i-service) | 核对 `viewport_width`、像素比及 JPEG 质量参数 | `bcc08e47274c69e5ace19bbf738b95260ce17ca7` | -| [ba-dragon](https://github.com/AlexanderHYu/ba-dragon) | BATrace 请求形态、ID 与字段语义研究 | 见 API_NOTES.md | +| [ba-dragon](https://github.com/AlexanderHYu/ba-dragon) | BATrace 接口参考;逐局评分、赛前 ELO 预测及兵种构成估算的 MIT 移植 | `072dc9bc2d73ffc87000c1d3db4c0f9b4dcab549`,详见下文及 API_NOTES.md | | [wows-stats-bot](https://github.com/benx1n/wows-stats-bot) | README 中绑定与 @ 查询的交互研究,未移植 HoshinoBot 实现 | master,`80c86970685887578054e61e1a76d1589ea1dc31` | | [BATrace](https://dash.batrace.top/) | 预期战绩数据来源 | 自身接入许可、配额及真实字段待确认 | | [astrbot_plugin_openai_native](https://github.com/timeance/astrbot_plugin_openai_native) | 参考用户跨群累计、群共享额度、配置提示与额度查询;按本任务要求统一私聊用户计数和北京时间日界 | main,`98bd76784bb2a35df0aea968138f87fd4d9ee207`;核对 README、配置 Schema、事件身份提取 | 研究不等于获得服务调用许可。插件不内置参考项目的获准标识或密钥。测试负载与卡片预览为明确标识的合成样本。 -未复制参考项目的非琐碎源码、图片、字体或样式到插件。依赖由宿主环境安装,安装 ZIP 不附带第三方库;各依赖许可证以其发布包为准。预览工具使用本地 Playwright/Chromium,仅用于开发验收,运行插件不需要安装它们。 +## ba-dragon 评分与模型 + +`scoring.py` 将固定提交中的 `src/shared/dragon/score.ts`、`roles.ts`、`model.ts` 相关逻辑移植为 Python;`assets/scoring-model.json` 使用同一提交的 `src/shared/dragon/model.json` 参数,以及评分和兵种构成所需的单位角色与基础价格信息。模型内的 `source` 记录仓库、提交、来源文件和 MIT 文本。 + +移植范围是逐局评分、基于赛前 ELO 的预测及按基础花费估算的兵种构成。展示统一称「评分」,按分数着色;不包含称号、时间线或 Kalman 生涯聚合。模型结果是估算,不代表官方评价。 + +完整上游版权与 MIT 许可原样保留于 [BA_DRAGON_LICENSE.txt](BA_DRAGON_LICENSE.txt),包括 `Copyright (c) 2026 AlexanderHYu` 及 `Copyright (c) 2025-2026 Zola (Zawinzala)` 与原文件的沿用部分说明。安装包、源码包及 Gemini 文案包均保留该文本;文案润色不修改许可证。 + +未移植参考项目的录像工具或 FFmpeg。其 README 提到的可选 GPL FFmpeg 不随本插件分发。 + +## 依赖与图像 + +`views/settings/` 中的 HTML/JS 由本插件独立编写,设置中心仅参考 `meme_manager` 的交互组织,未复制其源码。 + +依赖由宿主环境安装,安装 ZIP 不附带第三方库;各依赖许可证以其发布包为准。预览工具使用本地 Playwright/Chromium,仅用于开发验收,运行插件不需要安装它们。 + +`assets/github-avatar.png` 用于图片页脚的 GitHub 作者标识,与 `timeance/astrbot_plugin_BA_stats` 及「数据来源 BATracer」一同显示;不属于 ba-dragon 评分模型素材。 `logo.png` 与 `assets/readme-logo.png` 原样来自用户交接包,交付时核对 SHA-256 一致。它们的授权与来源由交接提供方负责说明,本项目没有代替权利人作版权声明。 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 1961765..f78c3e0 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,134 +1,80 @@ # 验证记录 -验证日期:2026-11-17(Asia/Hong_Kong)。版本:v0.1.1。 +验证日期:2026-11-17(Asia/Hong_Kong)。版本:v0.1.2。 -## 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 审阅 | -| 离线业务与契约测试 | **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 群聊与私聊 | 用户提供群聊提示和图片发送超时日志;v0.1.1 修复后的实际收发待验收 | -| GitHub PR / 发布 / 部署 | 远端检查以对应 PR 为准;本记录不代表发布或部署验收 | - -API 与模型 fixture、渲染预览均为合成数据。HTTP 测试使用 `httpx.MockTransport`,不调用 BATrace。`tests/test_main.py` 在测试作用域注入 AstrBot 桩并恢复,不代表真实框架启动成功。 - -## 文案导入与 CI +| 完整离线测试 | **635 passed,25.90 秒** | +| 评分与固定上游 TypeScript 对照 | **320 个合成样本一致**;中间值误差小于 1e-12 | +| 三类战报本地渲染 | 18 组 HTML/文字、36 张 PNG;无横向溢出或外部请求 | +| 设置中心本地交互 | 深色 390px、浅色 1100px 两组通过;4 张预览 | +| 依赖兼容性 | `uv pip check`:21 个已安装包兼容 | +| 完整 AstrBot 服务、真实渲染服务 | 未启动;按 v4.29.4 固定源码核对 API,使用事件与桥接桩验证 | +| BATrace / QQ 实际联调 | 开发环境未调用;用户已提供候选结果和图片超时日志 | +| 远端 PR / CI | 以对应 PR 的实时结果为准;本记录不表示已合并或部署 | -Gemini 返回的 331 条文案全部匹配导出基线;回填 68 条变化,并校正其中 4 处语义。README 沿用用户要求的简版,详细说明保留在 `docs`。同步旧文案断言后,推荐候选的 392 项离线测试全部通过;正式导入逐文件核对与候选一致。 +## 战报、评分与数据口径 -项目 CI 使用 Python 3.11 / 3.12,执行依赖兼容性、元数据和语法检查;插件实现 PR 增加完整离线测试和安装包构建检查。CI 不调用真实战绩 API,也不发送 QQ 消息。 +- 玩家概览、近期列表、单局战报共用展示数据和格式;精简重复说明,保留样本范围、未知值和旧缓存标识。 +- 分值 K/D 使用摧毁分与损失分;击杀/阵亡是单位数量,伤害/承伤是另一组数据。出兵花费、补给消耗保留有效小数,不被整数格式误判为缺失。 +- 分析接口只以明确布尔 `won` 及相同对局 ID 提供目标玩家胜负;不将 ELO 涨跌当成展示的权威胜负。单局页保留已知目标胜负。 +- 分析样本与近期样本分别标明;重复和相互矛盾的分析结果不重复计入分母。地图、单位按来源 ID 关联。 +- 「评分」移植固定 ba-dragon 模型的逐局 career 计算,按分数着色,不展示称号。保留 MIT 来源与完整许可。 +- Oracle 包含原始 160 个样本,以及逐个删除 `StartTime` 的 160 个边界样本。开始/结束时间分别保留;不以结束时间减时长反推开始时间。近期列表按真实结束时间、缺少时按真实开始时间排序,两者都缺少才放最后。 +- 赛前预测使用 A/B 队全部必要赛前 ELO;兵种构成按已收录单位基础价格估算。缺少成员单位数据或存在未知价格时,不把已识别部分重新归一化为完整构成。 +- 单局图片按 900 CSS 像素渲染:顶部预测,中部左右对比/构成,底部玩家。其他卡片为 390 CSS 像素;运行仍使用 JPEG 85、ultra 像素比。 +- 所有图片页脚为本地内嵌 GitHub 头像、`timeance/astrbot_plugin_BA_stats` 和「数据来源 BATracer」。不在运行时请求头像。 -PR 审查统一了以下行为,并增加对应回归验证: +## 设置中心与诊断 -- 近期列表、单局详情和展示层共用目标玩家身份核对;有参与者但缺少目标时明确拒绝。 -- 真实 At 组件保留来源,显式昵称和搜索文本中的 `@user:` 不再被误判;手写标记仍不能借用真实提及。 -- 常用单位按来源 ID 聚合,名称仅用于展示;不同 ID 同名时在图片和文字中统一区分。 -- 所有 SQLite 业务写入共用事务边界;异常和重复取消时等待回滚完成后才释放连接锁。 -- HTTP 发送准入同时协调节流、共享退避和额度记账,响应处理保持并发。 +- 独立视图 `views/settings/`,与原生配置共用 AstrBotConfig;常用、额度、维护、诊断分组。跟随宿主深浅主题,维护和诊断内容默认折叠。 +- 按 schema 描述与白名单校验字段,API origin 与客户端复用同一 HTTPS 校验规则;不返回或接受旧客户端标识、令牌、全局额度字段。 +- 保存检查磁盘配置版本,冲突返回 409 并保留页面草稿。普通设置等待手动重载,页面显示待生效项;诊断开关保存后即时应用,保存不重启业务对象或中断在途请求。 +- API 使用 AstrBot 登录鉴权,插件额外检查用户名。未登录、已关闭、无效 JSON、非法类型/范围、保存失败及旧实例卸载有回归测试。下载不通过公开静态目录。 +- 诊断仅记录允许的事件与字段:请求耗时/状态、渲染及图片发送阶段、文件类型/大小、受控错误分类等。日志上限为 `30 * 1024 * 1024` 字节,旧段自动淘汰;关闭后可下载既有日志。 +- 记录器覆盖轮换、并发导出、关闭、磁盘失败及脱敏;不记录令牌、请求头、完整响应、聊天正文或图片内容。导出为 ZIP,不清空原日志。 +- 本地浏览器验证保存开关、下载路由、409 草稿保留、重新读取后保留草稿、待重载提示及固定总额度。合成桥接不替代真实宿主收发;常用设置全页预览将悬浮保存栏放到文档末尾,交互测试使用原样 CSS。 -文案导入后重新生成 18 组 HTML/文字、36 张 PNG,布局与外部请求检查全部通过;复查手机概览,标题和常用单位区正常。预览仍全部为合成样本。 +## 图片超时的已知边界 -最终全量运行:`python -m pytest -q`,435 passed(24.70 秒)。新增准入测试验证事务中跨日回滚、退避期间跨午夜后新日最多 100 次 HTTP;取消回滚与响应并发均有覆盖。旧间隔测试的 15ms 时间窗口在 Windows 全量运行中出现抖动,改为 80ms 间隔并保留 70ms 下界和并发断言后,全量通过。 +用户环境为 AstrBot 4.29.4、NapCat.Core 4.18.18;其他插件能发图片。用户日志显示 OneBot `retcode=1200`、QQ `sendMsg` 确认超时。 -## 核对基线 +v0.1.1 已改为等待图片发送结果,并在未获成功确认时使用同一次查询回复文字、关闭文字自动转图。v0.1.2 增加受控诊断信息,**未证明 QQ 超时根因已修复**。本地卡片可渲染不等于实际 QQ 可接收;需在用户实例打开诊断并复现后检查日志。 -- 目标仓库初始 `main`:`c4272e87413734ec317fe937faa868bbbf70eb08`,原来仅有 Apache-2.0 LICENSE。 -- AstrBot:v4.29.4,`61335414433db721b3f7ecc93f90deafe0a59d78`。 -- 发布列表中有更新的 v4.30.0-alpha.1;虽然 GitHub `prerelease` 字段为 false,版本名仍为 alpha,本次没有作为稳定目标。 -- ba-dragon:`072dc9bc2d73ffc87000c1d3db4c0f9b4dcab549`,接口研究细节见 API_NOTES.md。 -- wows-stats-bot:`80c86970685887578054e61e1a76d1589ea1dc31`,只参考 README 中绑定/@ 查询的交互方式。 -- OpenAI Native 插件:`98bd76784bb2a35df0aea968138f87fd4d9ee207`,按用户指定参考额度交互和配置设计;本次采用用户默认 20、群默认 100、总额固定 100 及北京时间 0 点重置。 -- AstrBot T2I:`bcc08e47274c69e5ace19bbf738b95260ce17ca7`,核对视口、像素比、截图类型参数。运行插件使用 390 CSS 像素视口与 ultra 像素比;JPEG 质量 85。实际用户部署的渲染服务版本仍需联调。 - -## 环境和执行命令 - -Windows,Python 3.11.4;httpx 0.28.1、aiosqlite 0.22.1、Jinja2 3.1.6、pytest 9.2.0、pytest-asyncio 1.5.0、Playwright 1.65.2、tzdata 2026.6。 -本地 Chromium 为 159.0.8154.6(Playwright build 1255)。这是测试环境记录,不是对所有环境的兼容承诺。 - -会话工作目录:`H:\Codex\01a1e923-f766-7562-b804-35854a994fc4`;以下命令在其中的 `astrbot_plugin_ba_stats` 仓库执行。 +## 执行与证据 ```powershell -& ../.venv/Scripts/python.exe -m pytest -q --basetemp=../tmp/pytest-quota-final -# 392 passed in 19.49s - -$env:PLAYWRIGHT_BROWSERS_PATH = '../.playwright' -& ../.venv/Scripts/python.exe -B tools/render_previews.py --screenshots -# Synthetic previews: 18 HTML/text pairs; 36 screenshots; 0 layout/network failures. +& ../.venv/Scripts/python.exe -X utf8 -m pytest -q --basetemp=../tmp/pytest-v012-final --junitxml=../validation/pytest-v0.1.2.xml +# 635 passed in 25.90s -& ../.venv/Scripts/python.exe -m compileall -q . -# exit 0 -``` - -最初依赖安装遇到 Windows 临时目录写入限制,改用会话内临时目录后安装成功。Chromium 下载的一次连接重置由下载器切换官方镜像后恢复;最终安装成功。未更改共享环境、系统 ACL、SSH 配置或用户密钥。 - -## 测试覆盖的风险 - -- 命令别名一致、`recent 10` 和 `me recent 10`、带目标 `--limit`、空格昵称、数字/关键词昵称、真实结构化 @ 与手写标记拒绝。 -- STB/Steam 分离、未验证映射明确失败、规范 ID 回显核对、同名去重及候选截断提示。 -- 平台/用户/会话隔离、旧异步结果晚到、过期和越界、单次选择、选择期间新操作与跨群解绑竞争。 -- 只读选择不改绑定、绑定重启持久、失败保留原绑定、清缓存不删绑定。 -- 已确认字段的归一化、未知胜负/模式、数量和价值分离、缺失/零损失、重复与乱序对局。 -- 新鲜/旧缓存、同请求合并、force 刷新竞争、有界队列、限流/超时/鉴权/结构错误、取消和关闭恢复。 -- 管理员权限、未配置时本地命令、同一结果渲染失败回退、模板转义与 `{{7*7}}` 作为文字保留、卸载关闭资源。 -- 每用户默认 20、每群默认 100 可调,总上限 100 固定;并发及多 SQLite 连接同时扣额不超限,任一桶不足时其他桶不扣额。 -- 用户跨群及私聊累计、群跨用户累计、不同平台身份隔离、查询 @ 群友扣发送者;管理员查询无豁免,缓存与本地命令不扣额。 -- 北京时间 23:59:59/00:00 日期切换、跨午夜排队、重开数据库/清缓存/改凭据保留计数、提交前取消及异常回滚。 -- 每次 HTTP 尝试在发送前记账,失败及重试计入;设置项没有总额度或日界时区的可调入口。 -- 子代理复现的「额度耗尽后受退避阻塞,先超时再回退旧缓存」已修复:增加只读预检及回退前复核,新增回归测试通过。 - -## 图像验证 +& ../.venv/Scripts/python.exe -X utf8 -B tools/render_previews.py --screenshots +# 18 HTML/text pairs; 36 screenshots; 0 layout/network failures -预览矩阵:overview/recent/match × normal/long-name/missing × dark/light;每组检查 980px 和 390px。 -浏览器 context 使用离线模式并拦截外部请求,未打开外部网页、账号或登录态。 +& ../.venv/Scripts/python.exe -X utf8 -B tools/check_settings_view.py +# 2 local browser scenarios passed; 4 screenshots; no external requests -主代理实际打开并检查: - -- `overview-normal-dark-desktop.png`:主要数字、单位、样本范围与来源层级。 -- `recent-normal-light-mobile.png`:手机尺寸的逐局阅读、明确胜负样本标签、数量/价值指标区分。 -- `match-missing-light-mobile.png`:缺失字段、不完整队伍、零人队伍与旧缓存说明。 -- `overview-long-name-light-mobile.png`:长中文/英文、长 ID、Jinja 字面文本、折行不裁切。 - -预览明确标注「合成样本 · 非真实玩家战绩」。其中用于展示胜负、排位等状态的合成字段,不表示当前 BATrace 适配器已获得这些字段的权威语义。生产适配器对此保持未知。 -截图与 `manifest.json` 随总交付 ZIP 提供;布局自动检查与目视检查分别记录,不替代真实 QQ 图片显示验收。 +uv --cache-dir ../tmp/uv-cache pip check --python ../.venv/Scripts/python.exe +# All installed packages are compatible +``` -新增额度功能的可见界面变化为命令文字和原生设置;三类卡片模板和样式未修改,复用上述已经通过的本地渲染检查。 +主代理目视检查了近期浅色手机卡、玩家概览、单局深色宽图、常用设置浅色桌面页和诊断深色手机页。卡片矩阵含正常、长昵称、缺失数据三组,深浅两色,900/390px;预览均标明合成样本。浏览器拦截外部请求,只使用本地生成内容,没有使用外部账号或登录态。 -## 安装包与文案交付 +会话目录:`H:/Codex/01a1e923-f766-7562-b804-35854a994fc4`。Python 3.11.4;Playwright 1.65.2,本地 Chromium 159.0.8154.6。主测试使用 httpx.MockTransport、临时 SQLite 和 AstrBot 桩;没有访问真实战绩、QQ 账号、数据库或运行配置。 -构建工具:`python tools/build_delivery.py`。 +## 固定来源与交付 -- 插件 ZIP 有单一 `astrbot_plugin_ba_stats/` 根目录及原生入口、元数据、配置、依赖、模板和文档。 -- 完整源码另含测试和开发工具;安装 ZIP 不包含测试环境、真实凭据、个人数据库、缓存、Git 目录或参考项目源码。 -- 文案优化 ZIP 包含 Gemini 任务说明、事实约束、带位置的 JSON/CSV 清单、README、原始提示与模板,以及合成预览。占位符、命令、配置键和数据口径标为不可随意修改。 -- 总 ZIP 与嵌套 ZIP 使用 `testzip()` 检查,保存源码 SHA-256,原始 Logo 哈希如下。 +- AstrBot v4.29.4:`61335414433db721b3f7ecc93f90deafe0a59d78`。 +- ba-dragon:`072dc9bc2d73ffc87000c1d3db4c0f9b4dcab549`。 +- AstrBot T2I:`bcc08e47274c69e5ace19bbf738b95260ce17ca7`。 +- 设置中心仅参考 `anka-afk/astrbot_plugin_meme_manager` 的分组、折叠与共享配置交互,代码独立实现。 -```text -logo.png -7b93b4513cc84535155e4e4edf63b7a36b17321823e05ce0b494369d03b6e616 +`tools/build_delivery.py --output ../delivery/v0.1.2` 生成安装 ZIP、Gemini 文案优化 ZIP 及总交付 ZIP。安装包包含原生入口、元数据、配置、模板、设置视图、标题翻译、模型和许可;不含测试环境、个人数据库、缓存、真实凭据或参考项目源码。文案包覆盖提示、配置、HTML/JS、README、CHANGELOG,保留占位符、固定文字与许可约束。各 ZIP 用 `testzip()` 校验并附 SHA-256。 -assets/readme-logo.png -2acb2855440c8ec609370789866857ca80e9c4c73a1cd1379f9b23d5c15e65a7 -``` +原 Logo 保持不变: -## 下一步真实验收 +- `logo.png`:`7b93b4513cc84535155e4e4edf63b7a36b17321823e05ce0b494369d03b6e616` +- `assets/readme-logo.png`:`2acb2855440c8ec609370789866857ca80e9c4c73a1cd1379f9b23d5c15e65a7` -先取得本插件可用的 API origin、获准身份/鉴权方式、接口范围、请求额度与缓存政策。按 API_NOTES.md 的最小调用步骤验证 ID 回显、时间单位、胜负/模式与字段结构,再在明确授权的 AstrBot/QQ 测试会话验收绑定、搜索和三类战报。没有这些条件时保持在线开关关闭。 +v0.1.1 的命令正文/真实 At、超过 3 人改用 ID 绑定、发送失败文字回退,以及持久额度、北京时间日界、并发扣额、缓存与绑定隔离回归均包含在本次完整测试中。历史文案导入及早期验证见 Git 历史。 diff --git a/main.py b/main.py index dc4aae6..2c6702e 100644 --- a/main.py +++ b/main.py @@ -2,7 +2,7 @@ from __future__ import annotations import asyncio -from dataclasses import fields +from dataclasses import fields, replace import hashlib from pathlib import Path import re @@ -13,14 +13,17 @@ from astrbot.api.event import AstrMessageEvent, filter from astrbot.api.message_components import At, Plain from astrbot.api.star import Context, Star, StarTools +from astrbot.api.web import error_response, json_response, request, stream_response from .client import BatraceClient, ClientConfig, ClientError from .commands import mention_token, parse_command +from .diagnostics import DiagnosticLog from .quota import GLOBAL_DAILY_LIMIT, QuotaActor from .render import Renderer from .service import Caller, StatsService from .settings import Settings from .storage import Storage +from .web_settings import SettingsError, WebSettings def extract_arguments(event, prefixes): @@ -74,20 +77,83 @@ def __init__(self, context: Context, config: AstrBotConfig): super().__init__(context) self.settings = Settings.from_config(config) self.data_dir = StarTools.get_data_dir("astrbot_plugin_ba_stats") + self.diagnostics = DiagnosticLog(self.data_dir / "diagnostics", enabled=self.settings.diagnostics_enabled) self.storage = Storage(self.data_dir, max_entries=self.settings.cache_max_entries) values = {f.name: getattr(self.settings, f.name) for f in fields(ClientConfig)} self.client = BatraceClient(ClientConfig(**values), storage=self.storage) + self.client.diagnostics = self.diagnostics.record self.service = StatsService(self.client, self.storage, self.settings) self.renderer = Renderer(self.settings.theme, self.settings.timezone) self._images = self.data_dir / "images" self._image_lock = asyncio.Lock() self._tasks = set() self._closed = False + self.web_settings = WebSettings(config, self.settings, self.diagnostics) + # v4.29.4 exposes these through authenticated /api/v1/plugins/extensions/. + self._web_routes = { + "/astrbot_plugin_ba_stats/diagnostics/status": (self._diagnostics_status, ["GET"]), + "/astrbot_plugin_ba_stats/diagnostics/download": (self._download_diagnostics, ["GET"]), + "/astrbot_plugin_ba_stats/settings/config": (self._settings_config, ["GET", "POST"]), + } + for route, (handler, methods) in self._web_routes.items(): + context.register_web_api(route, handler, methods, "断箭战报设置中心") + + async def _settings_config(self): + if not request.username: + return error_response("请先登录 AstrBot 管理面板。", status_code=401, + headers={"Cache-Control": "no-store"}) + if self._closed: + return error_response("插件已关闭,请重载插件后重试。", status_code=503, + headers={"Cache-Control": "no-store"}) + try: + payload = await request.json() if request.method == "POST" else None + except (ValueError, TypeError): + return error_response("请求不是有效的 JSON 对象。", status_code=400, + headers={"Cache-Control": "no-store"}) + if self._closed: + return error_response("插件已关闭,请刷新后重试。", status_code=503, + headers={"Cache-Control": "no-store"}) + try: + data = self.web_settings.save(payload) if request.method == "POST" else self.web_settings.snapshot() + except SettingsError as exc: + return error_response(str(exc), status_code=exc.status_code, + headers={"Cache-Control": "no-store"}) + if request.method == "POST": + self.settings = replace(self.settings, diagnostics_enabled=self.diagnostics.enabled) + return json_response(data, headers={"Cache-Control": "no-store"}) + + async def _diagnostics_status(self): + if not request.username: + return error_response("请先登录 AstrBot 管理面板。", status_code=401, + headers={"Cache-Control": "no-store"}) + if self._closed: + return error_response("插件已关闭,请重载插件后重试。", status_code=503, + headers={"Cache-Control": "no-store"}) + return json_response(self.diagnostics.stats(), headers={"Cache-Control": "no-store"}) + + async def _download_diagnostics(self): + if not request.username: + return error_response("请先登录 AstrBot 管理面板。", status_code=401, + headers={"Cache-Control": "no-store"}) + if self._closed: + return error_response("插件已关闭,请重载插件后重试。", status_code=503, + headers={"Cache-Control": "no-store"}) + try: + data = await asyncio.to_thread(self.diagnostics.export_zip) + except OSError: + return error_response("读取诊断日志失败,请检查日志目录后重试。", status_code=500, + headers={"Cache-Control": "no-store"}) + return stream_response( + iter([data]), content_type="application/zip", + headers={"Content-Disposition": 'attachment; filename="ba-stats-diagnostics.zip"', + "Cache-Control": "no-store"}, + ) async def initialize(self): await self.storage.open() self._images.mkdir(parents=True, exist_ok=True) self._prune_images() + self.diagnostics.record("plugin_start", status="0.1.2") async def _run(self, awaitable): if self._closed: @@ -114,13 +180,14 @@ async def _image(self, view, umo): destination = self._images / f"{digest}.jpg" async with self._image_lock: if destination.exists() and time.time() - destination.stat().st_mtime <= 86400: + self.diagnostics.record("image_cache", path=destination.name, image_bytes=destination.stat().st_size) return str(destination) # Final HTML is DATA, never a second Jinja template. This preserves # literal {{...}} in nicknames after the first HTML escaping pass. source = await self.html_render( "{{ body | safe }}", {"body": html}, return_url=False, options={"type": "jpeg", "quality": 85, "full_page": True, - "viewport_width": 390, "device_scale_factor_level": "ultra"}, umo=umo) + "viewport_width": 900 if view.get("kind") == "match" else 390, "device_scale_factor_level": "ultra"}, umo=umo) if not Path(source).is_file(): raise ValueError("渲染服务未返回本地图片。") shutil.copyfile(source, destination) @@ -134,13 +201,13 @@ async def _status(self): "schema": "响应结构变化", "identity_mismatch": "身份校验失败", "no_data": "暂无收录", "upstream": "上游暂不可用", "queue_full": "队列已满", "not_configured": "接入未配置", "closed": "客户端已关闭", "daily_quota": "每日额度已用完"} - return (f"断箭战报 v0.1.1\n接入配置:{'已填写(不代表联调通过)' if status['configured'] else '未配置'}\n" + return (f"断箭战报 v0.1.2\n在线查询:{'已启用' if status['configured'] else '未启用或 API 地址无效'}\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" f"图片缓存:{len(list(self._images.glob('*.jpg')))} 张\n" f"最近错误:{labels.get(status['last_error'], '无' if not status['last_error'] else '请求失败')}\n" - "真实接口与 QQ 平台验收待完成。") + f"诊断模式:{'已开启' if self.settings.diagnostics_enabled else '已关闭'}") async def _quota(self, actor): usage = await self.storage.quota_usage(actor) @@ -173,6 +240,28 @@ def _response_result(self, event, response, config): # Instructions must remain copyable, and At components must stay interactive. return event.chain_result(parts).use_t2i(False) + def _log_image_send_failure(self, exc, path): + result = getattr(exc, "result", None) + result = result if isinstance(result, dict) else {} + # Include only diagnostic OneBot fields, never its payload/echo/base64. + detail = str(result.get("message") or result.get("wording") or "无平台错误详情")[:512] + detail = re.sub(r"base64://\S+|https?://\S+", "[已省略]", detail) + detail = " ".join(detail.split()) + try: + image_path = Path(path) + size = image_path.stat().st_size + with image_path.open("rb") as source: + signature = source.read(8) + image_type = "JPEG" if signature.startswith(b"\xff\xd8\xff") else ( + "PNG" if signature == b"\x89PNG\r\n\x1a\n" else "未知") + except OSError: + size, image_type = "不可读取", "未知" + self.logger.warning( + "断箭战报图片发送未获成功确认(%s,retcode=%s,%s);图片=%s;格式=%s;字节数=%s。改发文字。", + type(exc).__name__, result.get("retcode", "未知"), detail, path, image_type, size) + self.diagnostics.record("image_send_error", error=type(exc).__name__, retcode=result.get("retcode"), + message=detail, path=Path(path).name, image_type=image_type, image_bytes=size) + @filter.command("ba", alias={"BA", "Ba", "bA"}) async def ba(self, event: AstrMessageEvent): if self._closed: @@ -180,10 +269,12 @@ async def ba(self, event: AstrMessageEvent): event.stop_event() config = self.context.get_config(event.unified_msg_origin) or {} prefixes = config.get("wake_prefix", ["/"]) + started = time.monotonic() try: text, mentions = extract_arguments(event, prefixes) request = parse_command(text, mentions, self.settings.default_limit, self.settings.max_limit, self.settings.chinese_aliases) + self.diagnostics.record("command_start", action=request.action) caller = Caller(str(event.get_platform_id()), event.unified_msg_origin, str(event.get_sender_id())) if request.action == "quota": @@ -205,6 +296,9 @@ async def ba(self, event: AstrMessageEvent): return with self.client.request_scope(quota_actor(event)): response = await self._run(self.service.execute(request, caller)) + self.diagnostics.record("query_complete", action=request.action, + kind=response.view.get("kind") if response.view else "text", + duration_ms=round((time.monotonic() - started) * 1000)) if response.text: yield self._response_result(event, response, config) if response.view is not None: @@ -212,38 +306,58 @@ async def ba(self, event: AstrMessageEvent): for view in self.renderer.views(response.view): send_uncertain = False if send_images: + stage_started = time.monotonic() try: path = await self._run(self._image(view, event.unified_msg_origin)) - except Exception: + except Exception as exc: + self.diagnostics.record("image_render_error", error=type(exc).__name__, + duration_ms=round((time.monotonic() - stage_started) * 1000)) self.logger.warning("断箭战报图片渲染失败,已使用相同查询结果回复文字。") else: + self.diagnostics.record("image_render_complete", kind=view.get("kind"), path=Path(path).name, + duration_ms=round((time.monotonic() - stage_started) * 1000)) + stage_started = time.monotonic() + self.diagnostics.record("image_send_start", path=Path(path).name) 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__) + self._log_image_send_failure(exc, path) send_uncertain = True else: + self.diagnostics.record("image_send_complete", path=Path(path).name, + duration_ms=round((time.monotonic() - stage_started) * 1000)) continue send_images = False text = self.renderer.text(view) + self.diagnostics.record("text_report", kind=view.get("kind"), page=view.get("page", 1)) 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: + self.diagnostics.record("command_error", error=type(exc).__name__, status=getattr(exc, "code", "invalid_input")) yield event.plain_result(str(exc)) except asyncio.TimeoutError: + self.diagnostics.record("command_error", error="timeout") yield event.plain_result("查询等待超时,请稍后重试。") except Exception as exc: + self.diagnostics.record("command_error", error=type(exc).__name__) # Neither response bodies nor credential-bearing URLs enter logs. self.logger.error("断箭战报请求失败(%s)。", type(exc).__name__) yield event.plain_result("本次查询未完成,请稍后重试;如持续出现,请管理员使用 ba status 检查插件状态。") async def terminate(self): self._closed = True + # Remove only this instance's handlers. A newer instance may already + # have replaced the same routes during plugin reload. + apis = self.context.registered_web_apis + apis[:] = [api for api in apis if not ( + api[0] in self._web_routes + and (api[1], api[2]) == self._web_routes[api[0]] + )] tasks = list(self._tasks) for task in tasks: task.cancel() @@ -253,3 +367,5 @@ async def terminate(self): self.service.close() await self.client.close() await self.storage.close() + self.diagnostics.record("plugin_stop") + self.diagnostics.close() diff --git a/metadata.yaml b/metadata.yaml index 2ee20bc..dc0c4f9 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -1,8 +1,8 @@ name: astrbot_plugin_ba_stats display_name: 断箭战报 -short_desc: "《断箭》玩家战绩查询,支持账号绑定与图片战报。" -desc: "查询《断箭》(Broken Arrow)玩家概览、近期战绩和单局战报,支持账号绑定、群友查询及图片或文字展示。使用前需配置 BATrace 接入。" -version: "0.1.1" +short_desc: "《断箭》战绩查询,支持逐局评分、赛前预测与图片战报。" +desc: "查询《断箭》(Broken Arrow)玩家概览、近期战绩和单局战报,展示逐局评分、赛前预测、双方对比与兵种构成,支持账号绑定、群友查询及图片或文字展示。在设置中心或原生插件配置中开启在线查询后使用。" +version: "0.1.2" author: timeance repo: https://github.com/timeance/astrbot_plugin_BA_stats astrbot_version: ">=4.29.4" diff --git a/models.py b/models.py index 31e52e7..ec5d713 100644 --- a/models.py +++ b/models.py @@ -26,6 +26,8 @@ class Player: source_url: str | None = None updated_at: datetime | None = None elo_observed_at: datetime | None = None + # Source analysis keys are retained; IDs, numbers, booleans and times are normalized. + analysis: dict[str, Any] = field(default_factory=dict) @dataclass @@ -41,6 +43,15 @@ class Participant: destroyed_value: float | None = None lost_value: float | None = None units: list[dict[str, Any]] = field(default_factory=list) + damage_dealt: float | None = None + damage_received: float | None = None + objectives: int | None = None + spawned_value: float | None = None + supply: float | None = None + # Keep the pre-match observation even when NewRating is unavailable. + elo_before: float | None = None + # An empty supplied UnitData is different from a missing UnitData. + units_available: bool = False @dataclass @@ -55,6 +66,9 @@ class Match: complete: bool = False source_url: str | None = None updated_at: datetime | None = None + map_id: str | None = None + # Start/end are source observations, never inferred from duration. + ended_at: datetime | None = None @dataclass @@ -130,6 +144,109 @@ def _name(value: Any) -> str: return value +def _nonnegative(value: Any) -> float | None: + result = _number(value) + if result is not None and result < 0: + raise ValueError("expected a nonnegative number") + return result + + +def _percentage(value: Any) -> float | None: + result = _nonnegative(value) + if result is not None and result > 100: + raise ValueError("expected a percentage in 0..100") + return result + + +def _array(obj: dict[str, Any], key: str) -> list: + result = obj.get(key, []) + if not isinstance(result, list): + raise ValueError(f"invalid {key} array") + return result + + +def _parse_analysis(payload: Any) -> dict[str, Any]: + analysis = _object(payload) + if "matchCount" not in analysis and "trend" not in analysis: + raise ValueError("missing player analysis") + trend = _object(analysis.get("trend", {})) + points: list[dict[str, Any]] = [] + positions: dict[str, int] = {} + results: dict[str, set[bool]] = {} + for raw in _array(trend, "points"): + row = _object(raw) + won = row.get("won") + if won is not None and not isinstance(won, bool): + raise ValueError("expected a boolean won") + point = { + "matchId": canonical_id(row["matchId"]) if row.get("matchId") is not None else None, + "won": won, + "ratingBefore": _number(row.get("ratingBefore")), + "ratingAfter": _number(row.get("ratingAfter")), + "kdRatio": _nonnegative(row.get("kdRatio")), + "dmr": _nonnegative(row.get("dmr")), + "destructionScore": _nonnegative(row.get("destructionScore")), + "lossesScore": _nonnegative(row.get("lossesScore")), + "objectivesCaptured": _number(row.get("objectivesCaptured"), count=True), + "endTime": utc_datetime(row.get("endTime")), + } + mid = point["matchId"] + if mid is None: + points.append(point) + continue + outcomes = results.setdefault(mid, set()) + if won is not None: + outcomes.add(won) + if mid not in positions: + positions[mid] = len(points) + points.append(point) + else: + previous = points[positions[mid]] + # Keep the newest dated record, but never resolve contradictory results by order. + if point["endTime"] is not None and ( + previous["endTime"] is None or point["endTime"] > previous["endTime"] + ): + points[positions[mid]] = point + points[positions[mid]]["won"] = next(iter(outcomes)) if len(outcomes) == 1 else None + units = [] + for raw in _array(analysis, "highlightUnits"): + row = _object(raw) + units.append({ + "unitId": canonical_id(row.get("unitId")), + "unitName": _name(row.get("unitName")) or None, + "spawnCount": _number(row.get("spawnCount"), count=True), + "totalDamage": _nonnegative(row.get("totalDamage")), + "avgRoi": _number(row.get("avgRoi")), + **({"categoryType": _number(row["categoryType"], count=True)} + if "categoryType" in row else {}), + **({"totalCost": _nonnegative(row["totalCost"])} if "totalCost" in row else {}), + }) + categories = [] + for raw in _array(analysis, "categoryPreferences"): + row = _object(raw) + categories.append({ + "categoryKey": canonical_id(row.get("categoryKey")), + "percentage": _percentage(row.get("percentage")), + **({"totalCost": _nonnegative(row["totalCost"])} if "totalCost" in row else {}), + }) + maps = [] + for raw in _array(analysis, "mapPerformance"): + row = _object(raw) + maps.append({ + "mapId": canonical_id(row.get("mapId")), + "mapName": _name(row.get("mapName")) or None, + "matchCount": _number(row.get("matchCount"), count=True), + "winRate": _percentage(row.get("winRate")), + }) + return { + "matchCount": _number(analysis.get("matchCount"), count=True), + "trend": {"points": points}, + "highlightUnits": units, + "categoryPreferences": categories, + "mapPerformance": maps, + } + + def parse_search(payload: Any) -> list[Player]: """Search has an explicit players array; missing arrays are schema failures.""" rows = _object(payload).get("players") @@ -164,20 +281,11 @@ def parse_player(payload: Any, requested_id: str) -> Player: player = next((p for p in candidates if p.id == requested_id), None) if player is None: raise ValueError("canonical player ID was not echoed") - analysis = _object(envelope.get("analysis")) - if "matchCount" not in analysis and "trend" not in analysis: - raise ValueError("missing player analysis") - if "matchCount" in analysis: - _number(analysis["matchCount"], count=True) - trend = _object(analysis.get("trend", {})) - points = trend.get("points", []) - if not isinstance(points, list): - raise ValueError("invalid trend points") + player.analysis = _parse_analysis(envelope.get("analysis")) observations: list[tuple[datetime, float]] = [] - for row in points: - point = _object(row) - rating = _number(point.get("ratingAfter")) - at = utc_datetime(point.get("endTime")) + for point in player.analysis["trend"]["points"]: + rating = point["ratingAfter"] + at = point["endTime"] if rating is not None and at is not None: observations.append((at, rating)) if observations: @@ -220,10 +328,17 @@ def parse_match(payload: Any, requested_id: str, *, detail: bool = True) -> Matc normalized_units = [] for unit in units.values(): unit = _object(unit) + refunded = unit.get("WasRefunded", False) + if not isinstance(refunded, bool): + raise ValueError("expected a boolean WasRefunded") normalized_units.append({ "id": canonical_id(unit.get("Id")), "name": _name(unit.get("Name")) or None, "count": 1, + "spawn_time": _nonnegative(unit.get("SpawnTime", 0)), + "death_time": _nonnegative(unit.get("DeathTime", 0)), + "was_refunded": refunded, + "killed_count": _number(unit.get("KilledCount", 0), count=True), }) players.append(Participant( player_id=pid, name=_name(row.get("Name")), team=str(team), @@ -232,15 +347,18 @@ def parse_match(payload: Any, requested_id: str, *, detail: bool = True) -> Matc losses=_number(row.get("Losses", 0), count=True), destroyed_value=_number(row.get("DestructionScore", 0)), lost_value=_number(row.get("LossesScore", 0)), units=normalized_units, + damage_dealt=_nonnegative(row.get("DamageDealt")), + damage_received=_nonnegative(row.get("DamageReceived")), + objectives=_number(row.get("ObjectivesCaptured"), count=True), + spawned_value=_nonnegative(row.get("TotalSpawnedUnitScore")), + supply=_nonnegative(row.get("SupplyPointsConsumed")), + elo_before=old, units_available="UnitData" in row, )) duration = _number(info.get("TotalPlayTimeInSec")) if duration is not None and duration < 0: raise ValueError("negative duration") start = utc_datetime(info.get("StartTime")) end = utc_datetime(info.get("EndTime")) - if start is None and end is not None and duration is not None: - from datetime import timedelta - start = end - timedelta(seconds=duration) if end is not None and start is not None and end < start: raise ValueError("match ends before it starts") # The reference infers victory from rating changes. This is not an @@ -250,9 +368,11 @@ def parse_match(payload: Any, requested_id: str, *, detail: bool = True) -> Matc complete = detail and bool(players) and end is not None and all( isinstance(row, dict) and isinstance(row.get("UnitData"), dict) for row in rows.values() ) + map_id = canonical_id(info["MapId"]) if "MapId" in info else None return Match( - id=requested_id, map_name=(f"地图#{canonical_id(info['MapId'])}" if "MapId" in info else None), - started_at=start, duration_seconds=duration, + id=requested_id, map_name=(f"地图#{map_id}" if map_id is not None else None), + map_id=map_id, + started_at=start, duration_seconds=duration, ended_at=end, players=players, complete=complete, source_url=SOURCE_URL + "match/" + quote(requested_id, safe=""), ) @@ -271,4 +391,4 @@ def parse_recent(payload: Any) -> list[Match]: result[mid] = match from datetime import timezone minimum = datetime.min.replace(tzinfo=timezone.utc) - return sorted(result.values(), key=lambda m: (m.started_at or minimum, m.id), reverse=True) + return sorted(result.values(), key=lambda m: (m.ended_at or m.started_at or minimum, m.id), reverse=True) diff --git a/render.py b/render.py index 2567093..cdd2537 100644 --- a/render.py +++ b/render.py @@ -39,6 +39,7 @@ from __future__ import annotations from collections.abc import Mapping +import base64 from copy import deepcopy from datetime import datetime from decimal import Decimal, InvalidOperation @@ -123,6 +124,8 @@ def __init__(self, theme: str = "dark", timezone: str = "Asia/Shanghai"): raise ValueError("theme must be dark or light") self.theme = theme self.timezone = ZoneInfo(timezone) + self._avatar = "data:image/png;base64," + base64.b64encode( + (Path(__file__).parent / "assets" / "github-avatar.png").read_bytes()).decode("ascii") self._environment = Environment( loader=FileSystemLoader(Path(__file__).with_name("templates")), autoescape=select_autoescape(("html",)), @@ -195,20 +198,33 @@ def _metric(metric: Mapping) -> dict: } def _exchange(self, item: Mapping, *, elo: bool = False) -> list[dict]: - fields = [ - ("kills", "摧毁单位", "integer", "个"), - ("losses", "损失单位", "integer", "个"), - ("unit_exchange", "单位交换比", "decimal", ""), - ("destroyed_value", "摧毁价值", "decimal", ""), - ("lost_value", "损失价值", "decimal", ""), - ("value_exchange", "价值交换比", "decimal", ""), - ] + """Pair comparable values, preserving zero and unknown independently.""" + def value(key, style="decimal"): + raw = item.get(key) + return _plain(raw) if isinstance(raw, str) else _numeric(raw, style) + + def pair(first, second, style="decimal"): + return f"{value(first, style)} / {value(second, style)}" + + metrics = [] + if elo: + rating = value("elo") + delta = value("elo_delta", "signed") + metrics.append({"label": "ELO", "value": rating + (f" ({delta})" if delta != MISSING else "")}) + metrics.extend([ + {"label": "分值 K/D", "value": value("value_exchange")}, + {"label": "摧毁 / 损失", "value": pair("destroyed_value", "lost_value")}, + {"label": "击杀 / 阵亡", "value": pair("kills", "losses", "integer")}, + ]) if elo: - fields = [("elo", "ELO", "decimal", ""), ("elo_delta", "ELO 变化", "signed", "")] + fields - return [ - self._metric({"label": label, "value": item.get(key), "format": style, "unit": unit}) - for key, label, style, unit in fields - ] + if any(item.get(key) is not None for key in ("damage_dealt", "damage_received")): + metrics.append({"label": "伤害 / 承伤", "value": pair("damage_dealt", "damage_received")}) + for key, label, style in (("objectives", "占点", "integer"), + ("spawned_value", "出兵花费", "decimal"), + ("supply", "补给消耗", "decimal")): + if item.get(key) is not None: + metrics.append({"label": label, "value": value(key, style)}) + return [self._metric(metric) for metric in metrics] def _prepare(self, view: dict) -> dict: kind = view.get("kind", "overview") @@ -218,6 +234,7 @@ def _prepare(self, view: dict) -> dict: match = _mapping(view.get("match")) prepared = { "kind": kind, + "avatar": self._avatar, "title": _plain(view.get("title"), _TITLES[kind]), "theme": self.theme, "player": { @@ -234,15 +251,25 @@ def _prepare(self, view: dict) -> dict: "synthetic": view.get("synthetic") is True, "notes": [_plain(note) for note in view.get("notes", [])] if isinstance(view.get("notes"), (list, tuple)) else [], "common_units": [ - {"name": _plain(item.get("name")), "count": _numeric(item.get("count"), "integer")} + {"name": _plain(item.get("name")), "count": _numeric(item.get("count"), "integer"), + "damage": _numeric(item.get("damage")), "roi": _numeric(item.get("roi"))} for item in _records(view.get("common_units")) ], + "analysis_scope": _plain(view.get("analysis_scope"), ""), + "categories": [{"name": _plain(item.get("name")), "percentage": _numeric(item.get("percentage"))} + for item in _records(view.get("categories"))], + "map_stats": [{"name": _plain(item.get("name")), "count": _numeric(item.get("count"), "integer"), + "win_rate": _numeric(item.get("win_rate"))} + for item in _records(view.get("map_stats"))], "rows": [], "teams": [], "pagination": "", } for item in _records(view.get("rows")): + score = _number(item.get("score")) prepared["rows"].append({ + "score": format(score, ".1f") if score is not None else MISSING, + "score_band": item.get("score_band") if item.get("score_band") in {"low", "medium", "high"} else "medium", "id": _plain(item.get("id")), "started_at": self._time(item.get("started_at")), "map_name": _plain(item.get("map_name")), @@ -260,16 +287,36 @@ def _prepare(self, view: dict) -> dict: "started_at": self._time(match.get("started_at")), "duration": self._duration(match.get("duration_seconds")), "winner": _plain(match.get("winner")), + "target_outcome": _outcome(match.get("target_outcome")), } for team in _records(view.get("teams")): prepared["teams"].append({ "name": _plain(team.get("name")), "outcome": _outcome(team.get("outcome")), + "metrics": [self._metric(item) for item in _records(team.get("metrics"))], + "composition": [{"name": _plain(item.get("name")), "percentage": _numeric(item.get("percentage")), + "width": float(max(0, min(100, _number(item.get("percentage")) or 0)))} + for item in _records(team.get("composition"))], + "composition_note": _plain(team.get("composition_note"), ""), "players": [ - {"id": _plain(item.get("id")), "name": _plain(item.get("name")), "metrics": self._exchange(item, elo=True)} + {"id": _plain(item.get("id")), "name": _plain(item.get("name")), + "is_target": bool(player.get("id")) and item.get("id") == player.get("id"), + "metrics": self._exchange(item, elo=True)} for item in _records(team.get("players")) ], }) + prediction = _mapping(view.get("prediction")) + a, b = _number(prediction.get("a")), _number(prediction.get("b")) + prepared["prediction"] = ({"a": _numeric(a), "b": _numeric(b), "width": float(a)} + if a is not None and b is not None and 0 <= a <= 100 and 0 <= b <= 100 else None) + # Each comparison row keeps the actual team order and both denominators. + labels = list(dict.fromkeys(m["label"] for team in prepared["teams"][:2] for m in team["metrics"])) + prepared["comparisons"] = [] + for label in labels: + pair = [next((m for m in team["metrics"] if m["label"] == label), None) for team in prepared["teams"][:2]] + if len(pair) == 2: + prepared["comparisons"].append({"label": label, "values": [m["display"] if m else MISSING for m in pair], + "notes": [m["note"] if m else "" for m in pair]}) page = _number(view.get("page")) page_count = _number(view.get("page_count")) row_total = _number(view.get("row_total")) @@ -284,63 +331,98 @@ def template(self, view: dict) -> str: return self._environment.get_template(f"{prepared['kind']}.html").render(view=prepared) def text(self, view: dict) -> str: - """Use the HTML presentation values verbatim in a readable fallback.""" + """Compact report using the same formatted facts as the image card.""" data = self._prepare(view) lines = [f"断箭战报 · {data['title']}"] if data["synthetic"]: lines.append("合成样本 · 非真实玩家战绩") if data["kind"] != "match" or data["player"]["id"] != MISSING: - lines.extend([data["player"]["name"], f"玩家 ID:{data['player']['id']}"]) - lines.append(f"统计范围:{data['scope']}") + lines.append(f"{data['player']['name']} · ID {data['player']['id']}") + if data["kind"] == "match" and data["match"]["target_outcome"]["key"] != "unknown": + lines[-1] += " · " + data["match"]["target_outcome"]["label"] + if data["scope"] != MISSING: + lines.append(data["scope"]) if data["pagination"]: lines.append(data["pagination"]) - for metric in data["metrics"]: - lines.append(f"{metric['label']}:{metric['display']}" + (f"({metric['note']})" if metric["note"] else "")) + + def metrics(items): + return " · ".join(f"{m['label']}:{m['display']}" + (f"({m['note']})" if m["note"] else "") for m in items) + if data["kind"] == "overview": + for offset in range(0, len(data["metrics"]), 2): + lines.append(metrics(data["metrics"][offset:offset + 2])) if not data["metrics"]: lines.append("统计指标:暂无") - lines.append("常用单位 / 兵种") - lines.extend(f"{unit['name']}:{unit['count']}" + (" 个" if unit["count"] != MISSING else "") for unit in data["common_units"]) - if not data["common_units"]: - lines.append(MISSING) + if data["analysis_scope"]: + lines.append(data["analysis_scope"]) + if data["categories"]: + lines.append("兵种:" + " · ".join(f"{c['name']} {c['percentage']}%" for c in data["categories"])) + if data["common_units"]: + lines.append("常用单位") + for unit in data["common_units"]: + detail = [f"{unit['count']} 次出场"] if unit['count'] != MISSING else [] + if unit['damage'] != MISSING: + detail.append(f"伤害 {unit['damage']}") + if unit['roi'] != MISSING: + detail.append(f"回报 {unit['roi']}") + lines.append(unit['name'] + (" · " + " · ".join(detail) if detail else "")) + if data["map_stats"]: + lines.append("地图表现") + for row in data["map_stats"]: + rate = row['win_rate'] + '%' if row['win_rate'] != MISSING else MISSING + lines.append(f"{row['name']} · {row['count']} 场 · 胜率 {rate}") elif data["kind"] == "recent": - for index, row in enumerate(data["rows"], 1): - lines.extend([ - f"{index}. {row['map_name']} · {row['outcome']['label']}", - f"对局 ID:{row['id']}", - f"时间:{row['started_at']} · 模式:{row['mode']} · 时长:{row['duration']}", - f"ELO 变化:{row['elo_delta']}", - ";".join(f"{metric['label']}:{metric['display']}" for metric in row["exchange"]), - ]) - if row["source_url"]: - lines.append(f"对局来源:{row['source_url']}") + for row in data["rows"]: + heading = [f"评分 {row['score']}", row['outcome']['label'], row['map_name']] + if row['duration'] != MISSING: + heading.append(row['duration']) + lines.append(" · ".join(heading)) + detail = [f"ELO {row['elo_delta']}"] if row['elo_delta'] != MISSING else [] + detail.extend(f"{m['label']} {m['display']}" for m in row['exchange']) + lines.append(" · ".join(detail)) + lines[-1] += f" · #{row['id']}" if not data["rows"]: lines.append("近期对局:暂无") else: match = data["match"] - lines.extend([ - f"对局 ID:{match['id']}", - f"地图:{match['map_name']} · 模式:{match['mode']}", - f"时间:{match['started_at']} · 时长:{match['duration']}", - f"胜方:{match['winner']}", - ]) + lines.append(f"#{match['id']} · {match['map_name']} · {match['duration']}") + meta = [] + if match['mode'] != MISSING: + meta.append(match['mode']) + if match['started_at'] != MISSING: + meta.append(match['started_at']) + if match['winner'] != MISSING: + meta.append(f"胜方:{match['winner']}") + if meta: + lines.append(" · ".join(meta)) + prediction = data["prediction"] + lines.append(f"赛前预测 A {prediction['a']}% : B {prediction['b']}%(按赛前 ELO 估算)" if prediction else "赛前预测:暂无") + if data["comparisons"]: + lines.append("双方对比(" + " / ".join(t["name"] for t in data["teams"][:2]) + ")") + for row in data["comparisons"]: + lines.append(f"{row['label']}:" + " / ".join(v + (f"({n})" if n else "") for v, n in zip(row['values'], row['notes']))) + lines.append("兵种构成(基础花费估算)") for team in data["teams"]: - lines.append(f"{team['name']} · {team['outcome']['label']} · {len(team['players'])} 人") + lines.append(team['name'] + ":" + (" · ".join(f"{c['name']} {c['percentage']}%" for c in team['composition']) or "暂无")) + if team['composition_note']: + lines.append(team['composition_note']) + lines.append("玩家") + for team in data["teams"]: + heading = f"{team['name']} · {len(team['players'])} 人" + if team['outcome']['key'] != 'unknown': + heading += " · " + team['outcome']['label'] + lines.extend(["", heading]) for player in team["players"]: - lines.append(f"{player['name']} · 玩家 ID:{player['id']}") - lines.append(";".join(f"{metric['label']}:{metric['display']}" for metric in player["metrics"])) + lines.append(player['name'] + ("(查询玩家)" if player['is_target'] else "")) + for offset in range(0, len(player['metrics']), 3): + lines.append(metrics(player['metrics'][offset:offset + 3])) if not team["players"]: lines.append("队员:暂无") if not data["teams"]: lines.append("分队与玩家:暂无") lines.extend(data["notes"]) if data["stale"]: - lines.append("旧缓存 · 以抓取时间为准") - lines.extend([ - f"抓取时间:{data['fetched_at']}", - f"来源更新:{data['source_updated_at']}", - f"数据来源:{data['source_url'] or MISSING}", - ]) - if data["player"]["source_url"] and data["player"]["source_url"] != data["source_url"]: - lines.append(f"玩家来源:{data['player']['source_url']}") + lines.append(f"旧缓存 · 抓取时间:{data['fetched_at']}") + if data["source_url"]: + lines.append(f"BATrace:{data['source_url']}") return "\n".join(lines) diff --git a/scoring.py b/scoring.py new file mode 100644 index 0000000..83c655b --- /dev/null +++ b/scoring.py @@ -0,0 +1,297 @@ +"""Per-match scoring adapted from ba-dragon, under the MIT license. + +Copyright (c) 2026 AlexanderHYu +Copyright (c) 2025-2026 Zola (Zawinzala) +Full original copyright, license and pinned source paths are bundled in +assets/scoring-model.json. Only computeDragonScore's individual career rows +are reproduced: no player aggregate, titles, or timeline. Missing career +composition uses the upstream avgRoles fallback; missing match inputs do not. +""" + +from __future__ import annotations + +import json +import math +from collections.abc import Mapping +from pathlib import Path +from typing import Literal + +try: + from .models import Match, Participant +except ImportError: # Standalone tests use the repository as their import root. + from models import Match, Participant + + +MODEL = json.loads((Path(__file__).parent / "assets" / "scoring-model.json").read_text(encoding="utf-8")) +ROLE_KEYS = ("armor", "inf", "recon", "arty", "aa", "heli", "jet") +CAT_KEYS = ("recon", "infantry", "vehicles", "support", "logistic", "helicopters", "aircrafts") +ROLE_NAMES = {"armor": "装甲", "inf": "步兵", "recon": "侦察", "arty": "炮兵", + "aa": "防空", "heli": "直升机", "jet": "固定翼", "_": "后勤/运输"} +# score.ts TRADE and TRADE_NORM, unchanged from the pinned source. +_TRADE_KILL = dict(armor=1.2, inf=1.2, recon=1.1, aa=1.0, heli=0.9, jet=0.8, arty=0.75) +_TRADE_LOSS = dict(armor=0.75, inf=0.7, recon=0.9, aa=1.0, heli=1.0, jet=1.1, arty=1.4) +_TRADE_NORM = {"kill": 0.9719, "loss": 1.1218} + + +def _finite(value) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def _nonnegative(value) -> bool: + return _finite(value) and value >= 0 + + +def _old_rating(person: Participant) -> float | None: + old = person.elo_before + if old is None and _finite(person.elo) and _finite(person.elo_delta): + old = person.elo - person.elo_delta + return float(old) if _finite(old) else None + + +def _expect(own: float, opponent: float) -> float: + exponent = (opponent - own) / MODEL["expect"]["scale"] + # Equivalent limits of the upstream Elo formula, without numeric overflow. + if exponent > 308: + return 0.0 + return 1 / (1 + 10 ** exponent) + + +def match_prediction(match: Match) -> dict[str, float] | None: + """A=team '0', B=team '1'; percentages in 0..100, using pre-match ELO. + + Every participant on both teams must have a pre-match observation. No AFK + penalty applies to a pre-match prediction. Spectators are excluded. + """ + teams = [[p for p in match.players if p.team == team] for team in ("0", "1")] + if any(not team for team in teams): + return None + averages = [] + for team in teams: + ratings = [_old_rating(p) for p in team] + if any(r is None for r in ratings): + return None + averages.append(sum(ratings) / len(ratings)) + a = 100 * _expect(*averages) + return {"a": a, "b": 100 - a} + + +def _career_roles(analysis: Mapping | None) -> dict[str, float] | None: + """rolesFromCareer, including the upstream prior of 30% category spend.""" + analysis = analysis or {} + categories = analysis.get("categoryPreferences", []) + highlights = analysis.get("highlightUnits", []) + if not isinstance(categories, list) or not isinstance(highlights, list): + return None + buckets = {} + for unit in highlights: + if not isinstance(unit, Mapping): + return None + category, cost = unit.get("categoryType"), unit.get("totalCost") + if not _nonnegative(category) or int(category) != category or not _nonnegative(cost): + return None + if category >= len(CAT_KEYS): + continue + bucket = buckets.setdefault(CAT_KEYS[int(category)], {"total": 0.0}) + bucket["total"] += cost + entry = MODEL["units"].get(str(unit.get("unitId"))) + role = entry[0] if entry and entry[0] else "_none" + bucket[role] = bucket.get(role, 0.0) + cost + roles = dict.fromkeys(ROLE_KEYS, 0.0) + for category in categories: + if not isinstance(category, Mapping) or not _nonnegative(category.get("totalCost")): + return None + key, spend = str(category.get("categoryKey")), category["totalCost"] + default = MODEL["catSplit"].get(key, {}) + bucket = buckets.get(key, {}) + prior = 0.3 * spend + denominator = bucket.get("total", 0) + prior + for role in ROLE_KEYS: + share = ((bucket.get(role, 0) + prior * default.get(role, 0)) / denominator + if denominator > 0 else default.get(role, 0)) + roles[role] += spend * share + total = sum(roles.values()) + if total <= 0: + return dict(MODEL["avgRoles"]) + return {role: value / total for role, value in roles.items()} + + +def _career_trade(roles: Mapping) -> tuple[float, float]: + """tradeMult({Id: stbid}, roles): no per-unit trade data in career rows.""" + total = sum(roles.get(role, 0) for role in ROLE_KEYS) + if total <= 0: + return 1.0, 1.0 + kill = sum(roles.get(role, 0) * _TRADE_KILL[role] for role in ROLE_KEYS) / total + loss = sum(roles.get(role, 0) * _TRADE_LOSS[role] for role in ROLE_KEYS) / total + return kill * _TRADE_NORM["kill"], loss * _TRADE_NORM["loss"] + + +def _inactive(match: Match, players: list[Participant]) -> set[str]: + """score.ts detectInactive; protobuf-zero counters are normalized upstream.""" + result = set() + start = match.started_at.timestamp() if match.started_at else 0 + duration = match.duration_seconds or 0 + for team_id in ("0", "1"): + team = [p for p in players if p.team == team_id] + average = sum(p.destroyed_value for p in team) / (len(team) or 1) + for p in team: + if p.destroyed_value + p.lost_value == 0: + result.add(p.player_id) + continue + spawns = [u.get("spawn_time") for u in p.units if _nonnegative(u.get("spawn_time")) + and u["spawn_time"] != 0] + if spawns and start and duration: + if (max(spawns) - start) / duration < 0.4 and p.destroyed_value < 0.15 * average: + result.add(p.player_id) + return result + + +def _match_features(match: Match, me: Participant, trade: tuple[float, float]) -> dict | None: + """The matchFeatures inputs used by computeDragonScore, with strict gaps.""" + players = [p for p in match.players if p.team in ("0", "1")] + if me.team not in ("0", "1") or not players: + return None + # Financial counters and rating observations cannot be reconstructed from + # analysis trend points or post-match team averages. + if any(not _nonnegative(p.destroyed_value) or not _nonnegative(p.lost_value) + or _old_rating(p) is None or not _finite(p.elo) for p in players): + return None + old = _old_rating(me) + if old is None or not _finite(me.elo) or abs(me.elo - old) < 0.01: + return None + team = [p for p in players if p.team == me.team] + opponent = [p for p in players if p.team != me.team] + if not team or not opponent: + return None + # Remove OTHER inactive players only: do not give oneself AFK relief. + inactive = _inactive(match, players) - {me.player_id} + active_team = [p for p in team if p.player_id not in inactive] + active_opponent = [p for p in opponent if p.player_id not in inactive] + average = lambda members: sum(_old_rating(p) for p in members) / len(members) + penalty = MODEL["expect"]["afkPenalty"] + # The upstream model explicitly uses 0.5 when an entire side is inactive. + expected = 0.5 + if active_team and active_opponent: + expected = _expect(average(active_team) - penalty * (len(team) - len(active_team)), + average(active_opponent) - penalty * (len(opponent) - len(active_opponent))) + kill, loss = trade + dw, lw = me.destroyed_value * kill, me.lost_value * loss + avg_dw = sum(p.destroyed_value * (kill if p.player_id == me.player_id else 1) + for p in active_team) / len(active_team) + # The pinned model gives objectives zero weight; retain upstream zero + # handling without treating a missing displayed objective as an observation. + if MODEL["weights"]["obj"] and any(not _nonnegative(p.objectives) for p in players): + return None + objectives = me.objectives or 0 + avg_objectives = sum(p.objectives or 0 for p in active_team) / len(active_team) + return {"eloN": (old - 2100) / 400, "gapN": (old - average(players)) / 400, + "S": 1 if me.elo > old else 0, "E": expected, + "x": {"kd": math.log2((dw + 200) / (lw + 200)), + "con": math.log2((dw + 200) / (avg_dw + 200)), + "obj": math.log2((objectives + 1) / (avg_objectives + 1))}} + + +def _percentile(value: float, quantiles: list[float]) -> float: + """score.ts pctOf: linear interpolation in the fitted empirical CDF.""" + n = len(quantiles) - 1 + if value <= quantiles[0]: + return 0.0 + if value >= quantiles[n]: + return 1.0 + lo, hi = 0, n + while hi - lo > 1: + mid = (lo + hi) >> 1 + if quantiles[mid] <= value: + lo = mid + else: + hi = mid + span = quantiles[hi] - quantiles[lo] + return (lo + ((value - quantiles[lo]) / span if span > 0 else 0.5)) / n + + +def _to10(percentile: float) -> float: + # JS Math.round differs from Python round at exactly half-way values. + return math.floor((1 + 9 * percentile) * 10 + 0.5) / 10 + + +def recent_score(match: Match, participant: Participant, analysis: Mapping | None) -> float | None: + """Return the exact individual computeDragonScore career-row score, 1..10. + + Career categories with missing spend or highlight category/cost return None. + Empty career composition uses MODEL.avgRoles, exactly as upstream does. + UnitData affects the upstream AFK detector but never replaces career roles + or supplies per-unit trade multipliers here. Teammates use multiplier 1. + """ + me = next((p for p in match.players if p.player_id == participant.player_id), None) + if me is None or (analysis is not None and not isinstance(analysis, Mapping)): + return None + roles = _career_roles(analysis) + if roles is None: + return None + features = _match_features(match, me, _career_trade(roles)) + if features is None: + return None + norms, weights = MODEL["norm"]["career"], MODEL["weights"] + z = {} + for metric in ("kd", "con", "obj"): + norm = norms[metric] + mu = norm["elo"] * features["eloN"] + norm["gap"] * features["gapN"] + variance = 0.0 + for role in ROLE_KEYS: + mu += roles[role] * norm["mu"][role] + variance += roles[role] * norm["sigma"][role] ** 2 + z[metric] = (features["x"][metric] - mu) / math.sqrt(variance or 1) + obj_factor = sum(roles[r] for r in ("armor", "inf", "recon")) + obj_factor += 0.2 * sum(roles[r] for r in ("arty", "aa", "heli", "jet")) + stat = (weights["kd"] * z["kd"] + weights["con"] * z["con"] + + weights["obj"] * obj_factor * z["obj"]) + stat /= weights["kd"] + weights["con"] + weights["obj"] * obj_factor + combined = stat + weights["out"] * (features["S"] - features["E"]) / MODEL["outSd"] + return _to10(_percentile(combined, MODEL["matchPct"]["career"])) + + +def score_band(score: float | None) -> Literal["low", "medium", "high"] | None: + """Color bands only, using the displayed-score thresholds in markOf.""" + if not _finite(score) or not 1 <= score <= 10: + return None + displayed = math.floor(score * 10 + 0.5) / 10 + if displayed >= _to10(MODEL["marks"]["dragon"]): + return "high" + if displayed <= _to10(MODEL["marks"]["qu"]): + return "low" + return "medium" + + +def team_composition(match: Match, team: str | None) -> dict: + """Estimate spend shares from the pinned model's BASE prices per spawn. + + coverage is 0..1: identified, priced spawn count / all recorded spawn + count. It is NOT cost coverage. Missing UnitData is separately counted. + With an unpriced spawn or a missing participant's UnitData, the all-spawn + denominator is unknowable: categories stays empty instead of renormalizing + known spend to 100%. Transport/logistics with known IDs remain identified. + An explicitly empty UnitData produces no categories, never seven zeroes. + """ + members = [p for p in match.players if p.team == team] + missing = sum(not p.units_available for p in members) + total_count = known_count = unknown_count = 0 + costs = dict.fromkeys((*ROLE_KEYS, "_"), 0.0) + for person in members: + for unit in person.units: + count = unit.get("count", 1) + if not _nonnegative(count) or int(count) != count: + missing += 1 + continue + total_count += count + entry = MODEL["units"].get(str(unit.get("id"))) + if not entry or not _nonnegative(entry[1]): + unknown_count += count + continue + known_count += count + costs[entry[0] or "_"] += entry[1] * count + result = {"categories": [], "coverage": known_count / total_count if total_count else 0.0, + "unknown_count": unknown_count, "missing_participants": missing, "estimated": True} + total_cost = sum(costs.values()) + if not missing and not unknown_count and total_cost > 0: + result["categories"] = [{"name": ROLE_NAMES[role], "percentage": cost / total_cost * 100} + for role, cost in costs.items() if cost > 0] + return result diff --git a/service.py b/service.py index dd8391c..574e351 100644 --- a/service.py +++ b/service.py @@ -12,6 +12,7 @@ from .commands import Request, Target from .models import FetchResult, Match, Participant, Player from .pending import PendingManager +from .scoring import match_prediction, recent_score, score_band, team_composition from .storage import Binding @@ -54,40 +55,112 @@ def participant_view(p: Participant): return dict(id=p.player_id, name=p.name, elo=p.elo, elo_delta=p.elo_delta, kills=p.kills, losses=p.losses, destroyed_value=p.destroyed_value, lost_value=p.lost_value, unit_exchange=ratio(p.kills, p.losses), - value_exchange=ratio(p.destroyed_value, p.lost_value)) + value_exchange=ratio(p.destroyed_value, p.lost_value), + damage_dealt=p.damage_dealt, damage_received=p.damage_received, + objectives=p.objectives, spawned_value=p.spawned_value, supply=p.supply, + outcome=p.outcome, outcome_source=None) -def recent_rows(matches, player_id): +def analysis_outcomes(player): + """Only explicit booleans for this player's exact match IDs can supply results.""" + outcomes = {} + for point in player.analysis.get("trend", {}).get("points", []): + mid = point.get("matchId") + if mid is not None: + known = outcomes.setdefault(mid, set()) + if isinstance(point.get("won"), bool): + known.add(point["won"]) + return {mid: ("win" if True in known else "loss") if len(known) == 1 else "unknown" + for mid, known in outcomes.items()} + + +def map_name(match, player=None): + if player is not None and match.map_id is not None: + for row in player.analysis.get("mapPerformance", []): + if row["mapId"] == match.map_id and row["mapName"]: + return row["mapName"] + return match.map_name + + +def recent_rows(matches, player_id, player=None): rows = [] + outcomes = analysis_outcomes(player) if player is not None and player.id == player_id else {} for match in matches: person = participant_for(match, player_id) if person is None: continue row = participant_view(person) - row.update(id=match.id, started_at=match.started_at, map_name=match.map_name, - mode=match.mode, outcome=person.outcome, + score = recent_score(match, person, player.analysis if player is not None and player.id == player_id else None) + outcome = outcomes.get(match.id, person.outcome) + row.update(id=match.id, started_at=match.started_at, ended_at=match.ended_at, + map_name=map_name(match, player), + mode=match.mode, outcome=outcome, + outcome_source="analysis" if outcomes.get(match.id) in {"win", "loss"} else None, + score=score, score_band=score_band(score), duration_seconds=match.duration_seconds, source_url=match.source_url) rows.append(row) return rows +def team_metrics(players): + metrics = [] + for field, label, style in ( + ("destroyed_value", "摧毁分", "decimal"), ("lost_value", "损失分", "decimal"), + ("elo", "平均 ELO", "decimal"), ("kills", "击杀", "integer"), + ("losses", "阵亡", "integer"), ("damage_dealt", "伤害", "decimal"), + ("spawned_value", "出兵花费", "decimal"), ("objectives", "占点", "integer"), + ("supply", "补给", "decimal"), + ): + values = [p[field] for p in players if p[field] is not None] + if not values: + continue + value = sum(values) / len(values) if field == "elo" else sum(values) + metric = {"label": label, "value": value, "format": style} + if len(values) != len(players): + metric["note"] = f"{len(values)}/{len(players)} 人有数据" + metrics.append(metric) + return metrics + + def match_view(result, player=None): match = result.data - if player is not None: - participant_for(match, player.id) + target = participant_for(match, player.id) if player is not None else None + target_outcome = analysis_outcomes(player).get(match.id, "unknown") if target is not None else "unknown" teams = OrderedDict() for person in match.players: - key = person.team if person.team is not None else "未知" + key = person.team if key not in teams: - teams[key] = {"name": f"分队 {key}", "outcome": "unknown", "players": []} - teams[key]["players"].append(participant_view(person)) + teams[key] = {"name": {"0": "A 队", "1": "B 队"}.get(key, f"分队 {key if key is not None else '未知'}"), + "outcome": "unknown", "players": []} + row = participant_view(person) + if player is not None and person.player_id == player.id: + row.update(outcome=target_outcome, + outcome_source="analysis" if target_outcome != "unknown" else None) + teams[key]["players"].append(row) if match.winner_team is not None and person.team is not None: teams[key]["outcome"] = "win" if person.team == match.winner_team else "loss" + # Stable A/B ordering is independent of the source participant-map order. + teams = OrderedDict(sorted(teams.items(), key=lambda pair: {"0": 0, "1": 1}.get(pair[0], 2))) + for key, team in teams.items(): + team["metrics"] = team_metrics(team["players"]) + composition = team_composition(match, key) + team["composition"] = composition["categories"] + team["composition_coverage"] = composition["coverage"] + notes = [] + if composition["unknown_count"]: + notes.append(f"{composition['unknown_count']} 次出场单位无法定价,构成暂无") + if composition["missing_participants"]: + notes.append(f"{composition['missing_participants']} 人缺单位数据,构成暂无") + team["composition_note"] = ";".join(notes) view = {"kind": "match", "match": { - "id": match.id, "map_name": match.map_name, "mode": match.mode, - "started_at": match.started_at, "duration_seconds": match.duration_seconds, - "winner": f"分队 {match.winner_team}" if match.winner_team is not None else None, - }, "teams": list(teams.values()), "scope": f"单局 · 实际收录 {len(match.players)} 名玩家", + "id": match.id, "map_name": map_name(match, player), "mode": match.mode, + "started_at": match.started_at, "ended_at": match.ended_at, "duration_seconds": match.duration_seconds, + "winner": {"0": "A 队", "1": "B 队"}.get(match.winner_team, f"分队 {match.winner_team}") + if match.winner_team is not None else None, + "target_outcome": target_outcome, + "target_outcome_source": "analysis" if target_outcome != "unknown" else None, + }, "teams": list(teams.values()), "prediction": match_prediction(match), + "scope": f"单局 · 实际收录 {len(match.players)} 名玩家", "source_url": match.source_url, **freshness(result)} if player: view["player"] = asdict(player) @@ -96,6 +169,51 @@ def match_view(result, player=None): return view +def common_units(player, matches): + if player.analysis: + units = [{"id": u["unitId"], "name": u["unitName"] or f"单位#{u['unitId']}", + "count": u["spawnCount"], "damage": u["totalDamage"], "roi": u["avgRoi"]} + for u in player.analysis.get("highlightUnits", [])] + else: + # Older callers can still construct a Player without analysis data. + counts, names = Counter(), {} + for match in matches: + person = participant_for(match, player.id) + if person is not None: + for unit in person.units: + uid = unit["id"] + counts[uid] += unit["count"] + if unit.get("name"): + names.setdefault(uid, unit["name"]) + units = [{"id": uid, "name": names.get(uid, f"单位#{uid}"), "count": count} + for uid, count in counts.most_common()] + duplicates = Counter(unit["name"] for unit in units) + for unit in units: + if duplicates[unit["name"]] > 1: + unit["name"] += f"(ID:{unit['id']})" + return units[:3] + + +def overview_metrics(player, rows): + pairs = [row for row in rows if row["destroyed_value"] is not None and row["lost_value"] is not None] + points = player.analysis.get("trend", {}).get("points", []) + known = [point["won"] for point in points if isinstance(point.get("won"), bool)] + dated = [point for point in points if point.get("endTime") is not None and point.get("dmr") is not None] + latest = max(dated, key=lambda point: point["endTime"]) if dated else None + dmr_note = "分析单局" + if latest is not None: + dmr_note += f" · #{latest['matchId']}" if latest.get("matchId") is not None else "" + return [ + {"label": "ELO", "value": player.elo}, + {"label": "近期分值 K/D", "value": ratio(sum(row["destroyed_value"] for row in pairs), + sum(row["lost_value"] for row in pairs)) if pairs else None, + "note": f"近期 {len(pairs)} 场摧毁分 ÷ 损失分"}, + {"label": "分析样本胜率", "value": 100 * sum(known) / len(known) if known else None, + "format": "percent", "note": f"{sum(known)} 胜 / {len(known)} 场已知结果"}, + {"label": "伤害交换比", "value": latest["dmr"] if latest else None, "note": dmr_note}, + ] + + class StatsService: def __init__(self, client, storage, settings): self.client, self.storage, self.settings = client, storage, settings @@ -272,49 +390,30 @@ async def _report(self, request, player_id): view.update(freshness(player_result, result, detail)) return Response(view=view) return Response(f"{player.name} · STB ID:{player.id}\n当前返回样本中暂无可用单局战报。\n{player.source_url or ''}") - rows = recent_rows(matches, player.id) + rows = recent_rows(matches, player.id, player) times = [m.started_at for m in matches if m.started_at and any(p.player_id == player.id for p in m.players)] - scope = f"近期接口样本 · 实际 {len(rows)} 场(请求最多 {limit} 场);非完整历史,模式以单局标注为准" + scope = f"近期{len(rows)}场" + analysis_count = player.analysis.get("matchCount") + if analysis_count is None: + analysis_count = len(player.analysis.get("trend", {}).get("points", [])) view = {"kind": "recent" if request.action == "recent" else "overview", "player": asdict(player), "rows": rows, "scope": scope, + "analysis_scope": f"分析样本{analysis_count}场 · 与近期样本独立" if player.analysis else "", "source_url": player.source_url, **freshness(player_result, result)} if times: from zoneinfo import ZoneInfo zone = ZoneInfo(self.settings.timezone) - view["scope"] += f" · {min(times).astimezone(zone):%Y-%m-%d %H:%M} 至 {max(times).astimezone(zone):%Y-%m-%d %H:%M}" + view["scope"] += f" · {min(times).astimezone(zone):%m-%d}—{max(times).astimezone(zone):%m-%d}" + if len(times) != len(rows): + view["scope"] += f"({len(times)}/{len(rows)} 场有开始时间)" if view["kind"] == "overview": - outcomes = Counter(row["outcome"] for row in rows) - known = outcomes["win"] + outcomes["loss"] - view["metrics"] = [ - {"label": "ELO", "value": player.elo}, - {"label": "样本场数", "value": len(rows), "format": "integer"}, - {"label": "胜 / 负 / 未知", "value": f"{outcomes['win']} / {outcomes['loss']} / {outcomes['unknown']}"}, - {"label": "已知结果胜率", "value": 100 * outcomes["win"] / known if known else None, - "format": "percent", "note": f"分母为 {known} 场已知胜负样本"}, - ] - counts = Counter() - names = {} - for match in matches: - person = participant_for(match, player.id) - if person is not None: - for unit in person.units: - uid = unit["id"] - counts[uid] += unit["count"] - if unit.get("name"): - # Matches arrive newest first; names never define identity. - names.setdefault(uid, unit["name"]) - labels = {uid: names.get(uid, f"单位#{uid}") for uid in counts} - duplicates = Counter(labels.values()) - view["common_units"] = [ - {"id": uid, "name": f"{labels[uid]}(ID:{uid})" if duplicates[labels[uid]] > 1 else labels[uid], - "count": count} - for uid, count in counts.most_common(5) - ] - view["notes"] = ["常用单位按当前样本中的出场记录数统计;未收录名称时显示来源单位 ID。"] - if player.elo_observed_at: - from zoneinfo import ZoneInfo - at = player.elo_observed_at.astimezone(ZoneInfo(self.settings.timezone)) - view["notes"].append(f"ELO 对应时间:{at:%Y-%m-%d %H:%M %Z}") + view["metrics"] = overview_metrics(player, rows) + view["common_units"] = common_units(player, matches) + view["map_stats"] = [{"name": m["mapName"] or f"地图#{m['mapId']}", + "count": m["matchCount"], "win_rate": m["winRate"]} + for m in player.analysis.get("mapPerformance", [])[:5]] + view["categories"] = [{"name": c["categoryKey"], "percentage": c["percentage"]} + for c in player.analysis.get("categoryPreferences", [])] return Response(view=view) def close(self): diff --git a/settings.py b/settings.py index 1758839..780a070 100644 --- a/settings.py +++ b/settings.py @@ -1,8 +1,25 @@ """单一配置来源:AstrBotConfig;启动时校验并快照。""" from dataclasses import dataclass +from urllib.parse import urlsplit from zoneinfo import ZoneInfo, ZoneInfoNotFoundError +def valid_https_origin(value): + """Shared API origin contract for runtime and both settings interfaces.""" + if not isinstance(value, str) or not value: + return False + if any(character.isspace() or ord(character) < 32 for character in value) or "\\" in value: + return False + try: + url = urlsplit(value) + return bool(url.scheme == "https" and url.hostname + and url.username is None and url.password is None + and url.path in {"", "/"} and not url.query and not url.fragment + and (url.port is None or 1 <= url.port <= 65535)) + except ValueError: + return False + + def bounded(data, key, default, lower, upper, cast=float): try: value = cast(data.get(key, default)) @@ -24,8 +41,6 @@ def daily_limit(data, key, default): class Settings: enabled: bool = False base_url: str = "https://bot.batrace.top" - client_id: str = "" - api_token: str = "" default_limit: int = 5 max_limit: int = 20 cooldown_seconds: float = 3 @@ -43,6 +58,7 @@ class Settings: stale_hours: float = 24 user_daily_limit: int = 20 group_daily_limit: int = 100 + diagnostics_enabled: bool = False @classmethod def from_config(cls, config): @@ -51,6 +67,7 @@ def from_config(cls, config): output = config.get("output", {}) maintenance = config.get("maintenance", {}) limits = config.get("limits", {}) + diagnostics = config.get("diagnostics", {}) maximum = bounded(query, "max_limit", 20, 1, 20, int) timezone = str(output.get("timezone", "Asia/Shanghai")) try: @@ -63,8 +80,6 @@ def from_config(cls, config): return cls( enabled=bool(access.get("enabled", False)), base_url=str(access.get("base_url", cls.base_url)).strip(), - client_id=str(access.get("client_id", "")).strip(), - api_token=str(access.get("api_token", "")).strip(), default_limit=bounded(query, "default_limit", 5, 1, maximum, int), max_limit=maximum, cooldown_seconds=bounded(query, "cooldown_seconds", 3, 0, 60), @@ -81,4 +96,5 @@ def from_config(cls, config): stale_hours=bounded(maintenance, "stale_hours", 24, 0, 168), user_daily_limit=daily_limit(limits, "user_daily_limit", 20), group_daily_limit=daily_limit(limits, "group_daily_limit", 100), + diagnostics_enabled=bool(diagnostics.get("enabled", False)), ) diff --git a/templates/base.html b/templates/base.html index 1641a91..2a3d053 100644 --- a/templates/base.html +++ b/templates/base.html @@ -3,7 +3,7 @@ - + 断箭战报 · {{ view.title }} + + +
+

断箭战报设置中心

+

诊断开关保存后即时生效。其他设置保存后,请在 AstrBot 插件页手动重载;正在处理的请求不会因本页保存而中断。

+
+ +
+

+
+
+
+
+
+ + + +
+

正在读取设置…

+
+ + +
+
+
+
+
+ + + diff --git a/views/settings/settings.js b/views/settings/settings.js new file mode 100644 index 0000000..20ef74a --- /dev/null +++ b/views/settings/settings.js @@ -0,0 +1,193 @@ +const bridge = window.AstrBotPluginView; +const byId = id => document.getElementById(id); +const form = byId("settings-form"); +let snapshot = null; +let stats = null; +let busy = false; +const inputs = new Map(); + +function message(id, text, error = false) { + byId(id).textContent = text; + byId(id).dataset.error = String(error); +} + +function changes() { + const result = {}; + for (const field of snapshot?.fields || []) { + const input = inputs.get(field.path); + let value = field.type === "bool" ? input.checked : input.value; + if (["int", "float"].includes(field.type)) { + if (value.trim() === "" || !Number.isFinite(Number(value))) throw new Error(`请填写「${field.label}」的有效数值。`); + value = Number(value); + } + if (value !== field.value || snapshot.invalid_fields.includes(field.path) + || field.path === "diagnostics.enabled" && !snapshot.diagnostics_applied) result[field.path] = value; + } + return result; +} + +function hasDraft() { + try { return Object.keys(changes()).length > 0; } catch { return true; } +} + +function buttons() { + byId("save").disabled = busy || !snapshot || !hasDraft(); + byId("reload").disabled = busy || !bridge; + byId("refresh-diagnostics").disabled = busy || !bridge; + byId("download").disabled = busy || !stats || stats.bytes === 0; + for (const input of inputs.values()) input.disabled = busy; +} + +function diagnostics(value) { + if (!value || typeof value.enabled !== "boolean" + || ![value.bytes, value.limit_bytes, value.files].every(v => Number.isSafeInteger(v) && v >= 0)) { + throw new Error("诊断状态格式异常,请重试。"); + } + stats = value; + const size = bytes => bytes < 1024 ? `${bytes} B` : bytes < 1048576 + ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1048576).toFixed(2)} MB`; + byId("diagnostics-mode").textContent = value.enabled ? "已开启" : "已关闭"; + byId("diagnostics-capacity").textContent = `${size(value.bytes)} / ${size(value.limit_bytes)}`; + byId("diagnostics-files").textContent = `${value.files} 个`; + byId("log-state").textContent = value.bytes === 0 + ? "暂无诊断日志。请保存启用诊断模式,再复现需要排查的问题。" + : value.enabled ? "正在记录诊断信息。下载不会清除日志。" : "已停止记录,仍可下载之前保留的日志。"; +} + +function render(value, draft = {}) { + if (!value || typeof value.revision !== "string" || !Array.isArray(value.fields)) throw new Error("设置响应格式异常,请重试。"); + snapshot = value; + inputs.clear(); + for (const container of document.querySelectorAll("[data-group]")) { + container.replaceChildren(); + const group = container.dataset.group; + if (!["maintenance", "diagnostics"].includes(group)) { + const heading = document.createElement("h3"); + heading.textContent = value.groups[group]?.label || group; + container.append(heading); + } + if (value.groups[group]?.hint) { + const hint = document.createElement("p"); + hint.className = "hint"; + hint.textContent = value.groups[group].hint; + container.append(hint); + } + for (const field of value.fields.filter(item => item.group === group)) { + const row = document.createElement("div"); + row.className = "field"; + row.dataset.pending = String(value.pending_restart.includes(field.path)); + const input = document.createElement(field.options.length ? "select" : "input"); + input.id = `setting-${field.path.replaceAll(".", "-")}`; + if (field.options.length) { + field.options.forEach((option, i) => { + const element = document.createElement("option"); + element.value = option; + element.textContent = field.labels[i] || option; + input.append(element); + }); + } else { + input.type = field.type === "bool" ? "checkbox" : ["int", "float"].includes(field.type) ? "number" : "text"; + if (input.type === "number") { + input.step = field.type === "int" ? "1" : "any"; + if (field.bounds) [input.min, input.max] = field.bounds; + } + } + const current = Object.hasOwn(draft, field.path) ? draft[field.path] : field.value; + if (field.type === "bool") input.checked = current; + else input.value = current; + const label = document.createElement("label"); + label.htmlFor = input.id; + if (field.type === "bool") label.append(input); + label.append(document.createTextNode(field.label)); + row.append(label); + if (field.type !== "bool") row.append(input); + if (field.hint) { + const hint = document.createElement("p"); + hint.className = "hint"; + hint.id = `${input.id}-hint`; + hint.textContent = field.hint; + input.setAttribute("aria-describedby", hint.id); + row.append(hint); + } + inputs.set(field.path, input); + container.append(row); + } + } + diagnostics(value.diagnostics); + byId("apply-state").textContent = value.invalid_fields.length + ? "旧配置包含无效值,已隐藏原值并显示安全默认值。请核对后保存;API 地址需填写有效的 HTTPS 地址。" + : value.reload_required ? `有 ${value.pending_restart.length} 项已保存设置等待重载生效。请在请求结束后,从 AstrBot 插件页手动重载。` + : !value.diagnostics_applied ? "诊断开关的已保存值尚未应用,保存一次可同步当前运行状态。" : "当前已保存设置与本次运行一致。"; +} + +async function load(preserveDraft = true) { + let draft = {}; + try { + if (preserveDraft) draft = changes(); + busy = true; + buttons(); + const value = await bridge.apiGet("settings/config"); + render(value, draft); + message("save-status", Object.keys(draft).length ? "已读取最新配置并保留草稿,请核对后保存。" : "已读取设置。"); + } catch (error) { + message("save-status", error.message || "读取设置失败,请确认登录状态后重试。", true); + } finally { busy = false; buttons(); } +} + +form.addEventListener("input", () => { + message("save-status", hasDraft() ? "有未保存的更改。" : "没有未保存的更改。"); + buttons(); +}); +form.addEventListener("submit", async event => { + event.preventDefault(); + if (busy || !snapshot) return; + try { + const draft = changes(); + if (!Object.keys(draft).length) return; + busy = true; + buttons(); + message("save-status", "正在保存…"); + const value = await bridge.apiPost("settings/config", {revision: snapshot.revision, changes: draft}); + render(value); + message("save-status", value.message); + } catch (error) { + // In particular, a 409 never replaces inputs or silently retries a save. + message("save-status", error.message || "保存失败,草稿已保留。", true); + } finally { busy = false; buttons(); } +}); +byId("reload").addEventListener("click", () => load()); +byId("refresh-diagnostics").addEventListener("click", async () => { + busy = true; buttons(); + try { + diagnostics(await bridge.apiGet("diagnostics/status")); + message("download-status", "诊断状态已刷新。"); + } catch { message("download-status", "读取诊断状态失败,请重试。", true); } + finally { busy = false; buttons(); } +}); +byId("download").addEventListener("click", async () => { + busy = true; buttons(); + try { + diagnostics(await bridge.apiGet("diagnostics/status")); + if (!stats.bytes) { message("download-status", "暂无诊断日志,请启用后复现问题。"); return; } + await bridge.download("diagnostics/download", {}, "ba-stats-diagnostics.zip"); + message("download-status", "下载已交给浏览器。"); + } catch { message("download-status", "下载未完成,请确认登录状态后重试。", true); } + finally { busy = false; buttons(); } +}); +for (const tab of document.querySelectorAll("[data-section]")) { + tab.addEventListener("click", () => { + for (const other of document.querySelectorAll("[data-section]")) { + if (other === tab) other.setAttribute("aria-current", "page"); + else other.removeAttribute("aria-current"); + } + for (const panel of document.querySelectorAll("[data-panel]")) panel.hidden = panel.id !== tab.dataset.section; + }); +} +window.addEventListener("beforeunload", event => { if (hasDraft()) { event.preventDefault(); event.returnValue = ""; } }); + +if (bridge) { + try { await bridge.ready(); await load(false); } + catch { message("save-status", "无法连接 AstrBot,请重新打开设置中心。", true); } +} else { + message("save-status", "请从 AstrBot 插件详情 → 可视化视图 → 设置中心打开本页。", true); +} diff --git a/web_settings.py b/web_settings.py new file mode 100644 index 0000000..3b2e9ed --- /dev/null +++ b/web_settings.py @@ -0,0 +1,176 @@ +"""Small, schema-based editor for the host's existing AstrBotConfig. + +v4.29.4: save_config() writes an atomic snapshot; PluginManager.reload() +terminates the old instance first, so ordinary settings await a manual reload. +""" +from __future__ import annotations + +from copy import deepcopy +import hashlib +import json +import math +from pathlib import Path +import threading +from .settings import Settings, valid_https_origin + + +# Explicit public surface: legacy credentials/client IDs never become fields, +# even when they remain in an old configuration or schema. +_ATTRS = { + "access.enabled": "enabled", "access.base_url": "base_url", + "query.default_limit": "default_limit", "query.max_limit": "max_limit", + "query.cooldown_seconds": "cooldown_seconds", "query.chinese_aliases": "chinese_aliases", + "output.image_enabled": "image_enabled", "output.theme": "theme", "output.timezone": "timezone", + "limits.user_daily_limit": "user_daily_limit", "limits.group_daily_limit": "group_daily_limit", + **{f"maintenance.{key}": key for key in ( + "request_interval", "concurrency", "queue_size", "request_timeout", "wait_timeout", + "retries", "cache_max_entries", "stale_hours", + )}, + "diagnostics.enabled": "diagnostics_enabled", +} +_BOUNDS = { + "query.default_limit": (1, 20), "query.max_limit": (1, 20), + "query.cooldown_seconds": (0, 60), "limits.user_daily_limit": (0, 100), + "limits.group_daily_limit": (0, 100), "maintenance.request_interval": (.1, 60), + "maintenance.concurrency": (1, 5), "maintenance.queue_size": (1, 100), + "maintenance.request_timeout": (1, 120), "maintenance.wait_timeout": (1, 180), + "maintenance.retries": (0, 2), "maintenance.cache_max_entries": (10, 10000), + "maintenance.stale_hours": (0, 168), +} + + +class SettingsError(ValueError): + def __init__(self, message, status_code=400): + super().__init__(message) + self.status_code = status_code + + +class WebSettings: + def __init__(self, config, runtime_settings, diagnostics): + self.config, self.diagnostics = config, diagnostics + schema = getattr(config, "schema", None) + self.schema = schema if isinstance(schema, dict) else json.loads( + Path(__file__).with_name("_conf_schema.json").read_text(encoding="utf-8")) + self._running = {path: getattr(runtime_settings, attr) for path, attr in _ATTRS.items()} + self._lock = threading.RLock() + self._specs = {} + for path in _ATTRS: + group, key = path.split(".") + spec = self.schema.get(group, {}).get("items", {}).get(key) + if isinstance(spec, dict): + self._specs[path] = spec + + def _read(self): + # Dashboard saves can replace the on-disk config without updating this + # plugin instance. Read that same file for both GET and revision checks. + config_path = getattr(self.config, "config_path", None) + if not config_path: + raise SettingsError("配置文件暂不可用,请重载插件后重试。", 503) + try: + values = json.loads(Path(config_path).read_text(encoding="utf-8-sig")) + if not isinstance(values, dict): + raise ValueError + revision = hashlib.sha256(json.dumps(values, sort_keys=True, ensure_ascii=True, + allow_nan=False).encode()).hexdigest() + except (OSError, ValueError, TypeError): + raise SettingsError("无法读取配置文件,请先在 AstrBot 中检查配置。", 503) from None + return values, revision + + @staticmethod + def _value(values, path, spec): + group, key = path.split(".") + node = values.get(group, {}) + if not isinstance(node, dict): + raise SettingsError("配置分组格式异常,请先在 AstrBot 中检查配置。") + return node.get(key, deepcopy(spec["default"])) + + def _validate(self, path, value): + spec = self._specs[path] + kind, label = spec["type"], spec.get("description", path) + valid = ((kind == "bool" and type(value) is bool) + or (kind == "int" and type(value) is int) + or (kind == "float" and (type(value) is int or type(value) is float and math.isfinite(value))) + or (kind == "string" and isinstance(value, str) and len(value) <= 2048)) + if not valid: + raise SettingsError(f"「{label}」的类型或格式不正确。") + if spec.get("options") and value not in spec["options"]: + raise SettingsError(f"请为「{label}」选择有效选项。") + if path in _BOUNDS and not _BOUNDS[path][0] <= value <= _BOUNDS[path][1]: + lower, upper = _BOUNDS[path] + raise SettingsError(f"「{label}」必须在 {lower}–{upper} 之间。") + if path == "access.base_url" and not valid_https_origin(value): + raise SettingsError("API 地址必须是不含路径、参数和账号信息的 HTTPS 地址。") + + def _describe(self, values, revision): + fields, pending, invalid = [], [], [] + for path, spec in self._specs.items(): + value = self._value(values, path, spec) + # Invalid legacy values may include credential-bearing URLs or + # arbitrary objects. Never expose those through public fields. + try: + self._validate(path, value) + except SettingsError: + value = "" if path == "access.base_url" else deepcopy(spec["default"]) + invalid.append(path) + group = path.split(".")[0] + fields.append({"path": path, "group": group, "label": spec.get("description", path), + "type": spec["type"], "value": value, "default": spec["default"], + "hint": spec.get("hint", ""), "options": spec.get("options", []), + "labels": spec.get("labels", []), "bounds": _BOUNDS.get(path)}) + if path != "diagnostics.enabled" and value != self._running[path]: + pending.append(path) + return {"revision": revision, "fields": fields, + "groups": {key: {"label": spec.get("description", key), "hint": spec.get("hint", "")} + for key, spec in self.schema.items() if key in {p.split(".")[0] for p in self._specs}}, + "reload_required": bool(pending), "pending_restart": pending, + "invalid_fields": invalid, "diagnostics": self.diagnostics.stats(), + "diagnostics_applied": self.diagnostics.enabled == next( + (f["value"] for f in fields if f["path"] == "diagnostics.enabled"), False)} + + def snapshot(self): + with self._lock: + return self._describe(*self._read()) + + def save(self, payload): + with self._lock: + if not isinstance(payload, dict) or set(payload) != {"revision", "changes"}: + raise SettingsError("请求必须仅包含 revision 和 changes。") + if (not isinstance(payload["revision"], str) or len(payload["revision"]) != 64 + or any(char not in "0123456789abcdef" for char in payload["revision"])): + raise SettingsError("revision 格式无效,请重新读取设置。") + changes = payload["changes"] + if not isinstance(changes, dict) or not changes or any(path not in self._specs for path in changes): + raise SettingsError("没有有效更改,或包含未知配置项;旧令牌及客户端标识不可编辑。") + current, revision = self._read() + if payload["revision"] != revision: + raise SettingsError("配置已在其他页面更新。请重新读取后核对并再次保存,当前草稿仍保留。", 409) + updated = deepcopy(current) + for path, value in changes.items(): + self._validate(path, value) + group, key = path.split(".") + if not isinstance(updated.get(group, {}), dict): + raise SettingsError("配置分组格式异常,请先在 AstrBot 中检查配置。") + updated.setdefault(group, {})[key] = value + # from_config casts some values permissively: enforce all schema + # types first, then its complete cross-field/range/timezone checks. + for path, spec in self._specs.items(): + self._validate(path, self._value(updated, path, spec)) + try: + settings = Settings.from_config(updated) + except (ValueError, TypeError, OverflowError): + raise SettingsError("配置校验未通过:请检查场数范围、时区及请求限制。") from None + before = deepcopy(dict(self.config)) + try: + # v4.29.4 save_config(replace_config) merges then atomically + # replaces its file. No await between revision check and save. + self.config.clear() + self.config.save_config(updated) + except Exception: + self.config.clear() + self.config.update(before) + raise SettingsError("配置保存失败,当前运行设置未变;请检查配置目录后重试。", 500) from None + self.diagnostics.set_enabled(settings.diagnostics_enabled) + snapshot = self._describe(*self._read()) + snapshot["message"] = ("已保存;诊断开关已即时应用,其他更改需在 AstrBot 插件页手动重载后生效。" + if snapshot["reload_required"] else "已保存并应用诊断开关,无需重载。") + return snapshot