-
Notifications
You must be signed in to change notification settings - Fork 2
/
bot.py
1311 lines (1057 loc) · 51.5 KB
/
bot.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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import codecs
import cPickle as pickle
import datetime
import hashlib
import imp
import optparse
import os
import re
import sqlite3
import sys
import threading
import time
import traceback
import warnings
from utils import tounicode
from twisted.words.protocols import irc
from twisted.words.protocols.irc import lowDequote, numeric_to_symbolic, symbolic_to_numeric, split
from twisted.internet import reactor, protocol, threads
from twisted.python import threadable
threadable.init(1)
try:
import json # Available in python >= 2.6.
except ImportError:
try:
import simplejson as json # If no json library is found logging to sqlite and mysql will be disabled.
except ImportError:
json = None
try:
import MySQLdb
except ImportError:
MySQLdb = None
try:
from pytz import timezone
except ImportError:
timezone = None
config_defaults = {'nick': 'spiffy', 'prefix': r'!', 'chandebug': True,
'channels': [],
'logevents': ['PRIVMSG', 'JOIN', 'PART',
'MODE', 'TOPIC', 'KICK', 'QUIT',
'NOTICE', 'NICK', '332', '333'],
'verbose': True, 'reconnect': 10,
'logpath': 'logs', 'plugins_exclude': [],
'plugins_include': False, 'timezone': None,
'print_traffic': False, 'silent': False}
def sourcesplit(source):
"""Split nick!user@host and return a 3-value tuple."""
r = re.compile(r'([^!]*)!?([^@]*)@?(.*)')
m = r.match(source)
return m.groups()
class Bot(irc.IRCClient, object):
class BadInputError(Exception):
def __init__(self, value=None):
self.value = value
def __str__(self):
return repr(self.value)
# After the bot has connected all attributes will be stored in the
# botfactory.
def __getattribute__(self, attr):
try:
return object.__getattribute__(self, attr)
except AttributeError:
return getattr(object.__getattribute__(self, 'factory').settings, attr)
def __setattr__(self, attr, value):
if object.__getattribute__(self, 'loaded'):
if hasattr(self, attr):
object.__setattr__(self, attr, value)
else:
setattr(object.__getattribute__(self, 'factory').settings, attr, value)
else:
object.__setattr__(self, attr, value)
factory = None
loaded = False
def connectionMade(self):
self.loaded = True
self.connections[self.config['network']] = self
if not hasattr(self, 'logger'): #Executed on first connect only
self.config['logevents'] = [s.upper() for s in self.config['logevents']]
self.logger = IRCLogger(self, self.config.get('logpath'))
if not os.path.exists("data"):
os.mkdir("data")
self.loadPlugins()
self.lastmsg = time.mktime(time.gmtime())
self.sourceURL = None #Disable source reply.
self.split = split #Make the split function accessible to plugins
self.encoding = 'utf-8'
self.password = self.config.get('password', None)
if isinstance(self.config['nick'], (list, tuple)):
self.nickname = self.config['nick'][0]
self.nickbucket = self.config['nick'][1:]
else:
self.nickname = self.config['nick']
self.nickbucket = []
self.username = self.config.get('user', self.nickname)
self.realname = self.config.get('name', self.nickname)
self.me = '%s!%s@unknown' % (self.nickname, self.username)
self.chanlist = ChanList(self)
t = threading.Thread(target=self.connectionWatcher)
t.start()
irc.IRCClient.connectionMade(self)
self._print("Connected to %s:%s at %s" % (self.transport.connector.host, self.transport.connector.port, time.asctime(time.localtime(time.time()))))
def parsemsg(self, s):
"""Breaks a message from an IRC server into its prefix, command, arguments and text.
"""
prefix = None
text = None
if not s:
raise irc.IRCBadMessage("Empty line.")
if s[0] == ':':
prefix, s = s[1:].split(' ', 1)
if s.find(' :') != -1:
s, text = s.split(' :', 1)
args = s.split()
command = args.pop(0)
return prefix, command, args, text
def connectionWatcher(self):
"""Make sure that we are still connected by PINGing the server."""
while True:
#Send PING to the server If no data has been received for 200 seconds.
if (self.lastmsg+200) < time.mktime(time.gmtime()):
self.lastmsg = time.mktime(time.gmtime())
reactor.callFromThread(self.sendLine, "PING YO!")
time.sleep(200)
def loadPlugins(self):
self._print("Loading plugins...")
self.plugins = {} # Plugins loaded from the plugins directory.
self.plugins_nicktriggered = {} # plugins that have a <nick> trigger
self.doc = {} # Documentation for plugins.
self.plugin_aliases = {} # Aliases for plugin commands.
self.plugins_regex = {} # Plugins that use a regex for matching
plugins = []
if os.path.exists(os.path.join(sys.path[0], "plugins")):
filenames = []
if isinstance(self.config['plugins_include'], (list, tuple)):
for fn in self.config['plugins_include']:
if not "." in fn:
fn = fn + ".py"
filenames.append(os.path.join(sys.path[0], "plugins", fn))
else:
for fn in os.listdir(os.path.join(sys.path[0], "plugins")):
if fn.endswith('.py') and not fn.startswith('_'):
if not fn[:-3] in self.config['plugins_exclude']:
filenames.append(os.path.join(sys.path[0], "plugins", fn))
for filename in filenames:
name = os.path.basename(filename)[:-3]
try:
self.loadPlugin(filename)
plugins.append(name)
except Exception, e:
self._print("Error loading %s: %s (in bot.py)" % (name, e), 'err')
if plugins:
self._print('Registered plugins: %s' % ', '.join(plugins))
else:
if not self.config['plugins_include'] == []:
self._print("Warning: Couldn't find any plugins. Does /plugins exist?", 'err')
def loadPlugin(self, filename, function = None):
def createdoc(self, func, commands = None):
pcmd = self.config["prefix"] + func.name # pcmd = prefixed command
if commands:
commands = commands[:]
if func.__doc__:
doc = func.__doc__
else:
doc = None
if hasattr(func, "usage"):
usage = "\x02Usage:\x02\n "
usage += "\n ".join(cmd + " - " + text
for text,cmd in func.usage)
usage = usage.replace("$pcmd", pcmd)
usage = usage.replace("$cmd", func.name)
usage = usage.replace("$nick", self.nickname)
else:
usage = None
if hasattr(func, 'example'):
example = "\x02Example:\x02\n "
example += "\n ".join("\n ".join(e for e in f)
for f in func.example)
example = example.replace("$pcmd", pcmd)
example = example.replace("$cmd", func.name)
example = example.replace('$nick', self.nickname)
else:
example = None
for command in commands or []:
self.plugin_aliases[command.lower()] = func.name
if func.name in (commands or []):
commands.remove(func.name)
if commands:
aliases = "\x02Aliases for the %s command:\x02\n " % func.name
aliases += ", ".join(commands)
else:
aliases = None
self.doc[func.name] = (doc, usage, example, aliases)
def handlefunc(func):
if hasattr(func, 'rule'):
if not hasattr(func, 'name'):
func.name = func.__name__
func.name = func.name.lower()
if not hasattr(func, 'event'):
func.event = 'PRIVMSG'
else:
func.event = func.event.upper()
self.plugins[func.name] = func
if hasattr(func, 'setup'):
input = CommandInput(self, '', '', '', '', None, '', func.name)
bot = QuickReplyWrapper(self, input)
func.setup(bot, input)
if isinstance(func.rule, str):
if '$nick' in func.rule:
self.plugins_nicktriggered[func.name] = func
pattern = func.rule.replace('$nickname', self.nickname).replace('$nick', self.nickname)
regexp = re.compile(pattern)
createdoc(self, func)
self.plugins_regex[func.name] = regexp
elif isinstance(func.rule, (tuple, list)):
commands = func.rule
createdoc(self, func, commands)
for command in commands:
self.plugin_aliases[command] = func.name
if not function:
name = os.path.basename(filename)[:-3]
plugin = imp.load_source(name, filename)
for name, func in vars(plugin).iteritems():
handlefunc(func)
return plugin
else:
handlefunc(function)
return function
def nickChanged(self, nick):
"""Called when my nick has been changed.
"""
self.nickname = nick
for funcname in self.plugins_nicktriggered:
if funcname in self.plugins:
del self.plugins[funcname]
if funcname in self.plugins_regex:
del self.plugins_regex[funcname]
if funcname in self.doc:
del self.doc[funcname]
self.loadPlugin(filename=None, function = self.plugins_nicktriggered[funcname])
def rehash(self):
"""Reload the config file and plugins for this network.
If the current network has been removed or renamed only global settings
from the config file will be reloaded.
"""
self._print('Reloading configuration...')
config_name = os.path.join(sys.path[0], 'config.py')
if not os.path.isfile(config_name):
self._print('Error: Unable to rehash, no config(.py) file found.', 'err')
return False
config = imp.load_source('config', config_name)
config = config.__dict__
serverconfig = config_defaults.copy()
for setting in config:
if not setting.startswith('__'):
serverconfig[setting] = config[setting]
if 'networks' in config:
if self.config['network'] in config['networks']:
for setting in config['networks'][self.config['network']]:
serverconfig[setting] = config['networks'][self.config['network']][setting]
serverconfig['activeserver'] = self.config['activeserver']
serverconfig['network'] = self.config['network']
serverconfig['logevents'] = [s.upper() for s in serverconfig['logevents']]
if isinstance(serverconfig['nick'], (list, tuple)):
newnick = serverconfig['nick'][0]
self.nickbucket = serverconfig['nick'][1:]
else:
newnick = serverconfig['nick']
if not self.nickname == newnick:
self.setNick(newnick)
self.username = self.config.get('user', self.nickname)
self.realname = self.config.get('name', self.nickname)
added_settings = [(x, serverconfig[x]) for x in serverconfig if not x in self.config]
removed_settings = [x for x in self.config if not x in serverconfig]
changed_settings = [(x, self.config[x], serverconfig[x]) for x in serverconfig if (x in self.config) and (not serverconfig.get(x) == self.config.get(x)) and (not x == 'networks')]
self.config = serverconfig
oldplugins = self.plugins.keys()
self.loadPlugins()
newplugins = self.plugins.keys()
removed_plugins = [x for x in oldplugins if x not in newplugins]
added_plugins = [x for x in newplugins if x not in oldplugins]
if added_settings:
self._print('Added %s new settings:' % len(added_settings))
for setting in added_settings:
self._print(" + '%s': %s" % setting)
if removed_settings:
self._print('Removed %s settings:' % len(removed_settings))
for setting in removed_settings:
self._print(" - '%s'" % setting)
if changed_settings:
self._print('Changed %s settings:' % len(changed_settings))
for setting in changed_settings:
self._print(" * '%s': %s -> %s" % setting)
if added_plugins:
self._print('Loaded %s new plugins:' % len(added_plugins))
self._print(", ".join(added_plugins))
if removed_plugins:
self._print('Removed %s plugins:' % len(removed_plugins))
self._print(", ".join(removed_plugins))
return {'plugins': {'removed': removed_plugins,
'added': added_plugins
},
'settings': {'removed': removed_settings,
'added': added_settings,
'changed': changed_settings
}
}
def connectionLost(self, reason):
irc.IRCClient.connectionLost(self, reason)
self._print("Disconnected at %s" % time.asctime(time.localtime(time.time())))
def disconnect(self, reason = 'leaving'):
self.config['reconnect'] = False
self.sendLine('QUIT :%s' % reason)
def connect(self):
self.config['reconnect'] = 10
self.transport.connector.connect()
def jump(self, msg='Changing servers'):
self.sendLine('QUIT :%s' % msg)
def modeChanged(self, user, channel, set, modes, args):
"""Called when users or channel's modes are changed."""
# If voice/op was added or removed, args is a tuple containing the
# affected nickname(s)
modedict = {"v": "+", #voice
"o": "@", #op
"h": "%", #halfop (used by Unreal)
"a": "&", #admin (used by Unreal)
"q": "~", #owner (used by Unreal)
"!": "!" #service (used by KineIRCD)
}
if args and channel in self.chanlist.channels:
for user, mode in zip(args,list(modes)):
if mode not in modedict.keys():
continue
user = user.lower()
if user in self.chanlist[channel]['users']:
currentmode = self.chanlist[channel]['users'][user]["mode"]
if set:
if modedict[mode] not in currentmode:
currentmode += modedict[mode]
else:
currentmode = currentmode.replace(modedict[mode],"")
self.chanlist[channel]['users'][user]["mode"] = currentmode
def signedOn(self):
"""Called when bot has succesfully signed on to server."""
channels = self.config.get('channels', [])
for chan in channels:
self.join(chan)
def irc_ERR_ERRONEUSNICKNAME(self, prefix, params):
"""Called when we try to register an invalid nickname."""
self.irc_ERR_NICKNAMEINUSE(prefix, params)
def irc_ERR_NICKNAMEINUSE(self, prefix, params):
"""Called when we try to register an invalid nickname."""
if len(self.nickbucket) > 0:
newnick = self.nickbucket.pop(0)
else:
newnick = self.nickname+'_'
self._print('Error using %s as nickname. (%s)' % (params[1], params[2]))
self._print('Trying %s...' % newnick)
self.nickChanged(newnick)
self.register(newnick)
def joined(self, channel):
"""This will get called when the bot joins the channel."""
self._print("Joined %s" % channel)
def msg(self, receiver, message):
message = tounicode(message)
lines = message.split("\n")
for line in lines:
self.logger.log(self.me, ['PRIVMSG'], [receiver], line)
self.sendLine(u"PRIVMSG %s :%s" % (receiver, line))
def notice(self, receiver, message):
message = tounicode(message)
lines = message.split("\n")
for line in lines:
self.logger.log(self.me, ['NOTICE'], [receiver], line)
self.sendLine("NOTICE %s :%s" % (receiver, line))
def sendLine(self, line):
if self.encoding is not None:
if isinstance(line, unicode):
line = line.encode(self.encoding)
self.transport.write("%s%s%s" % (line, chr(015), chr(012)))
if self.config.get('print_traffic', False):
self._print('-> ' + line)
def lineReceived(self, line):
self.lastmsg = time.mktime(time.gmtime())
line = lowDequote(line)
line = tounicode(line)
try:
prefix, command, params, text = self.parsemsg(line)
if numeric_to_symbolic.has_key(command):
command = numeric_to_symbolic[command]
self.handleCommand(command, prefix, params, text, line)
except Exception, e:
self._print("Error: %s" % e, 'err')
print traceback.format_exc()
def handleCommand(self, command, prefix, params, text, line):
"""Determine the function to call for the given command and call
it with the given arguments."""
method = getattr(self, "irc_%s" % command, None)
if method is not None:
try:
method(prefix or '', text and params+[text] or params)
except:
pass
command = (symbolic_to_numeric.get(command, command), command)
if self.config.get('print_traffic', False):
self._print('<- ' + line)
self.logger.log(prefix, command, params, text) # Needs to be called before _handleChange
if command[0].upper() in ("JOIN", "331", "332", "333", "352", "353", "KICK", "PART", "QUIT", "NICK", "TOPIC"):
self.chanlist.handleChange(prefix, command, params, text)
if command[0] == "005":
self.sendLine('PROTOCTL NAMESX')
if not text:
return
if text.startswith(self.config["prefix"]):
splitline = text[1:].split(" ", 1)
cmd = splitline[0]
if len(splitline) == 1:
args = None
else:
args = splitline[1:]
if cmd in self.plugin_aliases:
func = self.plugins[self.plugin_aliases[cmd]]
if not func.event in command:
return
input = CommandInput(self, prefix, command, params, text, None, line, func.name)
bot = QuickReplyWrapper(self, input)
self.runPlugin(func, bot, input)
return
for name, regexp in self.plugins_regex.iteritems():
match = regexp.match(text)
if match:
func = self.plugins[name]
if func.event in command:
input = CommandInput(self, prefix, command, params, text, match, line, func.name)
bot = QuickReplyWrapper(self, input)
self.runPlugin(func, bot, input)
def runPlugin(self, func, bot, input):
if hasattr(func, 'usage') and not self.config.get('silent', False):
if input.args.split(' ',1)[0] in ('-h', '--help'):
if func.name in bot.doc:
for e in bot.doc[func.name]:
if e:
bot.msg(input.sender, e)
return
def errorHandler(failure):
f = failure.trap(bot.BadInputError, Exception)
e = failure.getErrorMessage().strip("'")
if f == bot.BadInputError:
if input.sender and not bot.config.get('silent', False):
if e != 'None':
bot.msg(input.sender, "\x02Error:\x02 %s" % e)
if bot.doc[func.__name__][1]:
bot.msg(input.sender, bot.doc[func.__name__][1])
else:
bot.msg(input.sender, 'Use %shelp %s for more info on how to use this command.'
% (bot.config.get('prefix',''), func.__name__))
else:
if bot.config.get('chandebug', True) and input.sender and not bot.config.get('silent', False):
try:
failure.printTraceback
bot.msg(input.sender, "\x02Unhandled error:")
bot.msg(input.sender, failure.getTraceback())
except Exception, e:
bot.msg(input.sender, "Got an error: %s" % e)
d = threads.deferToThread(func, bot, input)
d.addErrback(errorHandler)
def ctcpQuery_VERSION(self, user, channel, data):
if self.config.get('versionreply', None):
nick = user.split("!",1)[0]
self.ctcpMakeReply(nick, [('VERSION', '%s' % self.config['versionreply'])])
def localtime(self):
if timezone and self.config['timezone']:
try:
return datetime.datetime(*timezone(self.config['timezone']).fromutc(datetime.datetime.utcnow()).timetuple()[:6])
except KeyError:
pass
return datetime.datetime.now()
class CommandInput(object):
def __init__(self, bot, source, event, params, text, match, line, funcname):
self.nick, self.user, self.host = sourcesplit(source or '')
self.line = line
self.funcname = funcname
self.event = event
if match: # plugin uses regex
self.match = match
self.group = match.group
self.groups = match.groups
self.command = self.args = text
else: # plugin uses command list
self.command = text.split(" ",1)[0][len(bot.config['prefix']):]
self.args = text.split(" ",1)[1] if text.strip().count(" ") > 0 else ""
self.group = lambda i: self.args if i == 2 else text # placeholder until plugins are ported
self.params = params
if len(params) > 0:
self.sender = params[0]
else:
self.sender = None
mappings = {bot.nickname: self.nick, None: None}
self.sender = mappings.get(self.sender, self.sender)
self.channel = self.sender
self._bot = bot
def isowner(self, *args):
if not 'ownermask' in self._bot.config:
return False
if re.search(self._bot.config['ownermask'], self.nick+'!'+self.user+'@'+self.host, re.IGNORECASE):
return True
return False
def isprivate(self):
"""Returns False if the message was sent to a channel and True if
the message was sent directly to the bot."""
if self.sender == self.nick:
return True
return False
class QuickReplyWrapper(object):
def __init__(self, bot, input):
self.bot = bot
self.input = input
if not hasattr(bot, 'pluginstorage_%s' % input.funcname.lower()):
setattr(bot, 'pluginstorage_%s' % input.funcname.lower(), Storage("data/%s.%s.db" % (bot.config['network'], input.funcname.lower())))
self.storage = getattr(bot, 'pluginstorage_%s' % input.funcname.lower())
def __getattribute__(self, attr):
try:
return object.__getattribute__(self, attr)
except AttributeError:
return getattr(object.__getattribute__(self, 'bot'), attr)
def reply(self, msg):
if self.input.sender:
self.bot.msg(self.input.sender, self.input.nick + ': ' + msg)
def say(self, msg):
if self.input.sender:
self.bot.msg(self.input.sender, msg)
def OptionParser(self):
return self.ModOptionParser(self.bot, self.input)
class ModOptionParser(optparse.OptionParser):
def __init__(self, bot, input):
self.bot = bot
self.input = input
optparse.OptionParser.__init__(self, add_help_option=False)
def error(self, msg):
raise self.bot.BadInputError(msg)
class ChanList(object):
def __init__(self, bot):
self.channels = {}
self.bot = bot
def __getitem__(self, attr, default=None):
return self.channels[attr]
def handleChange(self, prefix, command, params, text):
command = command[0].lower()
nick, user, host = sourcesplit(prefix or '')
chan = text or params[0]
chan = chan.lower()
#JOIN
if command == "join":
#Clear the channels userlist and issue a who command when the bot joins a chan
if nick == self.bot.nickname:
self.channels[chan] = { 'users': {}, 'topic': [None, None, None], 'created': None, 'modes': None }
self.bot.sendLine('MODE %s' % chan)
self.bot.sendLine('WHO %s' % chan)
self.bot.sendLine('NAMES %s' % chan)
self.channels[chan]['users'][nick.lower()] = {'nick': nick, 'user': user, 'host': host, 'mode': None}
#RPL_WHOREPLY
elif command == "352":
chan = params[1].lower()
nick = params[5]
user = params[2]
host = params[3]
if not chan in self.channels:
self.channels[chan] = { 'users': {}, 'topic': [None, None, None], 'created': None, 'modes': None }
self.channels[chan]['users'][nick.lower()] = {'nick': nick, 'user': user, 'host': host, 'mode': None}
if nick == self.bot.nickname:
self.bot.me = '%s!%s@%s' % (nick, user, host)
#RPL_NAMREPLY
elif command == "353":
chan = params[2].lower()
nicks = text.lower().split()
if chan in self.channels:
exp = re.compile(r'(?P<mode>[~%&@+]*)(?P<nick>[^~%&@+]*)')
for nick in nicks:
m = exp.match(nick)
if m.group('nick') in self.channels[chan]:
self.channels[chan]['users'][m.group('nick')]['mode'] = m.group('mode')
#KICK
elif command == "kick":
chan = params[0].lower()
nick = params[1].lower()
if chan in self.channels:
if nick == self.bot.nickname.lower():
#Remove channel from userlist when the bot is kicked from the channel.
del self.channels[chan]
elif nick in self.channels[chan]['users']:
del self.channels[chan]['users'][nick]
#PART
elif command == "part":
chan = params[0].lower()
nick = nick.lower()
if chan in self.channels:
if nick == self.bot.nickname.lower():
#Remove channel from userlist when the bot parts a channel
del self.channels[chan]
elif nick in self.channels[chan]['users']:
del self.channels[chan]['users'][nick]
#QUIT
elif command == "quit":
nick = nick.lower()
for chan in self.channels:
if nick in self.channels[chan]['users']:
del self.channels[chan]['users'][nick]
#NICK
elif command == "nick":
nick = nick.lower()
newnick = text or params[0]
for chan in self.channels:
if nick in self.channels[chan]['users']:
self.channels[chan]['users'][newnick.lower()] = self.channels[chan]['users'][nick]
self.channels[chan]['users'][newnick.lower()]['nick'] = newnick
if nick != newnick.lower():
del self.channels[chan]['users'][nick]
#RPL_NOTOPIC
elif command == "331":
chan = params[1].lower()
self.channels[chan]['topic'] = [None, None, None]
#RPL_TOPIC
elif command == "332":
chan = params[1].lower()
self.channels[chan]['topic'][0] = text
#RPL_TOPIC_SETBY
elif command == "333":
chan = params[1].lower()
self.channels[chan]['topic'][1] = params[2]
try:
self.channels[chan]['topic'][2] = datetime.datetime.fromtimestamp(int(params[3]))
except (SyntaxError, ValueError, TypeError):
pass
#TOPIC
elif command == "topic":
chan = params[0].lower()
self.channels[chan]['topic'] = [text, prefix, datetime.datetime.now()]
#RPL_CHANNELMODEIS
elif command == "324":
chan = params[0].lower()
self.channels[chan]['modes'] = params[2:]
#RPL_CHANNEL_CREATED
elif command == "329":
chan = params[0].lower()
try:
self.channels[chan]['created'] = datetime.datetime.fromtimestamp(int(params[2]))
except (SyntaxError, ValueError, TypeError):
pass
#Is <nick> on <chan>?
def ison(self, nick, chan):
nick = nick.lower()
chan = chan.lower()
if chan in self.channels:
if nick in self.channels[chan]['users']:
return True
return False
#Returns <nick>'s attributes on <chan>
#Valid attributes are: 'nick', 'user', 'host', 'mode' (or 'all' for a dict with all attributes)
def uinfo(self, nick, chan, attr):
nick = nick.lower()
chan = chan.lower()
if self.ison(nick, chan):
if attr == 'all':
return self.channels[chan]['users'][nick]
elif attr in ('nick', 'user', 'host', 'mode'):
return self.channels[chan]['users'][nick][attr]
return None
#Returns <nick>'s modes on <chan>
def getmode(self, nick, chan):
nick = nick.lower()
chan = chan.lower()
if self.ison(nick, chan):
return self.channels[chan]['users'][nick]['mode']
return None
#Is <nick> op'd on <chan>?
def isop(self, nick, chan):
if self.getmode(nick, chan):
if '@' in self.getmode(nick, chan):
return True
return False
#Is <nick> voiced on <chan>?
def isvoice(self, nick, chan):
if self.getmode(nick, chan):
if '+' in self.getmode(nick, chan):
return True
return False
#Is <nick> a regular user on <chan>?
def isreg(self, nick, chan):
if self.getmode(nick, chan) == None:
return True
return False
#Return a list of channels <nick> is on
def chans(self, nick):
nick = nick.lower()
return [chan for chan in self.channels if nick in
self.channels[chan]['users']]
class RCursor(object):
"""A reconnecting cursor for MySQLdb."""
def __init__(self, connection):
self.connection = connection
self.cursor = connection.cursor()
warnings.filterwarnings("ignore", ".*table.*already exist.*")
def __getattribute__(self, attr):
try:
return object.__getattribute__(self, attr)
except AttributeError:
return getattr(object.__getattribute__(self, 'cursor'), attr)
def execute(self, sql, args=None):
try:
return self.cursor.execute(sql, args)
except (AttributeError, MySQLdb.OperationalError), e:
if e.args[0] == 2006: #MySQL server has gone away
self.connection.ping(True) # Reconnect
self.cursor = self.connection.cursor()
return self.cursor.execute(sql, args)
raise
def executemany(self, sql, args=None):
try:
return self.cursor.executemany(sql, args)
except (AttributeError, MySQLdb.OperationalError), e:
if e.args[0] == 2006: #MySQL server has gone away
self.connection.ping(True) # Reconnect
self.cursor = self.connection.cursor()
return self.cursor.executemany(sql, args)
raise
class IRCLogger(object):
def __init__(self, bot, logpath):
if logpath == None:
self.enabled = False
return
else:
self.enabled = True
self.bot = bot
self.logdir = "logs"
self.lastmsg = {}
if logpath.lower().startswith("sqlite") or ("." in logpath and logpath.lower().rsplit(".",1)[1] in ["s3db", "db", "sqlite", "sqlite3"]):
logtype = "sqlite"
elif logpath.lower().startswith("mysql"):
logtype = "mysql"
else:
logtype = 'text'
if logtype in ['sqlite', 'mysql']:
if not json:
self.bot._print("WARNING! No json library found, logging to plaintext.", "err")
logtype = "text"
logpath = "logs"
if logtype == "mysql":
if not MySQLdb:
self.bot._print("WARNING! No MySQLdb library found, logging to plaintext.", "err")
logtype = "text"
logpath = "logs"
#mysql://user:password@host:port/db?params
logpath = logpath.rsplit("?", 1)[0] #Remove params
r = re.compile(r"mysql://([^:@]+):([^@]+)@([^:]+)(?::(\d+))?/([^/]+)")
m = r.match(logpath)
if not m:
self.bot._print("WARNING! MySQL connection string is invalid, logging to plaintext.", "err")
logtype = "text"
logpath = "logs"
else:
self.mysql_user, self.mysql_pass, self.mysql_host, self.mysql_port, self.mysql_db = m.groups()
try:
conn = MySQLdb.connect(host = self.mysql_host, user = self.mysql_user,
passwd = self.mysql_pass, db = self.mysql_db,
port = self.mysql_port or 3306, charset = 'utf8')
except MySQLdb.Error, e:
self.bot._print("WARNING! Error connectiong to the MySQL database: %s. Logging to plaintext." % e, "err")
logtype = "text"
logpath = "logs"
else:
c = RCursor(conn) #conn.cursor()
# Create a channel index table
c.execute("""CREATE TABLE IF NOT EXISTS spiffy_channels (
`hash` char(39) CHARSET utf8 COLLATE utf8_general_ci,
plaintext text CHARSET utf8 COLLATE utf8_general_ci,
unique `idx_spiffy_channels` (`hash`)
) charset=utf8 collate=utf8_general_ci""")
self.mysql_conn = conn
self.mysql_curs = c
self._log = self._mysqllog
self._scrollback = self._mysql_scrollback
if logtype == "sqlite":
# logpath is either "sqlite://path/to/db.ext", "logs/db.ext", "/path/to/db.ext" or "C:\path\to\db.ext"
self.logdir = os.path.abspath(re.sub("sqlite3?://", "", logpath))
if not os.path.basename(self.logdir):
self.logdir = os.path.join(self.logdir, "logs.s3db")
self.bot._print("Logging to SQLite database at %s" % self.logdir)
conn = sqlite3.connect(self.logdir, detect_types = sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
conn.row_factory = sqlite3.Row
c = conn.cursor()
# check if the channel index exists in the database
c.execute("select tbl_name from sqlite_master where tbl_name = 'spiffy_channels'")
if not c.fetchone():
c.execute("CREATE TABLE spiffy_channels (hash TEXT, plaintext TEXT)")
self.bot._print("Created channel index table 'spiffy_channels' in SQLite database")
c.close()
conn.commit()
conn.close()
self._log = self._sqlitelog
self._scrollback = self._sqlite_scrollback
elif logtype == "text":
# logpath will be either an absolute path ("/path/to/logdir/", "C:\logs\", etc)
# or a relative path (e.g. "logs/", which would mean a subdir "logs" in the
# current working directory, or even "../../logs").
self.logdir = os.path.abspath(logpath)
if not os.path.exists(self.logdir):
os.mkdir(self.logdir)
self._log = self._plaintextlog
self._scrollback = self._plaintext_scrollback
def log(self, prefix, command, params, text):
if not self.enabled:
return
command = command[0].upper()
if not command in self.bot.config['logevents']:
return
self._log(prefix, command, params, text)