diff --git a/bot.conf.example b/bot.conf.example index a6a61d9c..b8afcfcd 100644 --- a/bot.conf.example +++ b/bot.conf.example @@ -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 = diff --git a/modules/spotify.py b/modules/spotify.py index 2f13d432..f8a0cad4 100644 --- a/modules/spotify.py +++ b/modules/spotify.py @@ -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: """ - 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"]):