lastfm.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import sys
  2. import urllib2
  3. import json
  4. class LastFM:
  5. def __init__(self, events=None, printer_handle=None, bot=None, say=None):
  6. self.bot_handle = bot
  7. self.events = events
  8. self.printer = printer_handle
  9. self.bot = bot
  10. self.interests = ['__.lastfm__']
  11. self.help = ".lastfm add <lastfm username>, .lastfm"
  12. for event in events:
  13. if event._type in self.interests:
  14. event.subscribe(self)
  15. def handle(self, event):
  16. msg = event.line.rsplit(":")[-1]
  17. # replace username in db if their nick already exists; otherwise insert new row
  18. if msg.startswith(".lastfm add"):
  19. lastfm_username = msg.split()[-1]
  20. try:
  21. self.bot_handle.db.e("REPLACE INTO lastfm (lastfm_username, nick) VALUES ('" + lastfm_username + "', '" + event.user + "')")
  22. except Exception, e:
  23. print e
  24. elif msg.startswith(".lastfm"):
  25. try:
  26. # go get it
  27. username = self.bot_handle.db.e("SELECT lastfm_username FROM lastfm WHERE nick = '" + event.user + "'")[0][0]
  28. api_key = "80688df02fc5af99f1ed97b5f667f0c4"
  29. url = "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user="+username+"&api_key="+api_key+"&format=json"
  30. response = urllib2.urlopen(url)
  31. text = response.read()
  32. j = json.loads(text)
  33. try:
  34. if "@attr" in j["recenttracks"]["track"][0]:
  35. if j["recenttracks"]["track"][0]["@attr"]["nowplaying"] == "true":
  36. output = j["recenttracks"]["track"][0]['artist']['#text'] + " - " + j["recenttracks"]["track"][0]['name']
  37. self.printer("PRIVMSG " + event.channel + " :" + event.user + " is now playing: " + output + '\n')
  38. else:
  39. output = j["recenttracks"]["track"][0]['artist']['#text'] + " - " + j["recenttracks"]["track"][0]['name']
  40. self.printer("PRIVMSG " + event.channel + " :" + event.user + " recently played: " + output + '\n')
  41. except Exception, e:
  42. print e
  43. except IndexError:
  44. self.printer("PRIVMSG " + event.channel + " : no lastfm username for " + event.user + '\n')