# -*- coding: utf-8 -*- import irc3 from docopt import Dict from irc3.plugins.command import command from irc3.utils import IrcString from psycopg2 import Error from . import DatabasePlugin from ..utils import parse_int @irc3.plugin class McManiac(DatabasePlugin): requires = ['irc3.plugins.command', 'bot.plugins.storage'] @command(options_first=True) def mcmaniac(self, mask: IrcString, target: IrcString, args: Dict): """Get a random McManiaC or by index. %%mcmaniac [] """ index = args.get('') if index: index = parse_int(index) if not index: return index, order = index order = 'id {order}'.format(order=order) offset = 'offset %s' else: order = 'random()' offset = '' # Fetch result from database self.cur.execute(''' select item, rank() over (order by id), count(*) over (rows between unbounded preceding and unbounded following) as total from mcmaniacs order by {order} limit 1 {offset} '''.format(order=order, offset=offset), [index]) result = self.cur.fetchone() if result: return '[{rank}/{total}] {item}'.format(**result) # TODO: fix regex ("McFooiaC McBariaC" adds "Mc\S+iaC") @irc3.event(r'^:(?P\S+) PRIVMSG \S+ :.*(?PMc\S+iaC).*') def save(self, mask: str, item: str): if IrcString(mask).nick != self.bot.nick: try: # Insert into database self.cur.execute(''' INSERT INTO mcmaniacs (item) VALUES (%s) ''', [item]) self.con.commit() except Error: # Rollback transaction on error self.con.rollback()