initial commit
No real output to terminal yet, but spotify api works. mostly.
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import requests
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
class SpotifyFactory():
|
||||
def __init__(self):
|
||||
self.token = None
|
||||
self.valid_until = None
|
||||
|
||||
def token_valid(self):
|
||||
if self.token and self.valid_until and (datetime.now() < self.valid_until):
|
||||
return True
|
||||
return False
|
||||
|
||||
def get_token(self):
|
||||
if self.token_valid():
|
||||
print("Token still valid")
|
||||
return self.token
|
||||
print("New token")
|
||||
url = 'https://accounts.spotify.com/api/token'
|
||||
headers = {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Authorization': 'Basic ' + os.getenv('SPOTIFY_ENCODED_ID')
|
||||
}
|
||||
data = {
|
||||
'grant_type': 'client_credentials'
|
||||
}
|
||||
r = requests.post(url, headers=headers, data=data)
|
||||
data = r.json()
|
||||
self.token = data["access_token"]
|
||||
self.valid_until = datetime.now() + timedelta(seconds=data["expires_in"]-300)
|
||||
return self.token
|
||||
|
||||
def get_song_info(self, spotify_id):
|
||||
token = self.get_token()
|
||||
url = 'https://api.spotify.com/v1/tracks/' + spotify_id
|
||||
headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ' + token
|
||||
}
|
||||
r = requests.get(url, headers=headers)
|
||||
return r.json()
|
||||
Reference in New Issue
Block a user