]> jfr.im git - erebus.git/blob - modules/subtext.py
2a87c0efd1d102b03937d275b304f0402b7fca0c
[erebus.git] / modules / subtext.py
1 # Erebus IRC bot - Author: Erebus Team
2 # vim: fileencoding=utf-8
3 # module for 's/regex/replacement/' style correction
4 # warning: arbitrary regex's are generally capable of various DoS attacks on CPU/memory usage. use with caution.
5 # see for usage examples: https://github.com/zonidjan/erebus/commit/d7e9802778477f1faa26a03078cb1b3c018a5e5c
6 # This file is released into the public domain; see http://unlicense.org/
7
8 # module info
9 modinfo = {
10 'author': 'Erebus Team',
11 'license': 'public domain',
12 'compatible': [0], # compatible module API versions
13 'depends': [], # other modules required to work properly?
14 'softdeps': [], # modules which are preferred but not required
15 }
16
17 # preamble
18 import modlib
19 lib = modlib.modlib(__name__)
20 modstart = lib.modstart
21 modstop = lib.modstop
22
23 # module code
24 import re
25 from collections import namedtuple
26 re_findsub = re.compile(r"""s([/'";:!@#$%^&-_=`~])(?P<search>.+?)\1(?P<replace>.+?)(?:\1(?P<global>g)?|$)""")
27 Line = namedtuple('Line', ['sender', 'msg'])
28 lastline = {}
29 @lib.hooknum("PRIVMSG")
30 def privmsg_hook(bot, line):
31 pieces = line.split(None, 3)
32 fromnick = pieces[0][1:].split('!')[0]
33 chan = pieces[2]
34 if chan[0] != "#": return
35 msg = pieces[3][1:]
36
37 mo = re_findsub.match(msg)
38 if mo:
39 if mo.group('global') is not None:
40 count = 0 # unlimited
41 else:
42 count = 1 # only first
43 try:
44 newline = re.sub(mo.group('search'), mo.group('replace'), lastline[chan].msg, count)
45 except Exception as e: return # ignore it if it doesn't work
46 if newline != lastline[chan].msg:
47 if lastline[chan].sender == fromnick:
48 bot.msg(chan, "<%s> %s" % (lastline[chan].sender, newline))
49 else:
50 bot.msg(chan, "%s: <%s> %s" % (fromnick, lastline[chan].sender, newline))
51 else:
52 lastline[chan] = Line(sender=fromnick, msg=msg)