Example #1
0
            try:
                if isinstance(events, (list, tuple)):
                    for event in events:
                        _tgclient.add_event_handler(
                            func_callback,
                            event(pattern=pattern, *args, **kwargs))
                else:
                    _tgclient.add_event_handler(
                        func_callback, events(pattern=pattern, *args,
                                              **kwargs))
                update_handlers(caller_name, func_callback)
            except Exception:
                self.log.error(
                    f"Failed to add command/feature '{name}' "
                    f"to client (in function "
                    f"'{function.__name__}' ({caller}))",
                    exc_info=True if self.traceback else False)
                return None
            return func_callback

        return decorator


sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=["_tgclient", "_is_active", "pre_register_cmd", "update_handlers"],
    warn_msg=("A module tried to access attribute '{0}' in an unauthorized "
              "way (requested by {1}:{2})"),
)
Example #2
0
@ehandler.on(command="sendlog", outgoing=True)
async def send_log(event):
    chat = await event.get_chat()
    await event.edit(msgRep.UPLD_LOG)
    time.sleep(1)
    try:
        await event.client.send_file(chat, "hyper.log")
        await event.edit(msgRep.SUCCESS_UPLD_LOG)
    except Exception as e:
        log.error(f"Failed to upload HyperUBot log file: {e}")
        await event.edit(msgRep.FAILED_UPLD_LOG)
    return


for cmd in ("status", "storage", "shutdown", "reboot", "neofetch", "sendlog"):
    register_cmd_usage(cmd,
                       usageRep.SYSTOOLS_USAGE.get(cmd, {}).get("args"),
                       usageRep.SYSTOOLS_USAGE.get(cmd, {}).get("usage"))

register_module_desc(descRep.SYSTOOLS_DESC)
register_module_info(name="System Tools",
                     authors="nunopenim, prototpye74",
                     version=VERSION)

sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=["_setprop", "setConfig"],
    warn_msg=("Access to protected attribute from System Tools denied"
              "(requested by {1}:{2})"),
    mlogger=log)
Example #3
0
        for module in user_module_list:
            for mod_source in module_sources:
                mod_name = mod_source.get("name", "")
                if module == mod_name:
                    break
            else:
                # new module installed but from unknown source
                module_sources.append({
                    "name": module,
                    "author": "Unknown",
                    "repo": "Unknown",
                    "version": "Unknown",
                    "size": 0
                })
                if not list_modified:
                    list_modified = True
        if list_modified:
            # update list
            pkg_list["module_sources"] = module_sources
            self._save_json(pkg_list)
        return pkg_list


sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=["_PackageManagerJSON"],
    warn_msg=("Package Manager JSON Component only accessible by "
              "Package Manager Module (requested by {1}:{2})"),
    allowed=os.path.join("userbot", "modules", "_package_manager.py"),
    mlogger=log)
Example #4
0
                text += f"\n{msgRep.PKG_HELP.format('`.help pkg`')}\n"
            else:
                _attempts += 1
            await event.edit(text)
            return
        text += (f"{msgRep.NO_OPTION}. "
                 f"{msgRep.PKG_HELP.format('`.help pkg`')}\n")
        await event.edit(text)
    if _attempts:
        _attempts = 0
    return


register_cmd_usage("pkg",
                   usageRep.PACKAGE_MANAGER_USAGE.get("pkg", {}).get("args"),
                   usageRep.PACKAGE_MANAGER_USAGE.get("pkg", {}).get("usage"))
register_module_desc(descRep.PACKAGE_MANAGER_DESC)
register_module_info(name="Package Manager",
                     authors="nunopenim, prototype74",
                     version=VERSION)

sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=[
        "import_module", "unimport_module", "_PackageManagerJSON",
        "_pkg_manager", "_pkg_list", "ctrl_modules", "_validate_code"
    ],
    warn_msg=("Access to protected attribute from Package Manager denied"
              "(requested by {1}:{2})"),
    mlogger=log)
Example #5
0
_featureMgr._read_json()  # initialize json


def _disable_feature(feature) -> bool:
    return _featureMgr._disable_feature(feature)


def _enable_feature(feature) -> bool:
    return _featureMgr._enable_feature(feature)


def _get_disabled_features() -> str:
    return _featureMgr._get_disabled_features()


def _is_active(feature) -> bool:
    return _featureMgr._is_active(feature)


sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=[
        "_featureMgr", "_FeatureManager", "_disable_feature",
        "_enable_feature", "_get_disabled_features", "_is_active"
    ],
    warn_msg=("Only Feature Manager Module is allowed to access these "
              "attributes (requested by {1}:{2})"),
    allowed=os.path.join("userbot", "modules", "_feature_manager.py"),
    mlogger=log
)
Example #6
0
                        "Telegram 'https://t.me/HyperUBotSupport' and keep "
                        "your hyper.log file ready!")
        if isWindows():
            options[0] += " (python recovery.py)"
            options[1] = contact_text
            options.pop()
            _services._suggest_options(options)
        else:
            option = _services._suggest_options(options)
            if option == 1:
                _services._reboot_recovery(False)
            elif option == 2:
                log.info(contact_text)
    except KeyboardInterrupt:
        print()
        log.info("Exiting...")
    quit(1)

sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=[
        "addConfig", "HyperClient", "_ConfigLoader", "_SecureConfigLoader",
        "_services", "_setprop", "_SysProperties", "_SysServices", "_tgclient",
        "_UserbotLogger", "__cfg_loader__", "__hyper_logger__",
        "__scfg_loader__"
    ],
    warn_msg="Illegal access to '{0}' blocked (requested by {1}:{2})",
    allowed=(path.join("userbot", "modules", "_systools.py"),
             path.join("userbot", "modules", "_updater.py")),
    mlogger=log)
Example #7
0
    Args:
        config (str): config ID
        default: default value to return if config doesn't exist

    Example:
        from userbot.sysutils.configuration import getConfig

        test_var = getConfig("EXAMPLE_BOOL", False)
        if test_var:
            print("EXAMPLE is True")

    Returns:
        the value from config, default if config doesn't exist
    """
    try:
        return _sysconfigs._getConfiguration(config, default)
    except AccessError as ae:
        log.warning(ae)
    return default


sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=["_sysconfigs", "_SysConfigurations", "addConfig", "setConfig"],
    warn_msg=("Unauthorized access to protected attribute blocked "
              "(requested by {1}:{2})"),
    allowed=(join("userbot", "modules",
                  "_systools.py"), join("userbot", "modules", "_updater.py")),
    mlogger=log)
Example #8
0
                    ".", "userbot", "userdata", "__pycache__")) and \
                   os.path.isdir(os.path.join(".", "userbot",
                                              "userdata", "__pycache__")):
                    for name in os.listdir(
                            os.path.join(".", "userbot", "userdata",
                                         "__pycache__")):
                        if name.startswith("_temp.cpython-") and \
                           name.endswith(".pyc"):
                            os.remove(
                                os.path.join(".", "userbot", "userdata",
                                             "__pycache__", name))
                            break
            except Exception:
                pass
        del s_cfg
        return (api_key, api_hash, string_session)

    def _getTooManyAttempts(self) -> bool:
        return self.__too_many_attempts

    def _load_cfg_failed(self) -> bool:
        return self.__load_cfg_failed


sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=["_ConfigLoader", "_SecureConfigLoader", "addConfig"],
    warn_msg=("Unauthorized access to config loader blocked "
              "(requested by {1}:{2})"),
    mlogger=log)
Example #9
0
        temp_list = []
        text = "Suggestions:\n"
        for i, item in enumerate(options, start=1):
            if isWindows():
                text += f"- {item}\n"
            else:
                temp_list.append(str(i))
                text += f"[{i}] {item}\n"
        print()
        print(text)
        if not isWindows():
            options_size = len(temp_list)
            while True:
                inp = input(f"Your input [1-{options_size}]: ")
                for i in temp_list:
                    if inp == i:
                        return int(i)
                else:
                    print(
                        setColorText("Invalid input. Try again...",
                                     Color.YELLOW))
        return 0


sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=["_SysServices"],
    warn_msg=("SysServices is accessible by core service "
              "only (requested by {1}:{2})"),
    mlogger=log)
Example #10
0
                except Exception as e:
                    log.warning("[NOTIFIER] Failed to set saved messages as "
                                f"unread: {e}")
            except Exception as e:
                log.warning("[NOTIFIER] Failed to send notification "
                            f"message: {e}")
            _scheduler.remove_job("updater_job_1")
            _scheduler.shutdown()
        return

    try:
        _scheduler.start()
    except (BaseException, Exception):
        _scheduler.shutdown()

register_cmd_usage("update",
                   usageRep.UPDATER_USAGE.get("update", {}).get("args"),
                   usageRep.UPDATER_USAGE.get("update", {}).get("usage"))
register_module_desc(descRep.UPDATER_DESC)
register_module_info(name="Updater",
                     authors="nunopenim, prototype74",
                     version=VERSION)

sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=(["_setprop", "setConfig", "_set_autoupdate"] +
           (["_tgclient"] if _update_scheduler else [])),
    warn_msg=("Access to protected attribute from Updater denied"
              "(requested by {1}:{2})"),
    mlogger=log)
Example #11
0
        self.__parser.read(self.__path)
        value = None
        for section in self.__parser.sections():
            if section == "SYSTEM":
                value = self.__parser["SYSTEM"].get(key.lower())
                break
        if value:
            # cast to proper datatype
            if value.startswith("[") and value.endswith("]"):
                value = strlist_to_list(value)  # list
            elif value.lower() == "no":
                value = False  # bool
            elif value.lower() == "yes":
                value = True  # bool
            else:
                try:  # integer
                    value = int(value)
                except ValueError:
                    try:  # float
                        value = float(value)
                    except ValueError:
                        pass
        return value


sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=["_SysProperties"],
    warn_msg="SysProp reserved for core service only (requested by {1}:{2})",
    mlogger=log)
Example #12
0
                               "into log: {}".format(e))
        return

    def _stop_logging(self):
        special_caller = [
            os.path.join("userbot", "__main__.py"),
            os.path.join("userbot", "sysutils", "_services.py")
        ]
        sys_caller = getouterframes(currentframe(), 2)[1].filename
        valid_caller = False
        for caller in special_caller:
            if sys_caller.endswith(caller):
                valid_caller = True
                break
        if not valid_caller:
            self.__log.warning("Not a valid caller "
                               f"(requested by {os.path.basename(caller)})")
            return
        if self.__fhandler:
            self.__fhandler.close()
        if self.__shandler:
            self.__shandler.close()
        return


sys.modules[__name__] = _protectedAccess(
    sys.modules[__name__],
    attrs=["_UserbotLogger"],
    warn_msg=("Main logger is reserved for core service only "
              "(requested by {1}:{2})"))