Files
spotify-fetch/fetch.py
2024-12-07 17:20:52 +01:00

81 lines
2.0 KiB
Python

import csv
import os
import spotipy
import spotipy.util as util
from utils import get_artists
def main():
"""
Main execution point.
"""
# get credentials and callback URL from environment variables
# HINT: callback URL has to match Spotify App settings
client_id: str = os.environ.get("SPOTIPY_CLIENT_ID")
client_secret: str = os.environ.get("SPOTIPY_CLIENT_SECRET")
redirect_uri: str = os.environ.get("SPOTIPY_REDIRECT_URI")
# don't edit scope, but edit user name!
scope: str = "user-library-read"
username: str = "username"
# get user auth token
token: str = util.prompt_for_user_token(
username,
scope,
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
)
# raw responses from Spotify API
items: list[dict] = []
# response elements reduced to (artist, title) tuples
tracks: list[tuple[str, str]] = []
shall_continue: bool = True
i: int = 0
if token:
# initialize API client
client = spotipy.Spotify(auth=token)
while shall_continue:
results = client.current_user_saved_tracks(offset=i, limit=50)
# break if response is empty
if len(results["items"]) == 0:
break
# add items; increase offset
print(results)
items += results["items"]
i += 50
# reduce API responses to just artists and tracks
for item in items:
track: str = item["track"]
artist: str = get_artists(track["artists"])
title: str = track["name"]
# add track
tracks.append((artist, title))
# output artist and track
print(f"{artist} - {title}")
# final step: write tracks to tracks.csv file
with open("tracks.csv", "w", encoding="utf8") as file:
writer = csv.writer(file, quotechar='"')
writer.writerow(("Artist", "Title"))
writer.writerows(tracks)
if __name__ == "__main__":
# execution
main()