-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcogs_logmanager.py
74 lines (58 loc) · 2.37 KB
/
cogs_logmanager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# The LogManager Cog, which handles logging and error reporting.
import os
import logging
from datetime import datetime
import discord as dc
from discord.ext import commands, tasks
import aiohttp
from cogs_textbanks import url_bank, query_bank, response_bank
from bot_common import bot, bot_coglist
log_chid = 830752125998596126
logger = logging.getLogger('discord')
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='r+')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
handler.setLevel(logging.WARNING)
logger.addHandler(handler)
def get_dev_key():
try:
with open('pbtoken.dat', 'r') as tokenfile:
return tokenfile.read().strip()
except FileNotFoundError:
return ''
class LoggingError(Exception):
"""When some shit happens to the logging. But if that happens, how does it log?"""
class LogManager(commands.Cog):
_post_data = {
'api_option': 'paste',
'api_dev_key': get_dev_key(),
'api_paste_private': '1',
'api_paste_expire_date': '1M',
}
def __init__(self, bot):
self.bot = bot
def cog_unload(self):
self.report_log.cancel()
@commands.Cog.listener()
async def on_ready(self):
print('D--> Dumping logs...')
self.log_channel = self.bot.get_channel(log_chid)
self.report_log.start()
@tasks.loop(hours=1)
async def report_log(self):
now = datetime.utcnow()
with open('discord.log', 'rb') as logfile:
if (code:=logfile.read()):
logfile.seek(0)
await self.log_channel.send(f'ArquiusBot Log @ {now}', file=dc.File(logfile, f'errors.log'))
with open('discord.log', 'r+') as logfile:
if not (code:=logfile.read()): return
logfile.truncate(0)
self._post_data.update(api_paste_code=code, api_paste_name=f'ArquiusBot Log {now}')
async with aiohttp.ClientSession() as session:
resp = await session.post('https://pastebin.com/api/api_post.php', data=self._post_data)
if resp.status != 200:
raise LoggingError(f'Error {resp.status}: {await resp.text()}')
await self.log_channel.send(f'ArquiusBot Log {now} @ <{await resp.text()}>')
async def setup():
await bot.add_cog(LogManager(bot))
bot_coglist.append(setup())