Unified import order n shit

This commit is contained in:
mrhanky 2017-06-30 14:04:50 +02:00
parent 2603909e3b
commit 36a3e5c49b
No known key found for this signature in database
GPG Key ID: 67D772C481CB41B8
5 changed files with 193 additions and 97 deletions

View File

@ -1,10 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import random import random
import irc3
from docopt import Dict as DocOptDict from docopt import Dict as DocOptDict
from irc3.plugins.command import command from irc3.plugins.command import command
from irc3.utils import IrcString from irc3.utils import IrcString
import irc3
from . import DatabasePlugin from . import DatabasePlugin
@ -12,7 +12,7 @@ from . import DatabasePlugin
@irc3.plugin @irc3.plugin
class Rape(DatabasePlugin): class Rape(DatabasePlugin):
requires = ['irc3.plugins.command', requires = ['irc3.plugins.command',
'nxy.plugins.database'] 'nxy.plugins.storage']
@command @command
def owe(self, mask: IrcString, target: IrcString, args: DocOptDict): def owe(self, mask: IrcString, target: IrcString, args: DocOptDict):
@ -23,12 +23,24 @@ class Rape(DatabasePlugin):
nick = args.get('<nick>') or mask.nick nick = args.get('<nick>') or mask.nick
# Fetch result from database # Fetch result from database
self.cur.execute('select amount from owes where nick = %s', [nick]) self.cur.execute('''
select
amount
from
owes
where
nick = %s
''', [nick])
owes = self.cur.fetchone() owes = self.cur.fetchone()
# Colorize owe amount and return string # Colorize owe amount and return string
total = '4${total}'.format(total=owes['amount']) if owes else '3$0' if owes:
return '{nick} owes: \x03{total}\x03'.format(nick=nick, total=total) amount = '4${total}'.format(total=owes['amount'])
else:
amount = '3$0'
# Return total owes
return '{nick} owes: \x03{amount}\x03'.format(nick=nick, amount=amount)
@command @command
def rape(self, mask: IrcString, target: IrcString, args: DocOptDict): def rape(self, mask: IrcString, target: IrcString, args: DocOptDict):
@ -37,22 +49,34 @@ class Rape(DatabasePlugin):
%%rape <nick> %%rape <nick>
""" """
nick = args.get('<nick>') or mask.nick nick = args.get('<nick>') or mask.nick
fine = random.randint(1, 500)
rand = random.randint(0, 3) rand = random.randint(0, 3)
if rand in (0, 1): if rand not in (0, 1):
self.cur.execute('''insert into owes (nick, amount) values (%s, %s) self.bot.action(target, 'rapes {nick}'.format(nick=nick))
on conflict (nick) do update set amount = owes.amount + else:
excluded.amount returning amount''', [nick, fine]) fine = random.randint(1, 500)
# Insert or add fine to database and return total owe
self.cur.execute('''
insert into
owes (nick, amount)
values
(%s, %s)
on conflict (nick) do update set
amount = owes.amount + excluded.amount
returning
amount
''', [nick, fine])
self.con.commit() self.con.commit()
total = self.cur.fetchone()['amount'] # Get reason based on rand value
reason = ('raping', 'being too lewd and getting raped')[rand] reason = ('raping', 'being too lewd and getting raped')[rand]
action = 'fines {nick} \x02${fine}\x02 for {reason}. You owe: ' \
'\x0304${total}\x03'.format(nick=nick, # Print fine and total owe
fine=fine, self.bot.action(target,
reason=reason, 'fines {nick} \x02${fine}\x02 for {reason}. '
total=total) 'You owe: \x0304${total}\x03'
else: .format(nick=nick,
action = 'rapes {nick}'.format(nick=nick) fine=fine,
self.bot.action(target, action) reason=reason,
total=self.cur.fetchone()['amount']))

View File

@ -1,8 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import re import re
import irc3
from datetime import datetime from datetime import datetime
import irc3
from docopt import Dict as DocOptDict from docopt import Dict as DocOptDict
from irc3.plugins.command import command from irc3.plugins.command import command
from irc3.utils import IrcString from irc3.utils import IrcString
@ -13,7 +13,7 @@ from . import DatabasePlugin
@irc3.plugin @irc3.plugin
class Seen(DatabasePlugin): class Seen(DatabasePlugin):
requires = ['irc3.plugins.command', requires = ['irc3.plugins.command',
'nxy.plugins.database'] 'nxy.plugins.storage']
@command @command
def seen(self, mask: IrcString, target: IrcString, args: DocOptDict): def seen(self, mask: IrcString, target: IrcString, args: DocOptDict):
@ -23,27 +23,44 @@ class Seen(DatabasePlugin):
""" """
nick = args.get('<nick>') or mask.nick nick = args.get('<nick>') or mask.nick
# Don't be stupid
if nick == mask.nick: if nick == mask.nick:
return '{nick}, have you seen in the mirror?'.format(nick=nick) return '{nick}, have you seen in the mirror?'.format(nick=nick)
self.cur.execute('select * from seens where nick = %s', [nick]) # Fetch seen from database
self.cur.execute('''
select
*
from
seens
where
nick = %s
''', [nick])
seen = self.cur.fetchone() seen = self.cur.fetchone()
# No result
if not seen: if not seen:
return 'I\'ve never seen {nick}'.format(nick=nick) return 'I\'ve never seen {nick}'.format(nick=nick)
# Return result
return '{nick} was last seen {delta} saying: {message}'.format( return '{nick} was last seen {delta} saying: {message}'.format(
nick=seen['nick'], nick=seen['nick'],
# TODO: relative string delta # TODO: relative string delta?
delta=datetime.now() - seen['seen_at'], delta=seen['seen_at'],
message=re.sub(r'\x01ACTION (.*)\x01', r'/me \1', seen['message']), message=re.sub(r'\x01ACTION (.*)\x01', r'/me \1', seen['message']),
) )
@irc3.event(r'(?i)^:(?P<mask>\S+) PRIVMSG (?P<target>\S+) :(?P<msg>.*)') @irc3.event(r'(?i)^:(?P<mask>\S+) PRIVMSG (?P<target>\S+) :(?P<msg>.*)')
def save(self, mask: str, target: str, msg: str): def save(self, mask: str, target: str, msg: str):
values = [IrcString(mask).nick, target.lower(), msg, datetime.now()] # Insert or update if user writes a message
self.cur.execute('''insert into seens (nick, channel, message, self.cur.execute('''
seen_at) values (%s, %s, %s, %s) on conflict (nick) do update set insert into
channel = excluded.channel, seen_at = excluded.seen_at, seens (nick, channel, message, seen_at)
message = excluded.message''', values) values
(%s, %s, %s, %s)
on conflict (nick) do update set
channel = excluded.channel,
seen_at = excluded.seen_at,
message = excluded.message
''', [IrcString(mask).nick, target, msg, datetime.now()])
self.con.commit() self.con.commit()

View File

@ -1,51 +1,82 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import irc3
from docopt import Dict as DocOptDict from docopt import Dict as DocOptDict
from irc3.plugins.command import command from irc3.plugins.command import command
from irc3.utils import IrcString from irc3.utils import IrcString
import irc3
from . import DatabasePlugin from . import DatabasePlugin
# TODO: fix sql shit
@irc3.plugin @irc3.plugin
class Tell(DatabasePlugin): class Tell(DatabasePlugin):
requires = ['irc3.plugins.command', requires = ['irc3.plugins.command',
'nxy.plugins.database'] 'nxy.plugins.storage']
def __init__(self, bot: irc3.IrcBot): def __init__(self, bot: irc3.IrcBot):
super().__init__(bot) super().__init__(bot)
self.tell_queue = {} self.tell_queue = {}
# Restore tells from database
self.cur.execute('select from_user, to_user, message from tells') # Fetch tells from database
self.cur.execute('''
select
from_nick, to_nick, message
from
tells
''')
# Add tells to queue
for res in self.cur.fetchall(): for res in self.cur.fetchall():
user = res['to_user'] nick = res['to_nick']
if user not in self.tell_queue:
self.tell_queue[user] = [] # Create list in queue and add tell
self.tell_queue[user].append(res) if nick not in self.tell_queue:
self.tell_queue[nick] = []
self.tell_queue[nick].append([res['from_nick'],
res['message']])
@command @command
def tell(self, mask: IrcString, channel: IrcString, args: DocOptDict): def tell(self, mask: IrcString, target: IrcString, args: DocOptDict):
"""Saves a message for nick to forward on activity """Saves a message for nick to forward on activity
%%tell <nick> <message>... %%tell <nick> <message>...
""" """
nick = args['<nick>'].lower() nick = args['<nick>'].lower()
tell = [mask.nick.lower(), nick, ' '.join(args['<message>']).strip()]
# Create list in queue and add tell
if nick not in self.tell_queue: if nick not in self.tell_queue:
self.tell_queue[nick] = [] self.tell_queue[nick] = []
tell = [mask.nick.lower(), nick, ' '.join(args['<message>']).strip()]
self.tell_queue[nick].append(tell) self.tell_queue[nick].append(tell)
self.cur.execute('insert into tells (from_user, to_user, message) '
'values (?, ?, ?)', tell) # Insert tell into database
self.cur.execute('''
insert into
tells (from_nick, to_nick, message)
values
(%s, %s, %s)
''', tell)
self.con.commit() self.con.commit()
@irc3.event(r'(?i)^:(?P<mask>.*) PRIVMSG .* :.*') @irc3.event(r'(?i)^:(?P<mask>.*) PRIVMSG .* :.*')
def check(self, mask: str): def check(self, mask: str):
"""If activ user has tells, forward and delete them.""" """If activ nick has tells, forward and delete them."""
nick = IrcString(mask).nick nick = IrcString(mask).nick
if nick in self.tell_queue: if nick in self.tell_queue:
# Forward all tells for nick
for tell in self.tell_queue[nick]: for tell in self.tell_queue[nick]:
self.bot.privmsg(nick, '[Tell] Message from {nick}: {message}' self.bot.privmsg(nick, '[Tell] Message from {nick}: {message}'
.format(nick=tell[0], message=tell[2])) .format(nick=tell[0], message=tell[1]))
# Remove nick from queue
del self.tell_queue[nick] del self.tell_queue[nick]
self.cur.execute('delete from tells where to_user = ?', [nick])
# Remove tells from database
self.cur.execute('''
delete from
tells
where
to_nick = %s
''', [nick])
self.con.commit() self.con.commit()

View File

@ -14,18 +14,27 @@ from ..utils import time_delta
@irc3.plugin @irc3.plugin
class Timer(DatabasePlugin): class Timer(DatabasePlugin):
requires = ['irc3.plugins.command', requires = ['irc3.plugins.command',
'nxy.plugins.database'] 'nxy.plugins.storage']
def __init__(self, bot: irc3.IrcBot): def __init__(self, bot: irc3.IrcBot):
super().__init__(bot) super().__init__(bot)
# Restore timers from database
self.cur.execute('select id, nick, channel, message, delay, ends_at ' # Fetch timers from database
'from timers') self.cur.execute('''
select
id, mask, target, message, delay, ends_at
from
timers
''')
# Recreate timers
for res in self.cur.fetchall(): for res in self.cur.fetchall():
delta = res['ends_at'] - datetime.now() self.start_timer(IrcString(res['mask']),
args = (IrcString(res['nick']), res['channel'], delta, res['target'],
res['message'], res['delay'], res['id']) res['message'],
asyncio.ensure_future(self._timer(*args)) res['delay'],
res['ends_at'] - datetime.now(),
res['id'])
@command @command
def timer(self, mask: IrcString, target: IrcString, args: DocOptDict): def timer(self, mask: IrcString, target: IrcString, args: DocOptDict):
@ -35,42 +44,54 @@ class Timer(DatabasePlugin):
""" """
delay = args['<delay>'] delay = args['<delay>']
delta = time_delta(delay) delta = time_delta(delay)
if delta:
if not delta:
self.bot.privmsg(target, 'Invalid timer delay')
else:
message = ' '.join(args['<message>']) message = ' '.join(args['<message>'])
# Insert into database values = [mask, target, message, delay]
self.cur.execute('insert into timers (nick, channel, message, '
'delay, ends_at) values (%s, %s, %s, %s, %s)', # Insert into database (add now + delta)
[mask.nick, target.lower(), message, delay, self.cur.execute('''
datetime.now() + delta]) insert into
timers (mask, target, message, delay, ends_at)
values
(%s, %s, %s, %s, %s)
returning id
''', values + [datetime.now() + delta])
self.con.commit() self.con.commit()
# Get id from inserted and start timer # Add delta and id from inserted and start timer
self.cur.execute('select lastval()') values.extend([delta, self.cur.fetchone()['id']])
lastid = self.cur.fetchone()['lastval'] self.start_timer(*values)
asyncio.ensure_future(self._timer(mask, target, delta, message,
delay, lastid))
# Send notice to user # Send notice to user that timer has been set
self.bot.notice(mask.nick, 'Timer in {delay} set: {message}' self.bot.notice(mask.nick, 'Timer in {delay} set: {message}'
.format(delay=delay, message=message)) .format(delay=delay, message=message))
else:
self.bot.privmsg(target, 'Invalid timer delay')
async def _timer(self, mask: IrcString, target: IrcString, delta: timedelta, def start_timer(self, mask: IrcString, target: IrcString, message: str,
message: str, delay: str, row_id: int): delay: str, delta: timedelta, row_id: int):
"""Async function, sleeps for `delay` seconds and sends notification""" """Async function, sleeps for `delay` seconds and sends notification"""
seconds = delta.total_seconds()
# Sleep if necessary until timed async def callback():
if seconds > 0: # Sleep if necessary until timed
await asyncio.sleep(seconds) seconds = delta.total_seconds()
if seconds > 0:
await asyncio.sleep(seconds)
# Send reminder # Send reminder
self.bot.privmsg(target, '\x02[Timer]\x0F {nick}: {message} ({delay})' self.bot.privmsg(target, '\x02[Timer]\x0F {nick}: {message} '
.format(message=message, '({delay})'.format(message=message,
nick=mask.nick, nick=mask.nick,
delay=delay)) delay=delay))
# Delete timer from database # Delete timer from database
self.cur.execute('delete from timers where id = %s', [row_id]) self.cur.execute('''
self.con.commit() delete from
timers
where
id = %s
''', [row_id])
self.con.commit()
asyncio.ensure_future(callback())

View File

@ -48,20 +48,23 @@ create table if not exists owes (
with ranked_quotes as ( with ranked_quotes as (
select select
id, id,
item, rank() over (partition by nick order by id desc)
nick, from
rank() over (partition by nick order by id), quotes
count(*) over (partition by nick) as total where
from nick = 'mrhanky'
quotes )
where
nick = 'mrhanky'
)
delete from delete from
quotes quotes
where where
id = id = (
ranked_quotes; select
id
from
ranked_quotes
where
rank = 1
)