import importlib import importlib.util import inspect import os import sys from commands.command_base import AbstractCommand def load_commands() -> dict: commands = compile_and_load() return commands def compile_and_load_file(path: str) -> (str, AbstractCommand): module_name = os.path.split(path)[1].replace(".py", "") spec = importlib.util.spec_from_file_location(module_name, path) module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.load_module(module_name) for name, obj in inspect.getmembers(module): if inspect.isclass(obj) and name.startswith("Command"): command_inst = obj() print("Successfully loaded %s: %s" % (name, command_inst.get_command())) return command_inst.get_command(), command_inst return "", None def compile_and_load() -> dict: dic = {} implementations = get_implementations_dir() for dirName, subdirList, fileList in os.walk(implementations): for file in fileList: name = os.path.join(dirName, file) print("compiling %s" % name) name, command = compile_and_load_file(name) if command is not None: dic[name] = command break return dic def get_base_dir() -> str: cwd = os.getcwd() split = os.path.split(cwd) current = split[len(split) - 1] if current == 'commands': return check_dir(cwd) if current == 'Praxis_Bot': return check_dir(os.path.join(current, "commands")) else: print("could not find working directory for Praxis_Bot/commands") raise def get_implementations_dir() -> str: return check_dir(os.path.join(get_base_dir(), "implemented")) def get_compiled_dir() -> str: return check_dir(os.path.join(get_base_dir(), "compiled")) def check_dir(path: str) -> str: if not os.path.exists(path): os.mkdir(path, 0x777) return path if __name__ == "__main__": load_commands()