Skip to content

Instantly share code, notes, and snippets.

@ALiwoto
Created July 31, 2021 11:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ALiwoto/b69709b055918b203cba94bcf2e41b8e to your computer and use it in GitHub Desktop.
Save ALiwoto/b69709b055918b203cba94bcf2e41b8e to your computer and use it in GitHub Desktop.
Spotify module which was going to be used in Nana (by Sayan Biswas)
from httpx import AsyncClient
class SpotifyUser:
authorize_url = "https://accounts.spotify.com/authorize"
token_url = "https://accounts.spotify.com/api/token"
def __init__(self, client_id, client_secret, redirect_uri):
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
async def getAuthUrl(self):
authorization_redirect_url = self.authorize_url + '?response_type=code&client_id=' + \
self.client_id + '&redirect_uri=' + self.redirect_uri + \
'&scope=user-read-currently-playing'
return authorization_redirect_url
async def getAccessToken(self, authCode):
data = {'grant_type': 'authorization_code',
'code': authCode, 'redirect_uri': self.redirect_uri}
async with AsyncClient() as ses:
r = await ses.post(self.token_url, data=data, allow_redirects=True,
auth=(self.client_id, self.client_secret))
if r.status_code in range(200, 299):
res = json.loads(r.text)
return res['refresh_token']
else:
return 'error'
async def getCurrentlyPlayingSong(self, refreshToken):
data = {
'grant_type': 'refresh_token',
'refresh_token': refreshToken,
'redirect_uri': self.redirect_uri,
'client_id': self.client_id,
'client_secret': self.client_secret
}
async with AsyncClient() as cl:
token = await cl.post(self.token_url, data=data).json()
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token['access_token']
}
async with AsyncClient(headers=headers) as cl:
r = await cl.post('https://api.spotify.com/v1/me/player/currently-playing')
return r
sp = SpotifyUser("CLIENT_ID", "CLIENT_SECRET", "REDIRECT_URI")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment