Migrated timer to pgsql

This commit is contained in:
mrhanky 2017-06-29 23:26:07 +02:00
parent 4a0a24e38a
commit bfd438e8fa
No known key found for this signature in database
GPG Key ID: 67D772C481CB41B8

View File

@ -19,16 +19,16 @@ class Timer(DatabasePlugin):
def __init__(self, bot: irc3.IrcBot):
super().__init__(bot)
# Restore timers from database
self.cur.execute('select id, mask, channel, message, delay, until '
self.cur.execute('select id, nick, channel, message, delay, ends_at '
'from timers')
for res in self.cur.fetchall():
delta = res['until'] - datetime.utcnow()
args = (IrcString(res['mask']), res['channel'], delta,
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))
@command
def timer(self, mask: IrcString, channel: IrcString, args: DocOptDict):
def timer(self, mask: IrcString, target: IrcString, args: DocOptDict):
"""Sets a timer, delay can be: s, m, h, w, mon, y(
%%timer <delay> <message>...
@ -37,29 +37,40 @@ class Timer(DatabasePlugin):
delta = time_delta(delay)
if delta:
message = ' '.join(args['<message>'])
self.cur.execute('insert into timers (mask, channel, message, '
'delay, until) values (?, ?, ?, ?, ?)',
[mask.nick, channel.lower(), message, delay,
datetime.utcnow() + delta])
# 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])
self.con.commit()
asyncio.ensure_future(self._timer(mask, channel, delta, message,
delay, self.cur.lastrowid))
# 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))
# Send notice to user
self.bot.notice(mask.nick, 'Timer in {delay} set: {message}'
.format(delay=delay, message=message))
else:
self.bot.privmsg(channel, 'Invalid timer delay')
self.bot.privmsg(target, 'Invalid timer delay')
async def _timer(self, mask: IrcString, channel: IrcString,
delta: timedelta, message: str, delay: str, row_id: int):
async def _timer(self, mask: IrcString, target: IrcString, delta: timedelta,
message: str, delay: str, 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)
text = '\x02[Timer]\x0F {nick}: {message} ({delay})'.format(
message=message,
delay=delay,
# Send reminder
self.bot.privmsg(target, '\x02[Timer]\x0F {nick}: {message} ({delay})'
.format(message=message,
nick=mask.nick,
)
self.bot.privmsg(channel, text)
self.cur.execute('delete from timers where id = ?', [row_id])
delay=delay))
# Delete timer from database
self.cur.execute('delete from timers where id = %s', [row_id])
self.con.commit()