PDBd/main.py
2019-08-19 01:12:17 +02:00

75 lines
2.1 KiB
Python

import os
import logging
import logging.config
import socket
import asyncio
import json
def setup_logging(default_path='config/log_config.json', default_level=logging.INFO, env_key='PDBd_LOG_CONFIG'):
"""Setup logging configuration
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
setup_logging()
class Logger(object):
def __init__(self, name):
self.__name__=name
self.logger=logging.getLogger(self.__name__)
self.debug = self.logger.debug
self.info = self.logger.info
self.warning = self.logger.warning
self.error = self.logger.error
self.critical = self.logger.critical
class Bot(Logger):
pass
class PDBd(Logger):
def handle_exception(self, loop, context):
# context["message"] will always be there; but context["exception"] may not
msg = context.get("exception", context["message"])
self.critical(f"Critical Runtime Error: {msg}")
self.info("Shutting down...")
loop.stop()
async def setup_data(self):
if not os.path.exists("data"):
self.warning("Data folder doesn't exist.")
self.info("Creating data folder.")
os.makedirs("data")
else:
if not os.path.isdir("data"):
raise Exception("Data is not a folder")
async def run(self):
self.info(self.__name__+" is starting...")
loop.set_exception_handler(self.handle_exception)
await self.setup_data()
"""self.info("Connecting...")
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("../bot-base.sock")
self.info("Connected.")
while True:
s.send(input(">>> ").encode('utf-8'))
s.close()"""
loop.stop()
daemon=PDBd("PDBd")
loop = asyncio.get_event_loop()
loop.create_task(daemon.run())
loop.run_forever()