nxy/bot/plugins/seen.py

75 lines
2.1 KiB
Python
Raw Normal View History

2017-05-29 12:39:48 +00:00
# -*- coding: utf-8 -*-
import re
from datetime import datetime
2017-06-30 12:04:50 +00:00
import irc3
2017-05-29 12:39:48 +00:00
from docopt import Dict as DocOptDict
from irc3.plugins.command import command
from irc3.utils import IrcString
from psycopg2 import Error
2017-05-29 12:39:48 +00:00
from . import DatabasePlugin
2017-06-01 15:38:34 +00:00
@irc3.plugin
2017-05-29 12:39:48 +00:00
class Seen(DatabasePlugin):
requires = ['irc3.plugins.command',
2017-07-07 00:11:20 +00:00
'bot.plugins.storage']
2017-05-29 12:39:48 +00:00
2017-06-29 21:04:21 +00:00
@command
def seen(self, mask: IrcString, target: IrcString, args: DocOptDict):
2017-05-29 12:39:48 +00:00
"""Get last seen date and message for a nick.
%%seen [<nick>]
"""
nick = args.get('<nick>') or 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 '{nick}, have you seen in the mirror?'.format(nick=nick)
2017-06-29 21:04:21 +00:00
2017-06-30 12:04:50 +00:00
# Fetch seen from database
self.cur.execute('''
select
*
from
seens
where
lower(nick) = lower(%s)
2017-06-30 12:04:50 +00:00
''', [nick])
2017-05-29 12:39:48 +00:00
seen = self.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 {nick}'.format(nick=nick)
2017-06-29 21:04:21 +00:00
2017-06-30 12:04:50 +00:00
# Return result
2017-05-29 12:39:48 +00:00
return '{nick} was last seen {delta} saying: {message}'.format(
nick=seen['nick'],
2017-06-30 12:04:50 +00:00
# TODO: relative string delta?
delta=seen['seen_at'],
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)
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)
2017-07-07 00:11:20 +00:00
on conflict (nick) do update set
host = excluded.host,
channel = excluded.channel,
2017-07-07 00:11:20 +00:00
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()