Don't give IRCBot instance to things that don't need it, use a better way of

doing default locations for config/database/log
This commit is contained in:
jesopo 2018-09-27 11:07:29 +01:00
parent 6274159ac6
commit af2b34b92b
5 changed files with 51 additions and 44 deletions

View file

@ -1,16 +1,12 @@
import configparser, os import configparser, os
class Config(object): class Config(object):
def __init__(self, bot, directory, filename="bot.conf"): def __init__(self, location):
self.bot = bot self.location = location
self.filename = filename
self.full_location = os.path.join(directory, filename)
self.bot.config = {}
self.load_config()
def load_config(self): def load_config(self):
if os.path.isfile(self.full_location): if os.path.isfile(self.location):
with open(self.full_location) as config_file: with open(self.location) as config_file:
parser = configparser.ConfigParser() parser = configparser.ConfigParser()
parser.read_string(config_file.read()) parser.read_string(config_file.read())
return dict(parser["bot"].items()) return dict(parser["bot"].items())

View file

@ -239,11 +239,10 @@ class UserChannelSettings(Table):
[user_id, channel_id, setting.lower()]) [user_id, channel_id, setting.lower()])
class Database(object): class Database(object):
def __init__(self, bot, directory, filename): def __init__(self, log, location):
self.bot = bot self.log = log
self.filename = filename self.location = location
self.full_location = os.path.join(directory, filename) self.database = sqlite3.connect(self.location,
self.database = sqlite3.connect(self.full_location,
check_same_thread=False, isolation_level=None) check_same_thread=False, isolation_level=None)
self.database.execute("PRAGMA foreign_keys = ON") self.database.execute("PRAGMA foreign_keys = ON")
self._cursor = None self._cursor = None
@ -273,7 +272,7 @@ class Database(object):
def _execute_fetch(self, query, fetch_func, params=[]): def _execute_fetch(self, query, fetch_func, params=[]):
printable_query = " ".join(query.split()) printable_query = " ".join(query.split())
self.bot.log.debug("executing query: \"%s\" (params: %s)", self.log.debug("executing query: \"%s\" (params: %s)",
[printable_query, params]) [printable_query, params])
start = time.monotonic() start = time.monotonic()
@ -283,7 +282,7 @@ class Database(object):
end = time.monotonic() end = time.monotonic()
total_milliseconds = (end - start) * 1000 total_milliseconds = (end - start) * 1000
self.bot.log.debug("executed in %fms", [total_milliseconds]) self.log.debug("executed in %fms", [total_milliseconds])
return value return value
def execute_fetchall(self, query, params=[]): def execute_fetchall(self, query, params=[]):

View file

@ -11,8 +11,7 @@ DEFAULT_EVENT_DELIMITER = "."
DEFAULT_MULTI_DELIMITER = "|" DEFAULT_MULTI_DELIMITER = "|"
class Event(object): class Event(object):
def __init__(self, bot, name, **kwargs): def __init__(self, name, **kwargs):
self.bot = bot
self.name = name self.name = name
self.kwargs = kwargs self.kwargs = kwargs
self.eaten = False self.eaten = False
@ -26,9 +25,8 @@ class Event(object):
self.eaten = True self.eaten = True
class EventCallback(object): class EventCallback(object):
def __init__(self, function, bot, priority, kwargs): def __init__(self, function, priority, kwargs):
self.function = function self.function = function
self.bot = bot
self.priority = priority self.priority = priority
self.kwargs = kwargs self.kwargs = kwargs
def call(self, event): def call(self, event):
@ -81,8 +79,8 @@ class EventHookContext(object):
return self._parent.get_children() return self._parent.get_children()
class EventHook(object): class EventHook(object):
def __init__(self, bot, name=None, parent=None): def __init__(self, log, name=None, parent=None):
self.bot = bot self.log = log
self.name = name self.name = name
self.parent = parent self.parent = parent
self._children = {} self._children = {}
@ -91,7 +89,7 @@ class EventHook(object):
self._context_hooks = {} self._context_hooks = {}
def _make_event(self, kwargs): def _make_event(self, kwargs):
return Event(self.bot, self.name, **kwargs) return Event(self.name, **kwargs)
def _get_path(self): def _get_path(self):
path = [] path = []
@ -110,7 +108,7 @@ class EventHook(object):
def _context_hook(self, context, function, priority, replay, kwargs): def _context_hook(self, context, function, priority, replay, kwargs):
self._hook(function, context, priority, replay, kwargs) self._hook(function, context, priority, replay, kwargs)
def _hook(self, function, context, priority, replay, kwargs): def _hook(self, function, context, priority, replay, kwargs):
callback = EventCallback(function, self.bot, priority, kwargs) callback = EventCallback(function, priority, kwargs)
if context == None: if context == None:
self._hooks.append(callback) self._hooks.append(callback)
@ -176,7 +174,7 @@ class EventHook(object):
return self._call(kwargs, maximum=maximum) return self._call(kwargs, maximum=maximum)
def _call(self, kwargs, maximum=None): def _call(self, kwargs, maximum=None):
event_path = self._get_path() event_path = self._get_path()
self.bot.log.debug("calling event: \"%s\" (params: %s)", self.log.debug("calling event: \"%s\" (params: %s)",
[event_path, kwargs]) [event_path, kwargs])
start = time.monotonic() start = time.monotonic()
@ -189,11 +187,11 @@ class EventHook(object):
returns.append(hook.call(event)) returns.append(hook.call(event))
except Exception as e: except Exception as e:
traceback.print_exc() traceback.print_exc()
self.bot.log.error("failed to call event \"%s\"", [ self.log.error("failed to call event \"%s\"", [
event_path], exc_info=True) event_path], exc_info=True)
total_milliseconds = (time.monotonic() - start) * 1000 total_milliseconds = (time.monotonic() - start) * 1000
self.bot.log.debug("event \"%s\" called in %fms", [ self.log.debug("event \"%s\" called in %fms", [
event_path, total_milliseconds]) event_path, total_milliseconds])
self.check_purge() self.check_purge()
@ -203,8 +201,8 @@ class EventHook(object):
def get_child(self, child_name): def get_child(self, child_name):
child_name_lower = child_name.lower() child_name_lower = child_name.lower()
if not child_name_lower in self._children: if not child_name_lower in self._children:
self._children[child_name_lower] = EventHook(self.bot, self._children[child_name_lower] = EventHook(self.log,
child_name_lower, self) child_name_lower)
return self._children[child_name_lower] return self._children[child_name_lower]
def remove_child(self, child_name): def remove_child(self, child_name):
child_name_lower = child_name.lower() child_name_lower = child_name.lower()

View file

@ -14,7 +14,7 @@ class BitBotFormatter(logging.Formatter):
return s return s
class Log(object): class Log(object):
def __init__(self, bot, directory, filename): def __init__(self, location):
self.logger = logging.getLogger(__name__) self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG) self.logger.setLevel(logging.DEBUG)
@ -29,7 +29,7 @@ class Log(object):
self.logger.addHandler(stdout_handler) self.logger.addHandler(stdout_handler)
file_handler = logging.handlers.TimedRotatingFileHandler( file_handler = logging.handlers.TimedRotatingFileHandler(
os.path.join(directory, filename), when="midnight", backupCount=5) location, when="midnight", backupCount=5)
file_handler.setLevel(logging.DEBUG) file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter) file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler) self.logger.addHandler(file_handler)

View file

@ -8,30 +8,44 @@ def bool_input(s):
result = input("%s (Y/n): " % s) result = input("%s (Y/n): " % s)
return not result or result[0].lower() in ["", "y"] return not result or result[0].lower() in ["", "y"]
directory = os.path.dirname(os.path.realpath(__file__))
arg_parser = argparse.ArgumentParser( arg_parser = argparse.ArgumentParser(
description="Python3 event-driven asynchronous modular IRC bot") description="Python3 event-driven modular IRC bot")
arg_parser.add_argument("--config", "-c", default="bot.conf",
help="Location of the JSON config file") arg_parser.add_argument("--config", "-c",
arg_parser.add_argument("--database", "-d", default="databases/bot.db", help="Location of the JSON config file",
help="Location of the sqlite3 database file") default=os.path.join(directory, "bot.conf"))
arg_parser.add_argument("--log", "-l", default="logs/bot.log",
help="Location of the main log file") arg_parser.add_argument("--database", "-d",
help="Location of the sqlite3 database file",
default=os.path.join(directory, "databases", "bot.db"))
arg_parser.add_argument("--log", "-l",
help="Location of the main log file",
default=os.path.join(directory, "logs", "bot.log"))
arg_parser.add_argument("--verbose", "-v", action="store_true") arg_parser.add_argument("--verbose", "-v", action="store_true")
args = arg_parser.parse_args() args = arg_parser.parse_args()
directory = os.path.dirname(os.path.realpath(__file__)) log = Logging.Log(args.log)
config = Config.Config(args.config).load_config()
database = Database.Database(log, args.database)
events = events = EventManager.EventHook(log)
exports = exports = Exports.Exports()
bot = IRCBot.Bot() bot = IRCBot.Bot()
bot._events = events = EventManager.EventHook(bot)
bot._exports = exports = Exports.Exports()
bot.modules = modules = ModuleManager.ModuleManager(bot, events, exports, bot.modules = modules = ModuleManager.ModuleManager(bot, events, exports,
os.path.join(directory, "modules")) os.path.join(directory, "modules"))
bot.line_handler = IRCLineHandler.LineHandler(bot, bot._events) bot.line_handler = IRCLineHandler.LineHandler(bot, events)
bot.log = Logging.Log(bot, directory, args.log)
bot.database = Database.Database(bot, directory, args.database) bot.log = log
bot.config = Config.Config(bot, directory, args.config).load_config() bot.config = config
bot.database = database
bot._events = events
bot._exports = exports
bot.args = args bot.args = args
bot._events.on("timer.reconnect").hook(bot.reconnect) bot._events.on("timer.reconnect").hook(bot.reconnect)