nxy/bot/mcmaniac.py

70 lines
2.1 KiB
Python
Raw Normal View History

2017-05-15 22:26:10 +00:00
# -*- coding: utf-8 -*-
2017-05-30 11:51:45 +00:00
import irc3
2017-08-22 13:57:57 +00:00
from docopt import Dict
2017-05-16 06:54:47 +00:00
from irc3.plugins.command import command
2017-05-16 10:06:29 +00:00
from irc3.utils import IrcString
2017-05-15 22:26:10 +00:00
from . import DatabasePlugin
2017-08-22 15:43:48 +00:00
from .utils import parse_int
2017-05-15 22:26:10 +00:00
class McManiac(DatabasePlugin):
@command(options_first=True)
2017-08-22 13:57:57 +00:00
def mcmaniac(self, mask: IrcString, target: IrcString, args: Dict):
"""Get a random McManiaC or by index.
2017-05-15 22:26:10 +00:00
%%mcmaniac [<index>]
"""
index = args.get('<index>')
if index:
index = parse_int(index)
if not index:
return
2017-07-07 00:11:20 +00:00
index, order = index
order = 'id {order}'.format(order=order)
2017-08-22 18:05:32 +00:00
offset = 'OFFSET %s'
2017-05-16 05:45:10 +00:00
else:
order = 'random()'
offset = ''
# Fetch result from database
with self.con.cursor() as cur:
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 = cur.fetchone()
if result:
return '[{rank}/{total}] {item}'.format(**result)
@irc3.event(r'^:(?P<mask>\S+) PRIVMSG (?P<channel>#\S+) :.*?\b(?P<item>Mc\S+iaC)\b.*')
def save(self, mask: str, channel: str, item: str):
2017-05-30 14:13:20 +00:00
if IrcString(mask).nick != self.bot.nick:
with self.con.cursor() as cur:
cur.execute('''
INSERT INTO
mcmaniacs (item)
VALUES
(%s)
ON CONFLICT DO NOTHING
RETURNING
(SELECT (count(*) + 1) AS total FROM mcmaniacs)
''', [item])
self.con.commit()
result = cur.fetchone()
if result is None:
return
self.bot.privmsg(channel, f"{result['total']}. mcmanic added: {item}")