From dd313df63dc6f977a4a90dc8dd541f2a09a11050 Mon Sep 17 00:00:00 2001 From: "hikari.ftg" Date: Tue, 22 Mar 2022 13:09:00 +0000 Subject: [PATCH] Update utils list, add geek compat layer --- .dockerignore | 157 ++++++++++++++++++++++++++++++++++++++++ docs/mods.md | 25 ++++++- hikka/compat/geek.py | 7 ++ hikka/modules/loader.py | 3 + hikka/utils.py | 52 ++++++++++++- run | 6 ++ 6 files changed, 245 insertions(+), 5 deletions(-) create mode 100644 .dockerignore create mode 100644 hikka/compat/geek.py create mode 100644 run diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3432d64 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,157 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + + +*__pycache__ +*.pyc +hikka/api_token.py +hikka/loaded_modules +hikka*.session* +database-*.json +*.swp +.setup_complete +.tox +.idea/ +venv/ +data/ +api_token.txt +.coverage +.vscode/ +ftg-install.log +config.ini +.cache +config-*.json +config.json +*cache*.json +*.png +*.jpg +*.jpeg +*.webp +*.webm \ No newline at end of file diff --git a/docs/mods.md b/docs/mods.md index 1e16a1f..61a7a5e 100755 --- a/docs/mods.md +++ b/docs/mods.md @@ -113,22 +113,41 @@ relocate_entities(entities: ListLike, offset: int, text: str = None) -> list ``` --- -Один из самых частоиспользуемых методов. Отвечает на заданное сообщение. Если оно отправлено, то редактирует, если получено, то отвечает. +Answer to a message (edit if possible, else send new message) ```python answer(message: Message, response: str, *args, **kwargs) -> Many ``` --- -Получает идентификатор пользователя, который является потенциальной целью выполнения команды +Get possible target id ```python get_target(message: Message, arg_no: int = 0) -> int or None ``` --- -Объединение двух словарей +Merge two dictionaries ```python merge(a: dict, b: dict) -> dict ``` +--- + +Create new channel (if needed) and return its entity +```python +asset_channel(a: dict, b: dict) -> dict +``` +--- + +Get telegram permalink to entity +```python +get_link(a: dict, b: dict) -> dict +``` +--- + +Split provided `_list` into chunks of `n` +```python +chunks(a: dict, b: dict) -> dict +``` + ## strings diff --git a/hikka/compat/geek.py b/hikka/compat/geek.py new file mode 100644 index 0000000..2aa0316 --- /dev/null +++ b/hikka/compat/geek.py @@ -0,0 +1,7 @@ + + +def compat(code: str) -> str: + """Reformats modules, built for GeekTG to work with Hikka""" + code = code.replace("GeekInlineQuery", "InlineQuery") + + return code diff --git a/hikka/modules/loader.py b/hikka/modules/loader.py index 5ce875c..b3781cb 100755 --- a/hikka/modules/loader.py +++ b/hikka/modules/loader.py @@ -31,6 +31,7 @@ from telethon.tl.types import Message import requests from .. import loader, utils, main +from ..compat import geek logger = logging.getLogger(__name__) @@ -336,6 +337,8 @@ class LoaderMod(loader.Module): module_name = "hikka.modules." + uid + doc = geek.compat(doc) + try: try: spec = ModuleSpec(module_name, StringLoader(doc, origin), origin=origin) diff --git a/hikka/utils.py b/hikka/utils.py index 244a842..45f409d 100755 --- a/hikka/utils.py +++ b/hikka/utils.py @@ -32,8 +32,13 @@ from telethon.tl.types import ( MessageEntityMentionName, User, MessageMediaWebPage, + Channel, ) +from typing import Tuple + +from telethon.tl.functions.channels import CreateChannelRequest + from . import __main__ @@ -218,7 +223,7 @@ async def answer(message, response, **kwargs): if not edit: kwargs.setdefault( "reply_to", - getattr(message, 'reply_to_msg_id', None), + getattr(message, "reply_to_msg_id", None), ) parse_mode = telethon.utils.sanitize_parse_mode( @@ -278,7 +283,7 @@ async def answer(message, response, **kwargs): else: kwargs.setdefault( "reply_to", - getattr(message, 'reply_to_msg_id', None), + getattr(message, "reply_to_msg_id", None), ) ret = (await message.client.send_file(message.chat_id, response, **kwargs),) @@ -330,3 +335,46 @@ def merge(a, b): b[key] = a[key] return b + + +async def asset_channel( + client: "TelegramClient", title: str, description: str # noqa: F821 +) -> Tuple[Channel, bool]: + """ + Create new channel (if needed) and return its entity + @client: Telegram client to create channel by + @title: Channel title + @description: Description + Returns peer and bool: is channel new or pre-existent + """ + async for d in client.iter_dialogs(): + if d.title == "acc-switcher-db": + return d.entity, False + + return ( + await client( + CreateChannelRequest( + "acc-switcher-db", + "This chat will handle your saved account via AccountSwitcher Module", + megagroup=True, + ) + ) + ).chats[0], True + + +def get_link(user: User or Channel) -> str: + """Get telegram permalink to entity""" + return ( + f"tg://user?id={user.id}" + if isinstance(user, User) + else ( + f"tg://resolve?domain={user.username}" + if getattr(user, "username", None) + else "" + ) + ) + + +def chunks(_list: list, n: int) -> list: + """Split provided `_list` into chunks of `n`""" + return [_list[i : i + n] for i in range(0, len(_list), n)] diff --git a/run b/run new file mode 100644 index 0000000..617164d --- /dev/null +++ b/run @@ -0,0 +1,6 @@ +echo " + █ █ █ █▄▀ █▄▀ ▄▀█ + █▀█ █ █ █ █ █ █▀█ + Is starting... +" +python3 -m hikka --root \ No newline at end of file