forked from RegsonDR/spotify-save-playlists-cron
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
80 lines (68 loc) · 2.62 KB
/
main.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
from dotenv import load_dotenv, find_dotenv
import requests
import urllib.request
import base64
import json
import os
load_dotenv(find_dotenv())
REFRESH_TOKEN = os.environ.get("REFRESH_TOKEN").strip()
CLIENT_ID = os.environ.get("CLIENT_ID").strip()
CLIENT_SECRET = os.environ.get("CLIENT_SECRET").strip()
NEW_MUSIC_FRIDAY_ID = os.environ.get("NEW_MUSIC_FRIDAY_ID").strip()
SAVE_TO_ID = os.environ.get("SAVE_TO_ID").strip()
OAUTH_TOKEN_URL = "https://accounts.spotify.com/api/token"
def refresh_access_token():
payload = {
"refresh_token": REFRESH_TOKEN,
"grant_type": "refresh_token",
"client_id": CLIENT_ID,
}
encoded_client = base64.b64encode((CLIENT_ID + ":" + CLIENT_SECRET).encode('ascii'))
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic %s" % encoded_client.decode('ascii')
}
response = requests.post(OAUTH_TOKEN_URL, data=payload, headers=headers)
return response.json()
def get_playlist(access_token):
url = "https://api.spotify.com/v1/playlists/%s" % NEW_MUSIC_FRIDAY_ID
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer %s" % access_token
}
response = requests.get(url, headers=headers)
return response.json()
def add_to_playlist(access_token, tracklist):
url = "https://api.spotify.com/v1/playlists/%s/tracks" % SAVE_TO_ID
payload = {
"uris" : tracklist
}
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer %s" % access_token
}
response = requests.post(url, data=json.dumps(payload), headers=headers)
return response.json()
def main():
if REFRESH_TOKEN is None or CLIENT_ID is None or CLIENT_SECRET is None or NEW_MUSIC_FRIDAY_ID is None or SAVE_TO_ID is None:
print("Environment variables have not been loaded!")
return
access_token = refresh_access_token()['access_token']
tracks = get_playlist(access_token)['tracks']['items']
tracklist = []
try:
for item in tracks:
if item['track'] is not None: # Thanks to https://stackoverflow.com/a/60496351/2220346
tracklist.append(item['track']['uri'])
except:
json_string = json.dumps(tracks)
tracklisterror = "%s_tracklisterror.json" % d2
with open(tracklisterror, 'w') as outfile:
outfile.write(json_string)
sys.exit(1) # Thanks to https://stackoverflow.com/a/69257826/2220346
response = add_to_playlist(access_token, tracklist)
if "snapshot_id" in response:
print("Successfully added all songs")
else:
print(response)
main()