Add !bot logs

Partial solution to #48.
This commit is contained in:
gammafn 2021-05-04 10:55:49 -05:00
parent b77b361d2a
commit 321a20d721
1 changed files with 21 additions and 0 deletions

View File

@ -1,4 +1,5 @@
import collections import collections
import logging
import json import json
import requests import requests
from datetime import timedelta from datetime import timedelta
@ -6,6 +7,15 @@ import time
from modules.common.module import BotModule, ModuleCannotBeDisabled from modules.common.module import BotModule, ModuleCannotBeDisabled
class LogDequeHandler(logging.Handler):
def __init__(self, count):
super().__init__(level = logging.NOTSET)
self.last_logs = collections.deque([], maxlen=10)
self.level = logging.INFO
def emit(self, record):
self.last_logs.append(self.format(record))
class MatrixModule(BotModule): class MatrixModule(BotModule):
def __init__(self, name): def __init__(self, name):
@ -16,6 +26,9 @@ class MatrixModule(BotModule):
def matrix_start(self, bot): def matrix_start(self, bot):
super().matrix_start(bot) super().matrix_start(bot)
self.starttime = time.time() self.starttime = time.time()
self.loghandler = LogDequeHandler(10)
self.loghandler.setFormatter(logging.Formatter('%(levelname)s - %(name)s - %(message)s'))
logging.root.addHandler(self.loghandler)
async def matrix_message(self, bot, room, event): async def matrix_message(self, bot, room, event):
args = event.body.split(None, 2) args = event.body.split(None, 2)
@ -39,6 +52,8 @@ class MatrixModule(BotModule):
await self.export_settings(bot, event) await self.export_settings(bot, event)
elif args[1] == 'ping': elif args[1] == 'ping':
await self.get_ping(bot, room, event) await self.get_ping(bot, room, event)
elif args[1] == 'logs':
await self.last_logs(bot, room, event)
elif len(args) == 3: elif len(args) == 3:
if args[1] == 'enable': if args[1] == 'enable':
@ -219,6 +234,12 @@ class MatrixModule(BotModule):
bot.save_settings() bot.save_settings()
await bot.send_msg(event.sender, f'Private message from {bot.matrix_user}', 'Updated bot settings') await bot.send_msg(event.sender, f'Private message from {bot.matrix_user}', 'Updated bot settings')
async def last_logs(self, bot, room, event):
bot.must_be_owner(event)
res = await bot.send_msg(event.sender, f'Private message from {bot.matrix_user}', '\n'.join(self.loghandler.last_logs))
self.logger.info(f'{event.sender} asked for the last {len(self.loghandler.last_logs)} log messages.')
return res
def disable(self): def disable(self):
raise ModuleCannotBeDisabled raise ModuleCannotBeDisabled