def installPkg(dist_name, upgrade: bool = False) -> bool: """ Installs the given name of the distribution Args: dist_name (string): name of distribution upgrade (bool): if the distribution should be upgraded instead. This works only if the distribution is installed Example: if not checkPkgByDist("requests"): installPkg("requests") else: print("package requests installed already") Returns: True if installation was successful or not required else False if errors occurred """ caller = getouterframes(currentframe(), 2)[1] caller = f"{basename(caller.filename)}:{caller.lineno}" try: py_exec = (executable if " " not in executable else '"' + executable + '"') if not checkPkgByDist(dist_name): check_call([py_exec, "-m", "pip", "install", dist_name], stdout=DEVNULL, stderr=DEVNULL) log.info(f"Package '{dist_name}' installed successfully " f"({caller})") elif upgrade: curr_ver = verAsTuple(getVersionFromDist(dist_name)) check_call( [py_exec, "-m", "pip", "install", "--upgrade", dist_name], stdout=DEVNULL, stderr=DEVNULL) new_ver = verAsTuple(getVersionFromDist(dist_name)) if (curr_ver and new_ver and curr_ver == new_ver): log.info(f"Package '{dist_name}' is up-to-date already " f"({caller})") else: # default case log.info(f"Package '{dist_name}' upgraded successfully " f"({caller})") else: log.info(f"Package '{dist_name}' installed already ({caller})") return True except Exception as e: log.error(f"Failed to install package '{dist_name}' ({caller})", exc_info=True) return False
async def update_scheduler(): try: release_data = getLatestData("prototype74/HyperUBot") except Exception: log.warning("[NOTIFIER] Failed to get latest release") return try: tag_version = release_data["tag_name"][1:] release_version = verAsTuple(tag_version) except ValueError: log.warning("[NOTIFIER] Invalid tag version from release") return except Exception: log.warning("[NOTIFIER] Failed to parse tag version from release") return if VERSION_TUPLE < release_version: log.info(f"[NOTIFIER] An Update to {tag_version} is available") text = (f"**{msgRep.NOTIFIER_HEADER}**\n\n" f"__{msgRep.NOTIFIER_INFO.format(tag_version)}__") try: me = await _tgclient.get_me() await _tgclient.send_message(me.id, text) try: await _tgclient(MarkDialogUnreadRequest(me.id, True)) 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
_file.write(_sys_string) _file.close() except Exception as e: log.warning("Unable to write system information into log: {}".format(e)) # Check Python version if (version_info.major, version_info.minor) < (3, 8): log.error("Python v3.8+ is required! " "Please update Python to v3.8 or newer " "(current version: {}.{}.{}).".format(version_info.major, version_info.minor, version_info.micro)) quit(1) # Check Telethon version if verAsTuple(version.__version__) < (1, 21, 1): log.error("Telethon version 1.21.1+ is required! " "Please update Telethon to v1.21.1 or newer " f"(current version: {version.__version__}).") quit(1) if SAFEMODE: log.info(setColorText("Booting in SAFE MODE", Color.GREEN)) log.info("Loading required configurations") else: log.info("Loading configurations") if path.exists(path.join(".", "userbot", "config.env")): from userbot.include.aux_funcs import strlist_to_list, str_to_bool _len_before = len(environ.items()) load_dotenv(path.join(".", "userbot", "config.env"))
async def updater(event): arg = event.pattern_match.group(1) git_repo = await _is_git_repo() warn_emoji = u"\u26A0" update_now = True if arg.lower() == "upgrade" else False global _LATEST_VER if not update_now or (update_now and not _LATEST_VER): await event.edit(msgRep.CHECKING_UPDATES) if update_now and _LATEST_VER: await event.edit(msgRep.DOWNLOADING_RELEASE) if not _get_latest_release(_LATEST_VER.get("rules"), _LATEST_VER.get("zip")): await event.edit("Update failed") log.error("Failed to download latest release. Aborting process", exc_info=True) _LATEST_VER.clear() return _LATEST_VER.clear() commit_id = _get_commit_id() if not commit_id: await event.edit(msgRep.UPDATE_FAILED) return await event.edit(msgRep.DOWNLOAD_SUCCESS) if _set_autoupdate(commit_id): await event.client.disconnect() else: await event.edit(msgRep.START_RECOVERY_FAILED) return try: current_version = botVerAsTuple() except Exception: await event.edit(msgRep.UPDATE_FAILED) log.error("Failed to parse bot version", exc_info=True) return try: release_data = getLatestData("nunopenim/HyperUBot") if not release_data: raise Exception except Exception: await event.edit(msgRep.UPDATE_FAILED) log.error("Failed to get latest release") return try: tag_version = release_data["tag_name"][1:] release_version = verAsTuple(tag_version) except ValueError: await event.edit(msgRep.UPDATE_FAILED) log.error("Invalid tag version from release", exc_info=True) return except Exception: await event.edit(msgRep.UPDATE_FAILED) log.error("Failed to parse tag version from release", exc_info=True) return if current_version > release_version: log.warning(f"Current version newer than on release server " f"({VERSION} > {tag_version})") await event.edit(f"{msgRep.UPDATE_FAILED}: " f"{msgRep.UPDATE_INTERNAL_FAILED}") if _LATEST_VER: _LATEST_VER.clear() return if current_version == release_version: log.info(f"Already up-to-date ({VERSION} == {tag_version})") reply = f"**{msgRep.ALREADY_UP_TO_DATE}**\n\n" if git_repo: reply += f"{warn_emoji} __{msgRep.GIT_REPO}__\n\n" reply += f"{msgRep.LATEST}: {tag_version}\n" reply += f"{msgRep.CURRENT}: {VERSION}\n" if _LATEST_VER: _LATEST_VER.clear() await event.edit(reply) return if current_version < release_version: try: assets = release_data.get("assets", []) if assets: for asset in assets: if asset.get("name", "") == "rules.py": _LATEST_VER["rules"] = asset.get( "browser_download_url") break except Exception: await event.edit(msgRep.UPDATE_FAILED) log.error("Failed to get assets from release", exc_info=True) return _LATEST_VER["zip"] = release_data.get("zipball_url") release_url = release_data.get("html_url") publish_date = _parse_datetime(release_data["published_at"]) log.info(f"Update available ({VERSION} < {tag_version})") reply = f"**{msgRep.UPDATE_AVAILABLE}**\n\n" if git_repo: reply += f"{warn_emoji} __{msgRep.GIT_REPO}__\n\n" reply += f"**{msgRep.LATEST}: {tag_version}**\n" reply += f"{msgRep.CURRENT}: {VERSION}\n" reply += (f"{msgRep.RELEASE_DATE}: {publish_date}\n\n" if publish_date else "\n") reply += msgRep.CHANGELOG_AT.format(f"[GitHub]({release_url})\n\n") if update_now: reply += msgRep.DOWNLOADING_RELEASE await event.edit(reply) if not _get_latest_release(_LATEST_VER.get("rules"), _LATEST_VER.get("zip")): await event.edit(reply.replace(msgRep.DOWNLOADING_RELEASE, msgRep.UPDATE_FAILED)) log.error("Failed to download latest release. " "Aborting process", exc_info=True) _LATEST_VER.clear() return _LATEST_VER.clear() commit_id = _get_commit_id() if not commit_id: await event.edit(reply.replace(msgRep.DOWNLOADING_RELEASE, msgRep.UPDATE_FAILED)) return await event.edit(reply.replace(msgRep.DOWNLOADING_RELEASE, msgRep.DOWNLOAD_SUCCESS)) if _set_autoupdate(commit_id): await event.client.disconnect() else: await event.edit(reply.replace(msgRep.DOWNLOAD_SUCCESS, msgRep.START_RECOVERY_FAILED)) else: reply += msgRep.UPDATE_QUEUED await event.edit(reply) return
_file.write(_sys_string) _file.close() except Exception as e: log.warning("Unable to write system information into log: {}".format(e)) # Check Python version if (version_info.major, version_info.minor) < (3, 8): log.error("Python v3.8+ is required! " "Please update Python to v3.8 or newer " "(current version: {}.{}.{}).".format(version_info.major, version_info.minor, version_info.micro)) quit(1) # Check Telethon version if verAsTuple(version.__version__) < (1, 23, 0): log.error("Telethon version 1.23.0+ is required! " "Please update Telethon to v1.23.0 or newer " f"(current version: {version.__version__}).") quit(1) if SAFEMODE: log.info(setColorText("Booting in SAFE MODE", Color.GREEN)) log.info("Loading required configurations") else: log.info("Loading configurations") API_KEY, API_HASH, STRING_SESSION = get_secure_config() if not API_KEY and not API_HASH and not STRING_SESSION: if not check_secure_config():
# Check command line if len(sys.argv) >= 2: if sys.argv[1].lower() == "-safemode": # safe mode SAFEMODE = True elif sys.argv[1].lower() == "-safemode2": # advanced safe mode SAFEMODE = True SAFEMODE2 = True elif sys.argv[1].lower() == "-nomods": # core services only NO_MODS = True from telethon import version as tl_version # noqa: E402 from userbot.sysutils.sys_funcs import isWindows, verAsTuple # noqa: E402 # Check Telethon version if verAsTuple(tl_version.__version__) < (1, 24, 0): print( setColorText( "HyperUBot requires at least Telethon version 1.24.0! " "Please update Telethon to v1.24.0 or newer " f"(current version is {tl_version.__version__})", Color.RED)) quit(1) from userbot._core.access_controller import _protectedAccess # noqa: E402 from userbot._core.client import HyperClient # noqa: E402 from userbot.sysutils.config_loader import (_ConfigLoader, _SecureConfigLoader) # noqa: E402 from userbot.sysutils.configuration import addConfig, getConfig # noqa: E402 from userbot.sysutils.logger import _UserbotLogger # noqa: E402 from userbot.sysutils.properties import _SysProperties # noqa: E402 from userbot.sysutils._services import _SysServices # noqa: E402