#!/usr/bin/env python3 """ Fulvia Spelling correction module This module will fix spelling errors if someone corrects them using the sed notation (s///) commonly found in vi/vim. """ 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].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)