Skip to content

Commit

Permalink
Merge pull request #153 from metabrainz/spotify-playlist-tracks
Browse files Browse the repository at this point in the history
Get all tracks from spotify playlist
  • Loading branch information
mayhem authored Dec 4, 2024
2 parents 5bb8bc1 + b66a5e9 commit 6293c49
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions troi/tools/spotify_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,17 +177,30 @@ def get_tracks_from_spotify_playlist(spotify_token, playlist_id):
"""
sp = spotipy.Spotify(auth=spotify_token, requests_timeout=10, retries=10)
playlist_info = sp.playlist(playlist_id)
tracks = sp.playlist_items(playlist_id, limit=100)

offset = 0
tracks = []

# spotipy limits to 100 items for each call, so run iteratively with an offset until there are no more tracks
while True:
results = sp.playlist_items(playlist_id, limit=100, offset=offset)
if len(results['items']) == 0:
break

tracks.extend(results['items'])
# set new offset for the next loop
offset = offset + len(results['items'])

name = playlist_info["name"]
description = playlist_info["description"]

tracks = _convert_spotify_tracks_to_json(tracks)
return tracks, name, description


def _convert_spotify_tracks_to_json(spotify_tracks):
def _convert_spotify_tracks_to_json(spotify_tracks: list):
tracks = []
for track in spotify_tracks["items"]:
for track in spotify_tracks:
artists = track["track"].get("artists", [])
artist_names = []
for a in artists:
Expand Down

0 comments on commit 6293c49

Please sign in to comment.