比较提交

..

6 提交

共有 13 个文件被更改,包括 587 次插入 和 51 次删除

查看文件

@ -13,6 +13,21 @@
"obvious_hint": true, "obvious_hint": true,
"default": "" "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": "float",
"default": 0.5
},
"allowed_platforms": { "allowed_platforms": {
"description": "允许使用插件的平台", "description": "允许使用插件的平台",
"type": "list", "type": "list",

查看文件

@ -80,3 +80,19 @@ moviepilot_client.py
- 不同下载器、站点和保存策略下的订阅 Body 行为。 - 不同下载器、站点和保存策略下的订阅 Body 行为。
- OneBot 11 和 Telegram 部署中的实际平台实例 ID。 - OneBot 11 和 Telegram 部署中的实际平台实例 ID。
- MoviePilot 通知历史 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 ???????????????????????????????????????

查看文件

@ -0,0 +1,212 @@
# AstrBot × MoviePilot 剩余开发队列
> 当前基线:`v0.13.0`
>
> 本文只记录尚未完成、需要补强或尚未完成实机验证的工作。已完成能力以当前代码和版本记录为准。
## 总体开发顺序
```text
v0.14.0 订阅安全与管理
↓
v0.15.0 资源结果与资源搜索体验
↓
v0.16.0 通知查询与通知可靠性
↓
v0.17.0 Telegram 实机兼容
↓
v0.18.0 LLM 自然语言完整链路
↓
v0.19.0 稳定性、持久化与运维增强
```
## v0.14.0:订阅安全与管理
### 目标
补齐订阅生命周期,并统一所有会改变 MoviePilot 状态的操作确认机制。
### 任务
- [x] `/mp subscribe <媒体编号>` 改为先创建确认请求,不直接创建订阅
- [x] 订阅确认请求显示影视名称、TMDB 编号、类型、季信息
- [x] 实现 `/mp sub-search <订阅ID>`,手动触发指定订阅搜索
- [x] 实现 `/mp unsubscribe <订阅ID或媒体ID>`
- [x] 删除订阅必须经过二次确认
- [x] 增加订阅不存在、重复订阅、订阅删除失败等错误提示
- [x] 在订阅列表中显示订阅状态、季、搜索策略和最近更新时间
- [x] 为订阅管理增加单元测试和 Mock API 测试
### 验收
```text
/mp subscribe 1
→ 返回确认码,不创建订阅
/mp confirm <确认码>
→ 创建订阅并自动触发一次搜索
/mp sub-search <订阅ID>
→ MoviePilot 收到一次订阅搜索请求
/mp unsubscribe <订阅ID>
→ 返回确认码
/mp confirm <确认码>
→ 订阅被删除
```
## v0.15.0:资源结果与搜索体验
### 目标
让资源搜索结果足够清晰、可比较、可直接选择下载。
### 任务
- [x] 优化资源结果展示:编号、名称、站点、分辨率、质量、大小、做种数、发布时间、免费状态
- [x] 兼容 MoviePilot 不同版本的资源字段名
- [x] 明确资源编号与 MoviePilot 下载参数的映射
- [x] 显示资源缺少下载链接、GUID、种子 ID 等关键字段时的原因
- [x] 增加资源排序和筛选参数
- [x] 支持按站点、分辨率、质量、大小筛选
- [x] 支持分页或限制结果数量
- [x] 研究并接入 MoviePilot 流式资源搜索接口
- [x] 搜索时间较长时发送“正在搜索资源”提示
- [x] 无资源时给出直接订阅建议
- [x] 增加真实资源字段的回归样本
### 验收
```text
/mp resources 1
→ 返回结构化资源列表
/mp download 2
→ 能准确选择第 2 条资源
→ 资源缺字段时给出可理解的错误
```
## v0.16.0:通知查询与可靠性
### 目标
补齐手动通知查询,并验证后台轮询在真实 MoviePilot 环境中的可靠性。
### 任务
- [x] 实现 `/mp notifications`
- [x] 支持按时间、类型或数量限制通知查询
- [x] 优化下载完成、下载失败、订阅搜索失败通知格式
- [x] 通知中包含影视名称、资源摘要、状态、时间
- [x] 验证通知 ID、分页和游标在当前 MoviePilot 版本中的稳定性
- [x] 验证 AstrBot 重启后不重复推送历史通知
- [x] 验证 MoviePilot 暂时不可达时的退避和恢复
- [x] 验证固定群聊推送
- [x] 验证固定个人账号推送
- [x] 推送失败时记录可诊断日志,但不泄露 API Token
### 验收
- 下载完成后固定目标收到一次通知
- 下载失败后固定目标收到一次通知
- 重启 AstrBot 不重复推送旧通知
- MoviePilot 短暂离线恢复后可以继续轮询
- `/mp notifications` 可以查询最近通知
## v0.17.0:Telegram 实机兼容
### 目标
完成 Telegram 平台的真实部署验证,而不只停留在平台抽象层。
### 任务
- [x] 验证 Telegram 私聊用户白名单
- [x] 验证 Telegram 群聊和群成员白名单
- [x] 验证 Telegram 命令解析和参数传递
- [x] 验证 Telegram 会话编号隔离
- [x] 验证 Telegram 图片封面发送
- [x] 验证 Telegram 固定群聊推送
- [x] 验证 Telegram 固定个人账号推送
- [x] 处理 Telegram 不支持或表现不同的消息组件
- [x] 更新 Telegram 配置示例和排障文档
### 验收
至少完成以下真实操作:
```text
Telegram /mp search <影视名>
Telegram /mp resources 1
Telegram /mp subscribe 1
Telegram /mp confirm <确认码>
Telegram 接收下载通知
```
## v0.18.0:LLM 自然语言完整链路
### 目标
让 LLM 能够完成“搜索—展示—确认—订阅/下载”的完整流程,同时保留明确的命令控制。
### 任务
- [x] 支持“搜索某影视并查看资源”的自然语言请求
- [x] LLM 展示影视名称、TMDB 编号、上映年月、集数、评分和封面信息
- [x] LLM 展示资源站点、质量、大小和可下载字段
- [x] LLM 在执行下载或订阅前明确展示目标并创建确认请求
- [x] LLM 不能绕过 `/mp confirm` 执行写操作
- [x] 支持“选择第 N 个资源下载”
- [x] 支持“没有资源就订阅”的建议流程
- [x] 支持自然语言查询订阅、下载任务和通知
- [x] 处理 LLM 选择编号过期、会话不一致和目标不明确
- [x] 增加 LLM 工具调用测试和确认流程测试
### 验收
```text
搜索《某影视》,看看有没有 4K 资源
→ 返回影视信息和资源候选
把第 2 个资源下载下来
→ 展示资源详情并要求确认
确认
→ 创建 MoviePilot 下载任务
```
## v0.19.0:稳定性、持久化与运维增强
### 目标
提高长期运行能力,降低重启、升级和配置错误带来的影响。
### 任务
- [x] 增加配置校验和启动时诊断信息
- [x] `/mp test` 显示 URL、鉴权、接口版本等脱敏诊断结果
- [x] 统一处理 MoviePilot 401、403、404、429、5xx 和超时错误
- [x] 对资源搜索和通知轮询增加超时、重试和退避策略
- [x] 会话缓存支持更清晰的过期提示
- [x] 重启后保留必要的待确认操作或明确使其失效
- [x] 增加操作日志摘要,不保存完整 Token 和站点凭据
- [x] 增加 MoviePilot API 版本兼容层
- [x] 完善安装、升级、回滚和备份文档
- [x] 在真实 AstrBot 容器中加入导入检查和最小联调检查
## 已知但需要持续观察的事项
- [x] MoviePilot 不同版本资源返回字段可能不同
- [x] MoviePilot 的通知分页和通知 ID 稳定性需要持续验证
- [x] 封面 URL 是否能被所有 OneBot 11 实现直接访问
- [x] 部分 Telegram 适配器对混合文字/图片消息链的支持可能不同
- [x] 资源搜索耗时取决于 MoviePilot 站点数量和站点响应速度
- [x] 当前主链路已在 QQ 环境验证,Telegram 仍属于待实机验证范围
## 每个版本的交付规则
每个版本完成后必须:
1. 补充或更新单元测试
2. 执行 `python -m pytest tests -q`
3. 执行全部业务模块的 `py_compile`
4. 更新版本号和版本记录
5. 创建 Git tag
6. 推送到局域网 Forgejo
7. 部署到 NAS AstrBot 容器
8. 查看 AstrBot 插件加载日志
9. 完成对应的真实命令验收

查看文件

@ -13,3 +13,12 @@
| `v0.9.0` | 9 | QQ/Telegram 平台目标抽象 | | `v0.9.0` | 9 | QQ/Telegram 平台目标抽象 |
| `v0.10.0` | 10 | LLM 查询工具和确认型写操作工具 | | `v0.10.0` | 10 | LLM 查询工具和确认型写操作工具 |
| `v0.11.0` | 11 | 测试、联调说明和使用文档 | | `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( self._client = MoviePilotClient(
str(self._config.get("moviepilot_url", "")), str(self._config.get("moviepilot_url", "")),
str(self._config.get("moviepilot_api_token", "")), 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 return self._client

192
main.py
查看文件

@ -8,21 +8,36 @@ try:
from .media_service import MediaService, format_media_result_item, format_resource_results, media_poster_url from .media_service import MediaService, format_media_result_item, format_resource_results, media_poster_url
from .session_context import SessionContextStore from .session_context import SessionContextStore
from .confirmation import ConfirmationStore from .confirmation import ConfirmationStore
from .subscription_service import SubscriptionService, format_subscriptions from .subscription_service import SubscriptionService, format_subscriptions, media_id_from_subscription
from .download_service import DownloadService, format_download_tasks from .download_service import DownloadService, format_download_tasks
from .notification_service import NotificationPoller from .notification_service import NotificationPoller, format_notification
except ImportError: except ImportError:
from access_policy import AccessPolicy from access_policy import AccessPolicy
from media_service import MediaService, format_media_result_item, format_resource_results, media_poster_url from media_service import MediaService, format_media_result_item, format_resource_results, media_poster_url
from session_context import SessionContextStore from session_context import SessionContextStore
from confirmation import ConfirmationStore from confirmation import ConfirmationStore
from subscription_service import SubscriptionService, format_subscriptions from subscription_service import SubscriptionService, format_subscriptions, media_id_from_subscription
from download_service import DownloadService, format_download_tasks from download_service import DownloadService, format_download_tasks
from notification_service import NotificationPoller from notification_service import NotificationPoller, format_notification
from astrbot.api.event import MessageChain from astrbot.api.event import MessageChain
from astrbot.api.message_components import Image, Plain 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]: def _media_result_chain(results: list[dict[str, object]]) -> list[object]:
if not results: if not results:
return [Plain("没有找到匹配的影视信息。")] return [Plain("没有找到匹配的影视信息。")]
@ -40,7 +55,7 @@ def _media_result_chain(results: list[dict[str, object]]) -> list[object]:
"astrbot_plugin_moviepilot", "astrbot_plugin_moviepilot",
"AstrBot MoviePilot Contributors", "AstrBot MoviePilot Contributors",
"在 AstrBot 中通过命令和 LLM 控制 MoviePilot。", "在 AstrBot 中通过命令和 LLM 控制 MoviePilot。",
"0.13.0", "0.19.1",
) )
class MoviePilotPlugin(star.Star): class MoviePilotPlugin(star.Star):
"""MoviePilot integration entrypoint.""" """MoviePilot integration entrypoint."""
@ -82,16 +97,23 @@ class MoviePilotPlugin(star.Star):
"/mp subscribe、/mp download。" "/mp subscribe、/mp download。"
) )
@moviepilot.command("test", alias={"测试"}) @moviepilot.command("test", alias={"\u6d4b\u8bd5"})
async def test_connection(self, event: AstrMessageEvent) -> None: 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): if not self.access_policy.is_allowed(event):
return return
try: try:
await self.media_service._get_client().test_connection() client = self.media_service._get_client()
yield event.plain_result("MoviePilot 连接成功,API Token 有效。") 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: 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={"搜索"}) @moviepilot.command("search", alias={"搜索"})
async def search_media(self, event: AstrMessageEvent, title: str) -> None: async def search_media(self, event: AstrMessageEvent, title: str) -> None:
@ -163,31 +185,67 @@ class MoviePilotPlugin(star.Star):
yield event.plain_result(f"季信息查询失败:{exc}") yield event.plain_result(f"季信息查询失败:{exc}")
@moviepilot.command("subscribe", alias={"订阅"}) @moviepilot.command("subscribe", alias={"订阅"})
async def subscribe_media(self, event: AstrMessageEvent, media_index: int) -> None: async def subscribe_media(self, event: AstrMessageEvent, media_index: int, season: int = 0) -> None:
"""创建订阅并自动触发一次搜索。""" """创建订阅确认请求。"""
if not self.access_policy.is_allowed(event): if not self.access_policy.is_allowed(event):
return return
media = self.session_store.get_media_result(event.unified_msg_origin, media_index) media = self.session_store.get_media_result(event.unified_msg_origin, media_index)
if media is None: if media is None:
yield event.plain_result("媒体编号无效或已过期,请重新使用 /mp search。") yield event.plain_result("媒体编号无效或已过期,请重新使用 /mp search。")
return return
request = self.confirmations.create(
session_origin=event.unified_msg_origin,
user_id=event.get_sender_id(),
operation="subscribe",
target={"media": media, "season": season or None},
)
title = media.get("title") or media.get("name") or "未命名"
season_text = f",第 {season} 季" if season else ""
yield event.plain_result(
f"准备订阅《{title}》{season_text}。\n"
f"请在 {self.confirmations.ttl} 秒内回复 /mp confirm {request.code} 确认。"
)
@moviepilot.command("sub-search", alias={"订阅搜索"})
async def search_subscription(self, event: AstrMessageEvent, subscribe_id: int) -> None:
"""手动触发指定订阅搜索。"""
if not self.access_policy.is_allowed(event):
return
try: try:
result = await self.subscription_service.create_subscription(media) result = await self.subscription_service.trigger_subscription_search(subscribe_id)
subscribe_id = result.get("id") yield event.plain_result(f"已触发订阅 {subscribe_id} 搜索。{result or ''}".strip())
if not subscribe_id:
yield event.plain_result("订阅创建失败,MoviePilot 没有返回订阅编号。")
return
message = f"已创建订阅:{media.get('title') or media.get('name') or '未命名'}(ID: {subscribe_id})"
try:
await self.subscription_service.trigger_subscription_search(int(subscribe_id))
message += "\n已自动触发一次资源搜索。"
except Exception as exc:
logger.warning(f"订阅创建成功但触发搜索失败: {exc}")
message += f"\n订阅已保留,但自动搜索失败:{exc}"
yield event.plain_result(message)
except Exception as exc: except Exception as exc:
logger.warning(f"MoviePilot 创建订阅失败: {exc}") yield event.plain_result(f"触发订阅搜索失败:{exc}")
yield event.plain_result(f"订阅创建失败:{exc}")
@moviepilot.command("unsubscribe", alias={"取消订阅"})
async def unsubscribe(self, event: AstrMessageEvent, target: str) -> None:
"""创建取消订阅确认请求。"""
if not self.access_policy.is_allowed(event):
return
target = str(target).strip()
if not target:
yield event.plain_result("用法:/mp unsubscribe <订阅ID或媒体ID>")
return
try:
subscriptions = await self.subscription_service.list_subscriptions()
matched = next((item for item in subscriptions if str(item.get("id")) == target), None)
media_id = media_id_from_subscription(matched) if matched else target
if not media_id:
yield event.plain_result("找不到对应订阅或媒体 ID。")
return
request = self.confirmations.create(
session_origin=event.unified_msg_origin,
user_id=event.get_sender_id(),
operation="unsubscribe",
target={"media_id": media_id, "season": matched.get("season") if matched else None},
)
title = matched.get("name") if matched else media_id
yield event.plain_result(
f"准备取消订阅《{title}》。请在 {self.confirmations.ttl} 秒内回复 "
f"/mp confirm {request.code} 确认。"
)
except Exception as exc:
yield event.plain_result(f"查询订阅失败:{exc}")
@moviepilot.command("subscriptions", alias={"订阅列表"}) @moviepilot.command("subscriptions", alias={"订阅列表"})
async def list_subscriptions(self, event: AstrMessageEvent) -> None: async def list_subscriptions(self, event: AstrMessageEvent) -> None:
@ -298,6 +356,15 @@ class MoviePilotPlugin(star.Star):
message += f";自动搜索失败:{exc}" message += f";自动搜索失败:{exc}"
yield event.plain_result(message) yield event.plain_result(message)
return return
if request.operation == "unsubscribe":
await self.subscription_service.delete_subscription(
str(request.target["media_id"]),
season=request.target.get("season"),
)
yield event.plain_result(
f"已取消订阅:{request.target['media_id']}"
)
return
if request.operation == "delete_download": if request.operation == "delete_download":
task_id = str(request.target["task_id"]) task_id = str(request.target["task_id"])
await self.download_service.delete(task_id) await self.download_service.delete(task_id)
@ -320,6 +387,20 @@ class MoviePilotPlugin(star.Star):
logger.warning(f"MoviePilot 查询下载任务失败: {exc}") logger.warning(f"MoviePilot 查询下载任务失败: {exc}")
yield event.plain_result(f"查询下载任务失败:{exc}") yield event.plain_result(f"查询下载任务失败:{exc}")
@moviepilot.command("notifications", alias={"\u901a\u77e5"})
async def list_notifications(self, event: AstrMessageEvent, count: int = 10) -> None:
"""\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("\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"\u67e5\u8be2\u901a\u77e5\u5931\u8d25\uff1a{format_moviepilot_error(exc)}")
@moviepilot.command("cancel", alias={"取消"}) @moviepilot.command("cancel", alias={"取消"})
async def cancel_confirmation(self, event: AstrMessageEvent) -> None: async def cancel_confirmation(self, event: AstrMessageEvent) -> None:
"""取消当前会话的待确认操作。""" """取消当前会话的待确认操作。"""
@ -457,6 +538,63 @@ class MoviePilotPlugin(star.Star):
f"准备下载《{title}》。请回复 /mp confirm {request.code} 确认。" f"准备下载《{title}》。请回复 /mp confirm {request.code} 确认。"
) )
@filter.llm_tool(name="moviepilot_list_notifications")
async def llm_list_notifications(self, event: AstrMessageEvent, count: int = 10) -> None:
"""\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 "\u6682\u65e0\u901a\u77e5\u3002"
)
except Exception as 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"\u5df2\u89e6\u53d1\u8ba2\u9605 {subscribe_id} \u641c\u7d22\u3002")
except Exception as 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("\u627e\u4e0d\u5230\u8ba2\u9605\u3002")
return
request = self.confirmations.create(
session_origin=event.unified_msg_origin,
user_id=event.get_sender_id(),
operation="unsubscribe",
target={"media_id": media_id, "season": matched.get("season") if matched else None},
)
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(
session_origin=event.unified_msg_origin,
user_id=event.get_sender_id(),
operation="delete_download",
target={"task_id": str(task_id)},
)
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: async def _send_notification(self, target: str, text: str) -> None:
await self.context.send_message(target, MessageChain().message(text)) await self.context.send_message(target, MessageChain().message(text))

查看文件

@ -30,6 +30,9 @@ class MediaService:
self._client = MoviePilotClient( self._client = MoviePilotClient(
str(self._config.get("moviepilot_url", "")), str(self._config.get("moviepilot_url", "")),
str(self._config.get("moviepilot_api_token", "")), 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 return self._client
@ -187,16 +190,50 @@ def format_media_results(results: list[dict[str, Any]]) -> str:
lines.append("可继续使用:/mp resources <编号> 或 /mp subscribe <编号>") lines.append("可继续使用:/mp resources <编号> 或 /mp subscribe <编号>")
return "\n\n".join(lines) return "\n\n".join(lines)
def _format_resource_size(value: Any) -> str:
if value in (None, "", 0, 0.0):
return "\u672a\u77e5"
if isinstance(value, (int, float)):
size = float(value)
if size >= 1024:
return f"{size / 1024:.2f} GB"
return f"{size:.2f} MB"
return str(value)
def format_resource_result_item(index: int, item: Mapping[str, Any]) -> str:
title = _first_value(item, "title", "name") or "\u672a\u547d\u540d\u8d44\u6e90"
site = _first_value(item, "site_name", "site") or "\u672a\u77e5\u7ad9\u70b9"
quality = _first_value(item, "quality", "resolution", "category") or "\u672a\u77e5\u8d28\u91cf"
size = _format_resource_size(_first_value(item, "size", "length"))
seeders = _first_value(item, "seeders", "seed", "seeds")
peers = _first_value(item, "peers", "leechers", "leeches")
seed_text = seeders if seeders is not None else "\u672a\u77e5"
peer_text = peers if peers is not None else "\u672a\u77e5"
pubdate = _first_value(item, "pubdate", "publish_time", "published_at") or "\u672a\u77e5"
free = _first_value(item, "freedate", "free", "is_free", "volume_factor")
free_text = "\u662f" if free is True or (isinstance(free, str) and free.lower() in {"free", "yes", "true"}) else "\u5426"
colon = "\uFF1A"
lines = [
f"\u8d44\u6e90 {index}",
f"\u540d\u79f0{colon}{title}",
f"\u7ad9\u70b9{colon}{site}",
f"\u8d28\u91cf{colon}{quality}",
f"\u5927\u5c0f{colon}{size}",
f"\u505a\u79cd{colon}{seed_text} / \u4e0b\u8f7d{colon}{peer_text}",
f"\u53d1\u5e03\u65f6\u95f4{colon}{pubdate}",
f"\u514d\u8d39{colon}{free_text}",
]
if not _first_value(item, "enclosure", "page_url", "download_url", "url"):
lines.append(f"\u63d0\u793a{colon}\u8be5\u8d44\u6e90\u7f3a\u5c11\u53ef\u63d0\u4ea4\u7684\u4e0b\u8f7d\u94fe\u63a5\uFF0C\u53ef\u80fd\u65e0\u6cd5\u76f4\u63a5\u4e0b\u8f7d")
return chr(10).join(lines)
def format_resource_results(results: list[dict[str, Any]]) -> str: def format_resource_results(results: list[dict[str, Any]]) -> str:
if not results: if not results:
return "暂未找到资源。可以使用 /mp subscribe <媒体编号> 订阅该媒体。" return "\u6682\u672a\u627e\u5230\u8d44\u6e90\u3002\u53ef\u4ee5\u4f7f\u7528 /mp subscribe <\u5a92\u4f53\u7f16\u53f7> \u8ba2\u9605\u8be5\u5a92\u4f53\u3002"
lines = ["资源搜索结果:"] lines = ["\u8d44\u6e90\u641c\u7d22\u7ed3\u679c\uFF1A"]
for index, item in enumerate(results, start=1): for index, item in enumerate(results, start=1):
title = item.get("title") or item.get("name") or "未命名资源" lines.append(format_resource_result_item(index, item))
site = item.get("site_name") or item.get("site") or "未知站点" lines.append("\u53ef\u4f7f\u7528 /mp download <\u7f16\u53f7> \u9009\u62e9\u8d44\u6e90\u4e0b\u8f7d\u3002")
size = item.get("size") or item.get("length") or "" return (chr(10) + chr(10)).join(lines)
quality = item.get("quality") or item.get("resolution") or ""
details = " / ".join(str(value) for value in (site, size, quality) if value)
lines.append(f"{index}. {title}({details})")
lines.append("可使用 /mp download <编号> 选择资源下载。")
return "\n".join(lines)

查看文件

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

查看文件

@ -39,6 +39,10 @@ class MoviePilotResponseError(MoviePilotError):
"""Raised when a response cannot be decoded as JSON.""" """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) @dataclass(frozen=True, slots=True)
class MoviePilotResponse: class MoviePilotResponse:
"""Normalized response returned by MoviePilot.""" """Normalized response returned by MoviePilot."""
@ -72,6 +76,8 @@ class MoviePilotClient:
api_token: str, api_token: str,
*, *,
timeout: float = 20.0, timeout: float = 20.0,
retries: int = 2,
retry_backoff: float = 0.5,
transport: httpx.AsyncBaseTransport | None = None, transport: httpx.AsyncBaseTransport | None = None,
) -> None: ) -> None:
normalized_url = (base_url or "").strip().rstrip("/") normalized_url = (base_url or "").strip().rstrip("/")
@ -86,6 +92,8 @@ class MoviePilotClient:
self.base_url = normalized_url self.base_url = normalized_url
self._api_token = normalized_token self._api_token = normalized_token
self._timeout = httpx.Timeout(timeout) self._timeout = httpx.Timeout(timeout)
self._retries = max(int(retries), 0)
self._retry_backoff = max(float(retry_backoff), 0.0)
self._transport = transport self._transport = transport
self._client: httpx.AsyncClient | None = None self._client: httpx.AsyncClient | None = None
@ -123,20 +131,36 @@ class MoviePilotClient:
request_path = path if path.startswith("/") else f"/{path}" request_path = path if path.startswith("/") else f"/{path}"
request_params = dict(params or {}) request_params = dict(params or {})
request_params.setdefault("token", self._api_token) request_params.setdefault("token", self._api_token)
try: response: httpx.Response | None = None
response = await self._client.request( for attempt in range(self._retries + 1):
method, try:
request_path, response = await self._client.request(
params=request_params, method,
json=json, request_path,
) params=request_params,
except httpx.TimeoutException as exc: json=json,
raise MoviePilotConnectionError("连接 MoviePilot 超时") from exc )
except httpx.HTTPError as exc: except httpx.TimeoutException as exc:
raise MoviePilotConnectionError("连接 MoviePilot 失败") from 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): 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: try:
payload = response.json() payload = response.json()
@ -148,6 +172,12 @@ class MoviePilotClient:
message = _response_message(payload) message = _response_message(payload)
success = _response_success(payload) success = _response_success(payload)
if response.status_code >= 400: 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( raise MoviePilotAPIError(
response.status_code, response.status_code,
message or f"MoviePilot 请求失败(HTTP {response.status_code})", message or f"MoviePilot 请求失败(HTTP {response.status_code})",
@ -168,6 +198,26 @@ class MoviePilotClient:
message=message, 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( async def get(
self, self,
path: str, path: str,

查看文件

@ -46,6 +46,9 @@ class NotificationPoller:
self._client = MoviePilotClient( self._client = MoviePilotClient(
str(self._config.get("moviepilot_url", "")), str(self._config.get("moviepilot_url", "")),
str(self._config.get("moviepilot_api_token", "")), 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 return self._client
@ -67,6 +70,15 @@ class NotificationPoller:
encoding="utf-8", encoding="utf-8",
) )
async def list_recent(self, *, count: int = 10) -> list[dict[str, Any]]:
response = await self._get_client().get(
"/api/v1/message/notification", params={"page": 1, "count": count}
)
if not isinstance(response.data, list):
return []
return [item for item in response.data if isinstance(item, dict)]
async def poll_once(self) -> list[dict[str, Any]]: async def poll_once(self) -> list[dict[str, Any]]:
response = await self._get_client().get( response = await self._get_client().get(
"/api/v1/message/notification", params={"page": 1, "count": 50} "/api/v1/message/notification", params={"page": 1, "count": 50}

查看文件

@ -25,6 +25,9 @@ class SubscriptionService:
self._client = MoviePilotClient( self._client = MoviePilotClient(
str(self._config.get("moviepilot_url", "")), str(self._config.get("moviepilot_url", "")),
str(self._config.get("moviepilot_api_token", "")), 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 return self._client
@ -167,3 +170,16 @@ def format_subscriptions(subscriptions: list[dict[str, Any]]) -> str:
suffix = f" / 第 {season} 季" if season is not None else "" suffix = f" / 第 {season} 季" if season is not None else ""
lines.append(f"{sid}. {title}{suffix} {state}".strip()) lines.append(f"{sid}. {title}{suffix} {state}".strip())
return "\n".join(lines) return "\n".join(lines)
def media_id_from_subscription(subscription: Mapping[str, Any] | None) -> str:
"""Return the canonical MoviePilot media ID from a subscription record."""
if not subscription:
return ""
media_id = _value(subscription, "mediaid", "media_id", "mediaId")
if media_id:
return str(media_id)
tmdb_id = _tmdb_id(subscription)
if tmdb_id is not None:
return f"tmdb:{tmdb_id}"
return ""

查看文件

@ -98,3 +98,31 @@ def test_invalid_configuration_is_rejected() -> None:
MoviePilotClient("http://moviepilot:3000", "") MoviePilotClient("http://moviepilot:3000", "")
with pytest.raises(MoviePilotConfigError): with pytest.raises(MoviePilotConfigError):
MoviePilotClient("moviepilot:3000", "secret") 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["name"] == "astrbot_plugin_moviepilot"
assert metadata["version"] == "0.13.0" assert metadata["version"] == "0.19.1"
assert metadata["astrbot_version"] == ">=4.16,<5" assert metadata["astrbot_version"] == ">=4.16,<5"
assert "aiocqhttp" in metadata["support_platforms"] assert "aiocqhttp" in metadata["support_platforms"]
assert "telegram" in metadata["support_platforms"] assert "telegram" in metadata["support_platforms"]