Added tracking or deactivating anime via Anilist ID, it queries Anilist for the name and saves it

This commit is contained in:
florian committed 2026-10-17 16:51:28 +02:00
1 parent 162f73fe3f
commit b87c1e1896
3 files changed
+245 -2

No files matched your search

+130
View File
@@ -0,0 +1,130 @@
"""Look up anime on AniList by ID."""
import requests
from simple_logger_handler import setup_logger
logger = setup_logger(__name__)
ANILIST_API_URL = "https://graphql.anilist.co"
DEFAULT_TIMEOUT = 10 # seconds
_ID_QUERY = """
query ($id: Int) {
Media(id: $id, type: ANIME) {
id
title { romaji english native }
}
}
"""
# Preference order when picking a display name.
_TITLE_PREFERENCE = ("english", "romaji", "native")
class AniListError(RuntimeError):
"""The AniList request failed (network, HTTP, or GraphQL error)."""
class AnimeNotFoundError(AniListError):
"""No anime exists on AniList for this ID or name."""
class MissingAnimeName(AniListError):
"""The anime exists but has no usable title."""
def _post(
query: str,
variables: dict,
session: requests.Session | None,
timeout: float,
) -> dict:
"""POST a GraphQL query and return its ``data`` dict.
Raises:
AnimeNotFoundError: AniList answered HTTP 404 (unknown ID).
AniListError: Network failure, rate limiting, or any other error.
"""
http = session or requests
try:
response = http.post(
ANILIST_API_URL,
json={"query": query, "variables": variables},
timeout=timeout,
)
except requests.RequestException as e:
raise AniListError(f"Request to AniList failed: {type(e).__name__}") from e
if response.status_code == 404:
raise AnimeNotFoundError("Not found on AniList")
if response.status_code == 429:
retry_after = response.headers.get("Retry-After", "unknown")
raise AniListError(f"Rate limited by AniList (retry after {retry_after}s)")
try:
response.raise_for_status()
payload = response.json()
except (requests.HTTPError, ValueError) as e:
raise AniListError(f"Bad response from AniList: {e}") from e
if errors := payload.get("errors"):
messages = "; ".join(str(err.get("message", err)) for err in errors)
raise AniListError(f"AniList returned errors: {messages}")
return payload.get("data") or {}
def _pick_name(title: dict | None) -> str | None:
"""Return the best available title (English, romaji, then native)."""
title = title or {}
for key in _TITLE_PREFERENCE:
name = (title.get(key) or "").strip()
if name:
return name
return None
def get_anime_name(
anilist_id: int,
*,
session: requests.Session | None = None,
timeout: float = DEFAULT_TIMEOUT,
) -> str:
"""Return the best available title for an AniList anime ID.
Prefers the English title, then romaji, then native.
Args:
anilist_id: AniList media ID (positive integer).
session: Optional ``requests.Session`` to reuse connections when
looking up many IDs.
timeout: Request timeout in seconds.
Raises:
ValueError: ``anilist_id`` is not a positive integer.
AnimeNotFoundError: No anime exists for this ID.
MissingAnimeName: The anime exists but has no title.
AniListError: Network failure, rate limiting, or any other
AniList/HTTP error.
"""
if not isinstance(anilist_id, int) or isinstance(anilist_id, bool) or anilist_id <= 0:
raise ValueError(f"anilist_id must be a positive integer, got {anilist_id!r}")
try:
data = _post(_ID_QUERY, {"id": anilist_id}, session, timeout)
except AnimeNotFoundError:
raise AnimeNotFoundError(f"No anime found for AniList ID={anilist_id}") from None
media = data.get("Media")
if not media:
raise AnimeNotFoundError(f"No anime found for AniList ID={anilist_id}")
name = _pick_name(media.get("title"))
if name is None:
raise MissingAnimeName(f"Anime has no title for AniList ID={anilist_id}")
return name
if __name__ == "__main__":
asd = get_anime_name(2002927)
print(asd)