Skip to content

Instantly share code, notes, and snippets.

@justdionysus
Created September 23, 2016 16:18
Show Gist options
  • Save justdionysus/65e6162d99c2e2ea8049b0584dd00912 to your computer and use it in GitHub Desktop.
Save justdionysus/65e6162d99c2e2ea8049b0584dd00912 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import pylast
import requests
import time
import traceback
JW_API_KEY = ''
JW_API_SECRET = ''
JW_USERNAME = "jw_at_tb"
HC_AUTH_TOKEN = ''
lastfm = pylast.LastFMNetwork(api_key=JW_API_KEY, api_secret=JW_API_SECRET,
username=JW_USERNAME, password_hash='')
user_to_timestamp = {}
def send_msg(channel, msg):
url = 'https://hipchat.tb65.net/v1/rooms/message?format=json&auth_token={}'.format(HC_AUTH_TOKEN)
data = { 'room_id': channel,
'from': 'John Waters',
'message_format': 'html',
'message': msg }
r = requests.post(url, data=data, verify=False)
def announce_track(name, track):
try:
t_song_links = lastfm.get_track_play_links([track.track])
except pylast.WSError as e:
t_song_links = []
t_song = track.track.get_title()
try:
t_artist_links = lastfm.get_artist_play_links([track.track.get_artist().get_name()])
except pylast.WSError as e:
t_artist_links = []
t_artist = track.track.get_artist().get_name()
try:
t_album_links = lastfm.get_album_play_links([track.track.get_album()])
except pylast.WSError as e:
t_album_links = []
t_album = track.album
def linkem(x, xl):
def spotify_to_http(s):
if s.startswith('spotify:'):
return 'http://open.spotify.com/' + s[len('spotify:'):].replace(':', '/')
else:
return s
return x if len(xl) == 0 else '<a href="%s">%s</a>' % (spotify_to_http(xl[0]), x)
t_song = linkem(t_song, filter(lambda x: x is not None, t_song_links))
t_artist = linkem(t_artist, filter(lambda x: x is not None, t_artist_links))
t_album = linkem(t_album, filter(lambda x: x is not None, t_album_links))
send_msg('Music', '%s played "%s" by %s (from %s)' % (name, t_song, t_artist, t_album))
def dump_track(name, track):
t_song = track.track.get_title()
t_artist = track.track.get_artist().get_name()
t_album = track.album
print '%s played "%s" by %s (from %s)' % (name, t_song, t_artist, t_album)
def get_real_name(user):
return pylast._extract(user._request(user.ws_prefix + ".getInfo", True), "realname")
def get_tracked_users():
lfm_jw = pylast.AuthenticatedUser(lastfm)
return [(user.get_name(), get_real_name(user)) for user in lfm_jw.get_friends()]
def spin_and_check():
while True:
try:
check_for_new_tracks()
except Exception as e:
print e
time.sleep(10)
def check_for_new_tracks():
global user_to_timestamp
print user_to_timestamp
for user, name in get_tracked_users():
print 'Checking {} ({})'.format(user, name)
lfm_user = pylast.User(user, lastfm)
lfm_tracks = lfm_user.get_recent_tracks()
if user not in user_to_timestamp:
if len(lfm_tracks) > 0:
t_ts = int(lfm_tracks[0].timestamp)
user_to_timestamp[user] = t_ts
continue
latest_ts = ts = user_to_timestamp[user]
for track in lfm_tracks:
#dump_track(name, track)
t_ts = int(track.timestamp)
print '{}: {}'.format(name, track)
if t_ts > ts:
try:
announce_track(name, track)
except Exception as e:
traceback.print_exc()
if t_ts > latest_ts:
latest_ts = t_ts
user_to_timestamp[user] = latest_ts
if __name__ == '__main__':
#send_msg('Music', 'Testing...')
spin_and_check()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment