From: kaliko Date: Tue, 12 May 2020 12:05:00 +0000 (+0200) Subject: Add Log plugin X-Git-Tag: 0.1.0~9 X-Git-Url: https://git.kaliko.me/?a=commitdiff_plain;h=2bf3f2113341a56c8059a45d886e9b77ac3ab166;p=sid.git Add Log plugin --- diff --git a/sid/log.py b/sid/log.py new file mode 100644 index 0000000..ba216e5 --- /dev/null +++ b/sid/log.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2020 kaliko + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, version 3 only. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from datetime import datetime +from os import fdopen +from tempfile import mkstemp +from time import time + +from .plugin import Plugin, botcmd + + +class Log(Plugin): + """Logs presence. + """ + throttle_ts = int(time())-30 + + def __init__(self, bot): + Plugin.__init__(self, bot) + self.presence = list() + bot.add_event_handler("muc::%s::presence" % + self.bot.room, self.log_presence) + bot.add_event_handler("muc::%s::got_online" % + self.bot.room, self.log_online) + bot.add_event_handler("muc::%s::got_offline" % + self.bot.room, self.log_offline) + + def log_online(self, pres): + nick = pres['muc']['nick'] + self.log.info('got online: %s', nick) + self.presence.append((datetime.now(), 'online', nick)) + + def log_offline(self, pres): + nick = pres['muc']['nick'] + self.log.info('got offline: %s', nick) + self.presence.append((datetime.now(), 'offline', nick)) + + def log_presence(self, pres): + nick = pres['muc']['nick'] + self.log.debug('%s: %s', pres['muc']['nick'], pres['type']) + self.presence.append((datetime.now(), pres['type'], nick)) + + def _format_log(self): + log = [f'{d:%Y-%m-%d %H:%M}: {s:12} {n}' for d, s, n in self.presence] + return '\n'.join(log) + + @botcmd(hidden=True) + def write(self, message, args): + """ + **command** ``!write`` : Write log to file""" + delay = int(time()) - Log.throttle_ts + if delay < 30: + self.log.debug('throttling file creation') + self.reply(message, f'wait {30-delay}') + return + log = self._format_log() + mode = {'mode': 'w', 'encoding': 'utf-8'} + prefix = self.bot.room.split('@')[0] + '_' + tmp = mkstemp(prefix=prefix, text=True) + self.log.info('Writing to %s', tmp[1]) + with fdopen(tmp[0], **mode) as fileo: + fileo.writelines(log) + Log.throttle_ts = int(time()) + self.reply(message, tmp[1]) + + @botcmd(hidden=True) + def dump(self, message, args): + """**command** ``!dump`` : dump log online!""" + self.reply(message, self._format_log()) + + +# VIM MODLINE +# vim: ai ts=4 sw=4 sts=4 expandtab