Skip to content

Commit

Permalink
Use spotify api with key
Browse files Browse the repository at this point in the history
  • Loading branch information
lepinkainen committed Apr 16, 2018
1 parent aef0221 commit c21d3f8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,34 @@
from __future__ import unicode_literals, print_function, division
import re
import logging
import base64
import requests

log = logging.getLogger('spotify')

def init(botref):
"""Initialize the urltitle module"""

global config
global bot
bot = botref
config = bot.config.get("module_spotify", {})

def get_token(client_id, client_secret):
token = client_id + ":" + client_secret
encoded_token = base64.b64encode(token)

payload = {'grant_type': 'client_credentials'}
headers = {'Authorization': 'Basic ' + encoded_token}
auth_url = "https://accounts.spotify.com/api/token"
r = requests.post(auth_url, payload, headers=headers)

return r.json()['access_token']

def handle_privmsg(bot, user, channel, args):
"""Grab Spotify URLs from the messages and handle them"""

m = re.match(".*(https?:\/\/open.spotify.com\/|spotify:)(?P<item>album|artist|track|user[:\/]\S+[:\/]playlist)[:\/](?P<id>[a-zA-Z0-9]+)\/?.*", args)
m = re.match(r".*(https?:\/\/open.spotify.com\/|spotify:)(?P<item>album|artist|track|user[:\/]\S+[:\/]playlist)[:\/](?P<id>[a-zA-Z0-9]+)\/?.*", args)
if not m:
return None

Expand All @@ -23,13 +43,17 @@ def handle_privmsg(bot, user, channel, args):
# All playlists seem to return 401 at the time, even the public ones
return None

bearer_token = get_token(config.get("client_id"), config.get("client_secret"))

headers = {'Authorization': 'Bearer ' + bearer_token}
apiurl = "https://api.spotify.com/v1/%s/%s" % ('/'.join(item), spotify_id)
r = bot.get_url(apiurl)
r = bot.get_url(apiurl, headers=headers)

if r.status_code != 200:
if r.status_code not in [401, 403]:
log.warning('Spotify API returned %s while trying to fetch %s' % r.status_code, apiurl)
return
print(r.json())
return bot.say(channel, "Error: %s" % r.json()['error']['message'])

data = r.json()

Expand Down

0 comments on commit c21d3f8

Please sign in to comment.