]> jfr.im git - erebus.git/blame - modules/urls.py
weather - dont fail when wunderground screws up time
[erebus.git] / modules / urls.py
CommitLineData
a83e1f9c 1# Erebus IRC bot - Author: Erebus Team
2# URL Checker
3# This file is released into the public domain; see http://unlicense.org/
4
5# module info
6modinfo = {
7 'author': 'Erebus Team',
8 'license': 'public domain',
fa93b933 9 'compatible': [0],
a62d0d18 10 'depends': [],
11 'softdeps': [],
a83e1f9c 12}
13
99366200
CS
14# http://embed.ly/tools/generator
15
a83e1f9c 16# preamble
17import modlib
18lib = modlib.modlib(__name__)
19modstart = lib.modstart
20modstop = lib.modstop
21
22# module code
a28e2ae9 23import sys
24if sys.version_info.major < 3:
25 import urllib2
26 import urlparse
27 import HTMLParser
28 from BeautifulSoup import BeautifulSoup
29else:
30 import urllib.request as urllib2
31 import urllib.parse as urlparse
32 import html.parser as HTMLParser
33 from bs4 import BeautifulSoup
34
35import re, json
a83e1f9c 36
390fbad4 37html_parser = HTMLParser.HTMLParser()
a83e1f9c 38
390fbad4 39hostmask_regex = re.compile(r'^(.*)!(.*)@(.*)$')
c6880712 40url_regex = re.compile(r'https?://[^/\s]+\.[^/\s]+(?:/\S+)?')
a83e1f9c 41spotify_regex = (
42 re.compile(r'spotify:(?P<type>\w+):(?P<track_id>\w{22})'),
c6880712 43 re.compile(r'https?://open.spotify.com/(?P<type>\w+)/(?P<track_id>\w+)')
a83e1f9c 44)
45youtube_regex = (
46 re.compile(r'https?://(?:www\.)?youtube\.com/watch\?[a-zA-Z0-9=&_\-]+'),
47)
48twitch_regex = (
01a6184a 49 re.compile(r'https?:\/\/(?:www\.)?twitch.tv\/([A-Za-z0-9]*)'),
a83e1f9c 50)
51
52def parser_hostmask(hostmask):
53 if isinstance(hostmask, dict):
54 return hostmask
55
56 nick = None
57 user = None
58 host = None
59
60 if hostmask is not None:
61 match = hostmask_regex.match(hostmask)
62
63 if not match:
64 nick = hostmask
65 else:
66 nick = match.group(1)
67 user = match.group(2)
68 host = match.group(3)
69
70 return {
71 'nick': nick,
72 'user': user,
73 'host': host
74 }
75
394a7b69
CS
76class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
77 def http_error_301(self, req, fp, code, msg, headers):
78 result = urllib2.HTTPRedirectHandler.http_error_301(
79 self, req, fp, code, msg, headers)
80 result.status = code
81 return result
82
83 def http_error_302(self, req, fp, code, msg, headers):
84 result = urllib2.HTTPRedirectHandler.http_error_302(
85 self, req, fp, code, msg, headers)
86 result.status = code
87 return result
88
a83e1f9c 89@lib.hooknum("PRIVMSG")
390fbad4
CS
90def privmsg_hook(bot, textline):
91 user = parser_hostmask(textline[1:textline.find(' ')])
92 chan = textline.split()[2]
a83e1f9c 93
94 try:
390fbad4 95 line = textline.split(None, 3)[3][1:]
a83e1f9c 96 except IndexError:
390fbad4 97 line = ''
a83e1f9c 98
390fbad4
CS
99 for match in url_regex.findall(line):
100 if match:
c6880712 101 response = goturl(match)
102 if response is not None:
103 bot.msg(chan, response)
a83e1f9c 104
390fbad4
CS
105def unescape(line):
106 return html_parser.unescape(line)
a83e1f9c 107
108def gotspotify(type, track):
109 url = 'http://ws.spotify.com/lookup/1/?uri=spotify:%s:%s' % (type, track)
110 xml = urllib2.urlopen(url).read()
390fbad4 111 soup = BeautifulSoup(xml, convertEntities=BeautifulSoup.HTML_ENTITIES)
a83e1f9c 112 lookup_type = soup.contents[2].name
390fbad4 113
a83e1f9c 114 if lookup_type == 'track':
115 name = soup.find('name').string
116 album_name = soup.find('album').find('name').string
117 artist_name = soup.find('artist').find('name').string
118 popularity = soup.find('popularity')
119 if popularity:
120 popularity = float(popularity.string)*100
121 length = float(soup.find('length').string)
122 minutes = int(length)/60
123 seconds = int(length)%60
390fbad4 124
dafa38fc 125 return unescape('Track: %s - %s / %s %s:%.2d %2d%%' % (artist_name, name, album_name, minutes, seconds, popularity))
390fbad4 126
a83e1f9c 127 elif lookup_type == 'album':
128 album_name = soup.find('album').find('name').string
129 artist_name = soup.find('artist').find('name').string
130 released = soup.find('released').string
dafa38fc 131 return unescape('Album: %s - %s - %s' % (artist_name, album_name, released))
390fbad4 132
a83e1f9c 133 else:
134 return 'Unsupported type.'
135
136def gotyoutube(url):
137 url_data = urlparse.urlparse(url)
138 query = urlparse.parse_qs(url_data.query)
139 video = query["v"][0]
140 api_url = 'http://gdata.youtube.com/feeds/api/videos/%s?alt=json&v=2' % video
141 try:
142 respdata = urllib2.urlopen(api_url).read()
143 video_info = json.loads(respdata)
144
145 title = video_info['entry']['title']["$t"]
146 author = video_info['entry']['author'][0]['name']['$t']
147
dafa38fc 148 return unescape("Youtube: %s (%s)" % (title, author))
a83e1f9c 149 except:
150 pass
151
390fbad4
CS
152def gottwitch(uri):
153 url = 'http://api.justin.tv/api/stream/list.json?channel=%s' % uri.split('/')[0]
154 respdata = urllib2.urlopen(url).read()
155 twitch = json.loads(respdata)
156 try:
dafa38fc 157 return unescape('Twitch: %s (%s playing %s)' % (twitch[0]['channel']['status'], twitch[0]['channel']['login'], twitch[0]['channel']['meta_game']))
390fbad4
CS
158 except:
159 return 'Twitch: Channel offline.'
160
161def goturl(url):
394a7b69
CS
162 request = urllib2.Request(url)
163 opener = urllib2.build_opener(SmartRedirectHandler())
993046cc 164 try:
394a7b69 165 soup = BeautifulSoup(opener.open(request, timeout=2))
dafa38fc 166 return unescape('Title: %s' % (soup.title.string))
993046cc 167 except:
c6880712 168 return None