From 3d9d243d1b7f4bc63af540fc57ffc303c317f22e Mon Sep 17 00:00:00 2001 From: hikariatama Date: Mon, 9 May 2022 18:14:58 +0000 Subject: [PATCH] 1.1.18 - Add notification about not exact match in help - Add automatic progress bar generation to `self.fast_upload` and `self.fast_download` - Make `Mod` ending in modules class name not mandatory --- hikka/fast_uploader.py | 60 ++++++++++++++++++++++++++++++++++++++++++ hikka/loader.py | 8 +++--- hikka/modules/help.py | 7 ++++- hikka/version.py | 2 +- 4 files changed, 71 insertions(+), 6 deletions(-) diff --git a/hikka/fast_uploader.py b/hikka/fast_uploader.py index 678a1ab..0f887a0 100644 --- a/hikka/fast_uploader.py +++ b/hikka/fast_uploader.py @@ -21,6 +21,8 @@ from typing import ( Union, ) +import time + from telethon import TelegramClient, helpers, utils from telethon.crypto import AuthKey from telethon.network import MTProtoSender @@ -44,8 +46,12 @@ from telethon.tl.types import ( InputPeerPhotoFileLocation, InputPhotoFileLocation, TypeInputFile, + Message, ) +from .inline.types import InlineMessage +from .utils import answer + try: from mautrix.crypto.attachments import async_encrypt_attachment except ImportError: @@ -409,9 +415,15 @@ async def _internal_transfer_to_telegram( ) +def _progressbar(progress: int) -> str: + filled = int(10 * progress // 100) + return f'{"▰" * filled}{"▱" * (10 - filled)}' + + async def download_file( location: TypeLocation = None, progress_callback: callable = None, + message_object: Optional[Union[Message, InlineMessage]] = None, _client: TelegramClient = None, ) -> BinaryIO: size = location.size @@ -421,6 +433,29 @@ async def download_file( downloader = ParallelTransferrer(_client, dc_id) downloaded = downloader.download(location, size) + ratelimiter = time.time() + 3 + + if progress_callback is None: + + async def progress_callback(current: int, total: int): + nonlocal message_object, ratelimiter + if ratelimiter > time.time(): + return + + ratelimiter = time.time() + 3 + + percentage = round(current * 100 / total) + try: + message_object = await answer( + message_object, + ( + "🌘 Hikka is downloading a file...\n" + f"{_progressbar(percentage)} {percentage}%" + ), + ) + except Exception: + pass + _out = io.BytesIO() async for x in downloaded: @@ -437,8 +472,33 @@ async def upload_file( file: BinaryIO = None, progress_callback: callable = None, filename: str = "upload", + message_object: Optional[Union[Message, InlineMessage]] = None, _client: TelegramClient = None, ) -> TypeInputFile: + + ratelimiter = time.time() + 3 + + if progress_callback is None: + + async def progress_callback(current: int, total: int): + nonlocal message_object, ratelimiter + if ratelimiter > time.time(): + return + + ratelimiter = time.time() + 3 + + percentage = round(current * 100 / total) + try: + message_object = await answer( + message_object, + ( + "🌘 Hikka is uploading a file...\n" + f"{_progressbar(percentage)} {percentage}%" + ), + ) + except Exception: + pass + res = ( await _internal_transfer_to_telegram(_client, file, progress_callback, filename) )[0] diff --git a/hikka/loader.py b/hikka/loader.py index efcce28..6ee1187 100755 --- a/hikka/loader.py +++ b/hikka/loader.py @@ -40,10 +40,10 @@ from types import FunctionType from typing import Any, Optional, Union from . import security, utils -from ._types import ( +from ._types import ( # noqa: F401 ConfigValue, LoadError, - Module, # noqa: F401 + Module, ModuleConfig, SelfUnload, StopLoop, @@ -176,7 +176,7 @@ def loop( :param interval: Loop iterations delay :param autostart: Start loop once module is loaded :param wait_before: Insert delay before actual iteration, rather than after - :param stop_clase: Database key, based on which the loop will run. + :param stop_clause: Database key, based on which the loop will run. This key will be set to `True` once loop is started, and will stop after key resets to `False` :attr status: Boolean, describing whether the loop is running @@ -363,7 +363,7 @@ class Modules: ret = None for key, value in vars(module).items(): - if key.endswith("Mod") and issubclass(value, Module): + if inspect.isclass(value) and issubclass(value, Module): ret = value() if hasattr(module, "__version__"): diff --git a/hikka/modules/help.py b/hikka/modules/help.py index 8d429b6..0e9a142 100755 --- a/hikka/modules/help.py +++ b/hikka/modules/help.py @@ -41,6 +41,7 @@ class HelpMod(loader.Module): "joined": "🌘 Joined the support chat", "join": "🌘 Join the support chat", "partial_load": "⚠️ Userbot is not fully loaded, so not all modules are shown", + "not_exact": "⚠️ No exact match occured, so the closest result is shown instead", } strings_ru = { @@ -63,6 +64,7 @@ class HelpMod(loader.Module): "_cmd_doc_support": "Вступает в чат помощи Hikka", "_cls_doc": "Модуль помощи, сделанный специально для Hikka <3", "partial_load": "⚠️ Юзербот еще не загрузился полностью, поэтому показаны не все модули", + "not_exact": "⚠️ Точного совпадения не нашлось, поэтому был выбран наиболее подходящее", } def __init__(self): @@ -114,6 +116,7 @@ class HelpMod(loader.Module): """[module] [-f] - Show help""" args = utils.get_args_raw(message) force = False + exact = True if "-f" in args: args = args.replace(" -f", "").replace("-f", "") force = True @@ -157,6 +160,8 @@ class HelpMod(loader.Module): if module.strings["name"] == module_name ) + exact = False + try: name = module.strings("name") except KeyError: @@ -194,7 +199,7 @@ class HelpMod(loader.Module): ), ) - await utils.answer(message, reply) + await utils.answer(message, f"{reply}\n\n{self.strings('not_exact') if not exact else ''}") return count = 0 diff --git a/hikka/version.py b/hikka/version.py index 217469f..582688e 100644 --- a/hikka/version.py +++ b/hikka/version.py @@ -1,2 +1,2 @@ """Represents current userbot version""" -__version__ = (1, 1, 17) +__version__ = (1, 1, 18)