Spotify now requires access tokens to use it's API (spotify.py)
This commit is contained in:
parent
0c319be1e5
commit
2d085e7f91
2 changed files with 33 additions and 3 deletions
|
@ -67,3 +67,7 @@ virustotal-api-key =
|
|||
|
||||
# https://apidocs.imgur.com/
|
||||
imgur-api-key =
|
||||
|
||||
# https://developer.spotify.com/dashboard/
|
||||
spotify-client-id =
|
||||
spotify-client-secret =
|
||||
|
|
|
@ -1,17 +1,43 @@
|
|||
#--require-config spotify-client-id
|
||||
#--require-config spotify-client-secret
|
||||
|
||||
import json
|
||||
from src import ModuleManager, utils
|
||||
|
||||
URL_SPOTIFY = "https://api.spotify.com/v1/search"
|
||||
URL_SEARCH = "https://api.spotify.com/v1/search"
|
||||
URL_TOKEN = "https://accounts.spotify.com/api/token"
|
||||
|
||||
class Module(ModuleManager.BaseModule):
|
||||
def on_load(self):
|
||||
self._token = None
|
||||
self._token_expires = None
|
||||
|
||||
def _get_token(self):
|
||||
if self._token and (self._token_expires+10) < time.time():
|
||||
return self._token
|
||||
else:
|
||||
client_id = self.bot.config["spotify-client-id"]
|
||||
client_secret = self.bot.config["spotify-client-secret"]
|
||||
bearer = "%s:%s" % (client_id, client_secret)
|
||||
bearer = base64.b64encode(bearer).decode("utf8")
|
||||
|
||||
page = utils.http.request(URL_TOKEN, method="POST",
|
||||
headers={"Authorization": "Basic %s" % bearer},
|
||||
data={"grant_type": "client_credentials"},
|
||||
json=True)
|
||||
self._token_expire = time.time()+page.data["expires_in"]
|
||||
return page.data["access_token"]
|
||||
|
||||
@utils.hook("received.command.spotify", min_args=1)
|
||||
def spotify(self, event):
|
||||
"""
|
||||
:help: Search for a track on spotify
|
||||
:usage: <term>
|
||||
"""
|
||||
page = utils.http.request(URL_SPOTIFY, get_params=
|
||||
{"type": "track", "limit": 1, "q": event["args"]},
|
||||
token = self._get_token()
|
||||
page = utils.http.request(URL_SPOTIFY,
|
||||
get_params={"type": "track", "limit": 1, "q": event["args"]},
|
||||
headers={"Authorization", "Bearer %s" % token},
|
||||
json=True)
|
||||
if page:
|
||||
if len(page.data["tracks"]["items"]):
|
||||
|
|
Loading…
Reference in a new issue