nxy/bot/regex.py

59 lines
1.9 KiB
Python
Raw Normal View History

2017-07-04 13:22:20 +00:00
# -*- coding: utf-8 -*-
import re
import irc3
from irc3.utils import IrcString
from . import DatabasePlugin
class Useless(DatabasePlugin):
2017-08-22 15:43:48 +00:00
requires = []
2017-07-04 13:22:20 +00:00
@irc3.event(r'^:(?P<mask>\S+) PRIVMSG (?P<target>#\S+) :s/'
r'(?P<search>(?:[^/\\]|\\.)*)/'
r'(?P<replace>(?:.*?))'
r'(?:/ ?(?P<nick>.*))?$')
def regex(self, mask: str, target: str, search: str, replace: str, nick: str = None):
2017-07-04 13:22:20 +00:00
nick = (nick or IrcString(mask).nick).strip()
if nick == self.bot.nick:
return
with self.con.cursor() as cur:
cur.execute('''
SELECT
item
FROM
last_messages
WHERE
nick = lower(%s)
AND channel = lower(%s)
''', [nick, target])
result = cur.fetchone()
2017-07-04 13:22:20 +00:00
if result:
old = result['item']
2017-07-06 18:12:42 +00:00
msg = old.replace(search, '\x02{}\x0F'.format(replace), 1)
2017-07-04 16:57:53 +00:00
msg = re.sub(r'\x01ACTION (.*)\x01', r'/me \1', msg)
2017-07-04 13:22:20 +00:00
if old != msg:
self.bot.privmsg(target, '<{nick}> {msg}'.format(nick=nick,
msg=msg))
@irc3.event(r'(?i)^:(?P<mask>\S+) PRIVMSG (?P<target>#\S+) :(?P<msg>.*)$')
def last_message(self, mask: str, target: str, msg: str):
"""Saves the last message of a user for each channel (for regex)."""
mask = IrcString(mask)
with self.con.cursor() as cur:
cur.execute('''
INSERT INTO
last_messages (nick, host, channel, item)
VALUES
(lower(%s), %s, lower(%s), %s)
ON CONFLICT (nick, channel) DO UPDATE SET
host = excluded.host,
item = excluded.item
''', [mask.nick, mask.host, target, msg])
2017-07-04 13:22:20 +00:00
self.con.commit()