1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2020 kaliko <kaliko@azylum.org>
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, version 3 only.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 from datetime import datetime
19 from tempfile import mkstemp
22 from .plugin import Plugin, botcmd
28 throttle_ts = int(time())-30
30 def __init__(self, bot):
31 Plugin.__init__(self, bot)
32 self.presence = list()
33 bot.add_event_handler("muc::%s::presence" %
34 self.bot.room, self.log_presence)
35 bot.add_event_handler("muc::%s::got_online" %
36 self.bot.room, self.log_online)
37 bot.add_event_handler("muc::%s::got_offline" %
38 self.bot.room, self.log_offline)
40 def log_online(self, pres):
41 nick = pres['muc']['nick']
42 self.log.info('got online: %s', nick)
43 self.presence.append((datetime.now(), 'online', nick))
45 def log_offline(self, pres):
46 nick = pres['muc']['nick']
47 self.log.info('got offline: %s', nick)
48 self.presence.append((datetime.now(), 'offline', nick))
50 def log_presence(self, pres):
51 nick = pres['muc']['nick']
52 self.log.debug('%s: %s', pres['muc']['nick'], pres['type'])
53 self.presence.append((datetime.now(), pres['type'], nick))
55 def _format_log(self):
56 log = [f'{d:%Y-%m-%d %H:%M}: {s:12} {n}' for d, s, n in self.presence]
60 def write(self, message, args):
62 **command** ``!write`` : Write log to file"""
63 delay = int(time()) - Log.throttle_ts
65 self.log.debug('throttling file creation')
66 self.reply(message, f'wait {30-delay}')
68 log = self._format_log()
69 mode = {'mode': 'w', 'encoding': 'utf-8'}
70 prefix = self.bot.room.split('@')[0] + '_'
71 tmp = mkstemp(prefix=prefix, text=True)
72 self.log.info('Writing to %s', tmp[1])
73 with fdopen(tmp[0], **mode) as fileo:
75 Log.throttle_ts = int(time())
76 self.reply(message, tmp[1])
79 def dump(self, message, args):
80 """**command** ``!dump`` : dump log online!"""
81 self.reply(message, self._format_log())
85 # vim: ai ts=4 sw=4 sts=4 expandtab