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