Esempio n. 1
0
 def import_load_modules(self):
     def tryImportModule(path, module) -> bool:
         try:
             self.__imported_module = import_module(path + module)
             return True
         except KeyboardInterrupt:
             raise KeyboardInterrupt
         except (BaseException, Exception):
             log.error(f"Unable to start module '{module}' due "
                       "to an unhandled exception",
                       exc_info=True)
         return False
     try:
         all_modules, sys_modules, user_modules = self.__load_modules()
         for module in sorted(all_modules):
             update_all_modules(module)
         for module in sys_modules:
             if tryImportModule("userbot.modules.", module):
                 update_load_modules(module, True)
                 self.__load_modules_count += 1
             else:
                 update_load_modules(module, False)
         for module in user_modules:
             if not SAFEMODE:
                 if module not in self.__not_load_modules:
                     if tryImportModule("userbot.modules_user.", module):
                         update_load_modules(module, True)
                         self.__load_modules_count += 1
                     else:
                         update_load_modules(module, False)
             update_user_modules(module)
     except:
         raise
     return
Esempio n. 2
0
    def import_load_modules(self):
        def tryImportModule(path, module) -> bool:
            try:
                self.__imported_module = import_module(path + module)
                return True
            except Exception:
                log.error(f"Unable to start module '{module}' due to an unhandled exception", exc_info=True)
            return False

        all_modules, sys_modules, user_modules = self.__load_modules()
        try:
            for module in sorted(all_modules):
                update_all_modules(module)
            for module in sys_modules:
                if tryImportModule("userbot.modules.", module):
                    update_load_modules(module, True)
                    self.__load_modules_count += 1
                else:
                    update_load_modules(module, False)
            for module in user_modules:
                if not SAFEMODE:
                    if not module in self.__not_load_modules:
                        if tryImportModule("userbot.modules_user.", module):
                            update_load_modules(module, True)
                            self.__load_modules_count += 1
                        else:
                            update_load_modules(module, False)
                update_user_modules(module)
        except Exception as e:
            log.critical(f"Failed to load modules [CORE]: {e}", exc_info=True)
            quit(1)
        return
Esempio n. 3
0
    def _import_module(self, module: str, is_usermodule: bool,
                       display_info: bool):
        """
        Import a module and straight start it
        """
        special_caller = [
            os.path.join("userbot", "__main__.py"),
            os.path.join("userbot", "modules", "_package_manager.py"),
            os.path.join("userbot", "modules", "sideloader.py")
        ]
        sys_caller = getouterframes(currentframe(), 2)[2].filename
        valid_caller = False
        for caller in special_caller:
            if sys_caller.endswith(caller):
                valid_caller = True
                break
        if not valid_caller:
            caller = getouterframes(currentframe(), 2)[2]
            caller = f"{os.path.basename(caller.filename)}:{caller.lineno}"
            log.warning(f"Not a valid caller (requested by {caller})")
            return

        if NO_MODS:
            return

        if module.startswith("__"):
            log.warning(f"Illegal module name '{module}'")
            return

        path = (f"userbot.modules_user.{module}"
                if is_usermodule else f"userbot.modules.{module}")

        if is_usermodule:
            if module in getBuiltInModules():
                log.warning(f"Module '{module}' present as "
                            "built-in module already")
                return
            if path in sys.modules or module in getAllModules():
                self._unimport_module(module)

        update_all_modules(module)
        if is_usermodule:
            update_user_modules(module)
            if SAFEMODE:
                return
        else:
            update_built_in_modules(module)

        if SAFEMODE2:
            core_mods = [
                "_feature_manager", "_modules_utils", "_package_manager",
                "_systools", "_updater"
            ]
            if module not in core_mods:
                return

        if module in self.__not_load_modules:
            return

        try:
            importlib.import_module(path)
            update_load_modules(module, True)
            if display_info:
                log.info(f"Module '{module}' imported successfully")
        except KeyboardInterrupt:
            raise KeyboardInterrupt
        except (BaseException, Exception):
            log.error(
                f"Failed to start module '{module}' due "
                "to an unhandled exception",
                exc_info=True)
            update_load_modules(module, False)
        return
Esempio n. 4
0
    def _unimport_module(self, module: str):
        """
        Tries to remove all data from the target module and finally to
        unimport it from runtime
        """
        special_caller = [
            os.path.join("userbot", "_core", os.path.basename(__file__)),
            os.path.join("userbot", "modules", "_package_manager.py")
        ]
        sys_caller = getouterframes(currentframe(), 2)[2].filename
        valid_caller = False
        for caller in special_caller:
            if sys_caller.endswith(caller):
                valid_caller = True
                break
        if not valid_caller:
            caller = getouterframes(currentframe(), 2)[2]
            caller = f"{os.path.basename(caller.filename)}:{caller.lineno}"
            log.warning(f"Not a valid caller (requested by {caller})")
            return

        if NO_MODS:
            return

        if module.startswith("__"):
            log.warning(f"Illegal module name '{module}'")
            return

        if module not in getAllModules():
            return

        if module not in getUserModules():
            log.error(f"Target module '{module}' is not an user module!")
            return

        handlers_from_module = getHandlers().get(module)
        if handlers_from_module:
            for handler in handlers_from_module:
                _tgclient.remove_event_handler(handler)
            log.info(f"Event handlers from '{module}' removed")
        else:
            log.info(f"Module '{module}' has no registered event handlers")
        update_handlers(module, None, True)
        unregister_module_desc(module)
        unregister_module_info(module)
        cmds_to_remove = []
        for cmd, cmd_attrs in getRegisteredCMDs().items():
            mod_name = cmd_attrs.get("module_name", "")
            if module == mod_name:
                cmds_to_remove.append(cmd)
        if cmds_to_remove:
            for cmd in cmds_to_remove:
                unregister_cmd(cmd)
        update_all_modules(module, True)
        update_load_modules(module, False, True)
        update_user_modules(module, True)
        try:
            path = f"userbot.modules_user.{module}"
            if path in sys.modules:
                sys.modules.pop(path)
                log.info(f"Module '{module}' unimported successfully")
            else:
                log.info(f"Removed module '{module}' from modules data "
                         "successfully")
        except KeyError:
            log.error(f"Failed to unimport module '{module}'")
        return