]> jfr.im git - erebus.git/blame - modules/spotify.py
Various fixed to spotify.py
[erebus.git] / modules / spotify.py
CommitLineData
d776b529
CS
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
6modinfo = {
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
14import modlib
15lib = modlib.modlib(__name__)
16modstart = lib.modstart
17modstop = lib.modstop
18
19# module code
20import re
21import ctlmod
22import urllib2
23from BeautifulSoup import BeautifulSoup
24
822b8906 25checkfor = "spotify"
d776b529
CS
26hostmask_regex = re.compile('^(.*)!(.*)@(.*)$')
27spotify_regex = ( re.compile(r'spotify:(?P<type>\w+):(?P<track_id>\w{22})'),
28 re.compile(r'http://open.spotify.com/(?P<type>\w+)/(?P<track_id>\w{22})') )
29spotify_gateway = 'http://ws.spotify.com/lookup/1/'
30def parser_hostmask(hostmask):
31 if isinstance(hostmask, dict):
32 return hostmask
33
34 nick = None
35 user = None
36 host = None
37
38 if hostmask is not None:
39 match = hostmask_regex.match(hostmask)
40
41 if not match:
42 nick = hostmask
43 else:
44 nick = match.group(1)
45 user = match.group(2)
46 host = match.group(3)
47
48 return {
49 'nick': nick,
50 'user': user,
51 'host': host
52 }
53
54@lib.hooknum("PRIVMSG")
55def privmsg_hook(bot, line):
56 sender = parser_hostmask(line[1:line.find(' ')])
57
58 try:
822b8906 59 linetx = line.split(None, 3)[3][1:]
d776b529
CS
60 except IndexError:
61 linetx = ''
62
822b8906
JR
63 if checkfor not in line:
64 return # doesn't concern us
65
d776b529
CS
66 for r in spotify_regex:
67 for type, track in r.findall(linetx):
822b8906 68 url = '%s?uri=spotify:%s:%s' % (spotify_gateway, type, track)
d776b529
CS
69 xml = urllib2.urlopen(url).read()
70 soup = BeautifulSoup(xml)
71 lookup_type = soup.contents[2].name
72
73 if lookup_type == 'track':
74 name = soup.find('name').string
75 album_name = soup.find('album').find('name').string
76 artist_name = soup.find('artist').find('name').string
77 popularity = soup.find('popularity')
78 if popularity:
79 popularity = float(popularity.string)*100
80 length = float(soup.find('length').string)
81 minutes = int(length)/60
82 seconds = int(length)%60
83
84 bot.msg(line.split()[2], 'Track: %s - %s / %s %s:%.2d %2d%%' %(artist_name, name,
85 album_name, minutes, seconds, popularity))
86
87 elif lookup_type == 'album':
88 album_name = soup.find('album').find('name').string
89 artist_name = soup.find('artist').find('name').string
90 released = soup.find('released').string
91 bot.msg(line.split()[2], 'Album: %s - %s - %s' %(artist_name, album_name, released))
92
93 else:
94 bot.notice(sender['nick'], "Unsupported type.")