-
Notifications
You must be signed in to change notification settings - Fork 0
/
spotify.py
82 lines (64 loc) · 2.41 KB
/
spotify.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'''
spotipy functions
'''
from random import shuffle
import spotipy
from spotipy import util
def login_to_spotify(client_username, client_id, client_secret):
'''
This handles logging in to Spotify and returning a Spotipy object
to be used to gather our data
'''
scope = 'user-follow-modify playlist-modify-public \
playlist-read-private'
token = util.prompt_for_user_token(
username=client_username,
scope=scope,
client_id=client_id,
client_secret=client_secret,
redirect_uri='http://localhost:8888/callback/')
spotify = spotipy.Spotify(auth=token)
return spotify
def create_playlist(spot_obj, username, artists, week):
'''
Create a playlist with top songs from artists
'''
if get_playlist_id(spot_obj, username, week) is None:
new_playlist = spot_obj.user_playlist_create( # pylint: disable=unused-variable
username,
week,
)
new_playlist_id = get_playlist_id(spot_obj, username, week)
tracks = []
dup_artists = set()
shuffle(artists)
for artist in artists:
for item in spot_obj.search(artist, type='artist')['artists']['items']:
if item['name'].lower() == artist.lower() and \
item['name'].lower() not in dup_artists:
i = 0
dup_artists.add(item['name'].lower())
a_id = item['id']
try:
while spot_obj.artist_top_tracks(
a_id)['tracks'][i]['artists'][0]['name'].lower() \
!= artist.lower():
i += 1
print("Adding song: ", spot_obj.artist_top_tracks(
a_id)['tracks'][i]['name'])
tracks.append(spot_obj.artist_top_tracks(
a_id)['tracks'][i]['id'])
except LookupError:
continue
spot_obj.user_playlist_add_tracks(username, new_playlist_id, tracks)
print("success! done adding tracks to playlist")
def get_playlist_id(spot_obj, username, playlist_name):
'''
get playlist id bc spotify's api is odd
'''
playlists = spot_obj.user_playlists(username)
for playlist in playlists['items']:
if playlist['name'].lower() == playlist_name.lower():
return playlist['id']
print("no playlist found, creating playlist")
return None