Added DatabasePlugin._insert

This commit is contained in:
mrhanky 2017-05-30 13:51:45 +02:00
parent 0a119dbec3
commit 4edbfe8d5c
No known key found for this signature in database
GPG Key ID: 67D772C481CB41B8
10 changed files with 46 additions and 30 deletions

View File

@ -19,7 +19,18 @@ class Plugin(BasePlugin):
class DatabasePlugin(Plugin): class DatabasePlugin(Plugin):
table = None
def __init__(self, bot): def __init__(self, bot):
super().__init__(bot) super().__init__(bot)
self.con = bot.con.db self.con = bot.con.db
self.cur = self.con.cursor() self.cur = self.con.cursor()
def _insert(self, **kwargs):
qry = 'insert into {table} ({rows}) values ({placeholders})'.format(
table=self.table,
rows=', '.join(kwargs),
placeholders=', '.join('?' * len(kwargs))
)
self.cur.execute(qry, kwargs.values())
self.cur.commit()

View File

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import sqlite3 import sqlite3
import irc3 import irc3
from . import Plugin from . import Plugin

View File

@ -18,8 +18,8 @@ GNU_LINUX = """I'd Just Like To Interject For A Moment. What you're referring
OS as defined by POSIX.""" OS as defined by POSIX."""
class Kernel(Plugin): class Linux(Plugin):
URL = 'https://www.kernel.org/feeds/kdist.xml' KERNEL_FEED = 'https://www.kernel.org/feeds/kdist.xml'
@irc3.event(r'(?i)^:\S+ PRIVMSG (?P<channel>\S+) :' @irc3.event(r'(?i)^:\S+ PRIVMSG (?P<channel>\S+) :'
r'.*(?<!gnu[/+])linux(?! kernel).*') r'.*(?<!gnu[/+])linux(?! kernel).*')
@ -33,11 +33,14 @@ class Kernel(Plugin):
%%kernel %%kernel
""" """
feed = feedparser.parse(self.URL) feed = feedparser.parse(self.KERNEL_FEED)
releases = [] releases = []
for e in feed['entries']: for e in feed['entries']:
version, branch = e['title'].split(': ') version, branch = e['title'].split(': ')
if '(EOL)' in e['description']: if '(EOL)' in e['description']:
branch = '%s, \x1DEOL\x0F' % branch branch = '{branch}, \x1DEOL\x0F'.format(branch=branch)
releases.append('\x02%s\x0F (%s)' % (version, branch)) releases.append('\x02{version}\x0F ({branch})'.format(
version=version,
branch=branch,
))
return '[Kernel] {releases}'.format(releases=', '.join(releases)) return '[Kernel] {releases}'.format(releases=', '.join(releases))

View File

@ -1,8 +1,9 @@
# -*- 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
from ..utils import parse_int from ..utils import parse_int
@ -11,6 +12,7 @@ from ..utils import parse_int
class McManiac(DatabasePlugin): class McManiac(DatabasePlugin):
requires = ['irc3.plugins.command', requires = ['irc3.plugins.command',
'nxy.plugins.database'] 'nxy.plugins.database']
table = 'mcmaniacs'
@command(options_first=True) @command(options_first=True)
def mcmaniac(self, mask: IrcString, channel: IrcString, args: DocOptDict): def mcmaniac(self, mask: IrcString, channel: IrcString, args: DocOptDict):
@ -40,9 +42,9 @@ class McManiac(DatabasePlugin):
if result: if result:
return '[{idx}/{len}] {item}'.format(**result) return '[{idx}/{len}] {item}'.format(**result)
@irc3.event(r'(?i)^:(?P<mask>\S+) PRIVMSG \S+ :(?P<msg>.*(?P<item>Mc\S+iaC).*)') @irc3.event(r'(?i)^:(?P<mask>\S+) PRIVMSG \S+ :'
r'(?P<msg>.*(?P<item>Mc\S+iaC).*)')
def save(self, mask: str, msg: str, item: str): def save(self, mask: str, msg: str, item: str):
nick = IrcString(mask).nick nick = IrcString(mask).nick
if nick != self.bot.nick and msg != '.reload mcmaniac': if nick != self.bot.nick and msg != '.reload mcmaniac':
self.cur.execute('insert into mcmaniacs (item) values (?)', [item]) self._insert(item=item)
self.con.commit()

View File

@ -1,21 +1,19 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import irc3 import irc3
import re
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
from . import DatabasePlugin from . import DatabasePlugin
from ..utils import parse_int from ..utils import NICK_REGEX, parse_int
@irc3.plugin @irc3.plugin
class Quotes(DatabasePlugin): class Quotes(DatabasePlugin):
requires = ['irc3.plugins.command', requires = ['irc3.plugins.command',
'nxy.plugins.database'] 'nxy.plugins.database']
table = 'quotes'
NICK_REGEX = re.compile(r'<?[~&@%+]?([a-zA-Z0-9_\-^`|\\\[\]{}]+)>?')
@command(options_first=True) @command(options_first=True)
def q(self, mask: IrcString, channel: IrcString, args: DocOptDict): def q(self, mask: IrcString, channel: IrcString, args: DocOptDict):
@ -30,9 +28,10 @@ class Quotes(DatabasePlugin):
if cmd and item: if cmd and item:
if self.guard.has_permission(mask, 'admin'): if self.guard.has_permission(mask, 'admin'):
if cmd == 'add': if cmd == 'add':
nick = self.NICK_REGEX.match(nick).group(1) nick = NICK_REGEX.match(nick).group(1)
self.cur.execute('insert into quotes (nick, item) ' if not nick:
'values (?, ?)', [nick, ' '.join(item)]) return '[Quotes] Error parsing nick'
self._insert(nick=nick, item=' '.join(item))
if cmd == 'del': if cmd == 'del':
index, order, op = parse_int(''.join(item), select=False) index, order, op = parse_int(''.join(item), select=False)
if not index: if not index:

View File

@ -13,6 +13,7 @@ from . import DatabasePlugin
class Seen(DatabasePlugin): class Seen(DatabasePlugin):
requires = ['irc3.plugins.command', requires = ['irc3.plugins.command',
'nxy.plugins.database'] 'nxy.plugins.database']
table = 'seens'
@command(options_first=True) @command(options_first=True)
def seen(self, mask: IrcString, channel: IrcString, args: DocOptDict): def seen(self, mask: IrcString, channel: IrcString, args: DocOptDict):
@ -38,7 +39,5 @@ class Seen(DatabasePlugin):
def save(self, mask: str, channel: str, msg: str): def save(self, mask: str, channel: str, msg: str):
nick = IrcString(mask).nick nick = IrcString(mask).nick
if nick != self.bot.nick: if nick != self.bot.nick:
self.cur.execute('insert or replace into seens (nick, channel, ' self._insert(nick=nick, channel=channel.lower(), message=msg,
'message, last_seen) values (?, ?, ?, ?)', last_seen=datetime.now())
[nick, channel.lower(), msg, datetime.now()])
self.con.commit()

View File

@ -11,6 +11,7 @@ from . import DatabasePlugin
class Tell(DatabasePlugin): class Tell(DatabasePlugin):
requires = ['irc3.plugins.command', requires = ['irc3.plugins.command',
'nxy.plugins.database'] 'nxy.plugins.database']
table = 'tells'
def __init__(self, bot: irc3.IrcBot): def __init__(self, bot: irc3.IrcBot):
super().__init__(bot) super().__init__(bot)
@ -34,9 +35,7 @@ class Tell(DatabasePlugin):
self.tell_queue[nick] = [] self.tell_queue[nick] = []
tell = [mask.nick.lower(), nick, ' '.join(args['<message>']).strip()] 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)' self._insert(from_user=tell[0], to_user=tell[1], message=tell[2])
'values (?, ?, ?)', tell)
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):

View File

@ -15,6 +15,7 @@ from ..utils import time_delta
class Timer(DatabasePlugin): class Timer(DatabasePlugin):
requires = ['irc3.plugins.command', requires = ['irc3.plugins.command',
'nxy.plugins.database'] 'nxy.plugins.database']
table = 'timers'
def __init__(self, bot: irc3.IrcBot): def __init__(self, bot: irc3.IrcBot):
super().__init__(bot) super().__init__(bot)
@ -36,12 +37,9 @@ class Timer(DatabasePlugin):
delay = args['<delay>'] delay = args['<delay>']
delta = time_delta(delay) delta = time_delta(delay)
if delta: if delta:
date = datetime.utcnow() + delta
message = ' '.join(args['<message>']) message = ' '.join(args['<message>'])
self.cur.execute('''insert into timers (mask, channel, message, self._insert(mask=mask.nick, channel=channel, message=message,
delay, until) values (?, ?, ?, ?, ?)''', [mask.nick, channel, delay=delay, until=datetime.utcnow() + delta)
message, delay, date])
self.con.commit()
asyncio.ensure_future(self._timer(mask, channel, delta, message, asyncio.ensure_future(self._timer(mask, channel, delta, message,
delay, self.cur.lastrowid)) delay, self.cur.lastrowid))
self.bot.notice(mask.nick, 'Timer in {delay} set: {message}' self.bot.notice(mask.nick, 'Timer in {delay} set: {message}'

View File

@ -2,7 +2,7 @@
from pprint import pprint as pp from pprint import pprint as pp
from .date import date_from_iso, time_delta, time_since from .date import date_from_iso, time_delta, time_since
from .misc import parse_int from .misc import NICK_REGEX, parse_int
__all__ = ( __all__ = (
# pprint alias # pprint alias
@ -12,5 +12,6 @@ __all__ = (
'time_delta', 'time_delta',
'time_since', 'time_since',
# misc # misc
'parse_int' 'NICK_REGEX',
'parse_int',
) )

View File

@ -1,4 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import re
NICK_REGEX = re.compile(r'<?[~&@%+]?([a-zA-Z0-9_\-^`|\\\[\]{}]+)>?')
def parse_int(val: str, select: bool = True) -> tuple: def parse_int(val: str, select: bool = True) -> tuple: