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
- 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):
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

View File

@ -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

View File

@ -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}")

View File

@ -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(

View File

@ -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)),

View File

@ -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))

View File

@ -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