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