Refactored to load cfg in base class

This commit is contained in:
Anon 2023-05-14 17:18:21 -07:00
parent e64ce4cadf
commit 700260ae3c

View File

@ -20,39 +20,40 @@ import os
from threading import Event
from mastodon import Mastodon, MastodonIllegalArgumentError, MastodonVersionError
def load_cfg(name):
try:
import importlib
return importlib.import_module(name)
except ImportError:
raise FailedToLoadCfg("Invalid config file: {}".format(name))
class YandereBot:
# From the threading library. Is responsible for putting the bot to sleep, and exiting when the user quits (Ctrl+C)
eventSleep = Event()
# The configuration module
cfg = None
# The below settings are required from the configuration module
settings = {
"settings_server": dict(),
"settings_behavior": dict(),
"settings_encrypt": dict()
}
# Class variables
mastodon_api = None
failed_uploads = 0
consecutive_failed_uploads = 0
currentSessionCount = 0
debug_mode = False
primed = False
decrypted = False
# YandereBot.__init__()
# @param cfg A dynamically loaded python module. See yanlib.module_load() for an example
# @param cfg Name of configuration file
# @param keyfile Keyfile to decrypt settings_post
# @param debug_mode Should the bot run in debug mode (do not sign in or post to Pleroma)
def __init__(self, cfg, keyfile=None, debug_mode=False):
settings = self.settings
self.cfg = cfg
self.load_settings(self.cfg)
self.debug_mode = debug_mode or settings["settings_behavior"]["debug"]
settings["settings_encrypt"]["keyfile"] = keyfile or settings["settings_encrypt"]["keyfile"]
# From the threading library. Is responsible for putting the bot to sleep, and exiting when the user quits (Ctrl+C)
self.eventSleep = Event()
# The below settings are required from the configuration module
self.settings = dict()
# The configuration module
self.cfg = load_cfg(cfg)
self.load_settings(["settings_server", "settings_behavior", "settings_encrypt"])
# Class variables
self.mastodon_api = None
self.failed_uploads = 0
self.consecutive_failed_uploads = 0
self.currentSessionCount = 0
self.primed = False
self.decrypted = False
self.debug_mode = debug_mode or self.settings["settings_behavior"]["debug"]
self.settings["settings_encrypt"]["keyfile"] = keyfile or self.settings["settings_encrypt"]["keyfile"]
# Setup Exit Calls
def exit(self):
@ -60,10 +61,10 @@ class YandereBot:
# Decryption settings
# Used to set class attributes with the same name to the value specified in the config file.
def load_settings(self, cfg):
def load_settings(self, keys):
try:
for key in self.settings:
self.settings[key] = getattr(cfg, key)
for key in keys:
self.settings[key] = getattr(self.cfg, key)
except AttributeError as e:
print(e)
@ -263,5 +264,6 @@ class FailedLogin(Exception):
class BadCfgFile(Exception):
pass
class FailedToLoadCfg(Exception):
pass