fulvia/modules/sed.py
2020-09-09 19:33:53 -04:00

104 lines
2.2 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Correct the last thing you or someone else said. Uses standard sed
substitute notation eg. s/search/replace/flags
"""
import re
from module import hook
def setup(bot):
bot.memory['sed_lines'] = {}
@hook(True)
def collectlines(bot, trigger):
"""Create a temporary log of what people say"""
if trigger.is_privmsg:
return
if trigger.channel not in bot.memory['sed_lines']:
bot.memory['sed_lines'][trigger.channel] = {}
if trigger.nick not in bot.memory['sed_lines'][trigger.channel]:
bot.memory['sed_lines'][trigger.channel][trigger.nick] = []
templist = bot.memory['sed_lines'][trigger.channel][trigger.nick]
line = ' '.join(trigger.args)
if line.startswith("s/"): # Don't remember substitutions
return
templist.append(line)
del templist[:-10] # Keep the log to 10 lines per person
bot.memory['sed_lines'][trigger.channel][trigger.nick] = templist
@hook(True)
def findandreplace(bot, trigger):
if trigger.is_privmsg:
return
if not trigger.args[0]:
return
if not trigger.args[0].startswith('s') and trigger.args[0][-1] not in ':,':
return
line = ' '.join(trigger.args)
if 's/' not in line:
return
items = []
line = line[line.index('s/')+2:]
i = 0
while True:
i = line.find('/', i)
if i == -1:
break
if line[max(i-1, 0)] == '\\' and line[max(i-2, 0)] != '\\':
i += 1
pass
else:
items.append(line[:i])
line = line[i+1:]
i = 0
items.append(line)
if len(items) < 2:
return
find, replace = items[:2]
find = find.replace(r'\/', '/')
flags = items[2] if len(items) >= 3 else ''
if 'g' in flags:
count = 0
else:
count = 1
try:
if 'i' in flags:
regex = re.compile(find, re.I)
else:
regex = re.compile(find)
except re.error:
return
if not trigger.args[0].startswith('s'):
nick = trigger.args[0][:-1]
if nick not in bot.memory['sed_lines'][trigger.channel]:
return
else:
nick = trigger.nick
for line in reversed(bot.memory['sed_lines'][trigger.channel][nick]):
new_line = re.sub(regex, replace, line, count)
if new_line != line:
break
else:
return
if trigger.args[0].startswith('s'):
msg = f"{trigger.nick} \x02meant\x0f to say: {new_line}"
else:
msg = f"{trigger.nick} thinks {nick} \x02meant\x0f to say: {new_line}"
bot.msg(msg)