Last active
July 20, 2020 03:03
-
-
Save rudiejd/e4745a3837eeab9043fbfdffb5133b1c to your computer and use it in GitHub Desktop.
get_random_rec method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import spotipy | |
from spotipy.ouath2 import SpotifyClientCredentials | |
from random import randrange | |
spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(client_id='MY_CLIENT_ID', client_secret='MY_CLIENT_SECRET')) | |
MAX_TRACKS = 10 | |
def get_random_rec(query): | |
artist = spotify.search(query, limit=1, offset=0, type="artist", market=None) | |
if len(artist["artists"]["items"]) == 0: | |
return None | |
artist_name = artist["artists"]["items"][0]["name"] | |
max_offset = spotify.search(query, limit=1, type="playlist", market=None)["playlists"]["total"] | |
if max_offset == 0: | |
return None | |
playlists = spotify.search(query, limit=50, offset = randrange(min(max_offset, 1950)), type="playlist", market=None) | |
playlist_results = playlists["playlists"]["items"] | |
if len(playlist_results) == 0: | |
return None | |
playlist = playlist_results[randrange(len(playlist_results))] | |
tracks = [] | |
tries = 0 | |
while len(tracks) == 0 and tries <= 10: | |
playlist = playlist_results[randrange(len(playlist_results))] | |
tracks = spotify.playlist_tracks(playlist["id"])["items"] | |
tracks = list(filter(lambda x: x["track"] != None and len(x["track"]["artists"]) > 0 and x["track"]["artists"][0]["name"] != artist_name, tracks)) | |
tries += 1 | |
if len(tracks) == 0: | |
return None | |
rand = randrange(len(tracks)) | |
return tracks[rand]["track"]["artists"][0]["name"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment