- 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
pull/1/head
hikariatama 2022-05-09 18:14:58 +00:00
parent 3599d260cd
commit 3d9d243d1b
4 changed files with 71 additions and 6 deletions

View File

@ -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,
(
"🌘 <b>Hikka is downloading a file...</b>\n"
f"<code>{_progressbar(percentage)} {percentage}%</code>"
),
)
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,
(
"🌘 <b>Hikka is uploading a file...</b>\n"
f"<code>{_progressbar(percentage)} {percentage}%</code>"
),
)
except Exception:
pass
res = (
await _internal_transfer_to_telegram(_client, file, progress_callback, filename)
)[0]

View File

@ -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__"):

View File

@ -41,6 +41,7 @@ class HelpMod(loader.Module):
"joined": "🌘 <b>Joined the</b> <a href='https://t.me/hikka_talks'>support chat</a>",
"join": "🌘 <b>Join the</b> <a href='https://t.me/hikka_talks'>support chat</a>",
"partial_load": "⚠️ <b>Userbot is not fully loaded, so not all modules are shown</b>",
"not_exact": "⚠️ <b>No exact match occured, so the closest result is shown instead</b>",
}
strings_ru = {
@ -63,6 +64,7 @@ class HelpMod(loader.Module):
"_cmd_doc_support": "Вступает в чат помощи Hikka",
"_cls_doc": "Модуль помощи, сделанный специально для Hikka <3",
"partial_load": "⚠️ <b>Юзербот еще не загрузился полностью, поэтому показаны не все модули</b>",
"not_exact": "⚠️ <b>Точного совпадения не нашлось, поэтому был выбран наиболее подходящее</b>",
}
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

View File

@ -1,2 +1,2 @@
"""Represents current userbot version"""
__version__ = (1, 1, 17)
__version__ = (1, 1, 18)