72 lines
2.6 KiB
Python

# -*- coding: utf-8 -*-
import irc3
import re
from docopt import Dict as DocOptDict
from irc3.plugins.command import command
from irc3.utils import IrcString
from . import DatabasePlugin
from ..utils import parse_int
@irc3.plugin
class Quotes(DatabasePlugin):
requires = ['irc3.plugins.command',
'nxy.plugins.database']
NICK_REGEX = re.compile(r'<?[~&@%+]?([a-zA-Z0-9_\-^`|\\\[\]{}]+)>?')
# noinspection PyUnusedLocal
@command(options_first=True)
def q(self, mask: IrcString, channel: IrcString, args: DocOptDict):
"""Get, add or delete quots for a user
%%q <cmd> <nick> <quote>...
%%q <nick> [<index>]
"""
cmd = args.get('<cmd>')
nick = args['<nick>']
item = args.get('<quote>')
if cmd and item:
if self.guard.has_permission(mask, 'admin'):
if cmd == 'add':
nick = self.NICK_REGEX.match(nick).group(1)
self.cur.execute('insert into quotes (nick, item) '
'values (?, ?)', [nick, ' '.join(item)])
if cmd == 'del':
index, order, op = parse_int(''.join(item), select=False)
if not index:
return
self.cur.execute('''delete from quotes where id =
(select id from quotes a where nick like ? and ? =
(select count(id) from quotes b where a.id {op} b.id)
order by id {order})
'''.format(op=op, order=order), [nick, index])
self.con.commit()
else:
self.bot.notice(mask.nick, 'Permission denied')
else:
index = args.get('<index>')
binds = [nick, nick, nick]
if index:
index = parse_int(index)
if not index:
return
index, order, _ = index
order = 'id {order}'.format(order=order)
extra = 'offset ?'
binds.append(index)
else:
order = 'random()'
extra = ''
self.cur.execute('''select nick, item,
(select count(id) from quotes b where b.nick like ? and
a.id >= b.id) as idx,
(select count(id) from quotes where nick like ?) as len
from quotes a where nick like ? order by {order} limit 1 {extra}
'''.format(order=order, extra=extra), binds)
result = self.cur.fetchone()
if result:
return '[{idx}/{len}] <{nick}> {item}'.format(**result)