]> jfr.im git - erebus.git/blob - modules/spotify.py
cd5e76767e55358872b5ef3b9c2c5195fc492d51
[erebus.git] / modules / spotify.py
1 # Erebus IRC bot - Author: John Runyon
2 # Spotify URL Checker
3 # This file is released into the public domain; see http://unlicense.org/
4
5 # module info
6 modinfo = {
7 'author': 'Conny Sjoblom (BiohZn)',
8 'license': 'public domain',
9 'compatible': [1], # compatible module API versions
10 'depends': [], # other modules required to work properly?
11 }
12
13 # preamble
14 import modlib
15 lib = modlib.modlib(__name__)
16 modstart = lib.modstart
17 modstop = lib.modstop
18
19 # module code
20 import re
21 import ctlmod
22 import urllib2
23 from BeautifulSoup import BeautifulSoup
24
25 hostmask_regex = re.compile('^(.*)!(.*)@(.*)$')
26 spotify_regex = ( re.compile(r'spotify:(?P<type>\w+):(?P<track_id>\w{22})'),
27 re.compile(r'http://open.spotify.com/(?P<type>\w+)/(?P<track_id>\w{22})') )
28 spotify_gateway = 'http://ws.spotify.com/lookup/1/'
29 def parser_hostmask(hostmask):
30 if isinstance(hostmask, dict):
31 return hostmask
32
33 nick = None
34 user = None
35 host = None
36
37 if hostmask is not None:
38 match = hostmask_regex.match(hostmask)
39
40 if not match:
41 nick = hostmask
42 else:
43 nick = match.group(1)
44 user = match.group(2)
45 host = match.group(3)
46
47 return {
48 'nick': nick,
49 'user': user,
50 'host': host
51 }
52
53 @lib.hooknum("PRIVMSG")
54 def privmsg_hook(bot, line):
55 sender = parser_hostmask(line[1:line.find(' ')])
56
57 try:
58 linetx = line.split(' ', 3)[3][1:]
59 except IndexError:
60 linetx = ''
61
62 for r in spotify_regex:
63 for type, track in r.findall(linetx):
64 url = '%s?uri=spotify:%s:%s' %(spotify_gateway, type, track)
65 xml = urllib2.urlopen(url).read()
66 soup = BeautifulSoup(xml)
67 lookup_type = soup.contents[2].name
68
69 if lookup_type == 'track':
70 name = soup.find('name').string
71 album_name = soup.find('album').find('name').string
72 artist_name = soup.find('artist').find('name').string
73 popularity = soup.find('popularity')
74 if popularity:
75 popularity = float(popularity.string)*100
76 length = float(soup.find('length').string)
77 minutes = int(length)/60
78 seconds = int(length)%60
79
80 bot.msg(line.split()[2], 'Track: %s - %s / %s %s:%.2d %2d%%' %(artist_name, name,
81 album_name, minutes, seconds, popularity))
82
83 elif lookup_type == 'album':
84 album_name = soup.find('album').find('name').string
85 artist_name = soup.find('artist').find('name').string
86 released = soup.find('released').string
87 bot.msg(line.split()[2], 'Album: %s - %s - %s' %(artist_name, album_name, released))
88
89 else:
90 bot.notice(sender['nick'], "Unsupported type.")