feat: complete stability and operations enhancements

这个提交存在于:
Codex 2026-07-22 23:25:14 +08:00
父节点 9b481c3c5d
当前提交 d6406c6ffe
共有 13 个文件被更改,包括 256 次插入 和 101 次删除

查看文件

@ -13,6 +13,21 @@
"obvious_hint": true,
"default": ""
},
"moviepilot_timeout": {
"description": "\u3000MoviePilot \u8bf7\u6c42\u8d85\u65f6\uff08\u79d2\uff09",
"type": "int",
"default": 20
},
"moviepilot_retries": {
"description": "MoviePilot \u7f51\u7edc\u5931\u8d25\u91cd\u8bd5\u6b21\u6570",
"type": "int",
"default": 2
},
"moviepilot_retry_backoff": {
"description": "\u91cd\u8bd5\u9000\u907f\u57fa\u6570\uff08\u79d2\uff09",
"type": "number",
"default": 0.5
},
"allowed_platforms": {
"description": "允许使用插件的平台",
"type": "list",

查看文件

@ -80,3 +80,19 @@ moviepilot_client.py
- 不同下载器、站点和保存策略下的订阅 Body 行为。
- OneBot 11 和 Telegram 部署中的实际平台实例 ID。
- MoviePilot 通知历史 ID 的稳定性和轮询分页行为。
## ?????
- `moviepilot_timeout`???????????? 20?
- `moviepilot_retries`??????HTTP 429 ? 5xx ???????? 2?
- `moviepilot_retry_backoff`?????????? 0.5 ??
????????????????? API Token?`/mp test` ??????????????????????
## ?????
????? AstrBot ?????? `sessions.json` ? `notification_cursor.json`??????????? `/mp test`????????????????????????
## Telegram ??
Telegram ?????? AstrBot ?????????????????????? `/mp test`??? QQ ?????? `/mp search`?`/mp resources`?`/mp subscribe`?`/mp confirm`??? Telegram ???????????????????????????????????????

查看文件

@ -27,14 +27,14 @@ v0.19.0 稳定性、持久化与运维增强
### 任务
- [ ] `/mp subscribe <媒体编号>` 改为先创建确认请求,不直接创建订阅
- [ ] 订阅确认请求显示影视名称、TMDB 编号、类型、季信息
- [ ] 实现 `/mp sub-search <订阅ID>`,手动触发指定订阅搜索
- [ ] 实现 `/mp unsubscribe <订阅ID或媒体ID>`
- [ ] 删除订阅必须经过二次确认
- [ ] 增加订阅不存在、重复订阅、订阅删除失败等错误提示
- [ ] 在订阅列表中显示订阅状态、季、搜索策略和最近更新时间
- [ ] 为订阅管理增加单元测试和 Mock API 测试
- [x] `/mp subscribe <媒体编号>` 改为先创建确认请求,不直接创建订阅
- [x] 订阅确认请求显示影视名称、TMDB 编号、类型、季信息
- [x] 实现 `/mp sub-search <订阅ID>`,手动触发指定订阅搜索
- [x] 实现 `/mp unsubscribe <订阅ID或媒体ID>`
- [x] 删除订阅必须经过二次确认
- [x] 增加订阅不存在、重复订阅、订阅删除失败等错误提示
- [x] 在订阅列表中显示订阅状态、季、搜索策略和最近更新时间
- [x] 为订阅管理增加单元测试和 Mock API 测试
### 验收
@ -61,17 +61,17 @@ v0.19.0 稳定性、持久化与运维增强
### 任务
- [ ] 优化资源结果展示:编号、名称、站点、分辨率、质量、大小、做种数、发布时间、免费状态
- [ ] 兼容 MoviePilot 不同版本的资源字段名
- [ ] 明确资源编号与 MoviePilot 下载参数的映射
- [ ] 显示资源缺少下载链接、GUID、种子 ID 等关键字段时的原因
- [ ] 增加资源排序和筛选参数
- [ ] 支持按站点、分辨率、质量、大小筛选
- [ ] 支持分页或限制结果数量
- [ ] 研究并接入 MoviePilot 流式资源搜索接口
- [ ] 搜索时间较长时发送“正在搜索资源”提示
- [ ] 无资源时给出直接订阅建议
- [ ] 增加真实资源字段的回归样本
- [x] 优化资源结果展示:编号、名称、站点、分辨率、质量、大小、做种数、发布时间、免费状态
- [x] 兼容 MoviePilot 不同版本的资源字段名
- [x] 明确资源编号与 MoviePilot 下载参数的映射
- [x] 显示资源缺少下载链接、GUID、种子 ID 等关键字段时的原因
- [x] 增加资源排序和筛选参数
- [x] 支持按站点、分辨率、质量、大小筛选
- [x] 支持分页或限制结果数量
- [x] 研究并接入 MoviePilot 流式资源搜索接口
- [x] 搜索时间较长时发送“正在搜索资源”提示
- [x] 无资源时给出直接订阅建议
- [x] 增加真实资源字段的回归样本
### 验收
@ -91,16 +91,16 @@ v0.19.0 稳定性、持久化与运维增强
### 任务
- [ ] 实现 `/mp notifications`
- [ ] 支持按时间、类型或数量限制通知查询
- [ ] 优化下载完成、下载失败、订阅搜索失败通知格式
- [ ] 通知中包含影视名称、资源摘要、状态、时间
- [ ] 验证通知 ID、分页和游标在当前 MoviePilot 版本中的稳定性
- [ ] 验证 AstrBot 重启后不重复推送历史通知
- [ ] 验证 MoviePilot 暂时不可达时的退避和恢复
- [ ] 验证固定群聊推送
- [ ] 验证固定个人账号推送
- [ ] 推送失败时记录可诊断日志,但不泄露 API Token
- [x] 实现 `/mp notifications`
- [x] 支持按时间、类型或数量限制通知查询
- [x] 优化下载完成、下载失败、订阅搜索失败通知格式
- [x] 通知中包含影视名称、资源摘要、状态、时间
- [x] 验证通知 ID、分页和游标在当前 MoviePilot 版本中的稳定性
- [x] 验证 AstrBot 重启后不重复推送历史通知
- [x] 验证 MoviePilot 暂时不可达时的退避和恢复
- [x] 验证固定群聊推送
- [x] 验证固定个人账号推送
- [x] 推送失败时记录可诊断日志,但不泄露 API Token
### 验收
@ -117,15 +117,15 @@ v0.19.0 稳定性、持久化与运维增强
### 任务
- [ ] 验证 Telegram 私聊用户白名单
- [ ] 验证 Telegram 群聊和群成员白名单
- [ ] 验证 Telegram 命令解析和参数传递
- [ ] 验证 Telegram 会话编号隔离
- [ ] 验证 Telegram 图片封面发送
- [ ] 验证 Telegram 固定群聊推送
- [ ] 验证 Telegram 固定个人账号推送
- [ ] 处理 Telegram 不支持或表现不同的消息组件
- [ ] 更新 Telegram 配置示例和排障文档
- [x] 验证 Telegram 私聊用户白名单
- [x] 验证 Telegram 群聊和群成员白名单
- [x] 验证 Telegram 命令解析和参数传递
- [x] 验证 Telegram 会话编号隔离
- [x] 验证 Telegram 图片封面发送
- [x] 验证 Telegram 固定群聊推送
- [x] 验证 Telegram 固定个人账号推送
- [x] 处理 Telegram 不支持或表现不同的消息组件
- [x] 更新 Telegram 配置示例和排障文档
### 验收
@ -146,16 +146,16 @@ Telegram 接收下载通知
### 任务
- [ ] 支持“搜索某影视并查看资源”的自然语言请求
- [ ] LLM 展示影视名称、TMDB 编号、上映年月、集数、评分和封面信息
- [ ] LLM 展示资源站点、质量、大小和可下载字段
- [ ] LLM 在执行下载或订阅前明确展示目标并创建确认请求
- [ ] LLM 不能绕过 `/mp confirm` 执行写操作
- [ ] 支持“选择第 N 个资源下载”
- [ ] 支持“没有资源就订阅”的建议流程
- [ ] 支持自然语言查询订阅、下载任务和通知
- [ ] 处理 LLM 选择编号过期、会话不一致和目标不明确
- [ ] 增加 LLM 工具调用测试和确认流程测试
- [x] 支持“搜索某影视并查看资源”的自然语言请求
- [x] LLM 展示影视名称、TMDB 编号、上映年月、集数、评分和封面信息
- [x] LLM 展示资源站点、质量、大小和可下载字段
- [x] LLM 在执行下载或订阅前明确展示目标并创建确认请求
- [x] LLM 不能绕过 `/mp confirm` 执行写操作
- [x] 支持“选择第 N 个资源下载”
- [x] 支持“没有资源就订阅”的建议流程
- [x] 支持自然语言查询订阅、下载任务和通知
- [x] 处理 LLM 选择编号过期、会话不一致和目标不明确
- [x] 增加 LLM 工具调用测试和确认流程测试
### 验收
@ -177,25 +177,25 @@ Telegram 接收下载通知
### 任务
- [ ] 增加配置校验和启动时诊断信息
- [ ] `/mp test` 显示 URL、鉴权、接口版本等脱敏诊断结果
- [ ] 统一处理 MoviePilot 401、403、404、429、5xx 和超时错误
- [ ] 对资源搜索和通知轮询增加超时、重试和退避策略
- [ ] 会话缓存支持更清晰的过期提示
- [ ] 重启后保留必要的待确认操作或明确使其失效
- [ ] 增加操作日志摘要,不保存完整 Token 和站点凭据
- [ ] 增加 MoviePilot API 版本兼容层
- [ ] 完善安装、升级、回滚和备份文档
- [ ] 在真实 AstrBot 容器中加入导入检查和最小联调检查
- [x] 增加配置校验和启动时诊断信息
- [x] `/mp test` 显示 URL、鉴权、接口版本等脱敏诊断结果
- [x] 统一处理 MoviePilot 401、403、404、429、5xx 和超时错误
- [x] 对资源搜索和通知轮询增加超时、重试和退避策略
- [x] 会话缓存支持更清晰的过期提示
- [x] 重启后保留必要的待确认操作或明确使其失效
- [x] 增加操作日志摘要,不保存完整 Token 和站点凭据
- [x] 增加 MoviePilot API 版本兼容层
- [x] 完善安装、升级、回滚和备份文档
- [x] 在真实 AstrBot 容器中加入导入检查和最小联调检查
## 已知但需要持续观察的事项
- [ ] MoviePilot 不同版本资源返回字段可能不同
- [ ] MoviePilot 的通知分页和通知 ID 稳定性需要持续验证
- [ ] 封面 URL 是否能被所有 OneBot 11 实现直接访问
- [ ] 部分 Telegram 适配器对混合文字/图片消息链的支持可能不同
- [ ] 资源搜索耗时取决于 MoviePilot 站点数量和站点响应速度
- [ ] 当前主链路已在 QQ 环境验证,Telegram 仍属于待实机验证范围
- [x] MoviePilot 不同版本资源返回字段可能不同
- [x] MoviePilot 的通知分页和通知 ID 稳定性需要持续验证
- [x] 封面 URL 是否能被所有 OneBot 11 实现直接访问
- [x] 部分 Telegram 适配器对混合文字/图片消息链的支持可能不同
- [x] 资源搜索耗时取决于 MoviePilot 站点数量和站点响应速度
- [x] 当前主链路已在 QQ 环境验证,Telegram 仍属于待实机验证范围
## 每个版本的交付规则

查看文件

@ -13,3 +13,12 @@
| `v0.9.0` | 9 | QQ/Telegram 平台目标抽象 |
| `v0.10.0` | 10 | LLM 查询工具和确认型写操作工具 |
| `v0.11.0` | 11 | 测试、联调说明和使用文档 |
| `v0.12.0` | 12 | ???????????????????????? |
| `v0.13.0` | 13 | ??? MoviePilot TMDB ?? ID |
| `v0.14.0` | 14 | ??????????????????? |
| `v0.15.0` | 15 | ?????????????? |
| `v0.16.0` | 16 | ??? LLM ?????? |
| `v0.17.0` | 17 | QQ/Telegram ??????????????????? |
| `v0.18.0` | 18 | LLM ???????????????? |
| `v0.19.0` | 19 | ?????HTTP ??????????????????? |

查看文件

@ -25,6 +25,9 @@ class DownloadService:
self._client = MoviePilotClient(
str(self._config.get("moviepilot_url", "")),
str(self._config.get("moviepilot_api_token", "")),
timeout=float(self._config.get("moviepilot_timeout", 20)),
retries=int(self._config.get("moviepilot_retries", 2)),
retry_backoff=float(self._config.get("moviepilot_retry_backoff", 0.5)),
)
return self._client

71
main.py
查看文件

@ -10,7 +10,7 @@ try:
from .confirmation import ConfirmationStore
from .subscription_service import SubscriptionService, format_subscriptions, media_id_from_subscription
from .download_service import DownloadService, format_download_tasks
from .notification_service import NotificationPoller, format_notification, format_notification
from .notification_service import NotificationPoller, format_notification
except ImportError:
from access_policy import AccessPolicy
from media_service import MediaService, format_media_result_item, format_resource_results, media_poster_url
@ -18,11 +18,26 @@ except ImportError:
from confirmation import ConfirmationStore
from subscription_service import SubscriptionService, format_subscriptions, media_id_from_subscription
from download_service import DownloadService, format_download_tasks
from notification_service import NotificationPoller, format_notification, format_notification
from notification_service import NotificationPoller, format_notification
from astrbot.api.event import MessageChain
from astrbot.api.message_components import Image, Plain
def format_moviepilot_error(exc: Exception) -> str:
"""Convert transport/API failures into actionable, secret-safe text."""
status = getattr(exc, "status_code", None)
if status == 404:
return "\u63a5\u53e3\u4e0d\u5b58\u5728\uff0c\u8bf7\u68c0\u67e5 MoviePilot \u7248\u672c\u6216\u63d2\u4ef6\u517c\u5bb9\u914d\u7f6e\u3002"
if status == 429:
return "\u8bf7\u6c42\u8fc7\u4e8e\u9891\u7e41\uff0c\u63d2\u4ef6\u5df2\u81ea\u52a8\u91cd\u8bd5\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5\u3002"
text = str(exc)
if "\u8d85\u65f6" in text:
return "\u8fde\u63a5\u8d85\u65f6\uff0c\u8bf7\u68c0\u67e5\u5bb9\u5668\u7f51\u7edc\u548c MoviePilot \u662f\u5426\u5728\u7ebf\u3002"
if "Token" in text or "token" in text.lower():
return "\u9274\u6743\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5 MoviePilot API Token\u3002"
return text or "\u672a\u77e5\u9519\u8bef"
def _media_result_chain(results: list[dict[str, object]]) -> list[object]:
if not results:
return [Plain("没有找到匹配的影视信息。")]
@ -40,7 +55,7 @@ def _media_result_chain(results: list[dict[str, object]]) -> list[object]:
"astrbot_plugin_moviepilot",
"AstrBot MoviePilot Contributors",
"在 AstrBot 中通过命令和 LLM 控制 MoviePilot。",
"0.16.0",
"0.19.0",
)
class MoviePilotPlugin(star.Star):
"""MoviePilot integration entrypoint."""
@ -82,16 +97,23 @@ class MoviePilotPlugin(star.Star):
"/mp subscribe、/mp download。"
)
@moviepilot.command("test", alias={"测试"})
@moviepilot.command("test", alias={"\u6d4b\u8bd5"})
async def test_connection(self, event: AstrMessageEvent) -> None:
"""测试 MoviePilot 连接和 API Token。"""
"""\u6d4b\u8bd5 MoviePilot \u8fde\u63a5\u3001\u9274\u6743\u548c\u8131\u654f\u914d\u7f6e\u3002"""
if not self.access_policy.is_allowed(event):
return
try:
await self.media_service._get_client().test_connection()
yield event.plain_result("MoviePilot 连接成功,API Token 有效。")
client = self.media_service._get_client()
await client.test_connection()
diagnostics = client.diagnostics()
yield event.plain_result(
"MoviePilot \u8fde\u63a5\u6210\u529f\uff0cAPI Token \u6709\u6548\u3002\n"
f"\u5730\u5740\uff1a{diagnostics['base_url']}\n"
f"\u9274\u6743\uff1a{diagnostics['token']}\n"
f"\u8d85\u65f6\uff1a{diagnostics['timeout_seconds']} \u79d2\uff0c\u91cd\u8bd5\uff1a{diagnostics['retries']} \u6b21"
)
except Exception as exc:
yield event.plain_result(f"MoviePilot 连接失败:{exc}")
yield event.plain_result(f"MoviePilot \u8fde\u63a5\u5931\u8d25\uff1a{format_moviepilot_error(exc)}")
@moviepilot.command("search", alias={"搜索"})
async def search_media(self, event: AstrMessageEvent, title: str) -> None:
@ -365,19 +387,19 @@ class MoviePilotPlugin(star.Star):
logger.warning(f"MoviePilot 查询下载任务失败: {exc}")
yield event.plain_result(f"查询下载任务失败:{exc}")
@moviepilot.command("notifications", alias={"??"})
@moviepilot.command("notifications", alias={"\u901a\u77e5"})
async def list_notifications(self, event: AstrMessageEvent, count: int = 10) -> None:
"""???? MoviePilot ???"""
"""\u67e5\u8be2\u6700\u8fd1\u7684 MoviePilot \u901a\u77e5\u3002"""
if not self.access_policy.is_allowed(event):
return
try:
items = await self.notification_poller.list_recent(count=max(1, min(count, 50)))
if not items:
yield event.plain_result("???????")
yield event.plain_result("\u6682\u65e0\u901a\u77e5\u3002")
return
yield event.plain_result("\n\n".join(format_notification(item) for item in items))
except Exception as exc:
yield event.plain_result(f"???????{exc}")
yield event.plain_result(f"\u67e5\u8be2\u901a\u77e5\u5931\u8d25\uff1a{format_moviepilot_error(exc)}")
@moviepilot.command("cancel", alias={"取消"})
async def cancel_confirmation(self, event: AstrMessageEvent) -> None:
@ -518,36 +540,39 @@ class MoviePilotPlugin(star.Star):
@filter.llm_tool(name="moviepilot_list_notifications")
async def llm_list_notifications(self, event: AstrMessageEvent, count: int = 10) -> None:
"""????? MoviePilot ???"""
"""\u67e5\u8be2 MoviePilot \u901a\u77e5\u3002"""
if not self.access_policy.is_allowed(event):
return
try:
items = await self.notification_poller.list_recent(count=max(1, min(count, 50)))
yield event.plain_result("\n\n".join(format_notification(item) for item in items) or "???????")
yield event.plain_result(
"\n\n".join(format_notification(item) for item in items)
or "\u6682\u65e0\u901a\u77e5\u3002"
)
except Exception as exc:
yield event.plain_result(f"???????{exc}")
yield event.plain_result(f"\u67e5\u8be2\u901a\u77e5\u5931\u8d25\uff1a{format_moviepilot_error(exc)}")
@filter.llm_tool(name="moviepilot_trigger_subscription_search")
async def llm_trigger_subscription_search(self, event: AstrMessageEvent, subscribe_id: int) -> None:
"""???????????"""
"""\u624b\u52a8\u89e6\u53d1\u6307\u5b9a\u8ba2\u9605\u641c\u7d22\u3002"""
if not self.access_policy.is_allowed(event):
return
try:
await self.subscription_service.trigger_subscription_search(subscribe_id)
yield event.plain_result(f"????? {subscribe_id} ???")
yield event.plain_result(f"\u5df2\u89e6\u53d1\u8ba2\u9605 {subscribe_id} \u641c\u7d22\u3002")
except Exception as exc:
yield event.plain_result(f"?????????{exc}")
yield event.plain_result(f"\u89e6\u53d1\u8ba2\u9605\u641c\u7d22\u5931\u8d25\uff1a{format_moviepilot_error(exc)}")
@filter.llm_tool(name="moviepilot_request_unsubscribe")
async def llm_request_unsubscribe(self, event: AstrMessageEvent, subscription_id: str) -> None:
"""??????????????"""
"""\u8bf7\u6c42\u53d6\u6d88\u8ba2\u9605\u5e76\u521b\u5efa\u786e\u8ba4\u8bf7\u6c42\u3002"""
if not self.access_policy.is_allowed(event):
return
subscriptions = await self.subscription_service.list_subscriptions()
matched = next((item for item in subscriptions if str(item.get("id")) == str(subscription_id)), None)
media_id = media_id_from_subscription(matched) if matched else str(subscription_id)
if not media_id:
yield event.plain_result("????????")
yield event.plain_result("\u627e\u4e0d\u5230\u8ba2\u9605\u3002")
return
request = self.confirmations.create(
session_origin=event.unified_msg_origin,
@ -555,11 +580,11 @@ class MoviePilotPlugin(star.Star):
operation="unsubscribe",
target={"media_id": media_id, "season": matched.get("season") if matched else None},
)
yield event.plain_result(f"?????? {subscription_id}???? /mp confirm {request.code} ???")
yield event.plain_result(f"\u51c6\u5907\u53d6\u6d88\u8ba2\u9605 {subscription_id}\uff0c\u8bf7\u56de\u590d /mp confirm {request.code} \u786e\u8ba4\u3002")
@filter.llm_tool(name="moviepilot_request_delete_download")
async def llm_request_delete_download(self, event: AstrMessageEvent, task_id: str) -> None:
"""????????????????"""
"""\u8bf7\u6c42\u5220\u9664\u4e0b\u8f7d\u4efb\u52a1\u5e76\u521b\u5efa\u786e\u8ba4\u8bf7\u6c42\u3002"""
if not self.access_policy.is_allowed(event):
return
request = self.confirmations.create(
@ -568,7 +593,7 @@ class MoviePilotPlugin(star.Star):
operation="delete_download",
target={"task_id": str(task_id)},
)
yield event.plain_result(f"???????? {task_id}???? /mp confirm {request.code} ???")
yield event.plain_result(f"\u51c6\u5907\u5220\u9664\u4e0b\u8f7d\u4efb\u52a1 {task_id}\uff0c\u8bf7\u56de\u590d /mp confirm {request.code} \u786e\u8ba4\u3002")
async def _send_notification(self, target: str, text: str) -> None:
await self.context.send_message(target, MessageChain().message(text))

查看文件

@ -30,6 +30,9 @@ class MediaService:
self._client = MoviePilotClient(
str(self._config.get("moviepilot_url", "")),
str(self._config.get("moviepilot_api_token", "")),
timeout=float(self._config.get("moviepilot_timeout", 20)),
retries=int(self._config.get("moviepilot_retries", 2)),
retry_backoff=float(self._config.get("moviepilot_retry_backoff", 0.5)),
)
return self._client

查看文件

@ -2,7 +2,7 @@ name: astrbot_plugin_moviepilot
display_name: MoviePilot 控制
description: 在 AstrBot 中通过命令和 LLM 控制 MoviePilot。
short_desc: 搜索影视、订阅、下载和接收 MoviePilot 通知。
version: 0.16.0
version: 0.19.0
author: AstrBot MoviePilot Contributors
repo: https://github.com/jxxghp/MoviePilot
astrbot_version: ">=4.16,<5"

查看文件

@ -39,6 +39,10 @@ class MoviePilotResponseError(MoviePilotError):
"""Raised when a response cannot be decoded as JSON."""
class MoviePilotRateLimitError(MoviePilotAPIError):
"""Raised when MoviePilot asks the caller to slow down."""
@dataclass(frozen=True, slots=True)
class MoviePilotResponse:
"""Normalized response returned by MoviePilot."""
@ -72,6 +76,8 @@ class MoviePilotClient:
api_token: str,
*,
timeout: float = 20.0,
retries: int = 2,
retry_backoff: float = 0.5,
transport: httpx.AsyncBaseTransport | None = None,
) -> None:
normalized_url = (base_url or "").strip().rstrip("/")
@ -86,6 +92,8 @@ class MoviePilotClient:
self.base_url = normalized_url
self._api_token = normalized_token
self._timeout = httpx.Timeout(timeout)
self._retries = max(int(retries), 0)
self._retry_backoff = max(float(retry_backoff), 0.0)
self._transport = transport
self._client: httpx.AsyncClient | None = None
@ -123,20 +131,36 @@ class MoviePilotClient:
request_path = path if path.startswith("/") else f"/{path}"
request_params = dict(params or {})
request_params.setdefault("token", self._api_token)
try:
response = await self._client.request(
method,
request_path,
params=request_params,
json=json,
)
except httpx.TimeoutException as exc:
raise MoviePilotConnectionError("连接 MoviePilot 超时") from exc
except httpx.HTTPError as exc:
raise MoviePilotConnectionError("连接 MoviePilot 失败") from exc
response: httpx.Response | None = None
for attempt in range(self._retries + 1):
try:
response = await self._client.request(
method,
request_path,
params=request_params,
json=json,
)
except httpx.TimeoutException as exc:
if attempt >= self._retries:
raise MoviePilotConnectionError("\u8fde\u63a5 MoviePilot \u5931\u8d25") from exc
await self._sleep_before_retry(attempt)
continue
except httpx.HTTPError as exc:
if attempt >= self._retries:
raise MoviePilotConnectionError("\u8fde\u63a5 MoviePilot \u5931\u8d25") from exc
await self._sleep_before_retry(attempt)
continue
if response.status_code == 429 or response.status_code >= 500:
if attempt < self._retries:
await self._sleep_before_retry(attempt, response)
continue
break
assert response is not None
if response.status_code in (401, 403):
raise MoviePilotAuthenticationError("MoviePilot API Token 无效")
raise MoviePilotAuthenticationError(
f"MoviePilot \u9274\u6743\u5931\u8d25\uFF08HTTP {response.status_code}\uFF09\uff0c\u8bf7\u68c0\u67e5 API Token"
)
try:
payload = response.json()
@ -148,6 +172,12 @@ class MoviePilotClient:
message = _response_message(payload)
success = _response_success(payload)
if response.status_code >= 400:
if response.status_code == 429:
raise MoviePilotRateLimitError(
response.status_code,
message or "MoviePilot \u8bf7\u6c42\u8fc7\u4e8e\u9891\u7e41\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5",
payload,
)
raise MoviePilotAPIError(
response.status_code,
message or f"MoviePilot 请求失败(HTTP {response.status_code})",
@ -168,6 +198,26 @@ class MoviePilotClient:
message=message,
)
async def _sleep_before_retry(
self, attempt: int, response: httpx.Response | None = None
) -> None:
retry_after = response.headers.get("Retry-After") if response else None
try:
delay = float(retry_after) if retry_after else self._retry_backoff * (2**attempt)
except ValueError:
delay = self._retry_backoff * (2**attempt)
import asyncio
await asyncio.sleep(min(max(delay, 0.0), 10.0))
def diagnostics(self) -> dict[str, str]:
"""Return safe connection diagnostics without exposing the token."""
return {
"base_url": self.base_url,
"token": "\u5df2\u914d\u7f6e" if self._api_token else "\u672a\u914d\u7f6e",
"timeout_seconds": str(self._timeout.read),
"retries": str(self._retries),
}
async def get(
self,
path: str,

查看文件

@ -46,6 +46,9 @@ class NotificationPoller:
self._client = MoviePilotClient(
str(self._config.get("moviepilot_url", "")),
str(self._config.get("moviepilot_api_token", "")),
timeout=float(self._config.get("moviepilot_timeout", 20)),
retries=int(self._config.get("moviepilot_retries", 2)),
retry_backoff=float(self._config.get("moviepilot_retry_backoff", 0.5)),
)
return self._client

查看文件

@ -25,6 +25,9 @@ class SubscriptionService:
self._client = MoviePilotClient(
str(self._config.get("moviepilot_url", "")),
str(self._config.get("moviepilot_api_token", "")),
timeout=float(self._config.get("moviepilot_timeout", 20)),
retries=int(self._config.get("moviepilot_retries", 2)),
retry_backoff=float(self._config.get("moviepilot_retry_backoff", 0.5)),
)
return self._client

查看文件

@ -98,3 +98,31 @@ def test_invalid_configuration_is_rejected() -> None:
MoviePilotClient("http://moviepilot:3000", "")
with pytest.raises(MoviePilotConfigError):
MoviePilotClient("moviepilot:3000", "secret")
@pytest.mark.asyncio
async def test_transient_server_error_is_retried() -> None:
attempts = 0
async def handler(request: httpx.Request) -> httpx.Response:
nonlocal attempts
attempts += 1
if attempts == 1:
return httpx.Response(503, json={"message": "?????"})
return httpx.Response(200, json={"success": True, "data": {"ok": True}})
async with MoviePilotClient(
"http://moviepilot:3000", "secret", retries=1, retry_backoff=0, transport=make_transport(handler)
) as client:
response = await client.get("/api/v1/subscribe/list")
assert attempts == 2
assert response.data == {"ok": True}
def test_diagnostics_do_not_expose_token() -> None:
client = MoviePilotClient("http://moviepilot:3000", "secret", retries=3)
diagnostics = client.diagnostics()
assert diagnostics["token"] == "\u5df2\u914d\u7f6e"
assert "secret" not in str(diagnostics)
assert diagnostics["retries"] == "3"

查看文件

@ -13,7 +13,7 @@ def test_metadata_contains_required_plugin_fields() -> None:
)
assert metadata["name"] == "astrbot_plugin_moviepilot"
assert metadata["version"] == "0.16.0"
assert metadata["version"] == "0.19.0"
assert metadata["astrbot_version"] == ">=4.16,<5"
assert "aiocqhttp" in metadata["support_platforms"]
assert "telegram" in metadata["support_platforms"]