lastfm.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. ##Lastfm module created by hlmtre##
  2. import json
  3. import sys
  4. if sys.version_info > (3, 0, 0):
  5. import urllib.request, urllib.error, urllib.parse
  6. try:
  7. from .basemodule import BaseModule
  8. except (ImportError, SystemError):
  9. from modules.basemodule import BaseModule
  10. else:
  11. import urllib2 as urllib
  12. try:
  13. from basemodule import BaseModule
  14. except (ImportError, SystemError):
  15. from modules.basemodule import BaseModule
  16. from event import Event
  17. class LastFM(BaseModule):
  18. def post_init(self):
  19. lastfm = Event("__.lastfm__")
  20. lastfm.define(msg_definition=r"^\.lastfm")
  21. lastfm.subscribe(self)
  22. self.help = ".lastfm add <lastfm username> then .last"
  23. # register ourself to our new custom event
  24. self.bot.register_event(lastfm, self)
  25. def handle(self, event):
  26. msg = event.line.rsplit(":")[-1]
  27. # replace username in db if their nick already exists; otherwise insert new row
  28. if msg.startswith(".lastfm add"):
  29. lastfm_username = msg.split()[-1]
  30. try:
  31. self.bot.db.e("REPLACE INTO lastfm (lastfm_username, nick) VALUES ('" + lastfm_username + "', '" + event.user + "')")
  32. except Exception as e:
  33. print(e)
  34. elif msg.startswith(".lastfm"):
  35. try:
  36. # go get it
  37. username = self.bot.db.e("SELECT lastfm_username FROM lastfm WHERE nick = '" + event.user + "'")[0][0]
  38. api_key = "80688df02fc5af99f1ed97b5f667f0c4"
  39. url = "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user="+username+"&api_key="+api_key+"&format=json"
  40. if sys.version_info > (3, 0, 0): # py3 has requests built in, and incorporated urllib functions
  41. response = urllib.request.urlopen(url)
  42. else:
  43. response = urllib.urlopen(url)
  44. text = response.read()
  45. j = json.loads(text.decode())
  46. if "@attr" in j["recenttracks"]["track"][0]:
  47. if j["recenttracks"]["track"][0]["@attr"]["nowplaying"] == "true":
  48. output = j["recenttracks"]["track"][0]['artist']['#text'] + " - " + j["recenttracks"]["track"][0]['name']
  49. self.say(event.channel, event.user + " is now playing: " + output) # What you are currently listening to
  50. else:
  51. output = j["recenttracks"]["track"][0]['artist']['#text'] + " - " + j["recenttracks"]["track"][0]['name']
  52. self.say(event.channel, event.user + " recently played: " + output) # If not listening anymore, what you were listening to
  53. except IndexError as e:
  54. print(e)
  55. self.say(event.channel, "no lastfm username for " + event.user)