nxy/nxy/plugins/seen.py
2017-06-30 14:04:50 +02:00

67 lines
1.8 KiB
Python

# -*- 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 . import DatabasePlugin
@irc3.plugin
class Seen(DatabasePlugin):
requires = ['irc3.plugins.command',
'nxy.plugins.storage']
@command
def seen(self, mask: IrcString, target: IrcString, args: DocOptDict):
"""Get last seen date and message for a nick.
%%seen [<nick>]
"""
nick = args.get('<nick>') or 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
nick = %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<mask>\S+) PRIVMSG (?P<target>\S+) :(?P<msg>.*)')
def save(self, mask: str, target: str, msg: str):
# Insert or update if user writes a message
self.cur.execute('''
insert into
seens (nick, channel, message, seen_at)
values
(%s, %s, %s, %s)
on conflict (nick) do update set
channel = excluded.channel,
seen_at = excluded.seen_at,
message = excluded.message
''', [IrcString(mask).nick, target, msg, datetime.now()])
self.con.commit()