Patch, fixing HikkaConfig

- Allow adding and removing multiple items in config
- Add `ast.literal_eval` to config
- Add explicit typecheck for `mod.config`
pull/1/head
hikariatama 2022-05-26 08:54:50 +00:00
parent 3fc77b5529
commit 89b3295454
8 changed files with 76 additions and 39 deletions

View File

@ -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 ## 🌑 Hikka 1.1.28
- Fix non-working param `share_link` in loader - Fix non-working param `share_link` in loader

View File

@ -50,11 +50,15 @@ def install_entity_caching(client: TelegramClient):
async def new(entity: EntityLike): async def new(entity: EntityLike):
if not hashable(entity): if not hashable(entity):
hashable_entity = next( try:
getattr(entity, attr) hashable_entity = next(
for attr in {"user_id", "channel_id", "chat_id", "id"} getattr(entity, attr)
if hasattr(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: else:
hashable_entity = entity hashable_entity = entity

View File

@ -608,22 +608,24 @@ class Modules:
"__config__", "__config__",
{}, {},
) )
for conf in mod.config.keys(): try:
try: for conf in mod.config.keys():
mod.config.set_no_raise( try:
conf, mod.config.set_no_raise(
( conf,
modcfg[conf] (
if conf in modcfg.keys() modcfg[conf]
else os.environ.get( if conf in modcfg.keys()
f"{mod.__class__.__name__}.{conf}", else os.environ.get(f"{mod.__class__.__name__}.{conf}")
None, or mod.config.getdef(conf)
) ),
or mod.config.getdef(conf) )
), except validators.ValidationError:
) pass
except validators.ValidationError: except AttributeError:
pass logger.warning(
f"Got invalid config instance. Expected `ModuleConfig`, got {type(mod.config)=}, {mod.config=}"
)
if skip_hook: if skip_hook:
return return

View File

@ -426,7 +426,7 @@ class Hikka:
ip = ( ip = (
"127.0.0.1" "127.0.0.1"
if "DOCKER" not in os.environ 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}") print(f"🌐 Please visit http://{ip}:{self.web.port}")

View File

@ -10,6 +10,7 @@
# scope: inline # scope: inline
import ast
import logging import logging
from typing import Union, Any from typing import Union, Any
@ -252,7 +253,18 @@ class HikkaConfigMod(loader.Module):
inline_message_id: str, inline_message_id: str,
): ):
try: 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: except loader.validators.ValidationError as e:
await call.edit( await call.edit(
self.strings("validation_error").format(e.args[0]), self.strings("validation_error").format(e.args[0]),
@ -292,13 +304,32 @@ class HikkaConfigMod(loader.Module):
inline_message_id: str, inline_message_id: str,
): ):
try: try:
for i, item in enumerate(self.lookup(mod).config[option]): try:
if str(item) == str(query): query = ast.literal_eval(query)
del self.lookup(mod).config[option][i] 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 break
else:
if not found:
raise loader.validators.ValidationError( 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: except loader.validators.ValidationError as e:
await call.edit( await call.edit(

View File

@ -189,9 +189,7 @@ class HikkaSecurityMod(loader.Module):
await call.edit( await call.edit(
self.strings("permissions").format( self.strings("permissions").format(
f"@{self.inline.bot_username} " f"@{self.inline.bot_username} " if is_inline else self.get_prefix(),
if is_inline
else self.get_prefix(),
command, command,
), ),
reply_markup=self._build_markup(cmd, is_inline), reply_markup=self._build_markup(cmd, is_inline),
@ -255,7 +253,6 @@ class HikkaSecurityMod(loader.Module):
] ]
] ]
return utils.chunks( return utils.chunks(
[ [
{ {
@ -508,7 +505,6 @@ class HikkaSecurityMod(loader.Module):
list(set(self._db.get(security.__name__, group, [])) - {user.id}), list(set(self._db.get(security.__name__, group, [])) - {user.id}),
) )
m = self.strings(f"{group}_removed").format( m = self.strings(f"{group}_removed").format(
user.id, user.id,
utils.escape_html(get_display_name(user)), utils.escape_html(get_display_name(user)),

View File

@ -10,7 +10,6 @@
# scope: inline # scope: inline
import asyncio
import inspect import inspect
import logging import logging
import os import os
@ -414,8 +413,6 @@ class TestMod(loader.Module):
self._logchat = int(f"-100{chat.id}") self._logchat = int(f"-100{chat.id}")
logger = logging.getLogger(__name__)
if not is_new or all( if not is_new or all(
participant.id != self.inline.bot_id participant.id != self.inline.bot_id
for participant in (await self._client.get_participants(chat, limit=3)) for participant in (await self._client.get_participants(chat, limit=3))

View File

@ -583,10 +583,11 @@ def get_named_platform() -> str:
model = f.read() model = f.read()
if "Orange" in model: if "Orange" in model:
return f"🍊 {model}" return f"🍊 {model}"
elif "Raspberry" in model:
if "Raspberry" in model:
return f"🍇 {model}" return f"🍇 {model}"
else:
return f"{model}" return f"{model}"
except Exception: except Exception:
# In case of weird fs, aka Termux # In case of weird fs, aka Termux
pass pass