68 lines
2.5 KiB
Python
68 lines
2.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
from datetime import datetime, timedelta
|
|
import asyncio
|
|
|
|
from docopt import Dict as DocOptDict
|
|
from irc3.plugins.command import command
|
|
from irc3.utils import IrcString
|
|
from irc3 import IrcBot
|
|
import irc3
|
|
|
|
from . import DatabasePlugin
|
|
from ..utils import fmt, time_delta
|
|
|
|
|
|
@irc3.plugin
|
|
class Futures(DatabasePlugin):
|
|
requires = [
|
|
'irc3.plugins.command',
|
|
'nxy.plugins.database',
|
|
]
|
|
|
|
def __init__(self, bot: IrcBot):
|
|
super().__init__(bot)
|
|
self.cur.execute('select * from timers')
|
|
for res in self.cur.fetchall():
|
|
delta = res['until'] - datetime.utcnow()
|
|
args = (IrcString(res['mask']), 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):
|
|
"""Timer command, delay can be: s(econd), m(min), h(our), w(week),
|
|
mon(th), y(ear)
|
|
|
|
%%timer <delay> <message>...
|
|
"""
|
|
delay = args['<delay>']
|
|
delta = time_delta(delay)
|
|
if delta:
|
|
date = datetime.utcnow() + delta
|
|
message = ' '.join(args['<message>'])
|
|
self.cur.execute('''insert into timers (mask, channel, message,
|
|
delay, until) values (?, ?, ?, ?, ?)''', [mask.nick, channel,
|
|
message, delay, date])
|
|
self.con.commit()
|
|
asyncio.ensure_future(self._timer(mask, channel, delta, message,
|
|
delay, self.cur.lastrowid))
|
|
self.bot.notice(mask.nick, 'Timer in {delay} set: {message}'
|
|
.format(delay=delay, message=message))
|
|
else:
|
|
self.bot.privmsg(channel, 'Invalid timer delay')
|
|
|
|
async def _timer(self, mask: IrcString, channel: IrcString,
|
|
delta: timedelta, message: str, delay: str, row_id: int):
|
|
"""
|
|
Actually the reminder function. Sleeps `delay` seconds and then sends
|
|
message to `channel` after that.
|
|
"""
|
|
seconds = delta.total_seconds()
|
|
if seconds > 0:
|
|
await asyncio.sleep(seconds)
|
|
text = fmt('{bold}[Timer]{reset} {nick}: {message} ({delay})',
|
|
message=message, delay=delay, nick=mask.nick)
|
|
self.bot.privmsg(channel, text)
|
|
self.cur.execute('delete from timers where id = ?', [row_id])
|
|
self.con.commit()
|