feat: complete subscription management and notification query

这个提交存在于:
Codex 2026-07-22 23:08:10 +08:00
父节点 7f07184e75
当前提交 3fef03a851
共有 5 个文件被更改,包括 105 次插入 和 24 次删除

103
main.py
查看文件

@ -8,17 +8,17 @@ try:
from .media_service import MediaService, format_media_result_item, format_resource_results, media_poster_url
from .session_context import SessionContextStore
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 .notification_service import NotificationPoller
from .notification_service import NotificationPoller, format_notification, format_notification
except ImportError:
from access_policy import AccessPolicy
from media_service import MediaService, format_media_result_item, format_resource_results, media_poster_url
from session_context import SessionContextStore
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 notification_service import NotificationPoller
from notification_service import NotificationPoller, format_notification, format_notification
from astrbot.api.event import MessageChain
from astrbot.api.message_components import Image, Plain
@ -40,7 +40,7 @@ def _media_result_chain(results: list[dict[str, object]]) -> list[object]:
"astrbot_plugin_moviepilot",
"AstrBot MoviePilot Contributors",
"在 AstrBot 中通过命令和 LLM 控制 MoviePilot。",
"0.13.0",
"0.14.0",
)
class MoviePilotPlugin(star.Star):
"""MoviePilot integration entrypoint."""
@ -163,31 +163,67 @@ class MoviePilotPlugin(star.Star):
yield event.plain_result(f"季信息查询失败:{exc}")
@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):
return
media = self.session_store.get_media_result(event.unified_msg_origin, media_index)
if media is None:
yield event.plain_result("媒体编号无效或已过期,请重新使用 /mp search。")
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:
result = await self.subscription_service.create_subscription(media)
subscribe_id = result.get("id")
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)
result = await self.subscription_service.trigger_subscription_search(subscribe_id)
yield event.plain_result(f"已触发订阅 {subscribe_id} 搜索。{result or ''}".strip())
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={"订阅列表"})
async def list_subscriptions(self, event: AstrMessageEvent) -> None:
@ -298,6 +334,15 @@ class MoviePilotPlugin(star.Star):
message += f";自动搜索失败:{exc}"
yield event.plain_result(message)
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":
task_id = str(request.target["task_id"])
await self.download_service.delete(task_id)
@ -320,6 +365,20 @@ class MoviePilotPlugin(star.Star):
logger.warning(f"MoviePilot 查询下载任务失败: {exc}")
yield event.plain_result(f"查询下载任务失败:{exc}")
@moviepilot.command("notifications", alias={"??"})
async def list_notifications(self, event: AstrMessageEvent, count: int = 10) -> None:
"""???? MoviePilot ???"""
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("???????")
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}")
@moviepilot.command("cancel", alias={"取消"})
async def cancel_confirmation(self, event: AstrMessageEvent) -> None:
"""取消当前会话的待确认操作。"""

查看文件

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

查看文件

@ -67,6 +67,15 @@ class NotificationPoller:
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]]:
response = await self._get_client().get(
"/api/v1/message/notification", params={"page": 1, "count": 50}

查看文件

@ -167,3 +167,16 @@ def format_subscriptions(subscriptions: list[dict[str, Any]]) -> str:
suffix = f" / 第 {season} 季" if season is not None else ""
lines.append(f"{sid}. {title}{suffix} {state}".strip())
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 ""

查看文件

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