From 89b3295454419e44191b89ba335bba2cfe2e0ff3 Mon Sep 17 00:00:00 2001 From: hikariatama Date: Thu, 26 May 2022 08:54:50 +0000 Subject: [PATCH] Patch, fixing HikkaConfig - Allow adding and removing multiple items in config - Add `ast.literal_eval` to config - Add explicit typecheck for `mod.config` --- CHANGELOG.md | 6 +++++ hikka/entity_cache.py | 14 +++++++---- hikka/loader.py | 34 ++++++++++++++------------ hikka/main.py | 2 +- hikka/modules/hikka_config.py | 43 ++++++++++++++++++++++++++++----- hikka/modules/hikka_security.py | 6 +---- hikka/modules/test.py | 3 --- hikka/utils.py | 7 +++--- 8 files changed, 76 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02f5ca2..e4be788 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## 🌘 Patch released + +- Allow adding and removing multiple items in config +- Add `ast.literal_eval` to config +- Add explicit typecheck for `mod.config` + ## 🌑 Hikka 1.1.28 - Fix non-working param `share_link` in loader diff --git a/hikka/entity_cache.py b/hikka/entity_cache.py index 45dc951..d83de6a 100644 --- a/hikka/entity_cache.py +++ b/hikka/entity_cache.py @@ -50,11 +50,15 @@ def install_entity_caching(client: TelegramClient): async def new(entity: EntityLike): if not hashable(entity): - hashable_entity = next( - getattr(entity, attr) - for attr in {"user_id", "channel_id", "chat_id", "id"} - if hasattr(entity, attr) - ) + try: + hashable_entity = next( + getattr(entity, attr) + for attr in {"user_id", "channel_id", "chat_id", "id"} + if hasattr(entity, attr) + ) + except StopIteration: + logger.debug(f"Can't parse hashable from {entity=}, using legacy resolve") + return await client.get_entity(entity) else: hashable_entity = entity diff --git a/hikka/loader.py b/hikka/loader.py index 28d2bf4..618dcad 100644 --- a/hikka/loader.py +++ b/hikka/loader.py @@ -608,22 +608,24 @@ class Modules: "__config__", {}, ) - for conf in mod.config.keys(): - try: - mod.config.set_no_raise( - conf, - ( - modcfg[conf] - if conf in modcfg.keys() - else os.environ.get( - f"{mod.__class__.__name__}.{conf}", - None, - ) - or mod.config.getdef(conf) - ), - ) - except validators.ValidationError: - pass + try: + for conf in mod.config.keys(): + try: + mod.config.set_no_raise( + conf, + ( + modcfg[conf] + if conf in modcfg.keys() + else os.environ.get(f"{mod.__class__.__name__}.{conf}") + or mod.config.getdef(conf) + ), + ) + except validators.ValidationError: + pass + except AttributeError: + logger.warning( + f"Got invalid config instance. Expected `ModuleConfig`, got {type(mod.config)=}, {mod.config=}" + ) if skip_hook: return diff --git a/hikka/main.py b/hikka/main.py index e201a10..d954809 100755 --- a/hikka/main.py +++ b/hikka/main.py @@ -426,7 +426,7 @@ class Hikka: ip = ( "127.0.0.1" if "DOCKER" not in os.environ - else subprocess.run(["hostname", "-i"], stdout=subprocess.PIPE).stdout + else subprocess.run(["hostname", "-i"], stdout=subprocess.PIPE, check=True).stdout ) print(f"🌐 Please visit http://{ip}:{self.web.port}") diff --git a/hikka/modules/hikka_config.py b/hikka/modules/hikka_config.py index 467ee0e..8ded92f 100755 --- a/hikka/modules/hikka_config.py +++ b/hikka/modules/hikka_config.py @@ -10,6 +10,7 @@ # scope: inline +import ast import logging from typing import Union, Any @@ -252,7 +253,18 @@ class HikkaConfigMod(loader.Module): inline_message_id: str, ): try: - self.lookup(mod).config[option] += [query] + try: + query = ast.literal_eval(query) + except Exception: + pass + + if isinstance(query, (set, tuple)): + query = list(query) + + if not isinstance(query, list): + query = [query] + + self.lookup(mod).config[option] = self.lookup(mod).config[option] + query except loader.validators.ValidationError as e: await call.edit( self.strings("validation_error").format(e.args[0]), @@ -292,13 +304,32 @@ class HikkaConfigMod(loader.Module): inline_message_id: str, ): try: - for i, item in enumerate(self.lookup(mod).config[option]): - if str(item) == str(query): - del self.lookup(mod).config[option][i] + try: + query = ast.literal_eval(query) + except Exception: + pass + + if isinstance(query, (set, tuple)): + query = list(query) + + if not isinstance(query, list): + query = [query] + + query = list(map(str, query)) + found = False + + while True: + for i, item in enumerate(self.lookup(mod).config[option]): + if str(item) in query: + del self.lookup(mod).config[option][i] + found = True + break + else: break - else: + + if not found: raise loader.validators.ValidationError( - f"Passed value ({utils.escape_html(query)}) is not in target list" + f"Nothing from passed value ({self.prep_value(query)}) is not in target list" ) except loader.validators.ValidationError as e: await call.edit( diff --git a/hikka/modules/hikka_security.py b/hikka/modules/hikka_security.py index d69137e..b6c1ce2 100755 --- a/hikka/modules/hikka_security.py +++ b/hikka/modules/hikka_security.py @@ -189,9 +189,7 @@ class HikkaSecurityMod(loader.Module): await call.edit( self.strings("permissions").format( - f"@{self.inline.bot_username} " - if is_inline - else self.get_prefix(), + f"@{self.inline.bot_username} " if is_inline else self.get_prefix(), command, ), reply_markup=self._build_markup(cmd, is_inline), @@ -255,7 +253,6 @@ class HikkaSecurityMod(loader.Module): ] ] - return utils.chunks( [ { @@ -508,7 +505,6 @@ class HikkaSecurityMod(loader.Module): list(set(self._db.get(security.__name__, group, [])) - {user.id}), ) - m = self.strings(f"{group}_removed").format( user.id, utils.escape_html(get_display_name(user)), diff --git a/hikka/modules/test.py b/hikka/modules/test.py index 04f35d9..143ba9a 100755 --- a/hikka/modules/test.py +++ b/hikka/modules/test.py @@ -10,7 +10,6 @@ # scope: inline -import asyncio import inspect import logging import os @@ -414,8 +413,6 @@ class TestMod(loader.Module): self._logchat = int(f"-100{chat.id}") - logger = logging.getLogger(__name__) - if not is_new or all( participant.id != self.inline.bot_id for participant in (await self._client.get_participants(chat, limit=3)) diff --git a/hikka/utils.py b/hikka/utils.py index a0cc9df..d9b8e23 100755 --- a/hikka/utils.py +++ b/hikka/utils.py @@ -583,10 +583,11 @@ def get_named_platform() -> str: model = f.read() if "Orange" in model: return f"🍊 {model}" - elif "Raspberry" in model: + + if "Raspberry" in model: return f"🍇 {model}" - else: - return f"❓ {model}" + + return f"❓ {model}" except Exception: # In case of weird fs, aka Termux pass