Skip to content

Instantly share code, notes, and snippets.

@rudiejd
Last active July 20, 2020 03:03
Show Gist options
  • Save rudiejd/e4745a3837eeab9043fbfdffb5133b1c to your computer and use it in GitHub Desktop.
Save rudiejd/e4745a3837eeab9043fbfdffb5133b1c to your computer and use it in GitHub Desktop.
get_random_rec method
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