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