nxy/nxy/plugins/quotes.py
2017-05-16 07:45:10 +02:00

62 lines
1.8 KiB
Python

# -*- coding: utf-8 -*-
from docopt import Dict as DocOptDict
from irc3.utils import IrcString
from irc3.plugins.command import command
import random
import irc3
import re
from . import DatabasePlugin
from ..utils import parse_int
@irc3.plugin
class Quotes(DatabasePlugin):
requires = [
'irc3.plugins.command',
]
REGEX = re.compile(r'<?[~&@%+]?([a-zA-Z0-9_\-^`|\\\[\]{}]+)>?')
# noinspection PyUnusedLocal
@command(options_first=True)
def q(self, mask: IrcString, channel: IrcString, args: DocOptDict) -> str:
"""
Manage quotes.
%%q <cmd> <nick> <quote>...
%%q <nick> [<quote>...]
"""
cmd = args.get('<cmd>')
nick = args['<nick>']
quote = args.get('<quote>')
if cmd:
if cmd == 'add':
nick = self.REGEX.match(nick).group(1)
if nick not in self.db:
self.db[nick] = []
quote = ' '.join(quote)
if quote not in self.db[nick]:
self.db[nick].append(quote)
elif cmd == 'del':
try:
self.db[nick].pop(parse_int(quote))
if not self.db[nick]:
del self.db[nick]
except (KeyError, IndexError, TypeError):
return ''
self._db.SIGINT()
else:
if quote:
try:
quote = self.db[nick][parse_int(quote)]
except (KeyError, IndexError, TypeError):
return ''
else:
quote = random.choice(self.db[nick])
return '[{index}/{total}] <{nick}> {quote}'.format(
index=self.db[nick].index(quote) + 1,
total=len(self.db[nick]),
nick=nick,
quote=quote,
)