-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
87 lines (58 loc) · 2.54 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
81
82
83
84
85
86
87
import json
import requests
from secrets import spotify_user_id, discover_weekly_id
from datetime import date
from refresh import Refresh
class SaveSongs:
def __init__(self):
self.user_id = spotify_user_id
self.spotify_token = ""
self.discover_weekly_id = discover_weekly_id
self.tracks = ""
self.new_playlist_id = ""
def find_songs(self):
print("Finding songs in discover weekly...")
# Loop through playlist tracks, add them to list
query = "https://api.spotify.com/v1/playlists/{}/tracks".format(
discover_weekly_id)
response = requests.get(query,
headers={"Content-Type": "application/json",
"Authorization": "Bearer {}".format(self.spotify_token)})
response_json = response.json()
print(response)
for i in response_json["items"]:
self.tracks += (i["track"]["uri"] + ",")
self.tracks = self.tracks[:-1]
self.add_to_playlist()
def create_playlist(self):
# Create a new playlist
print("Trying to create playlist...")
today = date.today()
todayFormatted = today.strftime("%d/%m/%Y")
query = "https://api.spotify.com/v1/users/{}/playlists".format(
spotify_user_id)
request_body = json.dumps({
"name": todayFormatted + " discover weekly", "description": "Discover weekly rescued once again from the brink of destruction by your friendly neighbourhood python script", "public": True
})
response = requests.post(query, data=request_body, headers={
"Content-Type": "application/json",
"Authorization": "Bearer {}".format(self.spotify_token)
})
response_json = response.json()
return response_json["id"]
def add_to_playlist(self):
# add all songs to new playlist
print("Adding songs...")
self.new_playlist_id = self.create_playlist()
query = "https://api.spotify.com/v1/playlists/{}/tracks?uris={}".format(
self.new_playlist_id, self.tracks)
response = requests.post(query, headers={"Content-Type": "application/json",
"Authorization": "Bearer {}".format(self.spotify_token)})
print(response.json)
def call_refresh(self):
print("Refreshing token")
refreshCaller = Refresh()
self.spotify_token = refreshCaller.refresh()
self.find_songs()
a = SaveSongs()
a.call_refresh()