# -*- coding: utf-8 -*- import re from datetime import datetime import irc3 from docopt import Dict as DocOptDict from irc3.plugins.command import command from irc3.utils import IrcString from psycopg2 import Error from . import DatabasePlugin @irc3.plugin class Seen(DatabasePlugin): requires = ['irc3.plugins.command', 'bot.plugins.storage'] @command def seen(self, mask: IrcString, target: IrcString, args: DocOptDict): """Get last seen date and message for a nick. %%seen [] """ nick = args.get('', mask.nick) # Don't be stupid if nick == mask.nick: return '{nick}, have you seen in the mirror?'.format(nick=nick) # Fetch seen from database self.cur.execute(''' select * from seens where lower(nick) = lower(%s) ''', [nick]) seen = self.cur.fetchone() # No result if not seen: return 'I\'ve never seen {nick}'.format(nick=nick) # Return result return '{nick} was last seen {delta} saying: {message}'.format( nick=seen['nick'], # TODO: relative string delta? delta=seen['seen_at'], message=re.sub(r'\x01ACTION (.*)\x01', r'/me \1', seen['message']), ) @irc3.event(r'(?i)^:(?P\S+) PRIVMSG (?P\S+) :(?P.*)') def save(self, mask: str, target: str, msg: str): mask = IrcString(mask) try: # Insert or update if user writes a message self.cur.execute(''' insert into seens (nick, host, channel, message, seen_at) values (%s, %s, %s, %s, %s) on conflict (nick) do update set host = excluded.host, channel = excluded.channel, seen_at = excluded.seen_at, message = excluded.message ''', [mask.nick, mask.host, target, msg, datetime.now()]) self.con.commit() except Error: # Rollback transaction on error self.con.rollback()