2018-01-28 04:01:42 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# Writes the now playing track to a text file
|
|
|
|
# License: MIT
|
|
|
|
# Copyright (c) 2018 c0de <c0defox.es>
|
|
|
|
|
2018-01-30 20:27:29 +00:00
|
|
|
# Edit "set_env.sh" to configure your API key
|
|
|
|
# $ virtualenv venv
|
|
|
|
# $ ./set_env.sh
|
|
|
|
# $ pip install -r requirements.txt
|
|
|
|
|
|
|
|
import sys
|
|
|
|
import time
|
2018-04-24 21:32:08 +00:00
|
|
|
|
2018-01-28 04:01:42 +00:00
|
|
|
import spotipy
|
|
|
|
import spotipy.util as util
|
2018-04-25 04:32:21 +00:00
|
|
|
from spotipy.exceptions import SpotifyException
|
2018-01-28 04:01:42 +00:00
|
|
|
|
|
|
|
start_time = time.time()
|
|
|
|
|
|
|
|
if len(sys.argv) > 2:
|
|
|
|
username = sys.argv[1]
|
|
|
|
outfile = sys.argv[2]
|
|
|
|
else:
|
|
|
|
print "Usage: %s username outfile" % sys.argv[0]
|
|
|
|
sys.exit()
|
|
|
|
|
|
|
|
def get_now_playing(sp):
|
2018-01-30 20:27:29 +00:00
|
|
|
try:
|
|
|
|
# Get the currently playing track and artist
|
2018-04-25 00:00:51 +00:00
|
|
|
np = sp.currently_playing()
|
2018-01-30 20:27:29 +00:00
|
|
|
# Take a look at the other goodies that gets returned here for future stuff
|
|
|
|
return "%s by: %s" % (np['item']['name'], np['item']['artists'][0]['name'])
|
|
|
|
except TypeError:
|
|
|
|
return "Nothing is playing"
|
2018-01-28 04:01:42 +00:00
|
|
|
|
2018-04-25 00:55:20 +00:00
|
|
|
# Authorization Scope, can possibly be a dict?
|
|
|
|
scope = 'user-read-currently-playing'
|
|
|
|
sp = util.authorize_api(username, scope, 'server')
|
2018-01-30 20:27:29 +00:00
|
|
|
|
|
|
|
# Main loop
|
|
|
|
while True:
|
|
|
|
try:
|
2018-01-28 04:01:42 +00:00
|
|
|
np = get_now_playing(sp)
|
2018-01-30 20:27:29 +00:00
|
|
|
except SpotifyException as e:
|
|
|
|
if e.http_status == '401' and e.code == '-1': # Unauthorized and Expired access token
|
|
|
|
print "[%.2fs] Access Token for %s Expired, reaquiring..." % \
|
|
|
|
(time.time()-start_time, username)
|
|
|
|
# Reauth and get the next now playing
|
2018-04-25 00:55:20 +00:00
|
|
|
sp = util.authorize_api(username, scope, 'server')
|
2018-01-30 20:27:29 +00:00
|
|
|
continue
|
|
|
|
else:
|
|
|
|
raise Exception(e)
|
2018-01-28 04:01:42 +00:00
|
|
|
|
2018-01-30 20:27:29 +00:00
|
|
|
try:
|
|
|
|
with open(outfile, 'w') as output:
|
|
|
|
output.write(np)
|
|
|
|
print "[%.2fs] %s" % (time.time()-start_time, np)
|
|
|
|
output.close()
|
|
|
|
except:
|
|
|
|
print "[%.2fs] Unable to open %s" % (time.time()-start_time, outfile)
|
|
|
|
sys.exit()
|
|
|
|
|
|
|
|
# Wait approximately 10s before checking again
|
|
|
|
time.sleep(10.0 - ((time.time() - start_time) % 10.0))
|