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 -*-
import random
import irc3
from docopt import Dict as DocOptDict
from irc3.plugins.command import command
from irc3.utils import IrcString
import irc3
from . import DatabasePlugin
@ -12,7 +12,7 @@ from . import DatabasePlugin
@irc3.plugin
class Rape(DatabasePlugin):
requires = ['irc3.plugins.command',
'nxy.plugins.database']
'nxy.plugins.storage']
@command
def owe(self, mask: IrcString, target: IrcString, args: DocOptDict):
@ -23,12 +23,24 @@ class Rape(DatabasePlugin):
nick = args.get('<nick>') or mask.nick
# 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()
# Colorize owe amount and return string
total = '4${total}'.format(total=owes['amount']) if owes else '3$0'
return '{nick} owes: \x03{total}\x03'.format(nick=nick, total=total)
if owes:
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
def rape(self, mask: IrcString, target: IrcString, args: DocOptDict):
@ -37,22 +49,34 @@ class Rape(DatabasePlugin):
%%rape <nick>
"""
nick = args.get('<nick>') or mask.nick
fine = random.randint(1, 500)
rand = random.randint(0, 3)
if rand in (0, 1):
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])
if rand not in (0, 1):
self.bot.action(target, 'rapes {nick}'.format(nick=nick))
else:
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()
total = self.cur.fetchone()['amount']
# Get reason based on rand value
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,
fine=fine,
reason=reason,
total=total)
else:
action = 'rapes {nick}'.format(nick=nick)
self.bot.action(target, action)
# Print fine and total owe
self.bot.action(target,
'fines {nick} \x02${fine}\x02 for {reason}. '
'You owe: \x0304${total}\x03'
.format(nick=nick,
fine=fine,
reason=reason,
total=self.cur.fetchone()['amount']))

View File

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

View File

@ -1,51 +1,82 @@
# -*- coding: utf-8 -*-
import irc3
from docopt import Dict as DocOptDict
from irc3.plugins.command import command
from irc3.utils import IrcString
import irc3
from . import DatabasePlugin
# TODO: fix sql shit
@irc3.plugin
class Tell(DatabasePlugin):
requires = ['irc3.plugins.command',
'nxy.plugins.database']
'nxy.plugins.storage']
def __init__(self, bot: irc3.IrcBot):
super().__init__(bot)
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():
user = res['to_user']
if user not in self.tell_queue:
self.tell_queue[user] = []
self.tell_queue[user].append(res)
nick = res['to_nick']
# Create list in queue and add tell
if nick not in self.tell_queue:
self.tell_queue[nick] = []
self.tell_queue[nick].append([res['from_nick'],
res['message']])
@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
%%tell <nick> <message>...
"""
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:
self.tell_queue[nick] = []
tell = [mask.nick.lower(), nick, ' '.join(args['<message>']).strip()]
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()
@irc3.event(r'(?i)^:(?P<mask>.*) PRIVMSG .* :.*')
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
if nick in self.tell_queue:
# Forward all tells for nick
for tell in self.tell_queue[nick]:
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]
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()

View File

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