discoverylidarr/lastfm_helpers.py
2025-06-23 10:31:25 +02:00

43 lines
1.2 KiB
Python

from config import *
import requests, time, urllib.parse
from collections import defaultdict
from datetime import datetime, timedelta
def lf_request(method, **params):
url = "https://ws.audioscrobbler.com/2.0/"
params.update({
"method": method,
"api_key": LASTFM_API_KEY,
"format": "json"
})
try:
r = requests.get(url, params=params)
r.raise_for_status()
return r.json()
except Exception as e:
print(f"[LFM ERR] {e}")
return None
def recent_artists():
since = int((datetime.utcnow() - timedelta(days=30 * RECENT_MONTHS)).timestamp())
counts = defaultdict(int)
page = 1
while True:
js = lf_request(
"user.getRecentTracks", user=LASTFM_USERNAME,
limit=200, page=page, from_=since
)
if not js:
break
for t in js.get("recenttracks", {}).get("track", []):
a = t["artist"]
counts[(a["#text"], a.get("mbid", ""))] += 1
attr = js.get("recenttracks", {}).get("@attr", {})
if page >= int(attr.get("totalPages", 1)):
break
page += 1
return [(n, m) for (n, m), c in counts.items() if c >= MIN_PLAYS]