-
Notifications
You must be signed in to change notification settings - Fork 6
/
spot.py
115 lines (93 loc) · 3.15 KB
/
spot.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
from pprint import pprint
from spotipy import util
import spotipy
import requests
import os
class SpotifyClient:
def __init__(self):
self.scope = 'playlist-modify-private'
self.user_id = os.getenv('SPOTIFY_USER_ID')
self.client_id = os.getenv('SPOTIFY_CLIENT_ID')
self.client_secret = os.getenv('SPOTIFY_CLIENT_SECRET')
self.redirect_uri = os.getenv('SPOTIFY_REDIRECT_URI')
@property
def token(self):
'''
Return the access token
'''
return util.prompt_for_user_token(
self.user_id,
scope=self.scope,
client_id=self.client_id,
client_secret=self.client_secret,
redirect_uri=self.redirect_uri
)
class Spotify:
def __init__(self):
self.spotify = SpotifyClient()
def create_playlist(self, playlist_name: str) -> str:
request_body = {
"name": playlist_name,
"description": "youtube playlist",
"public": False
}
query = f"https://api.spotify.com/v1/users/{self.spotify.user_id}/playlists"
response = requests.post(
query,
json=request_body,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {self.spotify.token}"
}
)
playlist = response.json()
return playlist['id']
def get_song_uri(self, artist: str, song_name: str) -> 'str':
q = f'artist:{artist} track:{song_name}'
query = f'https://api.spotify.com/v1/search?q={q}&type=track&limit=1'
response = requests.get(
query,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {self.spotify.token}"
}
)
if not response.ok:
return None
results = response.json()
items = results['tracks']['items']
if not items:
return None
return items[0]['uri']
def add_song_to_playlist(self, song_uri: str, playlist_id: str) -> bool:
url = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks"
response = requests.post(
url,
json={"uris": [song_uri]},
headers={
"Authorization": f"Bearer {self.spotify.token}",
"Content-Type": "application/json"
}
)
return response.ok
def _num_playlist_songs(self, playlist_id):
url = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks"
response = requests.get(
url,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {self.spotify.token}"
}
)
if not response.ok:
return print("Bad Response.")
results = response.json()
if 'total' in results:
return results['total']
return None
if __name__ == "__main__":
sp = Spotify()
pid = sp.create_playlist("loll")
uri = sp.get_song_uri('flor', 'hold on')
res = sp.add_song_to_playlist(uri, pid)
print(sp._num_playlist_songs(''))