nxy/bot/tell.py
2017-08-22 17:43:48 +02:00

79 lines
2.2 KiB
Python

# -*- coding: utf-8 -*-
from datetime import datetime
import irc3
from docopt import Dict
from irc3.plugins.command import command
from irc3.utils import IrcString
from psycopg2 import Error
from . import DatabasePlugin, Bot
class Tell(DatabasePlugin):
def __init__(self, bot: Bot):
super().__init__(bot)
self.tell_queue = {}
self.cur.execute('''
SELECT
to_nick, from_nick, message, created_at
FROM
tells
''')
for res in self.cur.fetchall():
nick = res['to_nick'].lower()
if nick not in self.tell_queue:
self.tell_queue[nick] = []
self.tell_queue[nick].append(res[1:])
@command
def tell(self, mask: IrcString, target: IrcString, args: Dict):
"""Saves a message for nick to forward on activity
%%tell <nick> <message>...
"""
nick = args['<nick>'].lower()
tell = [nick, mask.nick, ' '.join(args['<message>']).strip(), datetime.utcnow()]
if nick not in self.tell_queue:
self.tell_queue[nick] = []
self.tell_queue[nick].append(tell[1:])
try:
self.cur.execute('''
INSERT INTO
tells (to_nick, from_nick, message, created_at)
VALUES
(%s, %s, %s, %s)
''', tell)
self.con.commit()
except Error as ex:
self.log.error(ex)
self.con.rollback()
@irc3.event(r'(?i)^:(?P<mask>.*) PRIVMSG .* :.*')
def on_message(self, mask: str):
"""If activ nick has tells, forward and delete them."""
nick = IrcString(mask).nick.lower()
if nick in self.tell_queue:
# Forward all tells for nick
for tell in self.tell_queue[nick]:
self.bot.privmsg(nick, '\x02[Tell]\x02 Message from {nick} at {time}: {message}'.format(
nick=tell[0],
time=tell[1], # TODO: format time
message=tell[2],
))
del self.tell_queue[nick]
self.cur.execute('''
DELETE FROM
tells
WHERE
to_nick = %s
''', [nick])
self.con.commit()