__version__ = (9, 4, 1)
# meta developer: @NFModules
# meta pic: https://raw.githubusercontent.com/Fixyres/FModules/refs/heads/main/assets/FHeta/logo.png
# meta banner: https://raw.githubusercontent.com/Fixyres/FModules/refs/heads/main/assets/FHeta/logo.png
# scope: hikka_min 2.1.0
# ©️ Fixyres, 2024-2030
# 🌐 https://github.com/Fixyres/FModules
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 🔑 http://www.apache.org/licenses/LICENSE-2.0
import asyncio
import aiohttp
import base64
import re
import uuid
import inspect
import logging
from typing import Optional, Dict, List, Union, Tuple, Any
from urllib.parse import unquote
import telethon
from .. import loader, utils
from herokutl.tl.functions.contacts import UnblockRequest
class FHetaAPI:
def __init__(self) -> None:
self.token: Optional[str] = None
self.session: Optional[aiohttp.ClientSession] = None
async def connect(self) -> aiohttp.ClientSession:
if self.session is None or self.session.closed:
self.session = aiohttp.ClientSession()
return self.session
async def fetch(self, path: str, **params: Any) -> Dict[str, Any]:
session = await self.connect()
try:
async with session.get(
f"https://api.fixyres.com/{path}",
params=params,
headers={"Authorization": self.token},
timeout=aiohttp.ClientTimeout(total=10)
) as response:
if response.status == 200:
return await response.json()
return {}
except Exception:
return {}
async def send(self, path: str, payload: Optional[Dict[str, Any]] = None, **params: Any) -> Dict[str, Any]:
session = await self.connect()
try:
async with session.post(
f"https://api.fixyres.com/{path}",
json=payload,
params=params,
headers={"Authorization": self.token},
timeout=aiohttp.ClientTimeout(total=10)
) as response:
if response.status == 200:
return await response.json()
return {}
except Exception:
return {}
class FHetaUI:
def __init__(self, main: 'FHeta') -> None:
self.main = main
def emoji(self, key: str) -> str:
return self.main.THEMES[self.main.config["theme"]][key]
def format(self, data: Dict[str, Any], query: str = "", index: int = 1, total: int = 1, inline: bool = False) -> str:
version = data.get("version", "?.?.?")
limit = 3700
name = utils.escape_html(data.get("name", ""))
author = utils.escape_html(data.get("author", "???"))
text = f"{self.emoji('module')} {name} {self.main.strings['author']} {author}"
if version != "?.?.?":
text += f" (v{version})"
description = data.get("description")
if description:
if isinstance(description, dict):
string = description.get(self.main.strings["lang"]) or description.get("doc") or next(iter(description.values()), "")
else:
string = description
text += f"\n\n{self.emoji('description')} {self.main.strings['description']}:\n
{utils.escape_html(str(string))}" text += self.render(data.get("commands", []), "cmd", limit - len(re.sub(r'<[^>]+>', '', text))) text += self.render(data.get("placeholders", []), "ph", limit - len(re.sub(r'<[^>]+>', '', text))) return text def render(self, items: List[Dict[str, Any]], kind: str, limit: int) -> str: if not items: return "" lines = [] language = self.main.strings["lang"] title = "commands" if kind == "cmd" else "placeholders" more = "morecommands" if kind == "cmd" else "moreplaceholders" for index, item in enumerate(items): description = item.get("description", {}) if isinstance(description, dict): description = description.get(language) or description.get("doc") or "" description = utils.escape_html(description).split('\n')[0] if description else "" name = utils.escape_html(item.get("name", "")) if item.get('inline'): character = '@' + self.main.inline.bot_username + ' ' display_name = name elif kind == "ph": character = "" display_name = f"{{{name}}}" else: character = self.main.get_prefix() display_name = name row = f"
{character}{display_name} {description}".strip()
extra = f"{self.main.strings[more].format(remaining=len(items) - index)}"
test = "\n".join(lines + [row, extra])
if len(re.sub(r'<[^>]+>', '', test)) > limit and index > 0:
lines.append(extra)
break
lines.append(row)
return f"\n\n{self.emoji('command' if kind == 'cmd' else 'placeholder')} {self.main.strings[title]}:\n{chr(10).join(lines)}" def buttons(self, link: str, stats: Dict[str, Any], index: int, modules: Optional[List[Dict[str, Any]]] = None, query: str = "") -> List[List[Dict[str, Any]]]: buttons = [] decoded = unquote(link.replace('%20', '___SPACE___')).replace('___SPACE___', '%20') url = decoded[4:] if decoded.startswith('dlm ') else decoded if query: buttons.append([ {"text": self.main.strings["query"], "copy": query}, {"text": self.main.strings["install"], "callback": self.main.install, "args": (url, index, modules, query)}, {"text": self.main.strings["code"], "url": url} ]) buttons.append([ {"text": f"↑ {stats.get('likes', 0)}", "callback": self.main.rate, "args": (link, "like", index, modules, query)}, {"text": f"↓ {stats.get('dislikes', 0)}", "callback": self.main.rate, "args": (link, "dislike", index, modules, query)} ]) if modules and len(modules) > 1: count = {"text": self.main.strings["counter"].format(idx=index+1, total=len(modules)), "callback": self.main.show, "args": (index, modules, query)} buttons[-1].insert(1, count) navigation = [] if index > 0: navigation.append({"text": "←", "callback": self.main.navigate, "args": (index - 1, modules, query)}) if index < len(modules) - 1: navigation.append({"text": "→", "callback": self.main.navigate, "args": (index + 1, modules, query)}) if navigation: buttons.append(navigation) return buttons def pagination(self, modules: List[Dict[str, Any]], query: str, page: int = 0, current: int = 0) -> List[List[Dict[str, Any]]]: buttons = [] start = page * 8 end = min(start + 8, len(modules)) for index in range(start, end): name = modules[index].get('name', 'Unknown') author = modules[index].get('author', '???') buttons.append([ {"text": f"{index + 1}. {name} by {author}", "callback": self.main.navigate, "args": (index, modules, query)} ]) navigation = [] if page > 0: navigation.append({"text": "←", "callback": self.main.page, "args": (page - 1, modules, query, current)}) if page < (len(modules) + 7) // 8 - 1: navigation.append({"text": "→", "callback": self.main.page, "args": (page + 1, modules, query, current)}) if navigation: buttons.append(navigation) buttons.append([{"text": "✘", "callback": self.main.navigate, "args": (current, modules, query)}]) return buttons @loader.tds class FHeta(loader.Module): '''Module for searching modules! Watch all FHeta news in @NFHeta_Updates!''' strings = { "name": "FHeta", "lang": "en", "author": "by", "description": "Description", "commands": "Commands", "placeholders": "Placeholders", "morecommands": "...and {remaining} more commands.", "moreplaceholders": "...and {remaining} more placeholders.", "list": "All found modules:", "search": "Searching for {query}...", "noquery": "You didn't enter a search query, example: {prefix}fheta your query", "notfound": "Nothing found for query {query}.", "toolong": "Your query is too big, please try reducing it to 168 characters.", "added": "✔ Rating submitted!", "changed": "✔ Rating has been changed!", "deleted": "✔ Rating deleted!", "prompt": "Enter a query to search.", "hint": "Name, command, description, author.", "retry": "Try another query.", "query": "Query", "install": "Install", "counter": "{idx}/{total}", "code": "Code", "success": "✔ Module successfully installed!", "error": "✘ Error, perhaps the module is broken!", "overwrite": "✘ Error, module tried to overwrite built-in module!", "dependency": "✘ Dependencies installation error!", "docdevs": "Use only modules from official Heroku developers when searching?", "doctheme": "Theme for emojis.", "channel": "This is the channel with all updates in FHeta!", "install_via_fheta": "Enable Install via FHeta?" } strings_ru = { "_cls_doc": "Модуль для поиска модулей! Следите за всеми новостями FHeta в @NFHeta_Updates!", "lang": "ru", "author": "от", "description": "Описание", "commands": "Команды", "placeholders": "Плейсхолдеры", "morecommands": "...и еще {remaining} команд.", "moreplaceholders": "...и еще {remaining} плейсхолдеров.", "list": "Все найденные модули:", "search": "Поиск по запросу {query}...", "noquery": "Вы не ввели запрос для поиска, пример: {prefix}fheta ваш запрос", "notfound": "Ничего не найдено по запросу {query}.", "toolong": "Ваш запрос слишком большой, пожалуйста, сократите его до 168 символов.", "added": "✔ Оценка добавлена!", "changed": "✔ Оценка изменена!", "deleted": "✔ Оценка удалена!", "prompt": "Введите запрос для поиска.", "hint": "Название, команда, описание, автор.", "retry": "Попробуйте другой запрос.", "query": "Запрос", "install": "Установить", "counter": "{idx}/{total}", "code": "Код", "success": "✔ Модуль успешно установлен!", "error": "✘ Ошибка, возможно, модуль сломан!", "overwrite": "✘ Ошибка, модуль пытался перезаписать встроенный модуль!", "dependency": "✘ Ошибка установки зависимостей!", "docdevs": "Использовать только модули от официальных разработчиков Heroku при поиске?", "doctheme": "Тема для эмодзи.", "channel": "Это канал со всеми обновлениями в FHeta!", "install_via_fheta": "Включить Install via FHeta?" } strings_ua = { "_cls_doc": "Модуль для пошуку модулів! Слідкуйте за всіма новинами FHeta в @NFHeta_Updates!", "lang": "ua", "author": "від", "description": "Опис", "commands": "Команды", "placeholders": "Плейсхолдери", "morecommands": "...і ще {remaining} команд.", "moreplaceholders": "...і ще {remaining} плейсхолдерів.", "list": "Всі знайдені модули:", "search": "Пошук за запитом {query}...", "noquery": "Ви не ввели запит для пошуку, приклад: {prefix}fheta ваш запит", "notfound": "Нічого не знайдено за запитом {query}.", "toolong": "Ваш запит занадто великий, будь ласка, скоротіть його до 168 символів.", "added": "✔ Оцінку додано!", "changed": "✔ Оцінку змінено!", "deleted": "✔ Оцінку видалено!", "prompt": "Введіть запит для пошуку.", "hint": "Назва, команда, опис, автор.", "retry": "Спробуйте інший запит.", "query": "Запит", "install": "Встановити", "counter": "{idx}/{total}", "code": "Код", "success": "✔ Модуль успішно встановлено!", "error": "✘ Помилка, можливо, модуль поламаний!", "overwrite": "✘ Помилка, модуль намагався перезаписати вбудований модуль!", "dependency": "✘ Помилка встановлення залежностей!", "docdevs": "Використовувати тільки модулі від офіційних розробників Heroku при пошуку?", "doctheme": "Тема для емодзі.", "channel": "Це канал з усіма оновленнями в FHeta!", "install_via_fheta": "Увімкнути Install via FHeta?" } strings_kz = { "_cls_doc": "Модульдерді іздеу модулі! FHeta барлық жаңалықтарын @NFHeta_Updates арнасында қадағалаңыз!", "lang": "kz", "author": "авторы", "description": "Сипаттама", "commands": "Командалар", "placeholders": "Плейсхолдерлер", "morecommands": "...және тағы {remaining} команда.", "moreplaceholders": "...және тағы {remaining} плейсхолдер.", "list": "Барлық табылған модульдер:", "search": "{query} сұрауы бойынша іздеу...", "noquery": "Сіз іздеу сұрауын енгізбедіңіз, мысал: {prefix}fheta сіздің сұрауыңыз", "notfound": "{query} сұрауы бойынша ештеңе табылмады.", "toolong": "Сіздің сұрауыңыз тым үлкен, оны 168 таңбаға до қысқартыңыз.", "added": "✔ Бағалау қосылды!", "changed": "✔ Бағалау өзгертілді!", "deleted": "✔ Бағалау жойылды!", "prompt": "Іздеу үшін сұрау енгізіңіз.", "hint": "Атауы, команда, сипаттама, автор.", "retry": "Басқа сұрауды қолданып көріңіз.", "query": "Сұрау", "install": "Орнату", "counter": "{idx}/{total}", "code": "Код", "success": "✔ Модуль сәтті орнатылды!", "error": "✘ Қате, мүмкін модуль бұзылған!", "overwrite": "✘ Қате, модуль кіріктірілген модульді қайта жазуға тырысты!", "dependency": "✘ Тәуелділіктерді орнату қатесі!", "docdevs": "Іздеу кезінде тек ресми Heroku әзірлеушілерінің модульдерін пайдалану керек пе?", "doctheme": "Эмодзилер үшін тақырып.", "channel": "Бұл FHeta-дағы барлық жаңартулары бар арна!", "install_via_fheta": "Install via FHeta қосу керек пе?" } strings_uz = { "_cls_doc": "Modullarni qidirish moduli! FHeta barcha yangilanishlarini @NFHeta_Updates kanalida kuzatib boring!", "lang": "uz", "author": "muallif", "description": "Tavsif", "commands": "Buyruqlar", "placeholders": "Pleysholderlar", "morecommands": "...va yana {remaining} ta buyruq.", "moreplaceholders": "...va yana {remaining} ta pleysholder.", "list": "Barcha topilgan modullar:", "search": "{query} so'rovi bo'yicha qidiruv...", "noquery": "Siz qidiruv so'rovini kiritmadingiz, misol: {prefix}fheta sizning sorovingiz", "notfound": "{query} so'rovi bo'yicha hech narsa topilmadi.", "toolong": "Sizning so'rovingiz juda katta, iltimos uni 168 belgigacha qisqartiring.", "added": "✔ Reyting qo'shildi!", "changed": "✔ Reyting o'zgartirildi!", "deleted": "✔ Reyting o'chirildi!", "prompt": "Qidirish o'rniga so'rov kiritish.", "hint": "Nomi, buyruq, tavsif, muallif.", "retry": "Boshqa so'rovni sinab ko'ring.", "query": "So'rov", "install": "O'rnatish", "counter": "{idx}/{total}", "code": "Kod", "success": "✔ Modul muvaffaqiyatli o'rnatildi!", "error": "✘ Xatolik, ehtimol modul buzilgan!", "overwrite": "✘ Xatolik, modul o'rnatilgan modulni qayta yozishga harakat qildi!", "dependency": "✘ Bog'liqliklarni o'rnatish xatosi!", "docdevs": "Qidiruv paytida faqat rasmiy Heroku ishlab chiquvchilarining modullaridan foydalanish kerakmi?", "doctheme": "Emojilar uchun mavзу.", "channel": "Bu FHeta-dagi barcha yangilanishlari bo'lgan kanal!", "install_via_fheta": "Install via FHeta yoqilsinmi?" } strings_fr = { "_cls_doc": "Module de recherche de modules! Suivez toutes les actualités FHeta sur @NFHeta_Updates!", "lang": "fr", "author": "par", "description": "Description", "commands": "Commandes", "placeholders": "Espaces réservés", "morecommands": "...et {remaining} commandes supplémentaires.", "moreplaceholders": "...et {remaining} espaces réservés supplémentaires.", "list": "Tous les modules trouvés:", "search": "Recherche pour {query}...", "noquery": "Vous n'avez pas entré de requête de recherche, exemple: {prefix}fheta votre requête", "notfound": "Rien trouvé for query {query}.", "toolong": "Votre requête est too long, please try reducing it to 168 characters.", "added": "✔ Note ajoutée!", "changed": "✔ Note modifiée!", "deleted": "✔ Note supprimée!", "prompt": "Entrez une requête pour rechercher.", "hint": "Nom, commande, description, auteur.", "retry": "Essayez une autre requête.", "query": "Requête", "install": "Installer", "counter": "{idx}/{total}", "code": "Code", "success": "✔ Module installé com succès!", "error": "✘ Erreur, le module est peut-être cassé!", "overwrite": "✘ Erreur, le module a tenté d'écraser le module intégré!", "dependency": "✘ Erreur d'installation des dépendances!", "docdevs": "Utiliser uniquement les modules des développeurs Heroku officiels lors de la recherche?", "doctheme": "Thème pour les emojis.", "channel": "Voici le canal avec toutes les mises à jour dans FHeta!", "install_via_fheta": "Activer Install via FHeta ?" } strings_de = { "_cls_doc": "Modul zur Suche nach Modulen! Verfolgen Sie alle FHeta-Neuigkeiten auf @NFHeta_Updates!", "lang": "de", "author": "von", "description": "Beschreibung", "commands": "Befehle", "placeholders": "Platzhalter", "morecommands": "...und {remaining} weitere Befehle.", "moreplaceholders": "...und {remaining} weitere Platzhalter.", "list": "Alle gefundenen Module:", "search": "Suche nach {query}...", "noquery": "Sie haben keine Suchanfrage eingegeben, Beispiel: {prefix}fheta ihre anfrage", "notfound": "Nichts gefunden für Anfrage {query}.", "toolong": "Ihre Anfrage ist zu groß, bitte reduzieren Sie sie auf 168 Zeichen.", "added": "✔ Bewertung hinzugefügt!", "changed": "✔ Bewertung geändert!", "deleted": "✔ Bewertung gelöscht!", "prompt": "Geben Sie eine Suchanfrage ein.", "hint": "Name, Befehl, Beschreibung, Autor.", "retry": "Versuchen Sie eine другая запрос.", "query": "Anfrage", "install": "Installieren", "counter": "{idx}/{total}", "code": "Code", "success": "✔ Modul erfolgreich installiert!", "error": "✘ Fehler, vielleicht ist das Modul kaputt!", "overwrite": "✘ Fehler, Modul hat versucht, das integrierte Modul zu überschreiben!", "dependency": "✘ Fehler bei der Installation von Abhängigkeiten!", "docdevs": "Nur Module von offiziellen Heroku-Entwicklern bei की खोज में उपयोग करें?", "doctheme": "Theма für эмодзи.", "channel": "Dies ist der Kanal with all updates in FHeta!", "install_via_fheta": "Install via FHeta aktivieren?" } strings_jp = { "_cls_doc": "モジュール検索用モジュール!@NFHeta_UpdatesでFHetaのすべてのニュースをフォローしてください!", "lang": "jp", "author": "作成者", "description": "説明", "commands": "コマンド", "placeholders": "プレースホルダー", "morecommands": "...さらに {remaining} 個のコマンド。", "moreplaceholders": "...さらに {remaining} 個のプレースホルダー。", "list": "見つかったすべてのモジュール:", "search": "{query}を検索中...", "noquery": "検索クエリを入力していません、例: {prefix}fheta あなたのクエリ", "notfound": "クエリ{query}で何も見つかりませんでした。", "toolong": "クエリが大きすぎます。168文字に短縮してください。", "added": "✔ 評価が追加されました!", "changed": "✔ 評価が変更されました!", "deleted": "✔ 評価が削除されました!", "prompt": "検索するクエリを入力してください。", "hint": "名前、コマンド、説明、作成者。", "retry": "別のクエリを試してください。", "query": "クエリ", "install": "インストール", "counter": "{idx}/{total}", "code": "コード", "success": "✔ モジュールが正常にインストールされました!", "error": "✘ エラー, モジュールが壊れている可能性があります!", "overwrite": "✘ エラー, モジュールが組み込みモジュールを上書きしようとしました!", "dependency": "✘ 依存関係のインストールエラー!", "docdevs": "検索時に公式Heroku開発者のモジュールのみを使用しますか?", "doctheme": "絵文字のテーマ。", "channel": "これはFHetaのすべての更新を含むチャンネルです!", "install_via_fheta": "Install via FHetaを有効にしますか?" } THEMES = { "default": { "search": '
@{self.inline.bot_username} ')}",
"thumb": "https://raw.githubusercontent.com/Fixyres/FModules/refs/heads/main/assets/FHeta/magnifying_glass.png"
}
if len(query) > 168:
return {
"title": self.strings["toolong"],
"description": self.strings["retry"],
"message": f"{self.ui.emoji('warn')} {self.strings['toolong']}",
"thumb": "https://raw.githubusercontent.com/Fixyres/FModules/refs/heads/main/assets/FHeta/try_other_query.png"
}
modules = await self.api.fetch("search", query=query, inline="true", token=self.token, user_id=self.identifier, ood=str(self.config["only_official_developers"]).lower())
if not modules or not isinstance(modules, list):
return {
"title": self.strings["retry"],
"description": self.strings["hint"],
"message": f"{self.ui.emoji('error')} {self.strings['notfound'].format(query=f'{utils.escape_html(query)}')}",
"thumb": "https://raw.githubusercontent.com/Fixyres/FModules/refs/heads/main/assets/FHeta/try_other_query.png"
}
queryid = str(uuid.uuid4())[:8]
self.fheta_cache[queryid] = {"query": query, "mods": modules[:50]}
results = []
for index, data in enumerate(modules[:50]):
description = data.get("description", "")
if isinstance(description, dict):
description = description.get(self.strings["lang"]) or description.get("doc") or next(iter(description.values()), "")
thumb_url = data.get("pic") or "https://raw.githubusercontent.com/Fixyres/FModules/refs/heads/main/assets/FHeta/empty_pic.png"
if not hasattr(event, "builder"):
self.watch()
text = self.ui.format(data, query, 1, 1, True)
banner = data.get("banner")
if banner and banner not in text:
text = f'' + text
results.append({
"type": "article",
"id": f"fh_{queryid}_{index}",
"title": str(data.get("name", "")),
"description": str(description)[:250] + ("..." if len(str(description)) > 250 else ""),
"thumbnail_url": thumb_url,
"input_message_content": {
"message_text": text,
"parse_mode": "HTML",
"link_preview_options": {"url": banner, "show_above_text": True} if banner else {"is_disabled": True}
},
"reply_markup": self.inline.generate_markup(self.ui.buttons(data.get("install", ""), data, 0, [data], query))
})
continue
markup = self.inline.generate_markup(self.ui.buttons(data.get("install", ""), data, index, modules, query))
thumb = self.inline._web_document(thumb_url)
results.append(
await event.builder.article(
id=f"fh_{queryid}_{index}",
title=utils.escape_html(data.get("name", "")),
description=utils.escape_html(str(description)[:250] + ("..." if len(str(description)) > 250 else "")),
thumb=thumb,
text="🪐",
parse_mode="HTML",
buttons=markup
)
)
await event.answer(results, cache_time=0)
@loader.command(
ru_doc="(запрос) - поиск модулей.",
ua_doc="(запит) - пошук модулів.",
kz_doc="(сұрау) - модульдерді іздеу.",
uz_doc="(so'rov) - modullarni qidirish.",
fr_doc="(requête) - rechercher des modules.",
de_doc="(anfrage) - module suchen.",
jp_doc="(クエリ) - モジュールкоторого префикс."
)
async def fhetacmd(self, message: 'telethon.types.Message') -> Any:
'''(query) - search modules.'''
query = utils.get_args_raw(message)
if not query:
return await utils.answer(message, f"{self.ui.emoji('error')} {self.strings['noquery'].format(prefix=f'{self.get_prefix()}')}")
if len(query) > 168:
return await utils.answer(message, f"{self.ui.emoji('warn')} {self.strings['toolong']}")
message = await utils.answer(message, f"{self.ui.emoji('search')} {self.strings['search'].format(query=f'{utils.escape_html(query)}')}")
modules = await self.api.fetch("search", query=query, inline="false", token=self.token, user_id=self.identifier, ood=str(self.config["only_official_developers"]).lower())
if not modules or not isinstance(modules, list):
return await utils.answer(message, f"{self.ui.emoji('error')} {self.strings['notfound'].format(query=f'{utils.escape_html(query)}')}")
data = modules[0]
buttons = self.ui.buttons(data.get("install", ""), data, 0, modules, query)
text = self.ui.format(data, query, 1, len(modules))
banner = data.get("banner")
if banner and banner not in text:
text = f'' + text
msg = await self.inline.form(
text,
message,
reply_markup=buttons,
silent=True
)
if banner and msg:
await asyncio.sleep(0.4)
await self.edit(msg, text, buttons, banner)
@loader.watcher(chat_id=7575472403)
async def watcher(self, message: 'telethon.types.Message') -> None:
if not self.config["install_via_fheta"]:
return
url = message.raw_text.strip()
if not url.startswith("https://api.fixyres.com/module/") or url.split("?")[0].endswith(".hmod"):
return
ologs = self.get_logs()
res = await self.lookup("loader").download_and_install(url)
if res == 1:
reply = await message.respond("✅")
else:
alogs = self.get_logs()
nlogs = alogs[len(ologs):].lower()
if "overwrite" in nlogs:
reply = await message.respond("😨")
elif any(x in nlogs for x in ("requir", "depend", "package")):
reply = await message.respond("📋")
else:
reply = await message.respond("❌")
await asyncio.sleep(1)
await reply.delete()
await message.delete()