-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpungabot.py
494 lines (415 loc) · 15.3 KB
/
pungabot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Pungabot:
Python , twisted powered irc bot with userbase and twitter support
fork from pyfibot (http://code.google.com/p/pyfibot/) by Riku Lindblad
@license New-Style BSD
"""
import re
import sys
import os.path
import time
import urllib
import HTMLParser
import logging
import logging.handlers
import tweepy
import yaml
from BeautifulSoup import BeautifulSoup, UnicodeDammit
from util import *
from pysqlite2 import dbapi2 as sqlite3
from StringIO import StringIO
# twisted imports
try:
from twisted.internet import reactor, protocol, ssl
except ImportError:
print "Twisted Matrix library not found, please install it"
sys.exit(1)
import botcore
log = logging.getLogger('core')
# default timeout for socket connections
import socket
socket.setdefaulttimeout(20)
# twitter api keys
consumer_key = "tsh79PNCdSogwg9Dx3VNg"
consumer_secret = "Kg8H9ninvOkQfsiIyw03r2QsUGDOXqWBjWB1Nzt9lA"
class URLCacheItem(object):
"""URL cache item object, fetches data only when needed"""
def __init__(self, url):
self.url = url
self.content = None
self.headers = None
self.bs = None
# maximum size in kB to download
self.max_size = 2048
self.fp = None
def _open(self, url):
"""Returns the raw file pointer to the given URL"""
if not self.fp:
urllib._urlopener = BotURLOpener()
try:
self.fp = urllib.urlopen(self.url)
except IOError, e:
log.warn("IOError when opening url %s, error: %r" % (
url,
e.strerror.strerror
))
return self.fp
def _checkstatus(self):
"""Check if all data has already been cached and close socket if so"""
if self.content and \
self.headers and \
self.bs:
self.fp.close()
def getSize(self):
"""Get the content length of URL in kB
@return None if the server doesn't return a content-length header"""
if 'content-length' in self.getHeaders():
return int(self.getHeaders()['content-length']) / 1024
else:
return None
def getContent(self):
"""Get the actual file at the URL
@return None if the file is too large (over 2MB)"""
if not self.content:
f = self._open(self.url)
size = self.getSize()
if size > self.max_size:
log.warn("CONTENT TOO LARGE, WILL NOT FETCH %s %s" % (
size,
self.url
))
self.content = None
else:
if self.checkType():
# handle gzipped content
if f.info().get('Content-Encoding') == 'gzip':
log.debug("Gzipped data, uncompressing")
buf = StringIO(f.read())
f = GzipFile(fileobj=buf)
self.content = UnicodeDammit(f.read()).unicode
else:
contentType = self.getHeaders().getsubtype()
log.warn("WRONG CONTENT TYPE,WILL NOT FETCH %s, %s, %s" % (
size,
contentType,
self.url
))
self._checkstatus()
return self.content
def getHeaders(self):
"""Get headers for the URL"""
if not self.headers:
f = self._open(self.url)
if f:
self.headers = f.info()
else:
self.headers = {}
self._checkstatus()
return self.headers
def checkType(self):
if self.getHeaders().getsubtype() in \
['html', 'xml', 'xhtml+xml', 'atom+xml']:
return True
else:
return False
def getBS(self):
"""Get a beautifulsoup instance for the URL
@return None if the url doesn't contain HTML
"""
if not self.bs:
# only attempt a bs parsing if the content is html, xml or xhtml
if 'content-type' in self.getHeaders() and \
self.getHeaders().getsubtype() in \
['html', 'xml', 'xhtml+xml', 'atom+xml']:
try:
bs = BeautifulSoup(markup=self.getContent())
except HTMLParser.HTMLParseError:
log.warn("BS unable to parse content")
return None
self.bs = bs
else:
return None
self._checkstatus()
return self.bs
class BotURLOpener(urllib.FancyURLopener):
"""
URL opener that fakes itself as Firefox and ignores all basic auth prompts
"""
def __init__(self, *args):
# Firefox 1.0PR on w2k
self.version = "Mozilla/5.0 (Windows; U; Windows NT 5.0; rv:1.7.3)"
urllib.FancyURLopener.__init__(self, *args)
def prompt_user_passwd(self, host, realm):
log.info("PASSWORD PROMPT:", host, realm)
return ('', '')
class Network:
def __init__(
self, root, alias, address, nickname, channels=None, is_ssl=False
):
self.alias = alias # network name
self.address = address # server address
self.nickname = nickname # nick to use
self.channels = channels or {} # channels to join
self.is_ssl = is_ssl
# create network specific save directory
p = os.path.join(root, alias)
if not os.path.isdir(p):
os.mkdir(p)
def __repr__(self):
return 'Network(%r, %r)' % (self.alias, self.address)
class InstantDisconnectProtocol(protocol.Protocol):
def connectionMade(self):
self.transport.loseConnection()
class ThrottledClientFactory(protocol.ClientFactory):
"""Client that inserts a slight delay to connecting and reconnecting"""
lostDelay = 10
failedDelay = 60
def clientConnectionLost(self, connector, reason):
#print connector
log.info("connection lost (%s): reconnecting in %d seconds" % (
reason,
self.lostDelay
))
reactor.callLater(self.lostDelay, connector.connect)
def clientConnectionFailed(self, connector, reason):
#print connector
log.info("connection failed (%s): reconnecting in %d seconds" % (
reason,
self.failedDelay
))
reactor.callLater(self.failedDelay, connector.connect)
class pungaBotFactory(ThrottledClientFactory):
"""python bot factory"""
version = "20140401.0"
protocol = botcore.pungaBot
allBots = None
moduledir = os.path.join(sys.path[0], "modules/")
startTime = None
config = None
def regexp(self, expr, item):
r = re.compile(expr, re.MULTILINE | re.IGNORECASE)
return r.match(item) is not None
def getConn(self, db):
conn = sqlite3.connect(
db,
isolation_level=None,
check_same_thread=False
)
conn.create_function("regexp", 2, self.regexp)
return conn.cursor()
def __init__(self, config):
"""Initialize the factory"""
self.config = config
self.data = {}
self.data['networks'] = {}
self.ns = {}
# cache url contents for 5 minutes, check for old entries every minute
self._urlcache = timeoutdict.TimeoutDict(timeout=300, pollinterval=60)
if not os.path.exists("data"):
os.mkdir("data")
# connect to twitter
if self.config['twitter']:
key = config['twitter'][0]
secret = config['twitter'][1]
try:
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(key, secret)
self.twapi = tweepy.API(auth)
log.info('connection to TWITTER ok')
except:
log.info('could not connect to TWITTER')
self.dbCursor = self.getConn(
str.join('.', (self.config['nick'], 'db'))
)
def startFactory(self):
self.allBots = {}
self.starttime = time.time()
self._loadmodules()
ThrottledClientFactory.startFactory(self)
log.info("factory started")
def stopFactory(self):
del self.allBots
ThrottledClientFactory.stopFactory(self)
log.info("factory stopped")
def buildProtocol(self, address):
log.info("Building protocol for %s", address.host)
fqdn = socket.getfqdn(address.host)
# TODO We do need to know which network the address belongs to
for network, server in self.data['networks'].items():
log.debug("Conneting to : %s - %s", server, fqdn)
p = self.protocol(server)
self.allBots[server.alias] = p
p.factory = self
return p
# No address found
log.error("Unknown network address: " + repr(address))
return InstantDisconnectProtocol()
def createNetwork(
self, address, alias, nickname, channels=None, is_ssl=False
):
self.setNetwork(
Network("data", alias, address, nickname, channels, is_ssl)
)
def setNetwork(self, net):
nets = self.data['networks']
nets[net.alias] = net
self.data['networks'] = nets
def clientConnectionLost(self, connector, reason):
"""Connection lost for some reason"""
log.info("conn to %s lost" % str(connector.getDestination().host))
# find bot that connects to the address that just disconnected
for n in self.data['networks'].values():
dest = connector.getDestination()
if (dest.host, dest.port) == n.address:
if n.alias in self.allBots:
# did we quit intentionally?
if not self.allBots[n.alias].hasQuit:
# nope, reconnect
ThrottledClientFactory.clientConnectionLost(
self,
connector,
reason
)
del self.allBots[n.alias]
return
else:
log.info("No active connection to net %s" % n.address[0])
def _finalize_modules(self):
"""Call all module finalizers"""
for module in self._findmodules():
# if rehashing , finalize the old instance first
if module in self.ns:
if 'finalize' in self.ns[module][0]:
log.info("finalize - %s" % module)
self.ns[module][0]['finalize']()
def _loadmodules(self):
"""Load all modules"""
self._finalize_modules()
for module in self._findmodules():
env = self._getGlobals()
log.info("load module - %s" % module)
# Load new version of the module
execfile(os.path.join(self.moduledir, module), env, env)
# initialize module
if 'init' in env:
log.info("initialize module - %s" % module)
env['init'](self.config)
# add to namespace so we can find it later
self.ns[module] = (env, env)
def _unload_removed_modules(self):
"""Unload modules removed from modules -directory"""
# find all modules which aren't present in modules -directory
removed_modules = [m for m in self.ns if not m in self._findmodules()]
for m in removed_modules:
# finalize module before deleting it
# TODO: use general _finalize_modules instead of copy-paste
if 'finalize' in self.ns[m][0]:
log.info("finalize - %s" % m)
self.ns[m][0]['finalize']()
del self.ns[m]
log.info('removed module - %s' % m)
def _findmodules(self):
"""Find all modules"""
modules = [m for m in os.listdir(self.moduledir)
if m.startswith("module_") and m.endswith(".py")]
return modules
def _getGlobals(self):
"""Global methods for modules"""
g = {}
g['getUrl'] = self.getUrl
g['getNick'] = self.getNick
g['getHostmask'] = self.getHostmask
g['twapi'] = self.twapi
g['dbCursor'] = self.dbCursor
return g
def getUrl(self, url, nocache=False):
"""
Gets data, bs and headers for the given url,
using the internal cache if necessary
"""
if url in self._urlcache and not nocache:
log.info("cache hit : %s" % url)
else:
if nocache:
log.info("cache pass: %s" % url)
else:
log.info("cache miss: %s" % url)
self._urlcache[url] = URLCacheItem(url)
return self._urlcache[url]
def getNick(self, user):
"""Parses nick from nick!user@host
@type user: string
@param user: nick!user@host
@return: nick"""
return user.split('!', 1)[0]
def getHostmask(self, user):
"""Parses hostmask from nick!user@host
@type user: string
@param user: nick!user@host
@return: nick"""
return user.split('!', 1)[1]
def init_logging():
filename = os.path.join(sys.path[0], 'pungabot.log')
# get root logger
logger = logging.getLogger()
if False:
handler = logging.handlers.RotatingFileHandler(
filename,
maxBytes=5000 * 1024,
backupCount=20
)
else:
handler = logging.StreamHandler()
# time format is same format of strftime
formatter = logging.Formatter(
'%(asctime)-15s %(levelname)-8s %(name)-11s %(message)s'
)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
if __name__ == '__main__':
init_logging()
sys.path.append(os.path.join(sys.path[0], 'lib'))
config = os.path.join(sys.path[0], "bot.config")
if os.path.exists(config):
config = yaml.load(file(config))
factory = pungaBotFactory(config)
# write pidfile, for eggchk
pidfile = str.join('.', (config['nick'], 'pid'))
file4pid = open(pidfile, 'w')
file4pid.write('%s\n' % os.getpid())
file4pid.close()
for network, settings in config['networks'].items():
# use network specific nick if one has been configured
nick = settings.get('nick', None) or config['nick']
try:
port = int(settings.get('port'))
except:
port = 6667
is_ssl = bool(settings.get('is_ssl', False))
# prevent internal confusion with channels
chanlist = []
for channel in settings['channels']:
if channel[0] not in '&#!+':
channel = str.join('', ('#', channel))
chanlist.append(channel)
factory.createNetwork(
(settings['server'], port),
network,
nick,
chanlist
)
if is_ssl:
log.info("SSL connection to %s:%d" % (settings['server'], port))
reactor.connectSSL(
settings['server'],
port,
factory,
ssl.ClientContextFactory()
)
else:
log.info("connecting to %s:%d" % (settings['server'], port))
reactor.connectTCP(settings['server'], port, factory)
reactor.run()