nxy/bot/seen.py

67 lines
1.9 KiB
Python
Raw Normal View History

2017-05-29 12:39:48 +00:00
# -*- coding: utf-8 -*-
import re
2017-06-30 12:04:50 +00:00
import irc3
2017-08-22 13:57:57 +00:00
from docopt import Dict
2017-05-29 12:39:48 +00:00
from irc3.plugins.command import command
from irc3.utils import IrcString
from . import DatabasePlugin
class Seen(DatabasePlugin):
2017-06-29 21:04:21 +00:00
@command
2017-08-22 13:57:57 +00:00
def seen(self, mask: IrcString, target: IrcString, args: Dict):
"""Get last seen date and message for a nick
2017-05-29 12:39:48 +00:00
%%seen [<nick>]
"""
nick = args.get('<nick>', mask.nick)
2017-06-29 21:04:21 +00:00
2017-06-30 12:04:50 +00:00
# Don't be stupid
2017-05-29 12:39:48 +00:00
if nick == mask.nick:
return '{}, look in the mirror faggot!'.format(nick)
2017-06-29 21:04:21 +00:00
2017-06-30 12:04:50 +00:00
# Fetch seen from database
with self.con.cursor() as cur:
cur.execute('''
SELECT
seen_at, message, channel
FROM
seens
WHERE
nick = lower(%s)
''', [nick])
seen = cur.fetchone()
2017-06-29 21:04:21 +00:00
2017-06-30 12:04:50 +00:00
# No result
2017-05-29 12:39:48 +00:00
if not seen:
return 'I\'ve never seen {}'.format(nick)
2017-06-29 21:04:21 +00:00
2017-06-30 12:04:50 +00:00
# Return result
2017-09-05 17:55:41 +00:00
return '{nick} was last seen {delta} in {channel} saying: {message}'.format(
nick=nick,
2017-06-30 12:04:50 +00:00
# TODO: relative string delta?
delta=seen['seen_at'],
2017-09-05 17:55:41 +00:00
channel=seen['channel'],
2017-05-29 16:44:26 +00:00
message=re.sub(r'\x01ACTION (.*)\x01', r'/me \1', seen['message']),
2017-05-29 12:39:48 +00:00
)
2017-06-29 21:04:21 +00:00
@irc3.event(r'(?i)^:(?P<mask>\S+) PRIVMSG (?P<target>\S+) :(?P<msg>.*)')
def save(self, mask: str, target: str, msg: str):
mask = IrcString(mask)
with self.con.cursor() as cur:
cur.execute('''
INSERT INTO
seens (nick, host, channel, message)
VALUES
(lower(%s), %s, %s, %s)
ON CONFLICT (nick) DO UPDATE SET
host = excluded.host,
channel = excluded.channel,
seen_at = now(),
message = excluded.message
''', [mask.nick, mask.host, target, msg])
self.con.commit()