11import re
22import requests
3+ from requests .auth import HTTPBasicAuth
4+ from datetime import datetime
35
46from cloudbot import hook
57
68api_url = "https://api.spotify.com/v1/search?"
9+ token_url = "https://accounts.spotify.com/api/token"
710spuri = 'spotify:{}:{}'
11+ access_token = ""
12+ expires_at = datetime .min
813
9- spotify_re = re .compile (r'(spotify:(track|album|artist|user):([a-zA-Z0-9]+))' , re .I )
14+ spotify_re = re .compile (r'(spotify:(track|album|artist|user):([a-zA-Z0-9]+))' ,
15+ re .I )
1016http_re = re .compile (r'(open\.spotify\.com/(track|album|artist|user)/'
1117 '([a-zA-Z0-9]+))' , re .I )
1218
1319
20+ def sprequest (bot , params , alturl = None ):
21+ global access_token , expires_at
22+ if alturl == None :
23+ alturl = api_url
24+ if datetime .now () >= expires_at :
25+ basic_auth = HTTPBasicAuth (
26+ bot .config .get ("api_keys" , {}).get ("spotify_client_id" ),
27+ bot .config .get ("api_keys" , {}).get ("spotify_client_secret" ))
28+ gtcc = {"grant_type" : "client_credentials" }
29+ auth = requests .post (token_url , data = gtcc , auth = basic_auth ).json ()
30+ if 'access_token' in auth .keys ():
31+ access_token = auth ["access_token" ]
32+ expires_at = datetime .fromtimestamp (datetime .now ().timestamp () +
33+ auth ["expires_in" ])
34+ headers = {'Authorization' : 'Bearer ' + access_token }
35+ return requests .get (alturl , params = params , headers = headers )
36+
37+
1438@hook .command ('spotify' , 'sptrack' )
15- def spotify (text ):
39+ def spotify (bot , text ):
1640 """spotify <song> -- Search Spotify for <song>"""
17- params = {
18- "q" : text .strip (),
19- "offset" : 0 ,
20- "limit" : 1 ,
21- "type" : "track"
22- }
23-
24- request = requests .get (api_url , params = params )
41+ params = {"q" : text .strip (), "offset" : 0 , "limit" : 1 , "type" : "track" }
42+
43+ request = sprequest (bot , params )
2544 if request .status_code != requests .codes .ok :
26- return "Could not get track information: {}" .format (request .status_code )
45+ return "Could not get track information: {}" .format (
46+ request .status_code )
2747
2848 data = request .json ()["tracks" ]["items" ][0 ]
2949
3050 try :
31- return "\x02 {}\x02 by \x02 {}\x02 - {} / {}" .format (data ["artists" ][0 ]["name" ],
32- data ["external_urls" ]["spotify" ],
33- data ["name" ],
34- data ["uri" ])
51+ return "\x02 {}\x02 by \x02 {}\x02 - {} / {}" .format (
52+ data ["artists" ][0 ]["name" ], data ["external_urls" ]["spotify" ],
53+ data ["name" ], data ["uri" ])
3554 except IndexError :
3655 return "Unable to find any tracks!"
3756
3857
3958@hook .command ("spalbum" )
40- def spalbum (text ):
59+ def spalbum (bot , text ):
4160 """spalbum <album> -- Search Spotify for <album>"""
42- params = {
43- "q" : text .strip (),
44- "offset" : 0 ,
45- "limit" : 1 ,
46- "type" : "album"
47- }
48-
49- request = requests .get (api_url , params = params )
61+ params = {"q" : text .strip (), "offset" : 0 , "limit" : 1 , "type" : "album" }
62+
63+ request = sprequest (bot , params )
5064 if request .status_code != requests .codes .ok :
51- return "Could not get album information: {}" .format (request .status_code )
65+ return "Could not get album information: {}" .format (
66+ request .status_code )
5267
5368 data = request .json ()["albums" ]["items" ][0 ]
5469
5570 try :
56- return "\x02 {}\x02 by \x02 {}\x02 - {} / {}" .format (data ["artists" ][0 ]["name" ],
57- data ["name" ],
58- data ["external_urls" ]["spotify" ],
59- data ["uri" ])
71+ return "\x02 {}\x02 by \x02 {}\x02 - {} / {}" .format (
72+ data ["artists" ][0 ]["name" ], data ["name" ],
73+ data ["external_urls" ]["spotify" ], data ["uri" ])
6074 except IndexError :
6175 return "Unable to find any albums!"
6276
6377
6478@hook .command ("spartist" , "artist" )
65- def spartist (text ):
79+ def spartist (bot , text ):
6680 """spartist <artist> -- Search Spotify for <artist>"""
67- params = {
68- "q" : text .strip (),
69- "offset" : 0 ,
70- "limit" : 1 ,
71- "type" : "artist"
72- }
73-
74- request = requests .get (api_url , params = params )
81+ params = {"q" : text .strip (), "offset" : 0 , "limit" : 1 , "type" : "artist" }
82+
83+ request = sprequest (bot , params )
7584 if request .status_code != requests .codes .ok :
76- return "Could not get artist information: {}" .format (request .status_code )
85+ return "Could not get artist information: {}" .format (
86+ request .status_code )
7787
7888 data = request .json ()["artists" ]["items" ][0 ]
7989
8090 try :
81- return "\x02 {}\x02 - {} / {}" .format (data ["name" ],
82- data ["external_urls" ]["spotify" ],
83- data ["uri" ])
91+ return "\x02 {}\x02 - {} / {}" .format (
92+ data ["name" ], data ["external_urls" ]["spotify" ], data ["uri" ])
8493 except IndexError :
8594 return "Unable to find any artists!"
8695
8796
8897@hook .regex (http_re )
8998@hook .regex (spotify_re )
90- def spotify_url (match ):
91- api_method = {
92- 'track' : 'tracks' ,
93- 'album' : 'albums' ,
94- 'artist' : 'artists'
95- }
99+ def spotify_url (bot , match ):
100+ api_method = {'track' : 'tracks' , 'album' : 'albums' , 'artist' : 'artists' }
96101 _type = match .group (2 )
97102 spotify_id = match .group (3 )
98103 url = spuri .format (_type , spotify_id )
99104 # no error catching here, if the API is down fail silently
100- request = requests .get ('http://api.spotify.com/v1/{}/{}' .format (api_method [_type ], spotify_id ))
105+ request = sprequest (bot , {}, 'http://api.spotify.com/v1/{}/{}' .format (
106+ api_method [_type ], spotify_id ))
101107 if request .status_code != requests .codes .ok :
102108 return
103109 data = request .json ()
@@ -107,9 +113,13 @@ def spotify_url(match):
107113 album = data ["album" ]["name" ]
108114 url = data ['external_urls' ]['spotify' ]
109115
110- return "Spotify Track: \x02 {}\x02 by \x02 {}\x02 from the album \x02 {}\x02 {}" .format (name , artist , album , url )
116+ return "Spotify Track: \x02 {}\x02 by \x02 {}\x02 from the album \x02 {}\x02 {}" .format (
117+ name , artist , album , url )
111118 elif _type == "artist" :
112- return "Spotify Artist: \x02 {}\x02 , followers: \x02 {}\x02 , genres: \x02 {}\x02 " .format (data ["name" ], data ["followers" ]["total" ], ', ' .join (data ["genres" ]))
119+ return "Spotify Artist: \x02 {}\x02 , followers: \x02 {}\x02 , genres: \x02 {}\x02 " .format (
120+ data ["name" ], data ["followers" ]["total" ],
121+ ', ' .join (data ["genres" ]))
113122 elif _type == "album" :
114- return "Spotify Album: \x02 {}\x02 - \x02 {}\x02 {}" .format (data ["artists" ][0 ]["name" ], data ["name" ], data ['external_urls' ]['spotify' ])
115-
123+ return "Spotify Album: \x02 {}\x02 - \x02 {}\x02 {}" .format (
124+ data ["artists" ][0 ]["name" ], data ["name" ],
125+ data ['external_urls' ]['spotify' ])
0 commit comments