123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056 |
- # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
- # █▀█ █ █ █ █▀█ █▀▄ █
- # © Copyright 2022
- # https://t.me/hikariatama
- #
- # 🔒 Licensed under the GNU AGPLv3
- # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
- # scope: inline
- import ast
- import functools
- import logging
- from math import ceil
- from typing import Optional, Union, Any
- from telethon.tl.types import Message
- from .. import loader, utils, translations
- from ..inline.types import InlineCall
- logger = logging.getLogger(__name__)
- # Everywhere in this module, we use the following naming convention:
- # `obj_type` of non-core module = False
- # `obj_type` of core module = True
- # `obj_type` of library = "library"
- @loader.tds
- class HikkaConfigMod(loader.Module):
- """Interactive configurator for Hikka Userbot"""
- strings = {
- "name": "HikkaConfig",
- "choose_core": "🎚 <b>Choose a category</b>",
- "configure": "🎚 <b>Choose a module to configure</b>",
- "configure_lib": "🪴 <b>Choose a library to configure</b>",
- "configuring_mod": (
- "🎚 <b>Choose config option for mod</b> <code>{}</code>\n\n<b>Current"
- " options:</b>\n\n{}"
- ),
- "configuring_lib": (
- "🪴 <b>Choose config option for library</b> <code>{}</code>\n\n<b>Current"
- " options:</b>\n\n{}"
- ),
- "configuring_option": (
- "🎚 <b>Configuring option </b><code>{}</code><b> of mod"
- " </b><code>{}</code>\n<i>ℹ️ {}</i>\n\n<b>Default: {}</b>\n\n<b>Current:"
- " {}</b>\n\n{}"
- ),
- "configuring_option_lib": (
- "🪴 <b>Configuring option </b><code>{}</code><b> of library"
- " </b><code>{}</code>\n<i>ℹ️ {}</i>\n\n<b>Default: {}</b>\n\n<b>Current:"
- " {}</b>\n\n{}"
- ),
- "option_saved": (
- "🎚 <b>Option </b><code>{}</code><b> of module </b><code>{}</code><b>"
- " saved!</b>\n<b>Current: {}</b>"
- ),
- "option_saved_lib": (
- "🪴 <b>Option </b><code>{}</code><b> of library </b><code>{}</code><b>"
- " saved!</b>\n<b>Current: {}</b>"
- ),
- "option_reset": (
- "♻️ <b>Option </b><code>{}</code><b> of module </b><code>{}</code><b> has"
- " been reset to default</b>\n<b>Current: {}</b>"
- ),
- "option_reset_lib": (
- "♻️ <b>Option </b><code>{}</code><b> of library </b><code>{}</code><b> has"
- " been reset to default</b>\n<b>Current: {}</b>"
- ),
- "args": "🚫 <b>You specified incorrect args</b>",
- "no_mod": "🚫 <b>Module doesn't exist</b>",
- "no_option": "🚫 <b>Configuration option doesn't exist</b>",
- "validation_error": "🚫 <b>You entered incorrect config value. \nError: {}</b>",
- "try_again": "🔁 Try again",
- "typehint": "🕵️ <b>Must be a{eng_art} {}</b>",
- "set": "set",
- "set_default_btn": "♻️ Reset default",
- "enter_value_btn": "✍️ Enter value",
- "enter_value_desc": "✍️ Enter new configuration value for this option",
- "add_item_desc": "✍️ Enter item to add",
- "remove_item_desc": "✍️ Enter item to remove",
- "back_btn": "👈 Back",
- "close_btn": "🔻 Close",
- "add_item_btn": "➕ Add item",
- "remove_item_btn": "➖ Remove item",
- "show_hidden": "🚸 Show value",
- "hide_value": "🔒 Hide value",
- "builtin": "🛰 Built-in",
- "external": "🛸 External",
- "libraries": "🪴 Libraries",
- }
- strings_ru = {
- "choose_core": "🎚 <b>Выбери категорию</b>",
- "configure": "🎚 <b>Выбери модуль для настройки</b>",
- "configure_lib": "🪴 <b>Выбери библиотеку для настройки</b>",
- "configuring_mod": (
- "🎚 <b>Выбери параметр для модуля</b> <code>{}</code>\n\n<b>Текущие"
- " настройки:</b>\n\n{}"
- ),
- "configuring_lib": (
- "🪴 <b>Выбери параметр для библиотеки</b> <code>{}</code>\n\n<b>Текущие"
- " настройки:</b>\n\n{}"
- ),
- "configuring_option": (
- "🎚 <b>Управление параметром </b><code>{}</code><b> модуля"
- " </b><code>{}</code>\n<i>ℹ️ {}</i>\n\n<b>Стандартное:"
- " {}</b>\n\n<b>Текущее: {}</b>\n\n{}"
- ),
- "configuring_option_lib": (
- "🪴 <b>Управление параметром </b><code>{}</code><b> библиотеки"
- " </b><code>{}</code>\n<i>ℹ️ {}</i>\n\n<b>Стандартное:"
- " {}</b>\n\n<b>Текущее: {}</b>\n\n{}"
- ),
- "option_saved": (
- "🎚 <b>Параметр </b><code>{}</code><b> модуля </b><code>{}</code><b>"
- " сохранен!</b>\n<b>Текущее: {}</b>"
- ),
- "option_saved_lib": (
- "🪴 <b>Параметр </b><code>{}</code><b> библиотеки </b><code>{}</code><b>"
- " сохранен!</b>\n<b>Текущее: {}</b>"
- ),
- "option_reset": (
- "♻️ <b>Параметр </b><code>{}</code><b> модуля </b><code>{}</code><b>"
- " сброшен до значения по умолчанию</b>\n<b>Текущее: {}</b>"
- ),
- "option_reset_lib": (
- "♻️ <b>Параметр </b><code>{}</code><b> библиотеки </b><code>{}</code><b>"
- " сброшен до значения по умолчанию</b>\n<b>Текущее: {}</b>"
- ),
- "_cls_doc": "Интерактивный конфигуратор Hikka",
- "args": "🚫 <b>Ты указал неверные аргументы</b>",
- "no_mod": "🚫 <b>Модуль не существует</b>",
- "no_option": "🚫 <b>У модуля нет такого значения конфига</b>",
- "validation_error": (
- "🚫 <b>Введено некорректное значение конфига. \nОшибка: {}</b>"
- ),
- "try_again": "🔁 Попробовать еще раз",
- "typehint": "🕵️ <b>Должно быть {}</b>",
- "set": "поставить",
- "set_default_btn": "♻️ Значение по умолчанию",
- "enter_value_btn": "✍️ Ввести значение",
- "enter_value_desc": "✍️ Введи новое значение этого параметра",
- "add_item_desc": "✍️ Введи элемент, который нужно добавить",
- "remove_item_desc": "✍️ Введи элемент, который нужно удалить",
- "back_btn": "👈 Назад",
- "close_btn": "🔻 Закрыть",
- "add_item_btn": "➕ Добавить элемент",
- "remove_item_btn": "➖ Удалить элемент",
- "show_hidden": "🚸 Показать значение",
- "hide_value": "🔒 Скрыть значение",
- "builtin": "🛰 Встроенные",
- "external": "🛸 Внешние",
- "libraries": "🪴 Библиотеки",
- }
- _row_size = 3
- _num_rows = 5
- @staticmethod
- def prep_value(value: Any) -> Any:
- if isinstance(value, str):
- return f"</b><code>{utils.escape_html(value.strip())}</code><b>"
- if isinstance(value, list) and value:
- return (
- "</b><code>[</code>\n "
- + "\n ".join(
- [f"<code>{utils.escape_html(str(item))}</code>" for item in value]
- )
- + "\n<code>]</code><b>"
- )
- return f"</b><code>{utils.escape_html(value)}</code><b>"
- def hide_value(self, value: Any) -> str:
- if isinstance(value, list) and value:
- return self.prep_value(["*" * len(str(i)) for i in value])
- return self.prep_value("*" * len(str(value)))
- async def inline__set_config(
- self,
- call: InlineCall,
- query: str,
- mod: str,
- option: str,
- inline_message_id: str,
- obj_type: Union[bool, str] = False,
- ):
- try:
- self.lookup(mod).config[option] = query
- except loader.validators.ValidationError as e:
- await call.edit(
- self.strings("validation_error").format(e.args[0]),
- reply_markup={
- "text": self.strings("try_again"),
- "callback": self.inline__configure_option,
- "args": (mod, option),
- "kwargs": {"obj_type": obj_type},
- },
- )
- return
- await call.edit(
- self.strings(
- "option_saved" if isinstance(obj_type, bool) else "option_saved_lib"
- ).format(
- utils.escape_html(option),
- utils.escape_html(mod),
- self.prep_value(self.lookup(mod).config[option])
- if not self.lookup(mod).config._config[option].validator
- or self.lookup(mod).config._config[option].validator.internal_id
- != "Hidden"
- else self.hide_value(self.lookup(mod).config[option]),
- ),
- reply_markup=[
- [
- {
- "text": self.strings("back_btn"),
- "callback": self.inline__configure,
- "args": (mod,),
- "kwargs": {"obj_type": obj_type},
- },
- {"text": self.strings("close_btn"), "action": "close"},
- ]
- ],
- inline_message_id=inline_message_id,
- )
- async def inline__reset_default(
- self,
- call: InlineCall,
- mod: str,
- option: str,
- obj_type: Union[bool, str] = False,
- ):
- mod_instance = self.lookup(mod)
- mod_instance.config[option] = mod_instance.config.getdef(option)
- await call.edit(
- self.strings(
- "option_reset" if isinstance(obj_type, bool) else "option_reset_lib"
- ).format(
- utils.escape_html(option),
- utils.escape_html(mod),
- self.prep_value(self.lookup(mod).config[option])
- if not self.lookup(mod).config._config[option].validator
- or self.lookup(mod).config._config[option].validator.internal_id
- != "Hidden"
- else self.hide_value(self.lookup(mod).config[option]),
- ),
- reply_markup=[
- [
- {
- "text": self.strings("back_btn"),
- "callback": self.inline__configure,
- "args": (mod,),
- "kwargs": {"obj_type": obj_type},
- },
- {"text": self.strings("close_btn"), "action": "close"},
- ]
- ],
- )
- async def inline__set_bool(
- self,
- call: InlineCall,
- mod: str,
- option: str,
- value: bool,
- obj_type: Union[bool, str] = False,
- ):
- try:
- self.lookup(mod).config[option] = value
- except loader.validators.ValidationError as e:
- await call.edit(
- self.strings("validation_error").format(e.args[0]),
- reply_markup={
- "text": self.strings("try_again"),
- "callback": self.inline__configure_option,
- "args": (mod, option),
- "kwargs": {"obj_type": obj_type},
- },
- )
- return
- validator = self.lookup(mod).config._config[option].validator
- doc = utils.escape_html(
- next(
- (
- validator.doc[lang]
- for lang in self._db.get(translations.__name__, "lang", "en").split(
- " "
- )
- if lang in validator.doc
- ),
- validator.doc["en"],
- )
- )
- await call.edit(
- self.strings(
- "configuring_option"
- if isinstance(obj_type, bool)
- else "configuring_option_lib"
- ).format(
- utils.escape_html(option),
- utils.escape_html(mod),
- utils.escape_html(self.lookup(mod).config.getdoc(option)),
- self.prep_value(self.lookup(mod).config.getdef(option)),
- self.prep_value(self.lookup(mod).config[option])
- if not validator or validator.internal_id != "Hidden"
- else self.hide_value(self.lookup(mod).config[option]),
- self.strings("typehint").format(
- doc,
- eng_art="n" if doc.lower().startswith(tuple("euioay")) else "",
- )
- if doc
- else "",
- ),
- reply_markup=self._generate_bool_markup(mod, option, obj_type),
- )
- await call.answer("✅")
- def _generate_bool_markup(
- self,
- mod: str,
- option: str,
- obj_type: Union[bool, str] = False,
- ) -> list:
- return [
- [
- *(
- [
- {
- "text": f"❌ {self.strings('set')} `False`",
- "callback": self.inline__set_bool,
- "args": (mod, option, False),
- "kwargs": {"obj_type": obj_type},
- }
- ]
- if self.lookup(mod).config[option]
- else [
- {
- "text": f"✅ {self.strings('set')} `True`",
- "callback": self.inline__set_bool,
- "args": (mod, option, True),
- "kwargs": {"obj_type": obj_type},
- }
- ]
- )
- ],
- [
- *(
- [
- {
- "text": self.strings("set_default_btn"),
- "callback": self.inline__reset_default,
- "args": (mod, option),
- "kwargs": {"obj_type": obj_type},
- }
- ]
- if self.lookup(mod).config[option]
- != self.lookup(mod).config.getdef(option)
- else []
- )
- ],
- [
- {
- "text": self.strings("back_btn"),
- "callback": self.inline__configure,
- "args": (mod,),
- "kwargs": {"obj_type": obj_type},
- },
- {"text": self.strings("close_btn"), "action": "close"},
- ],
- ]
- async def inline__add_item(
- self,
- call: InlineCall,
- query: str,
- mod: str,
- option: str,
- inline_message_id: str,
- obj_type: Union[bool, str] = False,
- ):
- try:
- 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]),
- reply_markup={
- "text": self.strings("try_again"),
- "callback": self.inline__configure_option,
- "args": (mod, option),
- "kwargs": {"obj_type": obj_type},
- },
- )
- return
- await call.edit(
- self.strings(
- "option_saved" if isinstance(obj_type, bool) else "option_saved_lib"
- ).format(
- utils.escape_html(option),
- utils.escape_html(mod),
- self.prep_value(self.lookup(mod).config[option])
- if not self.lookup(mod).config._config[option].validator
- or self.lookup(mod).config._config[option].validator.internal_id
- != "Hidden"
- else self.hide_value(self.lookup(mod).config[option]),
- ),
- reply_markup=[
- [
- {
- "text": self.strings("back_btn"),
- "callback": self.inline__configure,
- "args": (mod,),
- "kwargs": {"obj_type": obj_type},
- },
- {"text": self.strings("close_btn"), "action": "close"},
- ]
- ],
- inline_message_id=inline_message_id,
- )
- async def inline__remove_item(
- self,
- call: InlineCall,
- query: str,
- mod: str,
- option: str,
- inline_message_id: str,
- obj_type: Union[bool, str] = False,
- ):
- try:
- 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))
- old_config_len = len(self.lookup(mod).config[option])
- self.lookup(mod).config[option] = [
- i for i in self.lookup(mod).config[option] if str(i) not in query
- ]
- if old_config_len == len(self.lookup(mod).config[option]):
- raise loader.validators.ValidationError(
- f"Nothing from passed value ({self.prep_value(query)}) is not in"
- " target list"
- )
- except loader.validators.ValidationError as e:
- await call.edit(
- self.strings("validation_error").format(e.args[0]),
- reply_markup={
- "text": self.strings("try_again"),
- "callback": self.inline__configure_option,
- "args": (mod, option),
- "kwargs": {"obj_type": obj_type},
- },
- )
- return
- await call.edit(
- self.strings(
- "option_saved" if isinstance(obj_type, bool) else "option_saved_lib"
- ).format(
- utils.escape_html(option),
- utils.escape_html(mod),
- self.prep_value(self.lookup(mod).config[option])
- if not self.lookup(mod).config._config[option].validator
- or self.lookup(mod).config._config[option].validator.internal_id
- != "Hidden"
- else self.hide_value(self.lookup(mod).config[option]),
- ),
- reply_markup=[
- [
- {
- "text": self.strings("back_btn"),
- "callback": self.inline__configure,
- "args": (mod,),
- "kwargs": {"obj_type": obj_type},
- },
- {"text": self.strings("close_btn"), "action": "close"},
- ]
- ],
- inline_message_id=inline_message_id,
- )
- def _generate_series_markup(
- self,
- call: InlineCall,
- mod: str,
- option: str,
- obj_type: Union[bool, str] = False,
- ) -> list:
- return [
- [
- {
- "text": self.strings("enter_value_btn"),
- "input": self.strings("enter_value_desc"),
- "handler": self.inline__set_config,
- "args": (mod, option, call.inline_message_id),
- "kwargs": {"obj_type": obj_type},
- }
- ],
- [
- *(
- [
- {
- "text": self.strings("remove_item_btn"),
- "input": self.strings("remove_item_desc"),
- "handler": self.inline__remove_item,
- "args": (mod, option, call.inline_message_id),
- "kwargs": {"obj_type": obj_type},
- },
- {
- "text": self.strings("add_item_btn"),
- "input": self.strings("add_item_desc"),
- "handler": self.inline__add_item,
- "args": (mod, option, call.inline_message_id),
- "kwargs": {"obj_type": obj_type},
- },
- ]
- if self.lookup(mod).config[option]
- else []
- ),
- ],
- [
- *(
- [
- {
- "text": self.strings("set_default_btn"),
- "callback": self.inline__reset_default,
- "args": (mod, option),
- "kwargs": {"obj_type": obj_type},
- }
- ]
- if self.lookup(mod).config[option]
- != self.lookup(mod).config.getdef(option)
- else []
- )
- ],
- [
- {
- "text": self.strings("back_btn"),
- "callback": self.inline__configure,
- "args": (mod,),
- "kwargs": {"obj_type": obj_type},
- },
- {"text": self.strings("close_btn"), "action": "close"},
- ],
- ]
- async def _choice_set_value(
- self,
- call: InlineCall,
- mod: str,
- option: str,
- value: bool,
- obj_type: Union[bool, str] = False,
- ):
- try:
- self.lookup(mod).config[option] = value
- except loader.validators.ValidationError as e:
- await call.edit(
- self.strings("validation_error").format(e.args[0]),
- reply_markup={
- "text": self.strings("try_again"),
- "callback": self.inline__configure_option,
- "args": (mod, option),
- "kwargs": {"obj_type": obj_type},
- },
- )
- return
- validator = self.lookup(mod).config._config[option].validator
- doc = utils.escape_html(
- next(
- (
- validator.doc[lang]
- for lang in self._db.get(translations.__name__, "lang", "en").split(
- " "
- )
- if lang in validator.doc
- ),
- validator.doc["en"],
- )
- )
- await call.edit(
- self.strings(
- "option_saved" if isinstance(obj_type, bool) else "option_saved_lib"
- ).format(
- utils.escape_html(option),
- utils.escape_html(mod),
- self.prep_value(self.lookup(mod).config[option])
- if not validator.internal_id == "Hidden"
- else self.hide_value(self.lookup(mod).config[option]),
- ),
- reply_markup=[
- [
- {
- "text": self.strings("back_btn"),
- "callback": self.inline__configure,
- "args": (mod,),
- "kwargs": {"obj_type": obj_type},
- },
- {"text": self.strings("close_btn"), "action": "close"},
- ]
- ],
- )
- await call.answer("✅")
- def _generate_choice_markup(
- self,
- call: InlineCall,
- mod: str,
- option: str,
- obj_type: Union[bool, str] = False,
- ) -> list:
- possible_values = list(
- self.lookup(mod)
- .config._config[option]
- .validator.validate.keywords["possible_values"]
- )
- return [
- [
- {
- "text": self.strings("enter_value_btn"),
- "input": self.strings("enter_value_desc"),
- "handler": self.inline__set_config,
- "args": (mod, option, call.inline_message_id),
- "kwargs": {"obj_type": obj_type},
- }
- ],
- *utils.chunks(
- [
- {
- "text": (
- f"{'☑️' if self.lookup(mod).config[option] == value else '🔘'} "
- f"{value if len(str(value)) < 20 else str(value)[:20]}"
- ),
- "callback": self._choice_set_value,
- "args": (mod, option, value, obj_type),
- }
- for value in possible_values
- ],
- 2,
- )[:6],
- [
- *(
- [
- {
- "text": self.strings("set_default_btn"),
- "callback": self.inline__reset_default,
- "args": (mod, option),
- "kwargs": {"obj_type": obj_type},
- }
- ]
- if self.lookup(mod).config[option]
- != self.lookup(mod).config.getdef(option)
- else []
- )
- ],
- [
- {
- "text": self.strings("back_btn"),
- "callback": self.inline__configure,
- "args": (mod,),
- "kwargs": {"obj_type": obj_type},
- },
- {"text": self.strings("close_btn"), "action": "close"},
- ],
- ]
- async def inline__configure_option(
- self,
- call: InlineCall,
- mod: str,
- config_opt: str,
- force_hidden: Optional[bool] = False,
- obj_type: Union[bool, str] = False,
- ):
- module = self.lookup(mod)
- args = [
- utils.escape_html(config_opt),
- utils.escape_html(mod),
- utils.escape_html(module.config.getdoc(config_opt)),
- self.prep_value(module.config.getdef(config_opt)),
- self.prep_value(module.config[config_opt])
- if not module.config._config[config_opt].validator
- or module.config._config[config_opt].validator.internal_id != "Hidden"
- or force_hidden
- else self.hide_value(module.config[config_opt]),
- ]
- if (
- module.config._config[config_opt].validator
- and module.config._config[config_opt].validator.internal_id == "Hidden"
- ):
- additonal_button_row = (
- [
- [
- {
- "text": self.strings("hide_value"),
- "callback": self.inline__configure_option,
- "args": (mod, config_opt, False),
- "kwargs": {"obj_type": obj_type},
- }
- ]
- ]
- if force_hidden
- else [
- [
- {
- "text": self.strings("show_hidden"),
- "callback": self.inline__configure_option,
- "args": (mod, config_opt, True),
- "kwargs": {"obj_type": obj_type},
- }
- ]
- ]
- )
- else:
- additonal_button_row = []
- try:
- validator = module.config._config[config_opt].validator
- doc = utils.escape_html(
- next(
- (
- validator.doc[lang]
- for lang in self._db.get(
- translations.__name__, "lang", "en"
- ).split(" ")
- if lang in validator.doc
- ),
- validator.doc["en"],
- )
- )
- except Exception:
- doc = None
- validator = None
- args += [""]
- else:
- args += [
- self.strings("typehint").format(
- doc,
- eng_art="n" if doc.lower().startswith(tuple("euioay")) else "",
- )
- ]
- if validator.internal_id == "Boolean":
- await call.edit(
- self.strings(
- "configuring_option"
- if isinstance(obj_type, bool)
- else "configuring_option_lib"
- ).format(*args),
- reply_markup=additonal_button_row
- + self._generate_bool_markup(mod, config_opt, obj_type),
- )
- return
- if validator.internal_id == "Series":
- await call.edit(
- self.strings(
- "configuring_option"
- if isinstance(obj_type, bool)
- else "configuring_option_lib"
- ).format(*args),
- reply_markup=additonal_button_row
- + self._generate_series_markup(call, mod, config_opt, obj_type),
- )
- return
- if validator.internal_id == "Choice":
- await call.edit(
- self.strings(
- "configuring_option"
- if isinstance(obj_type, bool)
- else "configuring_option_lib"
- ).format(*args),
- reply_markup=additonal_button_row
- + self._generate_choice_markup(call, mod, config_opt, obj_type),
- )
- return
- await call.edit(
- self.strings(
- "configuring_option"
- if isinstance(obj_type, bool)
- else "configuring_option_lib"
- ).format(*args),
- reply_markup=additonal_button_row
- + [
- [
- {
- "text": self.strings("enter_value_btn"),
- "input": self.strings("enter_value_desc"),
- "handler": self.inline__set_config,
- "args": (mod, config_opt, call.inline_message_id),
- "kwargs": {"obj_type": obj_type},
- }
- ],
- [
- {
- "text": self.strings("set_default_btn"),
- "callback": self.inline__reset_default,
- "args": (mod, config_opt),
- "kwargs": {"obj_type": obj_type},
- }
- ],
- [
- {
- "text": self.strings("back_btn"),
- "callback": self.inline__configure,
- "args": (mod,),
- "kwargs": {"obj_type": obj_type},
- },
- {"text": self.strings("close_btn"), "action": "close"},
- ],
- ],
- )
- async def inline__configure(
- self,
- call: InlineCall,
- mod: str,
- obj_type: Union[bool, str] = False,
- ):
- btns = [
- {
- "text": param,
- "callback": self.inline__configure_option,
- "args": (mod, param),
- "kwargs": {"obj_type": obj_type},
- }
- for param in self.lookup(mod).config
- ]
- await call.edit(
- self.strings(
- "configuring_mod" if isinstance(obj_type, bool) else "configuring_lib"
- ).format(
- utils.escape_html(mod),
- "\n".join(
- [
- f"▫️ <code>{utils.escape_html(key)}</code>:"
- f" <b>{self.prep_value(value) if not self.lookup(mod).config._config[key].validator or self.lookup(mod).config._config[key].validator.internal_id != 'Hidden' else self.hide_value(value)}</b>"
- for key, value in self.lookup(mod).config.items()
- ]
- ),
- ),
- reply_markup=list(utils.chunks(btns, 2))
- + [
- [
- {
- "text": self.strings("back_btn"),
- "callback": self.inline__global_config,
- "kwargs": {"obj_type": obj_type},
- },
- {"text": self.strings("close_btn"), "action": "close"},
- ]
- ],
- )
- async def inline__choose_category(self, call: Union[Message, InlineCall]):
- await utils.answer(
- call,
- self.strings("choose_core"),
- reply_markup=[
- [
- {
- "text": self.strings("builtin"),
- "callback": self.inline__global_config,
- "kwargs": {"obj_type": True},
- },
- {
- "text": self.strings("external"),
- "callback": self.inline__global_config,
- },
- ],
- *(
- [
- [
- {
- "text": self.strings("libraries"),
- "callback": self.inline__global_config,
- "kwargs": {"obj_type": "library"},
- }
- ]
- ]
- if self.allmodules.libraries
- and any(hasattr(lib, "config") for lib in self.allmodules.libraries)
- else []
- ),
- [{"text": self.strings("close_btn"), "action": "close"}],
- ],
- )
- async def inline__global_config(
- self,
- call: InlineCall,
- page: int = 0,
- obj_type: Union[bool, str] = False,
- ):
- if isinstance(obj_type, bool):
- to_config = [
- mod.strings("name")
- for mod in self.allmodules.modules
- if hasattr(mod, "config")
- and callable(mod.strings)
- and (getattr(mod, "__origin__", None) == "<core>" or not obj_type)
- and (getattr(mod, "__origin__", None) != "<core>" or obj_type)
- ]
- else:
- to_config = [
- lib.name for lib in self.allmodules.libraries if hasattr(lib, "config")
- ]
- to_config.sort()
- kb = []
- for mod_row in utils.chunks(
- to_config[
- page
- * self._num_rows
- * self._row_size : (page + 1)
- * self._num_rows
- * self._row_size
- ],
- 3,
- ):
- row = [
- {
- "text": btn,
- "callback": self.inline__configure,
- "args": (btn,),
- "kwargs": {"obj_type": obj_type},
- }
- for btn in mod_row
- ]
- kb += [row]
- if len(to_config) > self._num_rows * self._row_size:
- kb += self.inline.build_pagination(
- callback=functools.partial(
- self.inline__global_config, obj_type=obj_type
- ),
- total_pages=ceil(len(to_config) / (self._num_rows * self._row_size)),
- current_page=page + 1,
- )
- kb += [
- [
- {
- "text": self.strings("back_btn"),
- "callback": self.inline__choose_category,
- },
- {"text": self.strings("close_btn"), "action": "close"},
- ]
- ]
- await call.edit(
- self.strings(
- "configure" if isinstance(obj_type, bool) else "configure_lib"
- ),
- reply_markup=kb,
- )
- @loader.command(ru_doc="Настроить модули")
- async def configcmd(self, message: Message):
- """Configure modules"""
- args = utils.get_args_raw(message)
- if self.lookup(args) and hasattr(self.lookup(args), "config"):
- form = await self.inline.form("🌘 <b>Loading configuration</b>", message)
- mod = self.lookup(args)
- if isinstance(mod, loader.Library):
- type_ = "library"
- else:
- type_ = getattr(mod, "__origin__", None) == "<core>"
- await self.inline__configure(form, args, obj_type=type_)
- return
- await self.inline__choose_category(message)
- @loader.command(
- ru_doc=(
- "<модуль> <настройка> <значениеЮ - установить значение конфига для модуля"
- )
- )
- async def fconfig(self, message: Message):
- """<module_name> <property_name> <config_value> - set the config value for the module"""
- args = utils.get_args_raw(message).split(maxsplit=2)
- if len(args) < 3:
- await utils.answer(message, self.strings("args"))
- return
- mod, option, value = args
- instance = self.lookup(mod)
- if not instance:
- await utils.answer(message, self.strings("no_mod"))
- return
- if option not in instance.config:
- await utils.answer(message, self.strings("no_option"))
- return
- instance.config[option] = value
- await utils.answer(
- message,
- self.strings(
- "option_saved"
- if isinstance(instance, loader.Module)
- else "option_saved_lib"
- ).format(
- utils.escape_html(option),
- utils.escape_html(mod),
- self.prep_value(instance.config[option])
- if not instance.config._config[option].validator
- or instance.config._config[option].validator.internal_id != "Hidden"
- else self.hide_value(instance.config[option]),
- ),
- )
|