1 # Erebus IRC bot - Author: Conny Sjoblom
2 # vim: fileencoding=utf-8
4 # This file is released into the public domain; see http://unlicense.org/
8 'author': 'Erebus Team',
9 'license': 'public domain',
15 # http://embed.ly/tools/generator
19 lib
= modlib
.modlib(__name__
)
20 modstart
= lib
.modstart
25 if sys
.version_info
.major
< 3:
26 stringbase
= basestring
30 html
= HTMLParser
.HTMLParser()
31 from BeautifulSoup
import BeautifulSoup
34 import urllib
.request
as urllib2
35 import urllib
.parse
as urlparse
37 from bs4
import BeautifulSoup
39 import re
, json
, datetime
41 hostmask_regex
= re
.compile(r
'^(.*)!(.*)@(.*)$')
43 def parser_hostmask(hostmask
):
44 if isinstance(hostmask
, dict):
51 if hostmask
is not None:
52 match
= hostmask_regex
.match(hostmask
)
67 class SmartRedirectHandler(urllib2
.HTTPRedirectHandler
):
68 def http_error_301(self
, req
, fp
, code
, msg
, headers
):
69 result
= urllib2
.HTTPRedirectHandler
.http_error_301(
70 self
, req
, fp
, code
, msg
, headers
)
74 def http_error_302(self
, req
, fp
, code
, msg
, headers
):
75 result
= urllib2
.HTTPRedirectHandler
.http_error_302(
76 self
, req
, fp
, code
, msg
, headers
)
80 def process_line(line
):
83 limit
= lib
.parent
.cfg
.getint('urls', 'limit', 2)
84 for action
, group
, prefix
in regexes
:
86 for match
in regex
.findall(line
):
91 if isinstance(match
, stringbase
):
96 responses
.append("%s: %s" % (prefix
, resp
))
99 @lib.hooknum("PRIVMSG")
100 def privmsg_hook(bot
, textline
):
101 user
= parser_hostmask(textline
[1:textline
.find(' ')])
102 chan
= textline
.split()[2]
105 line
= textline
.split(None, 3)[3][1:]
109 responses
= process_line(line
)
110 if len(responses
) > 0:
111 if lib
.parent
.cfg
.getboolean('urls', 'multiline'):
113 bot
.msg(chan
, r
, True)
115 bot
.msg(chan
, ' | '.join(responses
), True)
118 return re
.sub('\s+', ' ', html
.unescape(line
))
120 def gotspotify(type, track
):
121 url
= 'http://ws.spotify.com/lookup/1/?uri=spotify:%s:%s' % (type, track
)
122 xml
= urllib2
.urlopen(url
).read()
123 soup
= BeautifulSoup(xml
, convertEntities
=BeautifulSoup
.HTML_ENTITIES
)
124 lookup_type
= soup
.contents
[2].name
126 if lookup_type
== 'track':
127 name
= soup
.find('name').string
128 album_name
= soup
.find('album').find('name').string
129 artist_name
= soup
.find('artist').find('name').string
130 popularity
= soup
.find('popularity')
132 popularity
= float(popularity
.string
)*100
133 length
= float(soup
.find('length').string
)
134 minutes
= int(length
)/60
135 seconds
= int(length
)%60
137 return unescape('Track: %s - %s / %s %s:%.2d %2d%%' % (artist_name
, name
, album_name
, minutes
, seconds
, popularity
))
139 elif lookup_type
== 'album':
140 album_name
= soup
.find('album').find('name').string
141 artist_name
= soup
.find('artist').find('name').string
142 released
= soup
.find('released').string
143 return unescape('Album: %s - %s - %s' % (artist_name
, album_name
, released
))
146 return 'Unsupported type.'
149 mo
= re
.match(r
'P(\d+D)?T(\d+H)?(\d+M)?(\d+S)?', s
)
150 pcs
= [x
for x
in mo
.groups() if x
]
151 return ''.join(pcs
).lower()
153 mo
= re
.match(r
'(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d+)Z', s
)
154 return datetime
.datetime(*(int(x
) for x
in mo
.groups())).strftime(f
)
158 return '%.1ft' % (n
/10**12)
160 return '%.1fb' % (n
/10**9)
162 return '%.1fm' % (n
/10**6)
164 return '%.1fk' % (n
/10**3)
169 url_data
= urlparse
.urlparse(url
)
170 query
= urlparse
.parse_qs(url_data
.query
)
171 video
= query
["v"][0]
172 api_url
= 'https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=%s&key=%s' % (video
, lib
.parent
.cfg
.get('urls', 'api_key'))
174 respdata
= urllib2
.urlopen(api_url
).read()
175 v
= json
.loads(respdata
)
178 return unescape(lib
.parent
.cfg
.get('urls', 'yt_format', "\002%(author)s\002: \037%(title)s\037 [%(duration)s, uploaded %(uploaded)s, %(views)s v/%(likes)s l/%(dislikes)s d]") % {
179 'title': v
['snippet']['title'],
180 'author': v
['snippet']['channelTitle'],
181 'duration': _yt_duration(v
['contentDetails']['duration']),
182 'uploaded': _yt_date(v
['snippet']['publishedAt'], lib
.parent
.cfg
.get('urls', 'yt_date_format', '%b %d %Y')),
183 'views': _yt_round(v
['statistics']['viewCount']),
184 'likes': _yt_round(v
['statistics']['likeCount']),
185 'dislikes': _yt_round(v
['statistics']['dislikeCount']),
187 except urllib2
.HTTPError
as e
:
188 if e
.getcode() == 403:
189 return 'API limit exceeded'
194 except Exception as e
:
198 url
= 'https://api.twitch.tv/helix/streams?user_login=%s' % uri
.split('/')[0]
199 opener
= urllib2
.build_opener()
200 opener
.addheaders
= [('Client-ID', lib
.parent
.cfg
.get('urls', 'twitch_api_key'))]
201 respdata
= opener
.open(url
).read()
202 twitch
= json
.loads(respdata
)['data']
204 # TODO: add current game.
205 return unescape('\037%s\037 is %s (%s)' % (twitch
[0]['user_name'], twitch
[0]['type'], twitch
[0]['title']))
207 return 'Channel offline.'
210 for _
, group
, _
in other_regexes
:
214 request
= urllib2
.Request(url
, headers
={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'}
)
215 opener
= urllib2
.build_opener(SmartRedirectHandler())
217 soup
= BeautifulSoup(opener
.open(request
, timeout
=2))
219 return unescape('%s' % (soup
.title
.string
))
222 except urllib2
.HTTPError
as e
:
223 return 'Error: %s %s' % (e
.code
, e
.reason
)
224 except urllib2
.URLError
as e
:
225 return 'Error: %s' % (e
.reason
)
226 except TimeoutError
as e
:
227 return 'Error: request timed out'
228 except Exception as e
:
229 return 'Error: %s %r' % (type(e
).__name
__, e
.args
)
232 re
.compile(r
'https?://[^/\s]+\.[^/\s]+(?:/\S+)?'),
236 regexes
= other_regexes
+ (
237 (goturl
, url_regex
, 'Title'),