diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..e7102cdf551d0fa0047130b3e2b7e237facab26e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,45 @@ +# ============================================================================= +# SarahUB — Docker build context exclusions +# Everything listed here is omitted from the image build context, which keeps +# the image small and — critically — keeps secrets and local runtime state out +# of the built layers. +# ============================================================================= + +# ---- Secrets / local runtime state (MUST never be baked into an image) ---- +.env +.env.* +!.env.sample +*.session +*.session-journal +asst.session +*.localdb.json +ultroid.json +ultroid.localdb.json + +# ---- Version control ---- +.git +.gitignore +.github + +# ---- Python ---- +.venv/ +venv/ +**/__pycache__/ +*.py[cod] +*.egg-info/ +.pytest_cache/ +.mypy_cache/ +build/ +dist/ + +# ---- Node ---- +node_modules/ + +# ---- Logs, caches, and generated artifacts ---- +*.log +vc.log +*.tar.xz +*.tar.xz.md5 + +# ---- Tests (not needed at runtime) ---- +tests/ diff --git a/.env.sample b/.env.sample deleted file mode 100644 index deb192e192a797eea84af5d218278b0d1362fa4f..0000000000000000000000000000000000000000 --- a/.env.sample +++ /dev/null @@ -1,13 +0,0 @@ -# Don't use quotes( " and ' ) - -API_ID= -API_HASH= -SESSION= - - -# [OPTIONAL] - -REDIS_URI= -REDIS_PASSWORD= -LOG_CHANNEL= -BOT_TOKEN= diff --git a/.gitignore b/.gitignore index ce5d8ae1e0e50fb836a0b1f846cf923f4e17a60f..1e5d0f8af5b77304b1b0acad3d4e5da6ae5b0c71 100644 --- a/.gitignore +++ b/.gitignore @@ -1,47 +1,42 @@ -.env -*.session-journal +# Session files *.session -build -test* -*.mp3 -*.webm -*.webp -*.mp4 -*.tgs -*.txt -/*.jpg -/*.png -/*.mp4 -*.log -target/npmlist.json -package-lock.json -ultroid.json -resources/extras/thumbnail.jpg -resources/auth/ +*.session-journal +asst.session -# Directories -addons/ -vcbot/ +# Environment files +.env +.venv +venv +env/ +.env.* +!.env.sample + +# Python caches __pycache__/ -venv/ +*.pyc +*.pyo +*.pyd + +# Node/JavaScript dependencies node_modules/ -glitch_me/ -src/glitch-me -.idea/ +dist/ +build/ + +# IDE files .vscode/ -temp/ -bin-debug/ -bin-release/ -[Oo]bj/ -[Bb]in/ -.settings/ -*.swf -*.air -*.ipa -*.apk +.idea/ -# temporary files -*.raw +# Local cache/temporary files +.cache/ +*.log +ultroid.json +ultroid.localdb.json +resources/error_cards/ +addons/ +mehrama.mp3 +pr-body-phase0-3.md -# fly.io configs -fly.toml \ No newline at end of file +# local agent/runtime artifacts +opencode.jsonc +env.txt +.codegraph/ diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index fabd8716071171936b76c41aca01f38437559ab0..0000000000000000000000000000000000000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,128 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -teamultroid@ultroid.tech. -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series -of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.0, available at -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. - -Community Impact Guidelines were inspired by [Mozilla's code of conduct -enforcement ladder](https://github.com/mozilla/diversity). - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see the FAQ at -https://www.contributor-covenant.org/faq. Translations are available at -https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index a69d36986aa278af32dd2c262b039c5f9b358072..0000000000000000000000000000000000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,23 +0,0 @@ -# Welcome To Contributing Guide -Any contribution done to this repository will be appreciated! 🎉 - -### About Ultroid -- **Ultroid** is Telegram Userbot, which allow you to perform many task easily. -- It's base core is a pip package named [`pyUltroid`](https://GitHub.com/TeamUltroid/pyUltroid). -- This repository, contains Ultroid's official plugin files. -- moreover, Ultroid User also have an option to get more plugins available at [`UltroidAddons`](https://github.com/TeamUltroid/UltroidAddons) - -### Issues -- Search for existing Similar issues. -- You can open a issue first before contributing, If it contain some major changes like `bug fixes` or `feature addition`. -- If you are busy or getting trouble while making changes, you can just open the issue (explaining it). - -### Contributing -- You can [fork](https://github.com/TeamUltroid/Ultroid/fork) this repository. -- You can commits your changes now. -- You can [Git-Squash](https://docs.github.com/en/get-started/using-git/about-git-rebase) your commits, if they are more. [Optional] -- At last, You are ready to [`make a Pull Request`](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). -- Make sure that, your `Pull Request` contain an explaining title and issue number if it closes any open issue. - -### Thanks -- Congrats! 💫 you have successfully made your Contribution to Ultroid. diff --git a/Dockerfile b/Dockerfile index 9538ceb50d366c88c2d893f6dbb7e7f68472b111..86699821abdb46ddc564cbe448f635a62076a361 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,20 +1,187 @@ -# Ultroid - UserBot -# Copyright (C) 2021-2026 TeamUltroid -# This file is a part of < https://github.com/TeamUltroid/Ultroid/ > -# PLease read the GNU Affero General Public License in . +# syntax=docker/dockerfile:1 -FROM theteamultroid/ultroid:main +# ============================================================================= +# SarahUB — container image (CUDA / GPU variant) +# ============================================================================= +# Build tunables are declared as ARGs below so they can be overridden at +# build time without editing this file. +# +# Secrets/env vars are consumed at BUILD time. Easiest way: export them in +# your shell, then pass the ARG by name with no value (Docker forwards the +# matching shell env var automatically): +# +# export GIT_TOKEN= +# docker build --build-arg TZ=Europe/London \ +# --build-arg GIT_TOKEN --build-arg PYTHON_VERSION=3.11 . +# +# Or pass the value inline: +# docker build --build-arg GIT_TOKEN="$GIT_TOKEN" . +# ============================================================================= -# set timezone -ENV TZ=Asia/Kolkata -RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone +# Base image is the only tunable the FROM instruction itself needs. +ARG BASE_IMAGE=nvidia/cuda:12.5.1-cudnn-devel-ubuntu22.04 +FROM ${BASE_IMAGE} -COPY installer.sh . +# ----------------------------------------------------------------------------- +# Build-time tunables (defaults mirror the original hardcoded values) +# ----------------------------------------------------------------------------- +ARG TZ=Asia/Kolkata +ARG APP_USER=sarah +ARG APP_HOME=/sarah +ARG MINICONDA_DIR=${APP_HOME}/miniconda +ARG CONDA_ENV=py311 +ARG PYTHON_VERSION=3.11 +ARG NODE_URL=https://deb.nodesource.com/setup_current.x +ARG MINIFORGE_URL=https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-x86_64.sh +ARG REPO_OWNER=Mahesh953-hub +ARG REPO_NAME=SarahUB +ARG REPO_BRANCH=main +ARG GIT_TOKEN +ARG EXPOSE_PORT=7860 -RUN bash installer.sh +# ----------------------------------------------------------------------------- +# Environment +# ----------------------------------------------------------------------------- +ENV DEBIAN_FRONTEND=noninteractive \ + TZ=${TZ} \ + CONDA_AUTO_UPDATE_CONDA=false \ + PYTHONUNBUFFERED=1 \ + GIT_TOKEN=${GIT_TOKEN} -# changing workdir -WORKDIR "/root/TeamUltroid" +RUN export TZ=${TZ} -# start the bot with a dummy web server in the background to satisfy Hugging Face -CMD ["bash", "-c", "python3 -m http.server 7860 & bash startup"] \ No newline at end of file +# ----------------------------------------------------------------------------- +# System dependencies +# ----------------------------------------------------------------------------- +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + curl \ + ca-certificates \ + sudo \ + git \ + wget \ + zip \ + unzip \ + neofetch \ + gnupg2 \ + libnss3 \ + libx11-xcb1 \ + libxcursor1 \ + libxi6 \ + libgtk-3-0 \ + libnspr4 \ + libdbus-1-3 \ + libatk1.0-0 \ + libatk-bridge2.0-0 \ + libgl1-mesa-glx \ + libcups2 \ + libdrm2 \ + libxkbcommon0 \ + libatspi2.0-0 \ + libxcomposite1 \ + libxdamage1 \ + libxfixes3 \ + libxrandr2 \ + libgbm1 \ + libasound2 \ + gosu \ + p7zip-full \ + mediainfo \ + procps \ + htop \ + vim \ + nano \ + bzip2 \ + build-essential \ + libsndfile-dev \ + software-properties-common \ + && rm -rf /var/lib/apt/lists/* + +# ----------------------------------------------------------------------------- +# Node.js — builds the web setup server's frontend +# ----------------------------------------------------------------------------- +RUN curl -fsSL ${NODE_URL} | bash - \ + && apt-get install -y nodejs + +# ----------------------------------------------------------------------------- +# Non-root runtime user +# ----------------------------------------------------------------------------- +RUN useradd -m -s /bin/bash ${APP_USER} \ + && echo "${APP_USER} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/90-${APP_USER} + +USER ${APP_USER} +ENV HOME=${APP_HOME} +WORKDIR ${APP_HOME} + +# ----------------------------------------------------------------------------- +# Miniforge (conda + mamba, conda-forge) + Python environment +# ----------------------------------------------------------------------------- +ENV PATH=${MINICONDA_DIR}/bin:$PATH + +RUN curl -sL -o ${APP_HOME}/miniforge.sh ${MINIFORGE_URL} \ + && bash ${APP_HOME}/miniforge.sh -b -p ${MINICONDA_DIR} \ + && rm ${APP_HOME}/miniforge.sh \ + && ${MINICONDA_DIR}/bin/mamba create -y -n ${CONDA_ENV} python=${PYTHON_VERSION} \ + && ${MINICONDA_DIR}/bin/mamba clean -afy + +ENV PATH=${MINICONDA_DIR}/envs/${CONDA_ENV}/bin:${MINICONDA_DIR}/bin:$PATH + +# ----------------------------------------------------------------------------- +# Application source — cloned so the container keeps `.git` and start.sh's +# `git pull` can keep the deployment updatable. `GIT_TOKEN` is only injected +# when provided (e.g. for a private fork): `--build-arg GIT_TOKEN=`. +# ----------------------------------------------------------------------------- +RUN echo "Better logs#2" + +RUN if [ -n "${GIT_TOKEN}" ]; then \ + GIT_URL="https://${GIT_TOKEN}@github.com/${REPO_OWNER}/${REPO_NAME}.git"; \ + else \ + GIT_URL="https://github.com/${REPO_OWNER}/${REPO_NAME}.git"; \ + fi \ + && git clone --branch "${REPO_BRANCH}" --single-branch "${GIT_URL}" "${APP_HOME}/${REPO_NAME}" + +WORKDIR ${APP_HOME}/${REPO_NAME} + +RUN ls -all && git pull + +RUN chown -R ${APP_USER}:${APP_USER} ${APP_HOME} + +# ----------------------------------------------------------------------------- +# Python dependencies +# `res*/st*/op*` expands to `resources/startup/optional-requirements.txt`. +# ----------------------------------------------------------------------------- +RUN echo "I want rebuild!!!!" + +# Core deps MUST succeed. The database drivers are pinned explicitly so a +# midway `requirements.txt` failure can no longer fall through the old `|| true` +# and ship an image whose Redis/Mongo/SQL clients are silently missing (that +# made the app fall back to LocalDB even when MONGO_URI was set). With this +# split, a broken core install fails the build instead. +RUN pip install --no-cache-dir -U pip \ + && pip install --no-cache-dir requests dnspython redis pymongo psycopg2-binary \ + && pip install --no-cache-dir fastapi uvicorn nest-asyncio \ + && pip install --no-cache-dir -r requirements.txt + +# Optional extras for local deploys (git deps + heavy native builds) can fail +# without breaking the bot, so THIS line alone is allowed to fail. +RUN pip install --no-cache-dir -r res*/st*/op* || true + +# ----------------------------------------------------------------------------- +# FFmpeg — pulled from a prebuilt static image (needs root to write /usr/local) +# ----------------------------------------------------------------------------- +USER root +COPY --from=mwader/static-ffmpeg:latest /ffmpeg /ffprobe /usr/local/bin/ + +# ----------------------------------------------------------------------------- +# Permissions + final runtime user +# ----------------------------------------------------------------------------- +USER ${APP_USER} +RUN chmod -R 755 ${APP_HOME} \ + && chmod +x ${APP_HOME}/${REPO_NAME}/start.sh + +USER ${APP_USER} +WORKDIR ${APP_HOME}/${REPO_NAME} + +EXPOSE ${EXPOSE_PORT} + +CMD ["./start.sh"] diff --git a/akipy/LICENSE b/akipy/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7698470bb0a95fe1c48bfc46fbc2d8acc41c07af --- /dev/null +++ b/akipy/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 advnpzn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/akipy/VENDORING.md b/akipy/VENDORING.md new file mode 100644 index 0000000000000000000000000000000000000000..44c3d8e873fb1ddac46e10f5e153419e624495ae --- /dev/null +++ b/akipy/VENDORING.md @@ -0,0 +1,11 @@ +# Vendored Akinator wrapper + +This package is the `akipy` 0.1.2 source from +(commit `2af0027d05ef32a89aa6dede27a7bde4d8c4ad0e`), retained here to keep +SarahUB's asynchronous Akinator feature intact without installing its stale +`httpx>=0.25,<0.26` distribution requirement. The upstream wrapper uses only +ordinary `httpx` client APIs; SarahUB declares the shared `httpx>=0.28.1` +dependency required by Gemini and tests the async game/transport path against +that client version. + +The upstream MIT license and copyright notice are in `LICENSE`. diff --git a/akipy/__init__.py b/akipy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..65cce9e3e3bd085a2853da303d9e7332818942b1 --- /dev/null +++ b/akipy/__init__.py @@ -0,0 +1,9 @@ +""" +akipy - A Python wrapper library for Akinator + +:copyright: (c) 2024, advnpzn +:license: MIT, see LICENSE for more details. +""" + +from .akinator import Akinator +from .exceptions import * diff --git a/akipy/akinator.py b/akipy/akinator.py new file mode 100644 index 0000000000000000000000000000000000000000..426a5dcbc5327d8233ec546c6b4ccc31e91a828b --- /dev/null +++ b/akipy/akinator.py @@ -0,0 +1,171 @@ +""" +MIT License + +Copyright (c) 2024 advnpzn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +""" +import json +import re +import httpx + +from .dicts import HEADERS, THEME_ID, THEMES, LANG_MAP +from .exceptions import InvalidLanguageError, CantGoBackAnyFurther +from .utils import get_answer_id, request_handler + + +class Akinator: + """ + The Akinator Class represents the Akinator Game. + You need to create an instance of this class to get started. + """ + + def __init__(self): + self.photo = None + self.pseudo = None + self.uri = None + self.theme = None + self.session = None + self.signature = None + self.child_mode = False + self.lang = None + self.available_themes = None + self.theme = None + + self.question = None + self.progression = None + self.step = None + self.akitude = None + self.step_last_proposition = "" + + self.win = False + self.name_proposition = None + self.description_proposition = None + self.completion = None + + def start_game(self, language: str = "en", child_mode: bool = False): + """ + Start the Akinator game with specified language and child mode. + :param language: Language code or name + :param child_mode: Whether to enable child mode + :return: None + """ + self.__get_region(lang=language) + self.__initialise() + + def answer(self, option): + url = f"{self.uri}/answer" + data = { + "step": self.step, + "progression": self.progression, + "sid": self.theme, + "cm": str(self.child_mode).lower(), + "answer": get_answer_id(option), + "step_last_proposition": self.step_last_proposition, + "session": self.session, + "signature": self.signature, + } + + try: + req = request_handler(url=url, method='POST', data=data) + resp = req.json() + + if "id_proposition" in resp: + self.__update(action="win", resp=resp) + else: + self.__update(action="answer", resp=resp) + self.completion = resp.get('completion') + except Exception as e: + raise e + + def back(self): + if self.step == 1: + raise CantGoBackAnyFurther("Cannot go back further.") + else: + url = f"{self.uri}/cancel_answer" + data = { + "step": self.step, + "progression": self.progression, + "sid": self.theme, + "cm": str(self.child_mode).lower(), + "session": self.session, + "signature": self.signature, + } + + try: + req = request_handler(url=url, method='POST', data=data) + resp = req.json() + self.__update(action="back", resp=resp) + except Exception as e: + raise e + + def __update(self, action: str, resp): + if action in ["answer", "back"]: + self.akitude = resp.get('akitude') + self.step = resp.get('step') + self.progression = resp.get('progression') + self.question = resp.get('question') + elif action == "win": + self.win = True + self.name_proposition = resp.get('name_proposition') + self.description_proposition = resp.get('description_proposition') + self.pseudo = resp.get('pseudo') + self.photo = resp.get('photo') + + def __get_region(self, lang): + try: + lang = LANG_MAP.get(lang, lang) # Get mapped language if available + if len(lang) > 2 and lang not in LANG_MAP.values(): + raise InvalidLanguageError(lang) + except Exception: + raise InvalidLanguageError(lang) + + url = f"https://{lang}.akinator.com" + try: + req = request_handler(url=url, method='GET') + if req.status_code != 200: + raise httpx.HTTPStatusError(f"HTTP status error: {req.status_code}") + self.uri = url + self.lang = lang + self.available_themes = THEMES.get(lang, []) + self.theme = THEME_ID.get(self.available_themes[0]) + except Exception as e: + raise e + + def __initialise(self): + url = f"{self.uri}/game" + data = { + "sid": self.theme, + "cm": str(self.child_mode).lower() + } + try: + req = request_handler(url=url, method='POST', data=data).text + match = re.findall(r"[a-zA-Z0-9+/]+==", req) + + if len(match) >= 2: + self.session = match[0] + self.signature = match[1] + + match = re.search(r'

(.*?)

', req) + self.question = match.group(1) if match else None + self.progression = "0.00000" + self.step = 0 + except Exception as e: + raise httpx.HTTPStatusError(f"Failed to initialise: {e}") diff --git a/akipy/async_akipy/__init__.py b/akipy/async_akipy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..286df35cca26269706dbc8c54277dba48324f749 --- /dev/null +++ b/akipy/async_akipy/__init__.py @@ -0,0 +1,8 @@ +""" +akipy - A Python wrapper library for Akinator + +:copyright: (c) 2024, advnpzn +:license: MIT, see LICENSE for more details. +""" + +from .async_akinator import Akinator, akipyLOGS diff --git a/akipy/async_akipy/async_akinator.py b/akipy/async_akipy/async_akinator.py new file mode 100644 index 0000000000000000000000000000000000000000..1ecf80933aa1f2d4c4cb8bd8b991c2320e3a2e27 --- /dev/null +++ b/akipy/async_akipy/async_akinator.py @@ -0,0 +1,205 @@ +""" +MIT License + +Copyright (c) 2024 advnpzn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +""" +import json +import re +import asyncio +import logging + +try: + import httpx +except ImportError: + raise ImportError('httpx is not installed') + +from ..dicts import HEADERS, THEME_ID, THEMES, LANG_MAP +from ..exceptions import InvalidLanguageError, CantGoBackAnyFurther +from ..utils import get_answer_id, async_request_handler + +akipyLOGS = logging.getLogger("Aᴋɪɴᴀᴛᴏʀ") + +class Akinator: + """ + The ``Akinator`` Class represents the Akinator Game. + You need to create an Instance of this Class to get started. + """ + + def __init__(self): + self.photo = None + self.pseudo = None + self.uri = None + self.theme = None + self.session = None + self.signature = None + self.identifiant = None + self.child_mode = False + self.lang = None + self.available_themes = None + + self.question = None + self.progression = None + self.step = None + self.akitude = None + self.step_last_proposition = "" + + self.win = False + self.name_proposition = None + self.description_proposition = None + self.completion = None + + async def __update(self, action: str, resp): + if action == "answer": + self.akitude = resp.get('akitude') + self.step = resp.get('step') + self.progression = resp.get('progression') + self.question = resp.get('question') + elif action == "back": + self.akitude = resp.get('akitude') + self.step = resp.get('step') + self.progression = resp.get('progression') + self.question = resp.get('question') + elif action == "win": + self.win = True + self.name_proposition = resp.get('name_proposition') + self.description_proposition = resp.get('description_proposition') + self.pseudo = resp.get('pseudo') + self.photo = resp.get('photo') + + async def __get_region(self, lang): + try: + if len(lang) > 2: + lang = LANG_MAP.get(lang) + else: + assert lang in LANG_MAP.values(), "Invalid language code" + except AssertionError as e: + raise InvalidLanguageError(lang) from e + url = f"https://{lang}.akinator.com" + try: + req = await async_request_handler(url=url, method='GET') + req.raise_for_status() + self.uri = url + self.lang = lang + + self.available_themes = THEMES.get(lang) + self.theme = THEME_ID.get(self.available_themes[0]) + except httpx.HTTPStatusError as e: + raise httpx.HTTPStatusError(f"HTTP error occurred: {e}") from e + except Exception as e: + raise Exception(f"An error occurred while getting region: {e}") from e + + async def __initialise(self): + url = f"{self.uri}/game" + data = { + "sid": self.theme, + "cm": str(self.child_mode).lower() + } + try: + req = await async_request_handler(url=url, method='POST', data=data) + req.raise_for_status() + match = re.findall(r"[a-zA-Z0-9+/]+==", req.text)[-2:] + + self.session = match[0] + self.signature = match[1] + + # Extract identifiant + identifiant_match = re.search(r'\$\(\'#identifiant\'\)\.val\([\'"](.*?)[\'"]\);', req.text) + self.identifiant = identifiant_match.group(1) if identifiant_match else None + + match = re.search(r'

(.*?)

', req.text) + if match: + self.question = match.group(1) + self.progression = "0.00000" + self.step = 0 + except httpx.HTTPStatusError as e: + raise httpx.HTTPStatusError(f"HTTP error occurred: {e}") from e + except Exception as e: + raise Exception(f"An error occurred while initializing: {e}") from e + + async def start_game(self, language: str = "en", child_mode: bool = False): + """ + This method is responsible for actually starting the game scene. + You can pass the following parameters to set your language preference and as well as the Child Mode. + If language is not set, English is used by default. Child Mode is set to ``False`` by default. + :param language: "en" + :param child_mode: False + :return: None + """ + await self.__get_region(lang=language) + await self.__initialise() + + async def answer(self, option): + url = f"{self.uri}/answer" + data = { + "step": self.step, + "progression": self.progression, + "sid": self.theme, + "cm": str(self.child_mode).lower(), + "answer": get_answer_id(option), + "step_last_proposition": self.step_last_proposition, + "session": self.session, + "signature": self.signature, + "identifiant": self.identifiant, + } + + try: + req = await async_request_handler(url=url, method='POST', data=data) + req.raise_for_status() + resp = req.json() + #akipyLOGS.info(f"API Response: {resp}") + + if "id_proposition" in resp: + await self.__update(action="win", resp=resp) + else: + await self.__update(action="answer", resp=resp) + + akipyLOGS.info(f"Updated question: {self.question}") + self.completion = resp.get('completion') + except httpx.HTTPStatusError as e: + raise httpx.HTTPStatusError(f"HTTP error occurred: {e}") from e + except Exception as e: + raise Exception(f"An error occurred while answering: {e}") from e + + async def back(self): + if self.step == 1: + raise CantGoBackAnyFurther + else: + url = f"{self.uri}/cancel_answer" + data = { + "step": self.step, + "progression": self.progression, + "sid": self.theme, + "cm": str(self.child_mode).lower(), + "session": self.session, + "signature": self.signature, + "identifiant": self.identifiant, + } + + try: + req = await async_request_handler(url=url, method='POST', data=data) + req.raise_for_status() + resp = req.json() + await self.__update(action="back", resp=resp) + except httpx.HTTPStatusError as e: + raise httpx.HTTPStatusError(f"HTTP error occurred: {e}") from e + except Exception as e: + raise Exception(f"An error occurred while going back: {e}") from e diff --git a/akipy/dicts.py b/akipy/dicts.py new file mode 100644 index 0000000000000000000000000000000000000000..38afa2a7ac6754a60d3b2a571245d0e9b82796e1 --- /dev/null +++ b/akipy/dicts.py @@ -0,0 +1,67 @@ +HEADERS = { + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", + "Accept-Encoding": "gzip, deflate", + "Accept-Language": "en-US,en;q=0.9", + "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/81.0.4044.92 " + "Chrome/81.0.4044.92 Safari/537.36", + "x-requested-with": "XMLHttpRequest", +} + +LANG_MAP = { + "english": "en", + "arabic": "ar", + "chinese": "cn", + "german": "de", + "spanish": "es", + "french": "fr", + "hebrew": "il", + "italian": "it", + "japanese": "jp", + "korean": "kr", + "dutch": "nl", + "polish": "pl", + "portuguese": "pt", + "russian": "ru", + "turkish": "tr", + "indonesian": "id" +} + +THEME_ID = { + "c": 1, + "a": 14, + "o": 2 +} + +""" +c - characters +a - animals +o - objects +""" + +THEMES = { + "en": ["c", "a", "o"], + "ar": ["c"], + "cn": ["c"], + "de": ["c", "a"], + "es": ["c", "a"], + "fr": ["c", "a", "o"], + "il": ["c"], + "it": ["c", "a"], + "jp": ["c", "a"], + "kr": ["c"], + "nl": ["c"], + "pl": ["c"], + "pt": ["c"], + "ru": ["c"], + "tr": ["c"], + "id": ["c"], +} + +ANSWERS = { + 0: ["yes", "y", '0'], + 1: ["no", "n", '1'], + 2: ["i", "idk", "i dont know", "i don't know", '2'], + 3: ["p", "probably", '3'], + 4: ["pn", "probably not", '4'], +} + diff --git a/akipy/exceptions.py b/akipy/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..d773014569e8ab5b82e8eec25dcc8a836a0c7f15 --- /dev/null +++ b/akipy/exceptions.py @@ -0,0 +1,8 @@ +class InvalidLanguageError(ValueError): + """Raise when the user input language is invalid or not supported by Akinator""" + pass + + +class CantGoBackAnyFurther(Exception): + """Raises when the user is in the first question and tries to go back further""" + pass diff --git a/akipy/utils.py b/akipy/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..08ef02eb3216c3018e8b13051b7acd362454869a --- /dev/null +++ b/akipy/utils.py @@ -0,0 +1,27 @@ +from typing import Union, Optional +import httpx + +from .dicts import ANSWERS, HEADERS + +def request_handler(url: str, method: str, data: Optional[dict] = None) -> httpx.Response: + if method == 'GET': + return httpx.get(url, headers=HEADERS, timeout=30.0) + elif method == 'POST': + return httpx.post(url, headers=HEADERS, data=data, timeout=30.0) + else: + raise ValueError(f"Unsupported HTTP method: {method}") + +async def async_request_handler(url: str, method: str, data: Optional[dict] = None) -> httpx.Response: + async with httpx.AsyncClient() as client: + if method == 'GET': + return await client.get(url, headers=HEADERS, timeout=30.0) + elif method == 'POST': + return await client.post(url, headers=HEADERS, data=data, timeout=30.0) + else: + raise ValueError(f"Unsupported HTTP method: {method}") + +def get_answer_id(ans): + for key, values in ANSWERS.items(): + if ans.lower() in values: + return key + return None diff --git a/app.json b/app.json deleted file mode 100644 index d192badba483b4ed8a94535876f392c504624720..0000000000000000000000000000000000000000 --- a/app.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "Ultroid UserBot", - "description": "Pluggable telegram userbot, made in python using Telethon.", - "logo": "https://graph.org/file/031957757a4f6a5191040.jpg", - "keywords": [ - "Telethon", - "telegram", - "userbot", - "python", - "ultroid" - ], - "repository": "https://github.com/TeamUltroid/Ultroid", - "website": "https://ultroid.tech", - "success_url": "https://t.me/TeamUltroid", - "stack": "container", - "env": { - "API_ID": { - "description": "You api id, from my.telegram.org or @ScrapperRoBot.", - "value": "", - "required": false - }, - "API_HASH": { - "description": "You api hash, from my.telegram.org or @ScrapperRoBot.", - "value": "", - "required": false - }, - "SESSION": { - "description": "Session String (telethon or pyrogram) for your telegram user account. The userbot will NOT work without a session string!!", - "value": "" - }, - "REDIS_URI": { - "description": "Redis endpoint URL, from redislabs.com", - "value": "" - }, - "REDIS_PASSWORD": { - "description": "Redis endpoint password, from redislabs.com", - "value": "" - }, - "HEROKU_API": { - "description": "Heroku API token. Mandatory for Heroku Deploy...", - "value": "", - "required": false - }, - "HEROKU_APP_NAME": { - "description": "Name of your Heroku app, given in the first blank on this page. To be added if deploying to heroku ONLY.", - "value": "", - "required": false - } - }, - "formation": { - "ultroid": { - "quantity": 1, - "size": "eco" - } - } -} diff --git a/assistant/__init__.py b/assistant/__init__.py index d80a174c4cd3ef7c04ec7e7ee627343e8df30505..9c92b4000e9c8559866e2825b2e65d5c26bdb30a 100644 --- a/assistant/__init__.py +++ b/assistant/__init__.py @@ -1,21 +1,38 @@ # Ultroid - UserBot -# Copyright (C) 2021-2026 TeamUltroid +# Copyright (C) 2021-2023 TeamUltroid # # This file is a part of < https://github.com/TeamUltroid/Ultroid/ > # PLease read the GNU Affero General Public License in # . +import unicodedata + from telethon import Button, custom +from telethon.errors.rpcerrorlist import ChatSendStickersForbiddenError +from telethon.utils import get_display_name +from custom.tg import ikm from plugins import ATRA_COL, InlinePlugin -from pyUltroid import * -from pyUltroid import _ult_cache +from pyUltroid import HNDLR, LOGS, ULTConfig, asst, udB, ultroid_bot, _ult_cache from pyUltroid._misc import owner_and_sudos +from pyUltroid._misc._decorators import ultroid_cmd +from pyUltroid._misc._wrappers import eod from pyUltroid._misc._assistant import asst_cmd, callback, in_pattern -from pyUltroid.fns.helper import * -from pyUltroid.fns.tools import get_stored_file +from pyUltroid.configs import Var +from pyUltroid.fns import fns +from pyUltroid.fns.tools import _webupload_cache +from pyUltroid.version import ultroid_version from strings import get_languages, get_string +from pyUltroid.dB import db as dbs +# The twelve submodules reach these through from . import *, so this module +# is the facade. Two rules keep that safe, and both are pinned by +# tests/test_assistant_facade.py: +# 1. nothing below imports a submodule of assistant - a package __init__ +# always finishes before any submodule body runs, which is what makes +# the star import deterministic rather than lucky; +# 2. pyUltroid is reached by explicit import, never by star, so the +# names the facade re-exports are provable instead of accidental. OWNER_NAME = ultroid_bot.full_name OWNER_ID = ultroid_bot.uid @@ -27,8 +44,48 @@ async def setit(event, name, value): udB.set_key(name, value) except BaseException as er: LOGS.exception(er) - return await event.edit("`Something Went Wrong`") + return await event.edit("Something Went Wrong") + + +def _clean_nav_label(label): + out = [] + for char in str(label or ""): + if ord(char) in { + 0x00AB, + 0x00BB, + 0x2039, + 0x203A, + 0x25C0, + 0x25B6, + 0x2190, + 0x2192, + 0x2022, + 0x00B7, + 0xFE0E, + 0xFE0F, + 0x200D, + 0x20E3, + }: + out.append(" ") + continue + try: + name = unicodedata.name(char) + except ValueError: + name = "" + if name.startswith("LATIN LETTER SMALL CAPITAL "): + out.append(name.rsplit(" ", 1)[-1].lower()) + elif unicodedata.category(char) in {"So", "Sk"}: + out.append(" ") + else: + out.append(char) + return " ".join("".join(out).split()) -def get_back_button(name): - return [Button.inline("« Bᴀᴄᴋ", data=f"{name}")] +def get_back_button(name, label="Back", style="primary"): + """Build a blue, glyph-free navigation row targeting name a destination's own + callback data (from assistant._cbs.cb, or a legacy bare token). + Reusing the destination's own data *is* the back-navigation mechanism: + the click is a real callback-query round trip dispatched straight to + that destination's handler (see assistant/_cbs.py). + """ + return ikm([(_clean_nav_label(label), name, style)], icon=False)[0] diff --git a/assistant/_cbs.py b/assistant/_cbs.py new file mode 100644 index 0000000000000000000000000000000000000000..60d6857ed27c3131015c7e560b60a09a35d0421e --- /dev/null +++ b/assistant/_cbs.py @@ -0,0 +1,86 @@ +# Ultroid - UserBot +# Copyright (C) 2021-2023 TeamUltroid +# +# This file is a part of < https://github.com/TeamUltroid/Ultroid/ > +# PLease read the GNU Affero General Public License in +# . + +"""Structured callback-data model ("cbs") for assistant/. + +Every inline button assistant/-side code sends carries callback data (or, for +@in_pattern results, an inline-query string) that some @callback / +@in_pattern handler must consume. Before this module, that data was a +grab-bag of ad-hoc prefixes (cbs_, abs_, aki_, hlp_, bare +atoms like "setter"...) with no single place documenting which handler +owns which prefix a classic "button times out, nobody knows why" trap: a +button emits data with no registered handler, or a handler's pattern has no +button that ever emits it. + +This module gives every assistant/ callback datum one of three shapes: + +1. help:: the group-manager help menu + (assistant/manager/_help.py); paged button indexation. +2. assistant:: everything else living in assistant/ + and assistant/manager/ (menus, convo flows, games, ytdl helpers, + standalone alert-and-return buttons all of it). is the + owning module's short name (callbacks, games, lang, start, + ...); is that module's own sub-format (colon-joined further, + free-form, whatever the handler needs). +3. **Standalones** call-and-cut buttons that only event.answer(...) an + alert or delete the message, with no further navigation/state. They are + *not* a fourth colon-prefix: they use the same assistant:: + shape as namespace 2. + +Symmetry rule +-------------- +Every callback data a button *emits* must have a matching @callback +pattern that *consumes* it, and vice versa. Emitters use :func:cb / +:func:cb_str; handlers use :func:cb_pattern / :func:cb_exact_pattern. +tests/test_assistant_cbs_symmetry.py statically scans every literal +call site of these four functions and fails on any one-sided +namespace:name prefix. + +Cross-boundary tokens +---------------------- +A handful of callback datas cross the assistant/ <-> plugins/ (or +pyUltroid core) boundary e.g. the group-manager help menu's "back to +plugin help" button is emitted by plugins/_help.py but consumed by +assistant/manager/_help.py. These tokens are **fully migrated** to the +colon model: both sides build/handle the same literal cb(...) segments, +with the primitives imported from the dependency-free leaf +pyUltroid._core._cbs (re-exported below) so no side introduces an +import-order cycle. The symmetry audit +(tests/test_assistant_cbs_symmetry.py) scans the participating files +across both layers and pins the migrated prefixes so a silent +re-literalization can't slip through. + +Back-navigation +---------------- +Every " Back" button targets a real, already-registered destination token +(e.g. assistant:callbacks:menu:otvars has its own @callback handler). +Reusing that destination's own callback data as the back button's data is +not a workaround a button click is a *real* Telegram callback-query round +trip, dispatched by Telethon exactly as if the destination button itself had +been clicked. No in-process redispatch engine is needed, and the symmetry +rule is satisfied automatically (the "emitter" is just every +get_back_button() call site, the "handler" is the destination's own +handler). +""" + +from pyUltroid._core._cbs import ( # noqa: F401 (re-export) + SEP, + _clean, + cb, + cb_pattern, + cb_exact_pattern, + cb_str, +) + +__all__ = [ + "SEP", + "_clean", + "cb", + "cb_str", + "cb_pattern", + "cb_exact_pattern", +] diff --git a/assistant/agent.py b/assistant/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..281c8c572c7fae500673b9ab766496e6a6a48148 --- /dev/null +++ b/assistant/agent.py @@ -0,0 +1,1164 @@ +# Ultroid - UserBot +# Copyright (C) 2021-2024 TeamUltroid +# +# This file is a part of < https://github.com/TeamUltroid/Ultroid/ > +# PLease read the GNU Affero General Public License in +# . + +"""/agent - a full agent-configuration menu tree for the assistant bot. + +This module owns the assistant:agent:* callback-data namespace (see +assistant/_cbs.py). One @asst_cmd(pattern="agent") entry point opens a +primary-blue dashboard; from there six coloured-button sections branch out, +each driven by @callback handlers over the colon callback model: + +* menu: - screen navigation (one MENU_PATTERN handler) +* conv:: - conversation-style value entry (CONV_PATTERN) +* act:[:] - real side-effects / fetches (ACT_PATTERN) + +Every button is built with cb(...) through the _menu/_conv/_act +wrappers below, and every wrapper call is paired with one of those three +cb_pattern(...) handlers - no dead buttons, no dead handlers (verified by +tests/test_assistant_cbs_symmetry.py, which resolves these wrappers). + +Menu tree (each level owns the next; back pops one level) +--------- +home + llama llama: + base/model/ctx/temp/sys + fetch-models (real GET) + cloud cloud: + key(model/masked)/model/sys/base + validate-key (real GET) + claude key(masked)/default-model/fallback + fetch-modelspaste URL (real GET) + keys masked credentials readout + clear (llama/cloud/claude/all) + modules importability probe of openai/anthropic/httpx/aiohttp/requests + act:syscheck Python/platform/memory + endpoint reachability (real GET) + +Persisted udB keys (namespace AGENT_*) +------------------------------------------ +Local LLM : AGENT_LLAMA__BASE|MODEL|CTX|TEMP|SYS +Cloud AI : AGENT_CLOUD__KEY|MODEL|SYS|BASE +Claude : AGENT_CLAUDE_KEY|MODEL|FALLBACK + +Real network calls (vs. key-gated) +---------------------------------- +* Llama "Fetch Models" - REAL GET, no key: Ollama {base}/api/tags; + OpenAI-compatible servers (llama.cpp/LM Studio/TGI/vLLM) {base}/v1/models. +* Cloud "Validate Key" - REAL authenticated GET per provider + (OpenAI/Anthropic/OpenRouter/Groq/Gemini). Requires a stored key. +* Claude "Fetch Models URL" - REAL GET api.anthropic.com/v1/models + (x-api-key). Requires a stored key; result pasted via get_paste + + make_html_telegraph. +* "Check System" reachability - REAL GET (short timeout) against each + configured provider host. + +All network calls go through async_searcher (the repo's standard async GET +helper, also used by callbackstuffs.py) wrapped in asyncio.wait_for with +a timeout and try/except, so the event loop is never blocked and the module +imports cleanly even when an optional client library is absent (the modules +probe uses importlib.util.find_spec, never an import). +""" + +import asyncio +import html +import platform +from datetime import datetime, timezone + +from custom.tg import ikm +from pyUltroid._core.richmsg import RichMarkup, send_rich +from pyUltroid.agent import agent +from pyUltroid.fns import fns + +from . import * +from ._cbs import cb, cb_pattern +from .rich_pages import body_page, edit_callback_page, rich_page + +# --------------------------------------------------------------------# +# Callback-data wrappers. _menu/_conv/_act are the emitter side; +# MENU/CONV/ACT_PATTERN are the three handler prefixes that consume them. The +# static symmetry audit (tests/test_assistant_cbs_symmetry.py) resolves these +# one-line wrappers, so a single pattern handler covers every key under it. + + +def _menu(*parts): + return cb("assistant", "agent", "menu", *parts) + + +def _conv(*parts): + return cb("assistant", "agent", "conv", *parts) + + +def _act(*parts): + return cb("assistant", "agent", "act", *parts) + + +MENU_PATTERN = cb_pattern("assistant", "agent", "menu") +CONV_PATTERN = cb_pattern("assistant", "agent", "conv") +ACT_PATTERN = cb_pattern("assistant", "agent", "act") + +# --------------------------------------------------------------------# +# Provider registries + persistence helpers. + +#: Local LLM servers. api selects the model-list endpoint shape: +#: ollama -> {base}/api/tags; openai -> {base}/v1/models. +LLAMA_PROVIDERS = { + "ollama": { + "label": "Ollama", + "default_base": "http://localhost:11434", + "api": "ollama", + }, + "llamacpp": { + "label": "llama.cpp", + "default_base": "http://localhost:8080", + "api": "openai", + }, + "lmstudio": { + "label": "LM Studio", + "default_base": "http://localhost:1234/v1", + "api": "openai", + }, + "tgi": { + "label": "TGI / WebUI", + "default_base": "http://localhost:5000/v1", + "api": "openai", + }, + "vllm": { + "label": "vLLM", + "default_base": "http://localhost:8000/v1", + "api": "openai", + }, +} + +#: Cloud LLM providers (provider id -> display label). +CLOUD_PROVIDERS = { + "openai": "OpenAI-compatible", + "gemini": "Google Gemini", + "anthropic": "Anthropic", + "apimix": "apmix.ai", + "openrouter": "OpenRouter", + "groq": "Groq", + "xai": "xAI (Grok)", + "meta_llama": "Meta Llama API", +} + +#: Host roots used only for the (key-gated) reachability probe in "check system". +CLOUD_HOSTS = { + "openai": "https://api.openai.com", + "gemini": "https://generativelanguage.googleapis.com", + "anthropic": "https://api.anthropic.com", + "apimix": "https://api.apmix.ai", + "openrouter": "https://openrouter.ai", + "groq": "https://api.groq.com", + "xai": "https://api.x.ai", + "meta_llama": "https://api.llama.com", +} + +#: Optional AI client libraries probed by the "modules" screen. +MODULES = [ + ("openai", "openai", 'pip install "openai>=1.40"'), + ("anthropic", "anthropic", "pip install anthropic"), + ("httpx", "httpx", "pip install httpx"), + ("aiohttp", "aiohttp", "pip install aiohttp"), + ("requests", "requests", "pip install requests"), +] + +#: Conversation-field metadata: field -> (label, prompt, validator). +#: validator is None | "int" | "float". +_CONV_FIELDS = { + "llama_base": ( + "Base URL", + "Send the base URL of the local server (e.g. http://localhost:11434). Use /cancel to abort.", + None, + ), + "llama_model": ( + "Model", + "Send the model name to use (e.g. llama3, qwen2.5:7b). Use /cancel to abort.", + None, + ), + "llama_ctx": ( + "Context Window", + "Send the context window size in tokens (e.g. 4096). Use /cancel to abort.", + "int", + ), + "llama_temp": ( + "Temperature", + "Send the sampling temperature, 0.0 2.0 (e.g. 0.7). Use /cancel to abort.", + "float", + ), + "llama_sys": ( + "System Prompt", + "Send the system prompt text. Use /cancel to abort.", + None, + ), + "cloud_key": ( + "API Key", + "Send the API key for this cloud provider. Use /cancel to abort.", + None, + ), + "cloud_model": ( + "Model", + "Send the model id (e.g. gpt-4o-mini, gemini-1.5-pro). Use /cancel to abort.", + None, + ), + "cloud_sys": ( + "System Prompt", + "Send the system prompt text. Use /cancel to abort.", + None, + ), + "cloud_base": ( + "Base URL", + "Send the OpenAI-compatible base URL (e.g. https://api.openai.com/v1). Use /cancel to abort.", + None, + ), + "claude_key": ( + "Anthropic API Key", + "Send your Anthropic API key (sk-ant-...). Use /cancel to abort.", + None, + ), + "claude_model": ( + "Default Model", + "Send the default Claude model id (e.g. claude-3-5-sonnet-20241022). Use /cancel to abort.", + None, + ), + "claude_fallback": ( + "Fallback Model", + "Send the fallback Claude model id. Use /cancel to abort.", + None, + ), +} + +#: Fields whose value may be echoed back in the convo confirmation (non-secret, +#: short). Keys and system prompts are never echoed. +_ECHO_FIELDS = { + "llama_base", + "llama_model", + "llama_ctx", + "llama_temp", + "cloud_model", + "cloud_base", + "claude_model", + "claude_fallback", +} + + +def _agent_var(field, scope=""): + """Build a udB key from a convo field (llama_base) + optional + provider scope (ollama) -> AGENT_LLAMA_OLLAMA_BASE.""" + section, _, suffix = field.partition("_") + base = f"AGENT_{section.upper()}" + if scope: + base = f"{base}_{scope.upper()}" + return f"{base}_{suffix.upper()}" + + +def _has_value(value): + """True when a setting is explicitly present, including a stored False/0.""" + return value is not None and not (isinstance(value, str) and not value.strip()) + + +def _state_style(value): + """Use green only for a configured value; leave unset controls unstyled.""" + return "success" if _has_value(value) else None + + +def _back_btn(*current): + """Back button for the screen at menu path current. + + Destination is the parent path - same segments minus the last one + (llama/ -> llama -> home). + """ + parent = current[:-1] or ("home",) + return ("Back", _menu(*parent), None) + + +def _conv_back(field, scope): + """Destination token for a convo flow's " Back" button - re-opens the + provider screen the field belongs to.""" + section = field.split("_", 1)[0] + if section == "llama": + return _menu("llama", scope) + if section == "cloud": + return _menu("cloud", scope) + return _menu("claude") + + +def _mask(value): + """Mask a secret for display - never echoes the raw value back.""" + if not value: + return "not set" + s = str(value) + if len(s) <= 8: + return "****" + return f"{s[:4]}****{s[-4:]}" + + +def _settings_page(title, description, rows, details=None): + """Build a native RichMessage settings table with consistent page chrome.""" + page = rich_page( + title, + rows, + description=description, + columns=("Setting", "Current value"), + total=len(rows), + ) + if not details: + return page + detail_title, detail_text = details + expandable = ( + f"
{html.escape(str(detail_title))}\n" + f"{html.escape(str(detail_text))}

" + ) + return RichMarkup(page.text.replace("
", expandable), "html") + + +# --------------------------------------------------------------------# +# Network helper. async_searcher is the repo's standard async GET (used by +# callbackstuffs.py too); asyncio.wait_for enforces the timeout so a +# hung host can never block the event loop. Returns (ok, status, body): +# ok=True -> (status, parsed-json-or-None) for any HTTP status (host reached) +# ok=False -> (None, "timed out" | "") on timeout / conn error. + + +async def _http_get(url, headers=None, timeout=10): + async def _eval(resp): + status = resp.status + try: + body = await resp.json() + except Exception: + body = None + return status, body + + try: + status, body = await asyncio.wait_for( + fns.async_searcher(url, headers=headers, evaluate=_eval), + timeout=timeout, + ) + return True, status, body + except TimeoutError: + return False, None, "timed out" + except Exception as e: + return False, None, f"{e.__class__.__name__}" + + +def _validate_spec(prov, key, base): + """Return (url, headers) for a real lightweight authenticated "whoami" + request, or (None, None) when no safe validation endpoint is known.""" + if prov == "openai": + b = (base or "https://api.openai.com/v1").rstrip("/") + return f"{b}/models", {"Authorization": f"Bearer {key}"} + if prov == "gemini": + return ( + f"https://generativelanguage.googleapis.com/v1beta/models?key={key}", + {}, + ) + if prov == "anthropic": + return ( + "https://api.anthropic.com/v1/models", + {"x-api-key": key, "anthropic-version": "2023-06-01"}, + ) + if prov == "openrouter": + return "https://openrouter.ai/api/v1/key", {"Authorization": f"Bearer {key}"} + if prov == "groq": + return "https://api.groq.com/openai/v1/models", { + "Authorization": f"Bearer {key}" + } + if prov == "xai": + return "https://api.x.ai/v1/models", {"Authorization": f"Bearer {key}"} + if prov == "meta_llama": + return "https://api.llama.com/v1/models", {"Authorization": f"Bearer {key}"} + return None, None + + +def _validate_hint(prov, body): + """A non-sensitive hint from a successful validation (model count / key + label) - never includes the key itself.""" + try: + if prov == "openrouter" and isinstance(body, dict): + d = body.get("data", {}) or {} + parts = [] + if d.get("label"): + parts.append(f"label: {d['label']}") + if d.get("usage") is not None: + parts.append(f"usage: {d['usage']}") + return f" ({', '.join(parts)})" if parts else "" + if isinstance(body, dict): + data = body.get("data") or body.get("models") or [] + if isinstance(data, list) and data: + return f" ({len(data)} models listed)" + except Exception: + pass + return "" + + +def _probe_modules(): + """Real importability probe - uses find_spec (no import side effects), + so the module imports fine even when a library is missing.""" + import importlib.util + + return {name: importlib.util.find_spec(name) is not None for name, _, _ in MODULES} + + +def _mem_info(): + """Best-effort memory readout: psutil if available, else /proc/meminfo, + else a clear 'unavailable' note.""" + try: + import psutil + + vm = psutil.virtual_memory() + return ( + f"{vm.percent}% used - {vm.available // (1024**2)} MB free / " + f"{vm.total // (1024**2)} MB total" + ) + except Exception: + pass + try: + with open("/proc/meminfo") as f: + d = {} + for line in f: + k, _, v = line.partition(":") + d[k.strip()] = v.strip().split()[0] + total = int(d["MemTotal"]) // 1024 + avail = int(d["MemAvailable"]) // 1024 + pct = (100 * (total - avail) / total) if total else 0 + return f"{pct:.0f}% used - {avail} MB free / {total} MB total" + except Exception: + return "unavailable (install psutil for details)" + + +def _collect_endpoints(): + """Endpoints to probe in "check system": user-configured local bases + the + hosts of cloud/Claude providers that actually have a stored key.""" + eps = [] + for pid, info in LLAMA_PROVIDERS.items(): + base = udB.get_key(_agent_var("llama_base", pid)) + if base: + eps.append((f"Llama - {info['label']}", base.rstrip("/"))) + for pid in CLOUD_PROVIDERS: + if udB.get_key(_agent_var("cloud_key", pid)): + if pid == "openai": + b = ( + udB.get_key(_agent_var("cloud_base", pid)) + or "https://api.openai.com/v1" + ).rstrip("/") + host = b.rsplit("/v1", 1)[0] if "/v1" in b else b + eps.append((f"Cloud - {CLOUD_PROVIDERS[pid]}", host)) + else: + eps.append((f"Cloud - {CLOUD_PROVIDERS[pid]}", CLOUD_HOSTS[pid])) + if udB.get_key("AGENT_CLAUDE_KEY"): + eps.append(("Claude - Anthropic", "https://api.anthropic.com")) + if not eps: + eps.append(("Ollama (default)", LLAMA_PROVIDERS["ollama"]["default_base"])) + return eps + + +# --------------------------------------------------------------------# +# Menu renderers - each returns native RichMarkup plus callback buttons. + + +def _home(): + primary = agent().config_default_provider() + primary_label = ( + CLOUD_PROVIDERS.get(primary) + or (LLAMA_PROVIDERS.get(primary) or {}).get("label") + or primary + ) + text = _settings_page( + "Agent Config", + "Configure local and cloud models, manage keys, inspect installed modules, and run a system health check.", + [ + ("Version", f"v{ultroid_version}"), + ("Primary provider", primary_label if primary else "Automatic routing"), + ("Native RichMessage engine", "Available for this assistant bot"), + ], + ) + buttons = ikm( + [ + [ + ("Llama / Local", _menu("llama"), "primary"), + ("Cloud AI", _menu("cloud"), "primary"), + ], + [ + ("Claude (Anthropic)", _menu("claude"), "primary"), + ("Keys", _menu("keys"), "primary"), + ], + [ + ("Modules", _menu("modules"), "primary"), + ("Check System", _act("syscheck"), "primary"), + ], + [("Close", _act("close"), None)], + ], + icon=False, + ) + return text, buttons + + +def _llama_menu(): + rows = [] + items = list(LLAMA_PROVIDERS.items()) + while items: + a = items.pop(0) + row = [(a[1]["label"], _menu("llama", a[0]), "primary")] + if items: + b = items.pop(0) + row.append((b[1]["label"], _menu("llama", b[0]), "primary")) + rows.append(row) + rows.append([_back_btn("llama")]) + text = _settings_page( + "Llama / Local", + "Choose a local inference server. Each server keeps its own URL, model, context, temperature, and prompt.", + [ + ( + info["label"], + ( + f"{udB.get_key(_agent_var('llama_base', pid)) or info['default_base']} · " + f"{udB.get_key(_agent_var('llama_model', pid)) or 'model not set'}" + ), + ) + for pid, info in LLAMA_PROVIDERS.items() + ], + ) + return text, ikm(rows, icon=False) + + +def _llama_prov(prov): + info = LLAMA_PROVIDERS.get(prov) + if not info: + return body_page("Llama", "

Unknown provider.

"), ikm( + [[_back_btn("llama", prov)]], icon=False + ) + stored_base = udB.get_key(_agent_var("llama_base", prov)) + base = stored_base or info["default_base"] + model = udB.get_key(_agent_var("llama_model", prov)) + context = udB.get_key(_agent_var("llama_ctx", prov)) + temperature = udB.get_key(_agent_var("llama_temp", prov)) + system_prompt = udB.get_key(_agent_var("llama_sys", prov)) + text = _settings_page( + f"Llama · {info['label']}", + "Settings for this local inference endpoint. Fetch Models checks the live server without changing configuration.", + [ + ("Base URL", base), + ("Model", model or "Not set"), + ("Context window", context if _has_value(context) else "Not set"), + ("Temperature", temperature if _has_value(temperature) else "Not set"), + ("API protocol", info["api"]), + ], + details=("System prompt", system_prompt or "Not set"), + ) + buttons = ikm( + [ + [ + ("Base URL", _conv("llama_base", prov), _state_style(stored_base)), + ("Model", _conv("llama_model", prov), _state_style(model)), + ], + [ + ("Context", _conv("llama_ctx", prov), _state_style(context)), + ("Temperature", _conv("llama_temp", prov), _state_style(temperature)), + ], + [("System Prompt", _conv("llama_sys", prov), _state_style(system_prompt))], + [("Fetch Models", _act("llama_fetch", prov), None)], + [_back_btn("llama", prov)], + ], + icon=False, + ) + return text, buttons + + +def _llama_prov_buttons(prov): + return ikm([[_back_btn("llama", prov)]], icon=False) + + +def _cloud_menu(): + rows = [] + items = list(CLOUD_PROVIDERS.items()) + while items: + a = items.pop(0) + row = [(a[1], _menu("cloud", a[0]), "primary")] + if items: + b = items.pop(0) + row.append((b[1], _menu("cloud", b[0]), "primary")) + rows.append(row) + rows.append([_back_btn("cloud")]) + text = _settings_page( + "Cloud AI", + "Store keys securely, choose a model and prompt, validate credentials, and select a primary provider.", + [ + ( + label, + "configured · " + + str(udB.get_key(_agent_var("cloud_model", pid)) or "model not set") + if udB.get_key(_agent_var("cloud_key", pid)) + else "not configured", + ) + for pid, label in CLOUD_PROVIDERS.items() + ], + ) + return text, ikm(rows, icon=False) + + +def _provider_pin_label(provider: str) -> str: + """Label for a provider's pin button, including its current state.""" + if not udB.get_key("AGENT_CLOUD_%s_KEY" % provider.upper()): + return "Not configured" + if agent().config_default_provider() == provider: + return "Primary for .ai/.ask" + return "Set as primary" + + +def _cloud_prov(prov): + label = CLOUD_PROVIDERS.get(prov, prov) + key = udB.get_key(_agent_var("cloud_key", prov)) + stored_base = udB.get_key(_agent_var("cloud_base", prov)) + base = stored_base + if not base and prov == "openai": + base = "https://api.openai.com/v1" + model = udB.get_key(_agent_var("cloud_model", prov)) + system_prompt = udB.get_key(_agent_var("cloud_sys", prov)) + data = [ + ("API key", _mask(key)), + ("Model", model or "Not set"), + ( + "Primary for .ai/.ask", + "Yes" if agent().config_default_provider() == prov else "No", + ), + ] + if prov == "openai": + data.insert(2, ("Base URL", base or "Not set")) + text = _settings_page( + f"Cloud · {label}", + "Credentials are masked. Validate Key performs a read-only authenticated provider check.", + data, + details=("System prompt", system_prompt or "Not set"), + ) + rows = [ + [ + ("API Key", _conv("cloud_key", prov), _state_style(key)), + ("Model", _conv("cloud_model", prov), _state_style(model)), + ], + [("System Prompt", _conv("cloud_sys", prov), _state_style(system_prompt))], + ] + if prov == "openai": + rows.insert( + 1, + [("Base URL", _conv("cloud_base", prov), _state_style(stored_base))], + ) + if _has_value(key): + rows.append([("Validate Key", _act("cloud_validate", prov), "success")]) + pinned = agent().config_default_provider() == prov + rows.append( + [ + ( + _provider_pin_label(prov), + _act("cloud_primary", prov), + "success" if pinned else None, + ) + ] + ) + rows.append([_back_btn("cloud", prov)]) + buttons = ikm(rows, icon=False) + return text, buttons + + +def _cloud_prov_buttons(prov): + return ikm([[_back_btn("cloud", prov)]], icon=False) + + +def _claude_menu(): + key = udB.get_key("AGENT_CLAUDE_KEY") + model = udB.get_key("AGENT_CLAUDE_MODEL") + fallback = udB.get_key("AGENT_CLAUDE_FALLBACK") + text = _settings_page( + "Claude · Anthropic", + "Configure model selection and fallback. Fetch Models checks Anthropic's live catalog and returns shareable specs.", + [ + ("API key", _mask(key)), + ("Default model", model or "Not set"), + ("Fallback model", fallback or "Not set"), + ], + ) + buttons = ikm( + [ + [ + ("API Key", _conv("claude_key"), _state_style(key)), + ("Default Model", _conv("claude_model"), _state_style(model)), + ], + [("Fallback Model", _conv("claude_fallback"), _state_style(fallback))], + [("Fetch Models", _act("claude_fetch"), None)], + [_back_btn("claude")], + ], + icon=False, + ) + return text, buttons + + +def _claude_menu_buttons(): + return ikm([[_back_btn("claude")]], icon=False) + + +def _keys_menu(): + rows = [] + for pid, label in CLOUD_PROVIDERS.items(): + k = udB.get_key(_agent_var("cloud_key", pid)) + rows.append((f"Cloud · {label}", _mask(k) if k else "Not set")) + ck = udB.get_key("AGENT_CLAUDE_KEY") + rows.append(("Claude · Anthropic", _mask(ck) if ck else "Not set")) + configured = [ + LLAMA_PROVIDERS[p]["label"] + for p in LLAMA_PROVIDERS + if udB.get_key(_agent_var("llama_base", p)) + ] + rows.append(("Local LLM endpoints", ", ".join(configured) if configured else "None configured")) + text = _settings_page( + "Credentials", + "Keys are shown masked and never echoed in full. Use the buttons to clear a provider section.", + rows, + ) + buttons = ikm( + [ + [ + ("Clear Llama", _act("keys_clear", "llama"), "danger"), + ("Clear Cloud", _act("keys_clear", "cloud"), "danger"), + ], + [ + ("Clear Claude", _act("keys_clear", "claude"), "danger"), + ("Clear All", _act("keys_clear", "all"), "danger"), + ], + [_back_btn("keys")], + ], + icon=False, + ) + return text, buttons + + +def _modules_menu(): + probe = _probe_modules() + rows = [] + for name, label, install in MODULES: + rows.append( + (label, "Installed" if probe[name] else f"Missing · {install}") + ) + text = _settings_page( + "AI Modules", + "Importability of optional AI client libraries. Missing modules affect only the features that use them.", + rows, + ) + buttons = ikm([[_back_btn("modules")]], icon=False) + return text, buttons + + +def _render_menu(key): + """Dispatch a menu: callback to its screen renderer. + + key is the path below assistant:agent:menu: - every level owns + the next (llama -> llama:), so back is always the parent + path (see :func:_back_btn). + """ + levels = key.split(":") if key else [] + if levels == ["home"]: + return _home() + if levels == ["llama"]: + return _llama_menu() + if len(levels) == 2 and levels[0] == "llama": + return _llama_prov(levels[1]) + if levels == ["cloud"]: + return _cloud_menu() + if len(levels) == 2 and levels[0] == "cloud": + return _cloud_prov(levels[1]) + if levels == ["claude"]: + return _claude_menu() + if levels == ["keys"]: + return _keys_menu() + if levels == ["modules"]: + return _modules_menu() + return None, None + + +# --------------------------------------------------------------------# +# Action bodies - real network fetches / probes. Each returns (text, buttons). + + +async def _llama_fetch(prov): + info = LLAMA_PROVIDERS.get(prov) + if not info: + return ( + f"Llama\n\nUnknown provider.", + ikm([[_back_btn("llama", prov)]], icon=False), + ) + base = (udB.get_key(_agent_var("llama_base", prov)) or info["default_base"]).rstrip( + "/" + ) + if info["api"] == "ollama": + url = f"{base}/api/tags" + elif base.endswith("/v1"): + # OpenAI-compatible servers whose configured base already carries the + # /v1 prefix (LM Studio, TGI and vLLM defaults do): appending another + # one doubled the prefix and every fetch 404'd. + url = f"{base}/models" + else: + url = f"{base}/v1/models" + ok, status, body = await _http_get(url, timeout=10) + head = f"Llama - {info['label']} - Models" + if not ok: + return ( + f"{head}\n\nUnreachable - needs a running provider at " + f"{html.escape(url)}.\n\nReason: {html.escape(str(body))}", + _llama_prov_buttons(prov), + ) + if status != 200: + return ( + f"{head}\n\nServer responded HTTP {status} at " + f"{html.escape(url)}. Is the right provider running there?", + _llama_prov_buttons(prov), + ) + if info["api"] == "ollama": + models = (body or {}).get("models", []) or [] + lines = [] + for m in models[:30]: + det = m.get("details", {}) or {} + lines.append( + f"- {html.escape(str(m.get('name', '?')))} - " + f"{html.escape(str(det.get('parameter_size', '?')))} - " + f"{html.escape(str(det.get('quantization_level', '?')))}" + ) + else: + models = (body or {}).get("data", []) or [] + lines = [f"- {html.escape(str(m.get('id', '?')))}" for m in models[:30]] + count = len(models) + if not lines: + msg = "No models returned by the server." + else: + msg = ( + f"Fetched {count} model(s) from {html.escape(url)}:\n\n" + + "\n".join(lines) + ) + if count > 30: + msg += f"\n... and {count - 30} more" + return f"{head}\n\n{msg}", _llama_prov_buttons(prov) + + +async def _cloud_validate(prov): + label = CLOUD_PROVIDERS.get(prov, prov) + back = _cloud_prov_buttons(prov) + head = f"Cloud - {label} - Validate" + key = udB.get_key(_agent_var("cloud_key", prov)) + if not key: + return ( + f"{head}\n\nNo API key set for this provider. Set one first.", + back, + ) + base = udB.get_key(_agent_var("cloud_base", prov)) if prov == "openai" else None + url, headers = _validate_spec(prov, key, base) + if url is None: + return ( + f"{head}\n\nNo safe validation endpoint is known for this " + f"provider. Validate by sending a real completion request with your key.", + back, + ) + ok, status, body = await _http_get(url, headers=headers, timeout=12) + if not ok: + return ( + f"{head}\n\nCould not reach provider.\nReason: " + f"{html.escape(str(status or body))}", + back, + ) + if status == 200: + return ( + f"{head}\n\nKey is valid. Provider authenticated the request." + + html.escape(_validate_hint(prov, body)), + back, + ) + if status in (401, 403): + return ( + f"{head}\n\nProvider rejected the key (HTTP {status}). " + f"Check the key and try again.", + back, + ) + return f"{head}\n\nUnexpected response (HTTP {status}).", back + + +async def _claude_fetch(): + back = _claude_menu_buttons() + head = f"Claude - Models" + key = udB.get_key("AGENT_CLAUDE_KEY") + if not key: + return ( + f"{head}\n\nNo Anthropic API key set. Set one first " + f"(Claude API Key).", + back, + ) + ok, status, body = await _http_get( + "https://api.anthropic.com/v1/models", + headers={"x-api-key": key, "anthropic-version": "2023-06-01"}, + timeout=12, + ) + if not ok: + return ( + f"{head}\n\nCould not reach Anthropic.\nReason: " + f"{html.escape(str(status or body))}", + back, + ) + if status != 200: + msg = f"Anthropic rejected the request (HTTP {status})." + if status in (401, 403): + msg += " Check your API key." + return f"{head}\n\n{msg}", back + data = (body or {}).get("data", []) or [] + if not data: + return f"{head}\n\nNo models returned.", back + + # Plaintext specs for the paste. + specs = [ + f"Anthropic Models - fetched {datetime.now(timezone.utc).isoformat(timespec='seconds')}", + "", + ] + for m in data: + specs.append(f"- {m.get('id', '?')}") + if m.get("display_name"): + specs.append(f" display_name: {m['display_name']}") + if m.get("created_at"): + specs.append(f" created_at: {m['created_at']}") + if m.get("type"): + specs.append(f" type: {m['type']}") + specs_text = "\n".join(specs) + + paste_url = None + try: + okp, pkey = await fns.get_paste(specs_text, extension="txt") + if okp and pkey: + paste_url = f"https://spaceb.in/{pkey}" + except Exception: + paste_url = None + + tele_url = None + try: + tele_url = await fns.make_html_telegraph( + "Anthropic Models", f"
{html.escape(specs_text)}
" + ) + except Exception: + tele_url = None + + summary = "\n".join(f"- {html.escape(str(m.get('id', '?')))}" for m in data[:20]) + if len(data) > 20: + summary += f"\n... and {len(data) - 20} more" + body_html = f"Fetched {len(data)} model(s):\n\n{summary}" + if not paste_url and not tele_url: + body_html += "\n\n( Paste generation failed - full list shown above. )" + + rows = [] + url_row = [] + if paste_url: + url_row.append(("Specs Paste", "url", paste_url, "primary")) + if tele_url: + url_row.append(("Telegraph", "url", tele_url, "primary")) + if url_row: + rows.append(url_row) + rows.append([_back_btn("claude")]) + return f"{head}\n\n{body_html}", ikm(rows, icon=False) + + +async def _keys_clear(scope): + cleared = [] + + def _del(var): + if udB.get_key(var): + udB.del_key(var) + cleared.append(var) + + if scope in ("llama", "all"): + for pid in LLAMA_PROVIDERS: + for f in ("BASE", "MODEL", "CTX", "TEMP", "SYS"): + _del(f"AGENT_LLAMA_{pid.upper()}_{f}") + if scope in ("cloud", "all"): + for pid in CLOUD_PROVIDERS: + for f in ("KEY", "MODEL", "SYS", "BASE"): + _del(f"AGENT_CLOUD_{pid.upper()}_{f}") + if scope in ("claude", "all"): + for f in ("KEY", "MODEL", "FALLBACK"): + _del(f"AGENT_CLAUDE_{f}") + # A pin that outlives its key is a trap: .ai would keep forcing a + # provider that can no longer authenticate. Drop the pin when the + # provider it points at just lost its credentials. + try: + pinned = agent().config_default_provider() + if pinned and not agent().config_ready(pinned): + agent().config_use_default(None) + except Exception: + pass + msg = ( + f"Cleared {len(cleared)} stored credential(s)." + if cleared + else "Nothing to clear - no credentials stored for this section." + ) + return ( + f"Credentials - Cleared\n\n{msg}", + ikm([[_back_btn("keys")]], icon=False), + ) + + +async def _syscheck(): + py = platform.python_version() + plat = platform.platform() + mem = _mem_info() + endpoints = _collect_endpoints() + + async def _one(label, url): + ok, _status, body = await _http_get(url, timeout=6) + if ok: + return label, url, "reachable" + return label, url, f"{html.escape(str(body))}" + + reach = ( + await asyncio.gather(*[_one(label, url) for label, url in endpoints]) + if endpoints + else [] + ) + + lines = [ + f"Python: {html.escape(py)}", + f"Platform: {html.escape(plat)}", + f"Memory: {html.escape(mem)}", + "", + "Endpoint reachability:", + ] + if reach: + for label, url, state in reach: + lines.append( + f"- {html.escape(label)} - {state} ({html.escape(url)})" + ) + else: + lines.append("- No provider endpoints configured yet.") + return ( + f"System Check\n\n" + "\n".join(lines), + ikm([[_back_btn("home")]], icon=False), + ) + + +# --------------------------------------------------------------------# +# Handlers. CallbackQuery.Event has no .buttons and event.client is the +# assistant bot (event.client._bot self-references it); all state is read +# from udB, so no get_message() is needed and routing stays on the bot. + + +@asst_cmd(pattern="agent", owner=True) +async def _agent_cmd(event): + text, buttons = _home() + await send_rich( + event.client, + event.chat_id, + text, + buttons=buttons, + reply_to=event.id, + link_preview=False, + ) + + +@callback(MENU_PATTERN, owner=True) +async def _menu_handler(event): + key = event.data_match.group(1).decode("utf-8") + text, buttons = _render_menu(key) + if text is None: + # A dead path (stale button after a reload of the module tree) must + # not just swallow the click; tell the owner and land on home. + text, buttons = _home() + try: + await event.answer( + "That screen no longer exists; reopened home.", alert=True + ) + except Exception: + pass + await edit_callback_page(event, text, buttons) + return + await event.answer() + await edit_callback_page(event, text, buttons) + + +@callback(CONV_PATTERN, owner=True) +async def _conv_handler(event): + key = event.data_match.group(1).decode("utf-8") + field, _, scope = key.partition(":") + meta = _CONV_FIELDS.get(field) + if not meta: + return + label, prompt, validator = meta + var = _agent_var(field, scope) + back = _conv_back(field, scope) + try: + await event.answer("Enter a value in the chat.") + await event.delete() + except Exception: + pass + async with event.client.conversation(event.sender_id, timeout=120) as conv: + await conv.send_message(prompt) + try: + response = await conv.get_response() + except TimeoutError: + return await conv.send_message( + "Timed out. Please try again.", buttons=get_back_button(back) + ) + value = response.message + value_text = str(value).strip() + cancel_command = ( + value_text.split(maxsplit=1)[0].split("@", 1)[0] if value_text else "" + ) + if cancel_command.casefold() == "/cancel": + return await conv.send_message("Cancelled.", buttons=get_back_button(back)) + if validator: + try: + value = float(value) if validator == "float" else int(value) + if validator == "float" and not 0 <= value <= 2: + raise ValueError("out of range") + except (ValueError, TypeError): + return await conv.send_message( + f"Invalid value for {label}.", + buttons=get_back_button(back), + ) + await setit(event, var, value) + if field in _ECHO_FIELDS: + shown = f"{value}" + elif field.endswith("_key"): + shown = " - (masked)" + else: + shown = "saved" + await conv.send_message( + f"{label} set to {shown}.", buttons=get_back_button(back) + ) + + +@callback(ACT_PATTERN, owner=True) +async def _act_handler(event): + key = event.data_match.group(1).decode("utf-8") + action, _, rest = key.partition(":") + if action == "close": + try: + return await event.delete() + except Exception: + return await event.answer("Could not close.", alert=True) + await event.answer("Working...") + if action == "syscheck": + text, buttons = await _syscheck() + elif action == "llama_fetch": + text, buttons = await _llama_fetch(rest) + elif action == "cloud_validate": + text, buttons = await _cloud_validate(rest) + elif action == "cloud_primary": + try: + if agent().config_default_provider() == rest: + agent().config_use_default(None) + text, buttons = _cloud_prov(rest) + else: + agent().config_use_default(rest, require_configured=True) + text, buttons = _cloud_prov(rest) + except (KeyError, ValueError) as exc: + text = body_page( + "Primary provider", + f"

Could not set {html.escape(CLOUD_PROVIDERS.get(rest, rest))} as primary: " + f"{html.escape(str(exc))}

", + ) + buttons = _cloud_prov_buttons(rest) + elif action == "claude_fetch": + text, buttons = await _claude_fetch() + elif action == "keys_clear": + text, buttons = await _keys_clear(rest) + else: + return + if isinstance(text, str): + text = body_page("Agent result", text) + await edit_callback_page(event, text, buttons) diff --git a/assistant/agent_bridge.py b/assistant/agent_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f2081f90d05d4a8f47ad9fb40b111e1053167032 --- /dev/null +++ b/assistant/agent_bridge.py @@ -0,0 +1,110 @@ +"""Routes the user's answer back to whatever the agent is waiting on. + +This is the half of the ask bridge that was missing: the tool half lives in +:mod:pyUltroid.agent._interactive and puts a styled keyboard on the Bot, but +a tap on that keyboard and a typed reply both have to arrive back here to +settle the future the tool is blocked on. + +Two handlers, both deliberately unfiltered: + +* every CallbackQuery is offered to the bridge, which claims only the + data it minted and ignores the rest - the assistant's own menu buttons share + the same dispatcher, so this must be a filter and not a pattern; +* every private inbound text message is offered as a typed answer to the + oldest open question in that chat, and is otherwise left completely alone, + so the PM bot and the session threads keep owning their own flows. + +The client note matters: Telegram does not deliver a callback query for a +message the *User* account sent itself. That is why the question goes out on +the Bot in the first place, and why this file binds bot=asst. +""" + +from __future__ import annotations + +from typing import Any + +from telethon import events + +from pyUltroid import asst +from pyUltroid.startup.logger import LOGS +from pyUltroid.agent._bridge import AskBridge, shared_bridge +from pyUltroid.agent._telegram import text_of + +__res_tags__ = ["ai", "agent", "bridge"] +_REGISTERED = False + + +def _bridge() -> AskBridge: + """The process-wide bridge, bound to the bot that paints the keyboards.""" + bridge = shared_bridge() + bridge.attach(bot=asst) + return bridge + + +async def on_ask_callback(event: Any) -> None: + """Settle the question whose button was tapped.""" + data = getattr(event, "data", None) + if not data: + return + bridge = _bridge() + if not bridge.owns(data): + return + try: + outcome = bridge.resolve_callback(data) + except Exception as exc: # noqa: BLE001 - one bad tap must not kill the bot + LOGS.exception("[agent/bridge] callback resolve failed: %s", exc) + return + if outcome is None: + return + # The keyboard has served its purpose; take it off the message so a second + # tap cannot re-answer a question that is already settled. + try: + await event.delete() + except Exception: # noqa: BLE001 - deleting is cosmetic + pass + LOGS.info( + "[agent/bridge] answered %r via button after %.1fs", + outcome.question[:60], + outcome.waited, + ) + raise events.StopPropagation + + +async def on_ask_reply(event: Any) -> None: + """Settle the oldest open question in this chat with typed text.""" + bridge = _bridge() + if bridge.pending == 0: + return + text = text_of(getattr(event, "message", event), "").strip() + if not text: + return + try: + outcome = bridge.submit_text(event.chat_id, text) + except Exception as exc: # noqa: BLE001 + LOGS.exception("[agent/bridge] text resolve failed: %s", exc) + return + if outcome is not None: + LOGS.info( + "[agent/bridge] answered %r by text after %.1fs", + outcome.question[:60], + outcome.waited, + ) + raise events.StopPropagation + + +def register() -> None: + """Bind the clients and attach both handlers to the bot.""" + global _REGISTERED + if _REGISTERED or asst is None: + return + _bridge() + asst.add_event_handler(on_ask_callback, events.CallbackQuery()) + asst.add_event_handler( + on_ask_reply, + events.NewMessage(incoming=True, func=lambda e: bool(e.is_private)), + ) + _REGISTERED = True + LOGS.info("[agent/bridge] ask bridge wired to the assistant bot") + + +register() diff --git a/assistant/ai_dm.py b/assistant/ai_dm.py new file mode 100644 index 0000000000000000000000000000000000000000..eb83270435f07f1a0716ee1bc054df1e88083e5e --- /dev/null +++ b/assistant/ai_dm.py @@ -0,0 +1,238 @@ +"""Agent sessions in the assistant bot's DM, one reply thread per session. + +A session-start card anchors a reply thread. Replies to that anchor continue +only that session; ordinary private messages and commands remain available to +the PM bot and other assistant handlers. + +Session metadata is stored under ``AGENT_DM_SESSIONS_`` and each +conversation uses a typed ``dm::`` key, keeping sessions +separate across users and restarts. +""" + +from __future__ import annotations + +import re +import time +from typing import Any + +from telethon import events + +from pyUltroid import asst +from pyUltroid._core.richmsg import ( + RichBlocks, + client_can_send_rich_message, + send_rich, +) +from pyUltroid._misc._assistant import asst_cmd +from pyUltroid.agent import AgentRequest, agent +from pyUltroid.agent import controls as ai_controls +from pyUltroid.agent._chatkey import DmSessionKey +from pyUltroid.agent._delivery import DeliveryError as _DeliveryError +from pyUltroid.agent._delivery import DeliveryStrategy as _SessionDelivery +from pyUltroid.agent._reporting import report_run +from pyUltroid.agent._sessions import SessionStoreError +from pyUltroid.startup.logger import LOGS as _LOGS + +__res_tags__ = ["ai", "agent", "sessions"] + +# Only strip a command at the beginning of the message. Never remove text that +# merely happens to contain "/ai" later in the user's prompt. +_AI_PREFIX = re.compile(r"^/ai(?:@\w+)?(?:\s+|$)", re.IGNORECASE) + + +async def send_session_card(user_id: Any, title: str) -> Any: + """Send the session-start card; its message is the session anchor.""" + blocks = ( + RichBlocks() + .header("AI session", level=3) + .header(str(title), level=4) + .paragraph( + "Reply to this message to continue this session. " + "Each session has its own conversation history." + ) + ) + return await send_rich(asst, user_id, blocks) + + +async def _send_session_list(event: Any, sessions: list[dict]) -> Any: + """Render a readable, consistently indented session index.""" + items = [] + for session in sessions: + when = time.strftime("%Y-%m-%d %H:%M", time.gmtime(session.get("created", 0))) + title = str(session.get("title") or "Untitled session") + anchor = session.get("anchor") + items.append(f"{title} — {when} (reply to message {anchor})") + + blocks = RichBlocks().header("Your AI sessions", level=2).list(items) + return await send_rich( + event.client, + event.chat_id, + blocks, + reply_to=event, + link_preview=False, + ) + + +@asst_cmd("ai") +async def dm_ai_cmd(event): + """Start an AI session or continue the session card being replied to.""" + if not event.is_private: + return + user_id = event.sender_id + prompt = _AI_PREFIX.sub("", (event.raw_text or "").strip(), count=1).strip() + + reply = await event.get_reply_message() + session = _session_for_reply(user_id, reply) if reply is not None else None + + if session is None: + title = (prompt or "New session")[:60] + card = await send_session_card(user_id, title) + try: + agent().session_create(user_id, card.id, title) + except SessionStoreError: + return await event.reply( + "This session could not be saved, so it cannot be continued later. " + "Please try again." + ) + anchor = card.id + else: + anchor = session["anchor"] + + if not prompt: + return await event.reply( + "Reply to the session card with a prompt, or send /ai " + "to start a new session." + ) + + await _run_session(event, user_id, anchor, prompt) + + +@asst_cmd("sessions") +async def dm_sessions_cmd(event): + """List this user's AI sessions in the assistant bot's private chat.""" + if not event.is_private: + return + sessions = agent().session_list(event.sender_id) + if not sessions: + return await event.reply("No sessions yet. Start one with /ai .") + return await _send_session_list(event, sessions) + + +@asst.on( + events.NewMessage( + incoming=True, + func=lambda event: ( + event.is_private + and event.is_reply + and bool((event.raw_text or "").strip()) + and not (event.raw_text or "").lstrip().startswith("/") + ), + ) +) +async def dm_thread_handler(event): + """Continue only the session associated with the replied-to anchor.""" + user_id = event.sender_id + session = agent().session_find(user_id, event.reply_to_msg_id) + if session is None: + session = _session_for_reply(user_id, await event.get_reply_message()) + if session is None: + return + anchor = session["anchor"] + try: + await _run_session(event, user_id, anchor, (event.raw_text or "").strip()) + except Exception: # noqa: BLE001 - outer Telegram handler boundary + _LOGS.error("[agent/dm] session reply failed") + try: + await event.reply( + "This AI session could not process that reply. " + "Try again or start a new session." + ) + except Exception: # noqa: BLE001 - failure notice is best-effort + _LOGS.error("[agent/dm] session error notice could not be sent") + raise events.StopPropagation + + +async def _run_session(event: Any, user_id: Any, anchor: int, prompt: str) -> None: + """Run one agent turn and deliver it in the session's reply thread.""" + key = DmSessionKey(user_id, anchor).value + controls = ai_controls.get_controls(f"dm:{user_id}") + started = time.time() + delivery = _SessionDelivery(event, anchor=anchor) + rich_allowed = await client_can_send_rich_message(event.client) + try: + status = await delivery.placeholder() + except _DeliveryError as exc: + return await event.reply( + f"Could not open session {anchor}: delivery failed at {exc.phase}. " + "Start a new session with /ai ." + ) + + try: + response = await agent().runtime_run( + AgentRequest( + prompt=prompt, + chat_id=key, + origin="dm-session", + user_id=user_id, + is_private=True, + use_tools=ai_controls.dm_tools_enabled(user_id, controls), + max_rounds=controls["rounds"], + model=controls["model"], + temperature=controls["temp"], + use_cache=True, + rich_messages_allowed=rich_allowed, + timeout_seconds=105.0, + ) + ) + except Exception: # noqa: BLE001 - report unexpected runtime/provider failures + _LOGS.error("[agent/dm] runtime failed") + try: + await delivery.render( + status, + "This session could not complete the request. Please try again.", + ) + except _DeliveryError: + _LOGS.error("[agent/dm] runtime failure notice could not be delivered") + return + + report_run( + origin="dm-session", + chat_id=event.chat_id, + user=getattr(getattr(event, "sender", None), "username", None), + provider=response.provider, + model=response.model, + prompt=prompt, + tools_used=list(getattr(response, "tools_used", None) or []), + duration=time.time() - started, + ok=response.ok, + error=getattr(response, "error", None), + ) + try: + await delivery.render(status, response) + except _DeliveryError as exc: + await event.reply( + f"Could not deliver response {anchor}: delivery failed at {exc.phase}." + ) + + +def _session_for_reply(user_id: Any, reply: Any) -> dict | None: + """Resolve replies to either a session anchor or a result in its thread.""" + store = agent() + message_id = getattr(reply, "id", None) + session = store.session_find(user_id, message_id) + if session is not None: + return session + header = getattr(reply, "reply_to", None) + # Telethon retains thread root metadata on replies even when the directly + # replied-to result has scrolled out of cache. + for candidate in ( + getattr(reply, "reply_to_top_id", None), + getattr(header, "reply_to_top_id", None), + getattr(reply, "reply_to_msg_id", None), + getattr(header, "reply_to_msg_id", None), + ): + if candidate: + session = store.session_find(user_id, candidate) + if session is not None: + return session + return None diff --git a/assistant/callbackstuffs.py b/assistant/callbackstuffs.py index 9568724ee9541784859c4999a8b6abf1cc450338..f8db4ff2d71d1f63752d12058e0a6dc7ea169abd 100644 --- a/assistant/callbackstuffs.py +++ b/assistant/callbackstuffs.py @@ -1,5 +1,5 @@ # Ultroid - UserBot -# Copyright (C) 2021-2026 TeamUltroid +# Copyright (C) 2021-2023 TeamUltroid # # This file is a part of < https://github.com/TeamUltroid/Ultroid/ > # PLease read the GNU Affero General Public License in @@ -7,11 +7,11 @@ import ast import asyncio -import re -import sys import time +import unicodedata from asyncio.exceptions import TimeoutError as AsyncTimeOut -from os import execl, remove +from os import remove +from pathlib import Path from random import choice from bs4 import BeautifulSoup as bs @@ -20,22 +20,295 @@ try: from pyUltroid.fns.gDrive import GDriveManager except ImportError: GDriveManager = None -from telethon import Button, events -from catbox import CatboxUploader +from telegraph import upload_file as upl +from telethon import events +from telethon.tl import types from telethon.tl.types import MessageMediaWebPage from telethon.utils import get_peer_id -from pyUltroid.fns.helper import fast_download, progress -from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client -from pyUltroid.startup.loader import Loader +from custom.fmt import fmtmsg, rawhtml +from pyUltroid._core.loader import AsyncPluginLoader +from pyUltroid._core.richmsg import send_rich +from pyUltroid.fns import fns +from pyUltroid.ultroid import core from . import * +from ._cbs import cb, cb_exact_pattern, cb_pattern +from .rich_pages import edit_callback_page, rich_page +telegraph = fns.telegraph_client() + +try: + GDrive = GDriveManager() if GDriveManager else None +except Exception: + GDrive = None + + +def _tok(*parts): + return cb("assistant", "callbacks", *parts) + + +def _handler(*parts): + return cb_exact_pattern("assistant", "callbacks", *parts) + + +def _menu(key): + return cb("assistant", "callbacks", "menu", key) + + +def _conv(key): + return cb("assistant", "callbacks", "conv", key) + + +def _message_text(message): + if isinstance(message, str): + return message + value = getattr(message, "raw_text", None) + if value is None: + value = getattr(message, "message", None) + if not isinstance(value, str): + value = getattr(value, "message", None) + return str(value or "") + + +def _is_cancel(message): + text = _message_text(message).strip() + command = text.split(maxsplit=1)[0].split("@", 1)[0] if text else "" + return command.casefold() == "/cancel" + + +def _row(*btns): + return ikm([list(btns)], icon=False)[0] + + +def _toggle(key): + value = udB.get_key(key) + if value is True or (isinstance(value, str) and value.lower() == "true"): + return "On" + return "Off" + + +def _val(key): + value = udB.get_key(key) + if value is None or value == "": + return "Not set" + return str(value) + + +def _mask_val(key): + value = udB.get_key(key) + if value is None or value == "": + return "Not set" + return "Set (hidden)" + + +def _plain(text): + """Remove common Markdown delimiters before showing text in a plain field.""" + value = str(text) + for delimiter in ("**", "__", "~~", "`"): + value = value.replace(delimiter, "") + return value + + +_BUTTON_VALUE_KEYS = { + "taglogger": "TAG_LOG", + "help_emoji": "EMOJI_IN_HELP", + "plugins": "PLUGIN_CHANNEL", + "handler": "HNDLR", + "sudo_handler": "SUDO_HNDLR", + "addons": "ADDONS", + "edon": "ADDONS", + "edof": "ADDONS", + "sudo": "SUDO", + "onsudo": "SUDO", + "ofsudo": "SUDO", + "fbangroup": "FBAN_GROUP_ID", + "excludefeds": "EXCLUDE_FED", + "alive_text": "ALIVE_TEXT", + "alive_media": "ALIVE_PIC", + "pm_txt": "PM_TEXT", + "set_pm_warns": "PMWARNS", + "pm_media": "PMPIC", + "pm_logger": "PMLOG", + "pm_logger_group": "PMLOGGROUP", + "pm_inline": "INLINE_PM", + "pm_normal": "INLINE_PM", + "auto_ap_on": "AUTOAPPROVE", + "auto_ap_off": "AUTOAPPROVE", + "pm_permit_on": "PMSETTING", + "pm_permit_off": "PMSETTING", + "bot_welcome": "STARTMSG", + "bot_welcome_media": "STARTMEDIA", + "bot_info_text": "BOT_INFO_START", + "bot_fsub": "PMBOT_FSUB", + "chatbot_on": "PMBOT", + "chatbot_off": "PMBOT", + "vc_session": "VC_SESSION", + "dual_mode": "DUAL_MODE", + "dual_mode_on": "DUAL_MODE", + "dual_mode_off": "DUAL_MODE", + "dual_mode_handler": "DUAL_HNDLR", + "rmbg_key_set": "RMBG_API", + "deep_key_set": "DEEP_AI", + "ocr_key_set": "OCR_API", + "serp_key_set": "SERPAPI", +} +_BUTTON_GROUP_KEYS = { + "othervars": ( + "TAG_LOG", + "SUDO", + "HNDLR", + "PLUGIN_CHANNEL", + "ADDONS", + "EMOJI_IN_HELP", + "INLINE_PIC", + "SUDO_HNDLR", + "DUAL_MODE", + ), + "superfban": ("FBAN_GROUP_ID", "EXCLUDE_FED"), + "alive_customisation": ("ALIVE_TEXT", "ALIVE_PIC"), + "pm_customisation": ("PM_TEXT", "PMPIC", "PMLOG", "PMWARNS", "INLINE_PM"), + "pm_type": ("INLINE_PM",), + "apauto": ("AUTOAPPROVE",), + "pm_settings": ("PMSETTING",), + "chatbot": ("PMBOT", "STARTMSG", "STARTMEDIA", "BOT_INFO_START", "PMBOT_FSUB"), + "vc_menu": ("VC_SESSION",), + "dual_mode": ("DUAL_MODE", "DUAL_HNDLR"), + "apiset": ("RMBG_API", "DEEP_AI", "OCR_API", "SERPAPI"), +} +_TOGGLE_BUTTONS = { + "edon": ("ADDONS", True), + "edof": ("ADDONS", False), + "onsudo": ("SUDO", True), + "ofsudo": ("SUDO", False), + "auto_ap_on": ("AUTOAPPROVE", True), + "auto_ap_off": ("AUTOAPPROVE", False), + "pm_permit_on": ("PMSETTING", True), + "pm_permit_off": ("PMSETTING", False), + "chatbot_on": ("PMBOT", True), + "chatbot_off": ("PMBOT", False), + "pm_inline": ("INLINE_PM", True), + "pm_normal": ("INLINE_PM", False), + "dual_mode_on": ("DUAL_MODE", True), + "dual_mode_off": ("DUAL_MODE", False), + "pm_logger_on": ("PMLOG", True), + "pm_logger_off": ("PMLOG", False), +} +_DESTRUCTIVE_BUTTONS = {"deltag", "del_alive_media", "del_pm_media"} + + +def _has_saved_value(value): + return value is not None and value != "" and value != [] + + +def _enabled(value): + return value is True or ( + isinstance(value, str) and value.strip().lower() in {"true", "on", "1", "yes"} + ) + + +def _button_action(data): + if isinstance(data, bytes): + data = data.decode("utf-8", "ignore") + return str(data or "").rstrip(":").split(":")[-1].lower() + + +def _menu_label(text): + out = [] + for char in str(text or ""): + if ord(char) in { + 0x00AB, + 0x00BB, + 0x2039, + 0x203A, + 0x25C0, + 0x25B6, + 0x2190, + 0x2192, + 0x2022, + 0x00B7, + 0xFE0E, + 0xFE0F, + 0x200D, + 0x20E3, + }: + out.append(" ") + continue + try: + name = unicodedata.name(char) + except ValueError: + name = "" + if name.startswith("LATIN LETTER SMALL CAPITAL "): + out.append(name.rsplit(" ", 1)[-1].lower()) + elif unicodedata.category(char) in {"So", "Sk"}: + out.append(" ") + else: + out.append(char) + return " ".join("".join(out).split()) + + +def _menu_button_style(data, label=None): + action = _button_action(data) + if _menu_label(label).lower() == "back": + return "primary" + if action in _DESTRUCTIVE_BUTTONS: + return "danger" + if action in _TOGGLE_BUTTONS: + key, desired = _TOGGLE_BUTTONS[action] + value = udB.get_key(key) + return ( + "success" + if _has_saved_value(value) and _enabled(value) is desired + else None + ) + key = _BUTTON_VALUE_KEYS.get(action) + if key and _has_saved_value(udB.get_key(key)): + return "success" + keys = _BUTTON_GROUP_KEYS.get(action, ()) + return "success" if any(_has_saved_value(udB.get_key(k)) for k in keys) else None + + +def _refresh_menu_buttons(buttons): + rows = [] + for row in buttons or []: + converted = [] + for btn in row: + legacy_callback = getattr(types, "KeyboardButtonCallback", None) + inline_button = getattr(types, "KeyboardInlineButton", None) + callback_type = getattr(types, "InlineButtonTypeCallback", None) + button_type = getattr(btn, "type", None) + is_callback = legacy_callback is not None and isinstance( + btn, legacy_callback + ) + is_callback = is_callback or ( + inline_button is not None + and callback_type is not None + and isinstance(btn, inline_button) + and isinstance(button_type, callback_type) + ) + if is_callback: + data = getattr(btn, "data", None) or getattr(button_type, "data", None) + converted.append( + ( + _menu_label(btn.text), + data, + _menu_button_style(data, btn.text), + ) + ) + else: + converted.append(btn) + rows.append(converted) + return ikm(rows, icon=False) + + +START_SETTER = cb("assistant", "start", "setter") + +MENU_PATTERN = cb_pattern("assistant", "callbacks", "menu") +CONV_PATTERN = cb_pattern("assistant", "callbacks", "conv") +CHANGES_PATTERN = cb_pattern("assistant", "callbacks", "changes") +WRNS_PATTERN = cb_pattern("assistant", "callbacks", "pm_warns") +PASTA_PATTERN = cb_pattern("assistant", "callbacks", "paste") +FDROID_PATTERN = cb_pattern("assistant", "fdroid") -# --------------------------------------------------------------------# -telegraph = telegraph_client() -GDrive = GDriveManager() if GDriveManager else None -uploader = CatboxUploader() -# --------------------------------------------------------------------# def text_to_url(event): """function to get media url (with|without) Webpage""" @@ -46,190 +319,333 @@ def text_to_url(event): return event.text -# --------------------------------------------------------------------# - _buttons = { - "otvars": { - "text": "Other Variables to set for @TeamUltroid:", - "buttons": [ - [ - Button.inline("Tᴀɢ Lᴏɢɢᴇʀ", data="taglog"), - Button.inline("SᴜᴘᴇʀFʙᴀɴ", data="cbs_sfban"), - ], - [ - Button.inline("Sudo Mode", data="sudo"), - Button.inline("Handler", data="hhndlr"), - ], - [ - Button.inline("Extra Plugins", data="plg"), - Button.inline("Addons", data="eaddon"), - ], + "othervars": { + "head": "Other Variables ", + "body": "Configure the remaining variables for your Ultroid assistant.", + "buttons": ikm( [ - Button.inline("Emoji in Help", data="emoj"), - Button.inline("Set gDrive", data="gdrive"), + [ + ("Tag Logger", _tok("taglogger"), "person", "blue"), + ("SuperFban", _menu("superfban"), "blue"), + ], + [ + ("Sudo Mode", _tok("sudo"), "blue"), + ("Handler", _tok("handler"), "blue"), + ], + [ + ("Extra Plugins", _tok("plugins"), "blue"), + ("Addons", _tok("addons"), "blue"), + ], + [ + ("Emoji in Help", _tok("help_emoji"), "blue"), + ("Set gDrive", _tok("gdrive"), "blue"), + ], + [ + ("Inline Pic", _tok("inline_pic"), "blue"), + ("Sudo HNDLR", _tok("sudo_handler"), "blue"), + ], + [("Dual Mode", _menu("dual_mode"), "blue")], + [("Back", START_SETTER, None)], ], + icon=False, + ), + }, + "superfban": { + "head": "SuperFban Settings ", + "body": "SuperFban bans spammers across federations for your channel.", + "foot": lambda: f"Currently: FBan group {_val('FBAN_GROUP_ID')}", + "buttons": ikm( [ - Button.inline("Inline Pic", data="inli_pic"), - Button.inline("Sudo HNDLR", data="shndlr"), + [("FBan Group", _tok("fbangroup"), "blue")], + [("Exclude Feds", _conv("excludefeds"), "blue")], + [("Back", _menu("othervars"), None)], ], - [Button.inline("Dual Mode", "cbs_oofdm")], - [Button.inline("« Back", data="setter")], - ], - }, - "sfban": { - "text": "SuperFban Settings:", - "buttons": [ - [Button.inline("FBᴀɴ Gʀᴏᴜᴘ", data="sfgrp")], - [Button.inline("Exᴄʟᴜᴅᴇ Fᴇᴅs", data="abs_sfexf")], - [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")], - ], + icon=False, + ), }, "apauto": { "text": "This'll auto approve on outgoing messages", - "buttons": [ - [Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ ON", data="apon")], - [Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ OFF", data="apof")], - [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")], - ], - }, - "alvcstm": { - "text": f"Customise your {HNDLR}alive. Choose from the below options -", - "buttons": [ - [Button.inline("Aʟɪᴠᴇ Tᴇxᴛ", data="abs_alvtx")], - [Button.inline("Aʟɪᴠᴇ ᴍᴇᴅɪᴀ", data="alvmed")], - [Button.inline("Dᴇʟᴇᴛᴇ Aʟɪᴠᴇ Mᴇᴅɪᴀ", data="delmed")], - [Button.inline("« Bᴀᴄᴋ", data="setter")], - ], - }, - "pmcstm": { - "text": "Customise your PMPERMIT Settings -", - "buttons": [ + "head": "Auto Approve ", + "body": "Automatically approve incoming private messages.", + "foot": lambda: f"Currently: {_toggle('AUTOAPPROVE')}", + "buttons": ikm( [ - Button.inline("Pᴍ Tᴇxᴛ", data="pmtxt"), - Button.inline("Pᴍ Mᴇᴅɪᴀ", data="pmmed"), + [("Auto Approve ON", _tok("auto_ap_on"), "green")], + [("Auto Approve OFF", _tok("auto_ap_off"), "danger")], + [("Back", _menu("pm_customisation"), None)], ], + icon=False, + ), + }, + "alive_customisation": { + "head": "Alive Customisation ", + "body": f"Customise your {HNDLR}alive. Choose from the options below.", + "foot": lambda: f"Currently: alive text {_val('ALIVE_TEXT')}", + "buttons": ikm( [ - Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ", data="cbs_apauto"), - Button.inline("PMLOGGER", data="pml"), + [("Alive Text", _conv("alive_text"), "blue")], + [("Alive media", _tok("alive_media"), "blue")], + [("Delete Alive Media", _tok("del_alive_media"), "danger")], + [("Back", START_SETTER, None)], ], + icon=False, + ), + }, + "pm_customisation": { + "head": "PM Permit Settings", + "body": "Customise your PMPERMIT settings below.", + "buttons": ikm( [ - Button.inline("Sᴇᴛ Wᴀʀɴs", data="swarn"), - Button.inline("Dᴇʟᴇᴛᴇ Pᴍ Mᴇᴅɪᴀ", data="delpmmed"), + [ + ("PM Text", _tok("pm_txt"), "blue"), + ("PM Media", _tok("pm_media"), "blue"), + ], + [ + ("Auto Approve", _menu("apauto"), "green"), + ("PM Logger", _tok("pm_logger"), "blue"), + ], + [ + ("Set Warns", _tok("set_pm_warns"), "green"), + ("Delete PM Media", _tok("del_pm_media"), "danger"), + ], + [("PM Permit Type", _menu("pm_type"), "blue")], + [("Back", _menu("pm_settings"), None)], ], - [Button.inline("PMPermit Type", data="cbs_pmtype")], - [Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")], - ], + icon=False, + ), }, - "pmtype": { - "text": "Select the type of PMPermit needed.", - "buttons": [ - [Button.inline("Inline", data="inpm_in")], - [Button.inline("Normal", data="inpm_no")], - [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")], - ], + "pm_type": { + "head": "PM Permit Type", + "body": "Choose how the PM Permit guard handles incoming private messages.", + "foot": lambda: ( + f"Currently: {'Inline' if udB.get_key('INLINE_PM') in (True, 'True') else 'Normal'}" + ), + "buttons": ikm( + [ + [("Inline", _tok("pm_inline"), "green")], + [("Normal", _tok("pm_normal"), "blue")], + [("Back", _menu("pm_customisation"), None)], + ], + icon=False, + ), }, - "ppmset": { - "text": "PMPermit Settings:", - "buttons": [ - [Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oɴ", data="pmon")], - [Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oғғ", data="pmoff")], - [Button.inline("Cᴜsᴛᴏᴍɪᴢᴇ PMPᴇʀᴍɪᴛ", data="cbs_pmcstm")], - [Button.inline("« Bᴀᴄᴋ", data="setter")], - ], + "pm_settings": { + "head": "PM Permit", + "body": "Control the PM Permit guard for incoming private messages.", + "foot": lambda: f"Currently: {_toggle('PMSETTING')}", + "buttons": ikm( + [ + [("Turn PM Permit On", _tok("pm_permit_on"), "success")], + [("Turn PM Permit Off", _tok("pm_permit_off"), "danger")], + [("Customize PM Permit", _menu("pm_customisation"))], + [("Back", START_SETTER, None)], + ], + icon=False, + ), }, "chatbot": { - "text": "From This Feature U can chat with ppls Via ur Assistant Bot.\n[More info](https://t.me/UltroidUpdates/2)", - "buttons": [ + "head": "Chat Bot ", + "body": "Chat with people through your assistant bot.", + "data": { + "More info": rawhtml( + 't.me/UltroidUpdates/2' + ) + }, + "foot": lambda: f"Currently: {_toggle('PMBOT')}", + "buttons": ikm( [ - Button.inline("Cʜᴀᴛ Bᴏᴛ Oɴ", data="onchbot"), - Button.inline("Cʜᴀᴛ Bᴏᴛ Oғғ", data="ofchbot"), + [ + ("Chat Bot On", _tok("chatbot_on"), "success"), + ("Chat Bot Off", _tok("chatbot_off"), "danger"), + ], + [ + ("Bot Welcome", _tok("bot_welcome"), "blue"), + ("Bot Welcome Media", _tok("bot_welcome_media"), "blue"), + ], + [("Bot Info Text", _tok("bot_info_text"), "blue")], + [("Force Subscribe", _tok("bot_fsub"), "blue")], + [("Back", START_SETTER, None)], ], + icon=False, + ), + }, + "vc_menu": { + "head": "VC Song Bot ", + "body": "Play songs in group voice chat.", + "data": { + "More info": rawhtml( + 't.me/UltroidUpdates/4' + ) + }, + "foot": lambda: f"Currently: session {_mask_val('VC_SESSION')}", + "buttons": ikm( [ - Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ", data="bwel"), - Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ Mᴇᴅɪᴀ", data="botmew"), + [("VC Session", _conv("vc_session"), "blue")], + [("Back", START_SETTER, None)], ], - [Button.inline("Bᴏᴛ Iɴғᴏ Tᴇxᴛ", data="botinfe")], - [Button.inline("Fᴏʀᴄᴇ Sᴜʙsᴄʀɪʙᴇ", data="pmfs")], - [Button.inline("« Bᴀᴄᴋ", data="setter")], - ], - }, - "vcb": { - "text": "From This Feature U can play songs in group voice chat\n\n[moreinfo](https://t.me/UltroidUpdates/4)", - "buttons": [ - [Button.inline("VC Sᴇssɪᴏɴ", data="abs_vcs")], - [Button.inline("« Bᴀᴄᴋ", data="setter")], - ], + icon=False, + ), }, - "oofdm": { - "text": "About [Dual Mode](https://t.me/UltroidUpdates/18)", - "buttons": [ + "dual_mode": { + "head": "Dual Mode ", + "data": { + "About": rawhtml( + 't.me/UltroidUpdates/18' + ) + }, + "foot": lambda: f"Currently: {_toggle('DUAL_MODE')}", + "buttons": ikm( [ - Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oɴ", "dmof"), - Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oғғ", "dmof"), + [ + ("Dual Mode On", _tok("dual_mode_on"), "success"), + ("Dual Mode Off", _tok("dual_mode_off"), "danger"), + ], + [("Dual Mode Handler", _tok("dual_mode_handler"), "blue")], + [("Back", _menu("othervars"), None)], ], - [Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Hɴᴅʟʀ", "dmhn")], - [Button.inline("« Back", data="cbs_otvars")], - ], + icon=False, + ), }, "apiset": { - "text": get_string("ast_1"), - "buttons": [ - [Button.inline("Remove.bg API", data="abs_rmbg")], - [Button.inline("DEEP API", data="abs_dapi")], - [Button.inline("OCR API", data="abs_oapi")], - [Button.inline("« Back", data="setter")], - ], + "head": "API Keys ", + "body": get_string("ast_1"), + "foot": lambda: ( + f"Keys set: " + f"{sum(1 for k in ('RMBG_API', 'DEEP_AI', 'OCR_API', 'SERPAPI') if udB.get_key(k))}/4" + ), + "buttons": ikm( + [ + [("Remove.bg API", _conv("rmbg_key_set"), "blue")], + [("DEEP API", _conv("deep_key_set"), "blue")], + [("OCR API", _conv("ocr_key_set"), "blue")], + [("SERP API", _conv("serp_key_set"), "blue")], + [("Back", START_SETTER, None)], + ], + icon=False, + ), }, } +_MENU_BUTTON_DESCRIPTIONS = { + "remove.bg api": "Set or replace the API key; its value stays hidden.", + "deep api": "Set or replace the DeepAI key; its value stays hidden.", + "ocr api": "Set or replace the OCR key; its value stays hidden.", + "serp api": "Set or replace the search key; its value stays hidden.", + "chat bot on": "Enable the private-message chat bot.", + "chat bot off": "Disable the private-message chat bot.", + "bot welcome": "Edit the welcome message shown by the bot.", + "bot welcome media": "Set the media shown with the welcome message.", + "bot info text": "Edit the information shown from the Info button.", + "force subscribe": "Set the channel or group membership requirement.", + "alive text": "Edit the assistant's alive message.", + "alive media": "Set media for the alive message.", + "delete alive media": "Remove the saved alive media.", + "turn pm permit on": "Enable the incoming private-message guard.", + "turn pm permit off": "Disable the incoming private-message guard.", + "customize pm permit": "Open text, media, logging, and approval options.", + "tag logger": "Choose the chat used for tag logs.", + "superfban": "Configure federated-ban group settings.", + "sudo mode": "Manage sudo access.", + "handler": "Change the assistant command prefix.", + "extra plugins": "Choose the source for additional plugins.", + "addons": "Enable or disable add-on plugins.", + "emoji in help": "Configure emoji labels in the help menu.", + "set gdrive": "Configure Google Drive access.", + "inline pic": "Set or clear the inline result picture.", + "sudo hndlr": "Change the sudo command prefix.", + "dual mode": "Configure dual-client routing and its handler.", + "vc session": "Set the voice-chat bot session; its value stays hidden.", + "fban group": "Set the group used by federated-ban actions.", + "exclude feds": "Set the federations excluded from these actions.", + "auto approve": "Choose whether outgoing messages are auto-approved.", + "pm logger": "Enable or configure private-message logging.", + "set warns": "Set the private-message warning limit.", + "delete pm media": "Remove the saved PM Permit media.", + "pm permit type": "Choose normal or inline PM Permit handling.", + "inline": "Use inline PM Permit responses.", + "normal": "Use normal PM Permit responses.", + "dual mode on": "Enable dual-client mode.", + "dual mode off": "Disable dual-client mode.", + "dual mode handler": "Set the dual-client command handler.", +} + + +def _menu_table_rows(menu): + """Describe visible submenu buttons without rendering stored values.""" + rows = [] + for button_row in menu.get("buttons", ()): + for button in button_row: + label = getattr(button, "text", None) + if label is None: + try: + label = button[0] + except (IndexError, TypeError): + continue + label = _menu_label(label) + if label.casefold() == "back": + continue + purpose = _MENU_BUTTON_DESCRIPTIONS.get( + label.casefold(), "Open or update this setting." + ) + rows.append((label, purpose)) + return rows + + _convo = { - "rmbg": { + "rmbg_key_set": { "var": "RMBG_API", "name": "Remove.bg API Key", "text": get_string("ast_2"), - "back": "cbs_apiset", + "back": _menu("apiset"), }, - "dapi": { + "deep_key_set": { "var": "DEEP_AI", "name": "Deep AI Api Key", "text": "Get Your Deep Api from deepai.org and send here.", - "back": "cbs_apiset", + "back": _menu("apiset"), }, - "oapi": { + "ocr_key_set": { "var": "OCR_API", "name": "Ocr Api Key", "text": "Get Your OCR api from ocr.space and send that Here.", - "back": "cbs_apiset", + "back": _menu("apiset"), + }, + "serp_key_set": { + "var": "SERPAPI", + "name": "Serp Api Key", + "text": "Get Your SERP api from https://serpapi.com/users/sign_in and send that Here.", + "back": _menu("apiset"), }, - "pmlgg": { + "pm_logger_group": { "var": "PMLOGGROUP", "name": "Pm Log Group", "text": "Send chat id of chat which you want to save as Pm log Group.", - "back": "pml", + "back": _tok("pm_logger"), }, - "vcs": { + "vc_session": { "var": "VC_SESSION", "name": "Vc Session", "text": "**Vc session**\nEnter the New session u generated for vc bot.\n\nUse /cancel to terminate the operation.", - "back": "cbs_vcb", + "back": _menu("vc_menu"), }, - "settag": { + "set_pm_logger": { "var": "TAG_LOG", "name": "Tag Log Group", - "text": f"Make a group, add your assistant and make it admin.\nGet the `{HNDLR}id` of that group and send it here for tag logs.\n\nUse /cancel to cancel.", - "back": "taglog", + "text": f"Make a group, add your assistant and make it admin.\nGet the {HNDLR}id of that group and send it here for tag logs.\n\nUse /cancel to cancel.", + "back": _tok("taglogger"), }, - "alvtx": { + "alive_text": { "var": "ALIVE_TEXT", "name": "Alive Text", "text": "**Alive Text**\nEnter the new alive text.\n\nUse /cancel to terminate the operation.", - "back": "cbs_alvcstm", + "back": _menu("alive_customisation"), }, - "sfexf": { + "excludefeds": { "var": "EXCLUDE_FED", "name": "Excluded Fed", - "text": "Send the Fed IDs you want to exclude in the ban. Split by a space.\neg`id1 id2 id3`\nSet is as `None` if you dont want any.\nUse /cancel to go back.", - "back": "cbs_sfban", + "text": "Send the Fed IDs you want to exclude in the ban. Split by a space.\negid1 id2 id3\nSet is as None if you dont want any.\nUse /cancel to go back.", + "back": _menu("superfban"), }, } @@ -237,189 +653,265 @@ _convo = { TOKEN_FILE = "resources/auths/auth_token.txt" -@callback( - re.compile( - "sndplug_(.*)", - ), - owner=True, -) +def _plugin_source_path(key, name, *, repo_root=None, registry=None): + """Resolve a plugin source file inside its allowed repository directory.""" + repo_root = ( + Path(repo_root).resolve() + if repo_root is not None + else Path(__file__).resolve().parents[1] + ) + roots = { + "Official": ("plugins",), + "Addons": ("addons",), + "VCBot": ("vc", "plugins"), + }.get(key, ()) + if not roots: + return None + + if registry is None: + registry = getattr(core, "registry", None) + manifest = registry.get(name) if registry is not None else None + manifest_path = getattr(manifest, "path", None) + if manifest_path: + candidate = Path(manifest_path) + if not candidate.is_absolute(): + candidate = repo_root / candidate + candidate = candidate.resolve() + if ( + candidate.suffix == ".py" + and candidate.is_file() + and any(candidate.is_relative_to(repo_root / folder) for folder in roots) + ): + return candidate + + normalized = str(name or "").replace("\\", "/").strip("/").removesuffix(".py") + candidates = [] + for folder in roots: + prefix = f"{folder}/" + dotted_prefix = f"{folder}." + if normalized.startswith(prefix): + relative = normalized[len(prefix) :] + elif normalized.startswith(dotted_prefix): + relative = normalized[len(dotted_prefix) :].replace(".", "/") + else: + relative = normalized + relative = relative.replace(".", "/") + if not relative.endswith(".py"): + relative += ".py" + candidate = (repo_root / folder / relative).resolve() + if ( + candidate.suffix == ".py" + and candidate.is_file() + and candidate.is_relative_to(repo_root / folder) + ): + candidates.append(candidate) + return candidates[0] if candidates else None + + +@callback(cb_pattern("assistant", "inline", "send_plugin"), owner=True) async def send(eve): - key, name = (eve.data_match.group(1)).decode("UTF-8").split("_") - thumb = "resources/extras/inline.jpg" - await eve.answer("■ Sending ■") - data = f"uh_{key}_" - index = None - if "|" in name: - name, index = name.split("|") - key = "plugins" if key == "Official" else key.lower() - plugin = f"{key}/{name}.py" - _ = f"pasta-{plugin}" + key, _, rest = (eve.data_match.group(1)).decode("UTF-8").partition(":") + name, index = rest.rsplit(":", 1) if ":" in rest else (rest, None) + plugin = _plugin_source_path(key, name) + if plugin is None: + return await eve.answer("The plugin source file is unavailable.", alert=True) + user_id = getattr(eve, "sender_id", None) or getattr( + getattr(eve, "query", None), "user_id", None + ) + if user_id is None: + return await eve.answer( + "I could not identify the requesting account.", alert=True + ) + paste_ref = plugin.relative_to(Path(__file__).resolve().parents[1]).as_posix() if index is not None: - data += f"|{index}" - _ += f"|{index}" - buttons = [ - [ - Button.inline( - "« Pᴀsᴛᴇ »", - data=_, - ) - ], - [ - Button.inline("« Bᴀᴄᴋ", data=data), - ], - ] + paste_ref = f"{paste_ref}|{index}" + buttons = ikm( + [[("Paste", cb("assistant", "callbacks", "paste", paste_ref), "primary")]], + icon=False, + ) try: - await eve.edit(file=plugin, thumb=thumb, buttons=buttons) - except Exception as er: - await eve.answer(str(er), alert=True) + await eve.client.send_file( + user_id, + file=str(plugin), + caption=f"{name} source", + buttons=buttons, + ) + except Exception: + LOGS.exception("Unable to deliver plugin source") + return await eve.answer( + "I could not send the source in a private message. Open the assistant bot and try again.", + alert=True, + ) + return await eve.answer("Source sent in your private chat.", alert=True) heroku_api, app_name = Var.HEROKU_API, Var.HEROKU_APP_NAME -@callback("updatenow", owner=True) +@callback(_handler("updatenow"), owner=True) async def update(eve): - repo = Repo() - ac_br = repo.active_branch - ups_rem = repo.remote("upstream") - if heroku_api: - import heroku3 + from pyUltroid.updater import up as update_engine - try: - heroku = heroku3.from_key(heroku_api) - heroku_app = None - heroku_applications = heroku.apps() - except BaseException as er: - LOGS.exception(er) - return await eve.edit("`Wrong HEROKU_API.`") - for app in heroku_applications: - if app.name == app_name: - heroku_app = app - if not heroku_app: - await eve.edit("`Wrong HEROKU_APP_NAME.`") - repo.__del__() - return - await eve.edit(get_string("clst_1")) - ups_rem.fetch(ac_br) - repo.git.reset("--hard", "FETCH_HEAD") - heroku_git_url = heroku_app.git_url.replace( - "https://", f"https://api:{heroku_api}@" - ) + await eve.edit( + fmtmsg("Updating ", msgs=_plain(get_string("clst_1"))), + parse_mode="html", + ) + msg_id = getattr(eve, "message_id", None) or getattr( + getattr(eve, "message", None), "id", 0 + ) - if "heroku" in repo.remotes: - remote = repo.remote("heroku") - remote.set_url(heroku_git_url) - else: - remote = repo.create_remote("heroku", heroku_git_url) - try: - remote.push(refspec=f"HEAD:refs/heads/{ac_br}", force=True) - except GitCommandError as error: - await eve.edit(f"`Here is the error log:\n{error}`") - repo.__del__() - return - await eve.edit("`Successfully Updated!\nRestarting, please wait...`") - else: - await eve.edit(get_string("clst_1")) - call_back() - await bash("git pull && pip3 install -r requirements.txt") - await bash("pip3 install -r requirements.txt --break-system-packages") - execl(sys.executable, sys.executable, "-m", "pyUltroid") - -@callback(re.compile("changes(.*)"), owner=True) -async def changes(okk): - match = okk.data_match.group(1).decode("utf-8") - await okk.answer(get_string("clst_3")) - repo = Repo.init() - button = [[Button.inline("Update Now", data="updatenow")]] - changelog, tl_chnglog = await gen_chlog( - repo, f"HEAD..upstream/{repo.active_branch}" + state = await update_engine.engine.apply( + restart_notice=("bot", eve.chat_id, msg_id), + ) + text = _plain(state.summary()) + foot = ( + "Core files changed restarting in 3s" + if (state.status == "done" and state.needs_restart) + else "" + ) + await eve.edit( + fmtmsg("Update", msgs=text, foot=foot), + parse_mode="html", ) - cli = "\n\nClick the below button to update!" + + +@callback(CHANGES_PATTERN, owner=True) +async def changes(event): + from pyUltroid.updater import up as update_engine + + match = event.data_match.group(1).decode("utf-8") + await event.answer(get_string("clst_3")) + diff = await update_engine.engine.check() + button = [_row(("Update Now", _tok("updatenow"), "green"))] + if not (diff and diff.has_changes): + return await event.edit( + fmtmsg("Updates ", msgs="Already up-to-date."), + buttons=button, + parse_mode="html", + ) + tl_chnglog = diff.changelog_text(max_entries=len(diff.commits)) + head = f"Ultroid {ultroid_version} updates for {diff.branch}" if not match: try: if len(tl_chnglog) > 700: tl_chnglog = f"{tl_chnglog[:700]}..." - button.append([Button.inline("View Complete", "changesall")]) - await okk.edit("• Writing Changelogs 📝 •") - img = await Carbon( + button.append( + _row( + ( + "View Complete", + cb("assistant", "callbacks", "changes", "all"), + "primary", + ) + ) + ) + + await event.edit( + fmtmsg("Updates ", msgs="Writing changelogs"), + parse_mode="html", + ) + img = await fns.Carbon( file_name="changelog", code=tl_chnglog, backgroundColor=choice(ATRA_COL), language="md", ) - return await okk.edit( - f"**• Ultroid Userbot •**{cli}", file=img, buttons=button + return await event.edit( + fmtmsg(" Ultroid Userbot "), + file=img, + buttons=button, + parse_mode="html", ) except Exception as er: LOGS.exception(er) - changelog_str = changelog + cli + changelog_str = ( + f"{head}:\n\n{_plain(diff.changelog_text(10))}" + "\n\nClick the below button to update!" + ) if len(changelog_str) > 1024: - await okk.edit(get_string("upd_4")) + await event.edit( + fmtmsg("Updates ", msgs=_plain(get_string("upd_4"))), + parse_mode="html", + ) await asyncio.sleep(2) with open("ultroid_updates.txt", "w+") as file: file.write(tl_chnglog) - await okk.edit( - get_string("upd_5"), + await event.edit( + fmtmsg("Updates ", msgs=_plain(get_string("upd_5"))), file="ultroid_updates.txt", buttons=button, ) remove("ultroid_updates.txt") return - await okk.edit( - changelog_str, + await event.edit( + fmtmsg( + head, + msgs=_plain(diff.changelog_text(10)), + foot="Click the below button to update!", + ), buttons=button, parse_mode="html", ) -@callback( - re.compile( - "pasta-(.*)", - ), - owner=True, -) +@callback(PASTA_PATTERN, owner=True) async def _(e): + ok = (e.data_match.group(1)).decode("UTF-8") index = None if "|" in ok: ok, index = ok.split("|") - with open(ok, "r") as hmm: - _, data = await get_paste(hmm.read()) - if not data.get("link"): + with open(ok) as hmm: + _, key = await fns.get_paste(hmm.read()) + link = f"https://spaceb.in/{key}" + raw = f"https://spaceb.in/api/v1/documents/{key}/raw" + if not _: return await e.answer(key[:30], alert=True) - if not key.startswith("http"): - link, raw = data["link"], data["raw"] - else: - link = key - raw = f"{key}/raw" if ok.startswith("addons"): key = "Addons" - elif ok.startswith("vcbot"): + elif ok.startswith(("vcbot", "vc/")): key = "VCBot" else: key = "Official" - data = f"uh_{key}_" - if index is not None: - data += f"|{index}" + + data = cb( + "assistant", "inline", "help_menu", key, index if index is not None else "0" + ) await e.edit( "", - buttons=[ - [Button.url("Lɪɴᴋ", link), Button.url("Rᴀᴡ", raw)], - [Button.inline("« Bᴀᴄᴋ", data=data)], - ], + buttons=ikm( + [ + [ + ("Link", "url", link, "green", "link"), + ("Raw", "url", raw, "green", "play"), + ], + [("Back", data, None)], + ], + icon=False, + ), ) -@callback(re.compile("cbs_(.*)"), owner=True) +@callback(MENU_PATTERN, owner=True) async def _edit_to(event): match = event.data_match.group(1).decode("utf-8") - data = _buttons.get(match) - if not data: + menu = _buttons.get(match) + if not menu: return - await event.edit(data["text"], buttons=data["buttons"], link_preview=False) + rows = _menu_table_rows(menu) + await edit_callback_page( + event, + rich_page( + _menu_label(menu["head"]), + rows, + description=_plain(menu.get("body", "")), + columns=("Button", "What it does"), + total=len(rows), + ), + buttons=_refresh_menu_buttons(menu["buttons"]), + ) -@callback(re.compile("abs_(.*)"), owner=True) +@callback(CONV_PATTERN, owner=True) async def convo_handler(event: events.CallbackQuery): match = event.data_match.group(1).decode("utf-8") if not _convo.get(match): @@ -428,44 +920,93 @@ async def convo_handler(event: events.CallbackQuery): get_ = _convo[match] back = get_["back"] async with event.client.conversation(event.sender_id) as conv: - await conv.send_message(get_["text"]) - response = await conv.get_response() - themssg = response.message + prompt = await send_rich( + event.client, + conv.chat_id, + rich_page( + get_["name"], + [("Instructions", _plain(get_["text"]))], + columns=("Step", "What to do"), + total=1, + ), + link_preview=False, + ) + response = await conv.get_response(prompt) + themssg = _message_text(response) try: themssg = ast.literal_eval(themssg) except Exception: pass - if themssg == "/cancel": - return await conv.send_message( - "Cancelled!!", + if _is_cancel(response): + return await send_rich( + event.client, + conv.chat_id, + rich_page( + "Settings cancelled", + [("Result", "Nothing was changed.")], + columns=("Status", "Details"), + total=1, + ), buttons=get_back_button(back), + link_preview=False, ) await setit(event, get_["var"], themssg) - await conv.send_message( - f"{get_['name']} changed to `{themssg}`", + secret_setting = get_["var"] in { + "RMBG_API", + "DEEP_AI", + "OCR_API", + "SERPAPI", + "VC_SESSION", + } + shown_value = "Set (hidden)" if secret_setting else _plain(themssg) + await send_rich( + event.client, + conv.chat_id, + rich_page( + f"{get_['name']} updated", + [("Result", shown_value)], + columns=("Setting", "Status"), + total=1, + ), buttons=get_back_button(back), + link_preview=False, ) -@callback("authorise", owner=True) +@callback(_handler("authorise"), owner=True) async def _(e): if not e.is_private: return + if not GDrive: + return await e.edit( + fmtmsg("Error ", msgs="Google Drive is not available right now."), + parse_mode="html", + ) url = GDrive._create_token_file() - await e.edit("Go to the below link and send the code!") + await e.edit( + fmtmsg("Google Drive ", msgs="Go to the below link and send the code!"), + parse_mode="html", + ) async with asst.conversation(e.sender_id) as conv: await conv.send_message(url) code = await conv.get_response() if GDrive._create_token_file(code=code.text): await conv.send_message( - "`Success!\nYou are all set to use Google Drive with Ultroid Userbot.`", - buttons=Button.inline("Main Menu", data="setter"), + fmtmsg( + "Success ", + msgs="You are all set to use Google Drive with Ultroid Userbot.", + ), + buttons=_row(("Main Menu", START_SETTER, "primary")), + parse_mode="html", ) else: - await conv.send_message("Wrong code! Click authorise again.") + await conv.send_message( + fmtmsg("Error ", msgs="Wrong code! Click authorise again."), + parse_mode="html", + ) -@callback("folderid", owner=True, func=lambda x: x.is_private) +@callback(_handler("folderid"), owner=True, func=lambda x: x.is_private) async def _(e): if not e.is_private: return @@ -479,48 +1020,75 @@ async def _(e): ) await e.delete() async with asst.conversation(e.sender_id, timeout=150) as conv: - await conv.send_message(msg) + await conv.send_message( + fmtmsg("Google Drive Folder ", msgs=msg), + parse_mode="html", + ) repl = await conv.get_response() id = repl.text if id.startswith("https"): id = id.split("?id=")[-1] udB.set_key("GDRIVE_FOLDER_ID", id) await repl.reply( - "`Success.`", - buttons=get_back_button("gdrive"), + fmtmsg("Success ", msgs="Folder ID saved."), + buttons=get_back_button(_tok("gdrive")), + parse_mode="html", ) -@callback("gdrive", owner=True) +@callback(_handler("gdrive"), owner=True) async def _(e): if not e.is_private: return await e.edit( - "Click Authorise and send the code.\n\nYou can use your own CLIENT ID and SECRET by [this](https://t.me/UltroidUpdates/37)", - buttons=[ + fmtmsg( + "Google Drive ", + msgs="Click Authorise and send the code.\n\nYou can use your own CLIENT ID and SECRET.", + data={ + "More info": rawhtml( + 't.me/UltroidUpdates/37' + ) + }, + ), + buttons=ikm( [ - Button.inline("Folder ID", data="folderid"), - Button.inline("Authorise", data="authorise"), + [ + ("Folder ID", _tok("folderid"), "blue"), + ("Authorise", _tok("authorise"), "green"), + ], + [("Back", _menu("othervars"), None)], ], - [Button.inline("« Back", data="cbs_otvars")], - ], + icon=False, + ), link_preview=False, ) -@callback("dmof", owner=True) +@callback(_handler("dual_mode_on"), owner=True) async def rhwhe(e): - if udB.get_key("DUAL_MODE"): - udB.del_key("DUAL_MODE") - key = "Off" - else: - udB.set_key("DUAL_MODE", "True") - key = "On" - Msg = f"Dual Mode : {key}" - await e.edit(Msg, buttons=get_back_button("cbs_otvars")) + udB.set_key("DUAL_MODE", "True") + await e.edit( + fmtmsg( + "Dual Mode ", msgs="Dual Mode has been turned on.", foot="Currently: On" + ), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", + ) + + +@callback(_handler("dual_mode_off"), owner=True) +async def rhwheoff(e): + udB.del_key("DUAL_MODE") + await e.edit( + fmtmsg( + "Dual Mode ", msgs="Dual Mode has been turned off.", foot="Currently: Off" + ), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", + ) -@callback("dmhn", owner=True) +@callback(_handler("dual_mode_handler"), owner=True) async def hndlrr(event): await event.delete() pru = event.sender_id @@ -529,59 +1097,75 @@ async def hndlrr(event): CH = udB.get_key(var) or "/" async with event.client.conversation(pru) as conv: await conv.send_message( - f"Send The Symbol Which u want as Handler/Trigger to use your Assistant bot\nUr Current Handler is [ `{CH}` ]\n\n use /cancel to cancel.", + fmtmsg( + name, + msgs=f"Send the symbol you want as Handler/Trigger for your assistant bot.\nCurrent Handler is {CH}.\n\nUse /cancel to cancel.", + ), + parse_mode="html", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message - if themssg == "/cancel": + if _is_cancel(response): await conv.send_message( - "Cancelled!!", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) elif len(themssg) > 1: await conv.send_message( - "Incorrect Handler", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Error ", msgs="Incorrect Handler."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) else: await setit(event, var, themssg) await conv.send_message( - f"{name} changed to {themssg}", - buttons=get_back_button("cbs_otvars"), + fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) -@callback("emoj", owner=True) -async def emoji(event): +@callback(_handler("help_emoji"), owner=True) +async def help_emoji(event): await event.delete() pru = event.sender_id var = "EMOJI_IN_HELP" - name = f"Emoji in `{HNDLR}help` menu" + name = f"Emoji in {HNDLR}help menu" async with event.client.conversation(pru) as conv: - await conv.send_message("Send emoji u want to set 🙃.\n\nUse /cancel to cancel.") + await conv.send_message( + fmtmsg( + name, + msgs="Send the emoji you want to set .\n\nUse /cancel to cancel.", + ), + parse_mode="html", + ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message - if themssg == "/cancel": + if _is_cancel(response): await conv.send_message( - "Cancelled!!", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) elif themssg.startswith(("/", HNDLR)): await conv.send_message( - "Incorrect Emoji", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Error ", msgs="Incorrect Emoji."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) else: await setit(event, var, themssg) await conv.send_message( - f"{name} changed to {themssg}\n", - buttons=get_back_button("cbs_otvars"), + fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) -@callback("plg", owner=True) +@callback(_handler("plugins"), owner=True) async def pluginch(event): await event.delete() pru = event.sender_id @@ -589,66 +1173,86 @@ async def pluginch(event): name = "Plugin Channel" async with event.client.conversation(pru) as conv: await conv.send_message( - "Send id or username of a channel from where u want to install all plugins\n\nOur Channel~ @ultroidplugins\n\nUse /cancel to cancel.", + fmtmsg( + name, + msgs="Send the id or username of the channel to install plugins from.\n\nOur Channel: @ultroidplugins\n\nUse /cancel to cancel.", + ), + parse_mode="html", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message - if themssg == "/cancel": + if _is_cancel(response): await conv.send_message( - "Cancelled!!", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) elif themssg.startswith(("/", HNDLR)): await conv.send_message( - "Incorrect channel", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Error ", msgs="Incorrect channel."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) else: await setit(event, var, themssg) await conv.send_message( - f"{name} changed to {themssg}\n After Setting All Things Do Restart", - buttons=get_back_button("cbs_otvars"), + fmtmsg( + f"{name} Changed ", + msgs=f"New value: {themssg}", + foot="Restart after setting all things.", + ), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) -@callback("hhndlr", owner=True) +@callback(_handler("handler"), owner=True) async def hndlrr(event): await event.delete() pru = event.sender_id var = "HNDLR" - name = "Handler/ Trigger" + name = "Handler/Trigger" async with event.client.conversation(pru) as conv: await conv.send_message( - f"Send The Symbol Which u want as Handler/Trigger to use bot\nUr Current Handler is [ `{HNDLR}` ]\n\n use /cancel to cancel.", + fmtmsg( + name, + msgs=f"Send the symbol you want as Handler/Trigger to use the bot.\nUse /cancel to cancel.", + foot=lambda: f"Current Handler is {_val('HNDLR')}", + ), + parse_mode="html", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message - if themssg == "/cancel": + if _is_cancel(response): await conv.send_message( - "Cancelled!!", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) elif len(themssg) > 1: await conv.send_message( - "Incorrect Handler", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Error ", msgs="Incorrect Handler."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) elif themssg.startswith(("/", "#", "@")): await conv.send_message( - "This cannot be used as handler", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Error ", msgs="This cannot be used as handler."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) else: await setit(event, var, themssg) await conv.send_message( - f"{name} changed to {themssg}", - buttons=get_back_button("cbs_otvars"), + fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) -@callback("shndlr", owner=True) +@callback(_handler("sudo_handler"), owner=True) async def hndlrr(event): await event.delete() pru = event.sender_id @@ -656,153 +1260,215 @@ async def hndlrr(event): name = "Sudo Handler" async with event.client.conversation(pru) as conv: await conv.send_message( - "Send The Symbol Which u want as Sudo Handler/Trigger to use bot\n\n use /cancel to cancel." + fmtmsg( + name, + msgs="Send the symbol you want as Sudo Handler/Trigger to use the bot.\n\nUse /cancel to cancel.", + foot=f" Prohibited Values: /, #, @.", + ), + parse_mode="html", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message - if themssg == "/cancel": + if _is_cancel(response): await conv.send_message( - "Cancelled!!", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) elif len(themssg) > 1: await conv.send_message( - "Incorrect Handler", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Error ", msgs="Incorrect Handler."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) elif themssg.startswith(("/", "#", "@")): await conv.send_message( - "This cannot be used as handler", - buttons=get_back_button("cbs_otvars"), + fmtmsg("Error ", msgs="This cannot be used as handler."), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) else: await setit(event, var, themssg) await conv.send_message( - f"{name} changed to {themssg}", - buttons=get_back_button("cbs_otvars"), + fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", ) -@callback("taglog", owner=True) -async def tagloggrr(e): - BUTTON = [ - [Button.inline("SET TAG LOG", data="abs_settag")], - [Button.inline("DELETE TAG LOG", data="deltag")], - get_back_button("cbs_otvars"), - ] +@callback(_handler("taglogger"), owner=True) +async def tagloggergrr(e): + BUTTON = ikm( + [ + [("SET TAG LOG", _conv("set_pm_logger"))], + [("DELETE TAG LOG", _tok("deltag"), "danger")], + ], + icon=False, + ) + BUTTON.append(get_back_button(_menu("othervars"))) await e.edit( - "Choose Options", + fmtmsg( + "Tag Logger ", + msgs="Choose whether to set or delete the tag log group.", + foot=f"Currently: {_val('TAG_LOG')}", + ), buttons=BUTTON, + parse_mode="html", ) -@callback("deltag", owner=True) +@callback(_handler("deltag"), owner=True) async def _(e): udB.del_key("TAG_LOG") - await e.answer("Done!!! Tag Logger has been turned Off") + await e.edit( + fmtmsg( + "Tag Logger ", + msgs="Tag Logger has been turned off.", + foot="Currently: Off", + ), + buttons=get_back_button(_menu("othervars")), + parse_mode="html", + ) -@callback("eaddon", owner=True) +@callback(_handler("addons"), owner=True) async def pmset(event): BT = ( - [Button.inline("Aᴅᴅᴏɴs Oғғ", data="edof")] + _row(("Addons Off", _tok("edof"), "danger")) if udB.get_key("ADDONS") - else [Button.inline("Aᴅᴅᴏɴs Oɴ", data="edon")] + else _row(("Addons On", _tok("edon"), "success")) ) await event.edit( - "ADDONS~ Extra Plugins:", + fmtmsg( + "Addons ", + msgs="Extra plugins can be enabled or disabled here.", + foot=f"Currently: {_toggle('ADDONS')}", + ), buttons=[ BT, - [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")], + get_back_button(_menu("othervars")), ], + parse_mode="html", ) -@callback("edon", owner=True) +@callback(_handler("edon"), owner=True) async def eddon(event): var = "ADDONS" await setit(event, var, "True") await event.edit( - "Done! ADDONS has been turned on!!\n\n After Setting All Things Do Restart", - buttons=get_back_button("eaddon"), + fmtmsg( + "Addons ", + msgs="ADDONS has been turned on.\nAfter setting all things, restart.", + foot="Currently: On", + ), + buttons=get_back_button(_tok("addons")), + parse_mode="html", ) -@callback("edof", owner=True) +@callback(_handler("edof"), owner=True) async def eddof(event): udB.set_key("ADDONS", "False") await event.edit( - "Done! ADDONS has been turned off!! After Setting All Things Do Restart", - buttons=get_back_button("eaddon"), + fmtmsg( + "Addons ", + msgs="ADDONS has been turned off.\nAfter setting all things, restart.", + foot="Currently: Off", + ), + buttons=get_back_button(_tok("addons")), + parse_mode="html", ) -@callback("sudo", owner=True) +@callback(_handler("sudo"), owner=True) async def pmset(event): BT = ( - [Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ Oғғ", data="ofsudo")] + _row(("Sudo Mode Off", _tok("ofsudo"), "danger")) if udB.get_key("SUDO") - else [Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ Oɴ", data="onsudo")] + else _row(("Sudo Mode On", _tok("onsudo"), "success")) ) await event.edit( - f"SUDO MODE ~ Some peoples can use ur Bot which u selected. To know More use `{HNDLR}help sudo`", + fmtmsg( + "Sudo Mode ", + msgs=f"Some people you select can use your bot.\nUse {HNDLR}help sudo to know more.", + foot=f"Currently: {_toggle('SUDO')}", + ), buttons=[ BT, - [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")], + get_back_button(_menu("othervars")), ], + parse_mode="html", ) -@callback("onsudo", owner=True) +@callback(_handler("onsudo"), owner=True) async def eddon(event): var = "SUDO" await setit(event, var, "True") await event.edit( - "Done! SUDO MODE has been turned on!!\n\n After Setting All Things Do Restart", - buttons=get_back_button("sudo"), + fmtmsg( + "Sudo Mode ", + msgs="SUDO MODE has been turned on.\nAfter setting all things, restart.", + foot="Currently: On", + ), + buttons=get_back_button(_tok("sudo")), + parse_mode="html", ) -@callback("ofsudo", owner=True) +@callback(_handler("ofsudo"), owner=True) async def eddof(event): var = "SUDO" await setit(event, var, "False") await event.edit( - "Done! SUDO MODE has been turned off!! After Setting All Things Do Restart", - buttons=get_back_button("sudo"), + fmtmsg( + "Sudo Mode ", + msgs="SUDO MODE has been turned off.\nAfter setting all things, restart.", + foot="Currently: Off", + ), + buttons=get_back_button(_tok("sudo")), + parse_mode="html", ) -@callback("sfgrp", owner=True) -async def sfgrp(event): +@callback(_handler("fbangroup"), owner=True) +async def fbangroup(event): await event.delete() name = "FBan Group ID" var = "FBAN_GROUP_ID" pru = event.sender_id async with asst.conversation(pru) as conv: await conv.send_message( - f"Make a group, add @MissRose_Bot, send `{HNDLR}id`, copy that and send it here.\nUse /cancel to go back.", + fmtmsg( + name, + msgs=f"Make a group, add @MissRose_Bot, send {HNDLR}id, copy that and send it here.\nUse /cancel to go back.", + foot=f"Current value: {_val('FBAN_GROUP_ID')}", + ), + parse_mode="html", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message - if themssg == "/cancel": + if _is_cancel(response): return await conv.send_message( - "Cancelled!!", - buttons=get_back_button("cbs_sfban"), + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(_menu("superfban")), + parse_mode="html", ) await setit(event, var, themssg) await conv.send_message( - f"{name} changed to {themssg}", - buttons=get_back_button("cbs_sfban"), + fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"), + buttons=get_back_button(_menu("superfban")), + parse_mode="html", ) -@callback("alvmed", owner=True) +@callback(_handler("alive_media"), owner=True) async def media(event): await event.delete() pru = event.sender_id @@ -810,15 +1476,20 @@ async def media(event): name = "Alive Media" async with event.client.conversation(pru) as conv: await conv.send_message( - "**Alive Media**\nSend me a pic/gif/media to set as alive media.\n\nUse /cancel to terminate the operation.", + fmtmsg( + name, + msgs="Send me a pic/gif/media to set as alive media.\n\nUse /cancel to terminate the operation.", + ), + parse_mode="html", ) response = await conv.get_response() try: themssg = response.message - if themssg == "/cancel": + if _is_cancel(response): return await conv.send_message( - "Operation cancelled!!", - buttons=get_back_button("cbs_alvcstm"), + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(_menu("alive_customisation")), + parse_mode="html", ) except BaseException as er: LOGS.exception(er) @@ -833,57 +1504,77 @@ async def media(event): else: media = await event.client.download_media(response, "alvpc") try: - url = uploader.upload_file(media) + x = upl(media) + url = f"https://graph.org/{x[0]}" remove(media) except BaseException as er: LOGS.exception(er) return await conv.send_message( - "Terminated.", - buttons=get_back_button("cbs_alvcstm"), + fmtmsg("Terminated ", msgs="The operation was terminated."), + buttons=get_back_button(_menu("alive_customisation")), + parse_mode="html", ) await setit(event, var, url) await conv.send_message( - f"{name} has been set.", - buttons=get_back_button("cbs_alvcstm"), + fmtmsg(f"{name} Changed ", msgs=f"New value: {url}"), + buttons=get_back_button(_menu("alive_customisation")), + parse_mode="html", ) -@callback("delmed", owner=True) +@callback(_handler("del_alive_media"), owner=True) async def dell(event): try: udB.del_key("ALIVE_PIC") return await event.edit( - get_string("clst_5"), buttons=get_back_button("cbs_alabs_vcstm") + fmtmsg( + "Alive Media ", + msgs="Alive media has been deleted.", + foot="Currently: Not set", + ), + buttons=get_back_button(_menu("alive_customisation")), + parse_mode="html", ) except BaseException as er: LOGS.exception(er) return await event.edit( - get_string("clst_4"), - buttons=get_back_button("cbs_alabs_vcstm"), + fmtmsg("Error ", msgs="Something went wrong."), + buttons=get_back_button(_menu("alive_customisation")), + parse_mode="html", ) -@callback("inpm_in", owner=True) +@callback(_handler("pm_inline"), owner=True) async def inl_on(event): var = "INLINE_PM" await setit(event, var, "True") await event.edit( - "Done!! PMPermit type has been set to inline!", - buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_pmtype")]], + fmtmsg( + "PM Permit Type", + msgs="PM Permit type has been set to inline.", + foot="Currently: Inline", + ), + buttons=get_back_button(_menu("pm_type")), + parse_mode="html", ) -@callback("inpm_no", owner=True) +@callback(_handler("pm_normal"), owner=True) async def inl_on(event): var = "INLINE_PM" await setit(event, var, "False") await event.edit( - "Done!! PMPermit type has been set to normal!", - buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_pmtype")]], + fmtmsg( + "PM Permit Type", + msgs="PM Permit type has been set to normal.", + foot="Currently: Normal", + ), + buttons=get_back_button(_menu("pm_type")), + parse_mode="html", ) -@callback("pmtxt", owner=True) +@callback(_handler("pm_txt"), owner=True) async def name(event): await event.delete() pru = event.sender_id @@ -891,56 +1582,83 @@ async def name(event): name = "PM Text" async with event.client.conversation(pru) as conv: await conv.send_message( - "**PM Text**\nEnter the new Pmpermit text.\n\nu can use `{name}` `{fullname}` `{count}` `{mention}` `{username}` to get this from user Too\n\nUse /cancel to terminate the operation.", + fmtmsg( + name, + msgs="Enter the new PM Permit message.\n\nYou can use {name}, {fullname}, {count}, {mention}, and {username} placeholders.\n\nSend /cancel to stop.", + ), + parse_mode="html", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message - if themssg == "/cancel": + if _is_cancel(response): return await conv.send_message( - "Cancelled!!", - buttons=get_back_button("cbs_pmcstm"), + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(_menu("pm_customisation")), + parse_mode="html", ) if len(themssg) > 4090: return await conv.send_message( - "Message too long!\nGive a shorter message please!!", - buttons=get_back_button("cbs_pmcstm"), + fmtmsg( + "Error ", msgs="Message too long!\nGive a shorter message please." + ), + buttons=get_back_button(_menu("pm_customisation")), + parse_mode="html", ) await setit(event, var, themssg) await conv.send_message( - f"{name} changed to {themssg}\n\nAfter Setting All Things Do restart", - buttons=get_back_button("cbs_pmcstm"), + fmtmsg( + f"{name} Changed ", + msgs=f"New value: {themssg}\n\nAfter setting all things, restart.", + ), + buttons=get_back_button(_menu("pm_customisation")), + parse_mode="html", ) -@callback("swarn", owner=True) +@callback(_handler("set_pm_warns"), owner=True) async def name(event): - m = range(1, 10) - tultd = [Button.inline(f"{x}", data=f"wrns_{x}") for x in m] - lst = list(zip(tultd[::3], tultd[1::3], tultd[2::3])) - lst.append([Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")]) + btns = [ + (f"{x}", cb("assistant", "callbacks", "pm_warns", x), "primary") + for x in range(1, 10) + ] + lst = ikm([btns[i : i + 3] for i in range(0, len(btns), 3)], icon=False) + lst.append(get_back_button(_menu("pm_customisation"))) await event.edit( - "Select the number of warnings for a user before getting blocked in PMs.", + fmtmsg( + "PM Warnings ", + msgs="Select the number of warnings for a user before getting blocked in PMs.", + foot=f"Currently: {_val('PMWARNS')}", + ), buttons=lst, + parse_mode="html", ) -@callback(re.compile(b"wrns_(.*)"), owner=True) +@callback(WRNS_PATTERN, owner=True) async def set_wrns(event): value = int(event.data_match.group(1).decode("UTF-8")) if dn := udB.set_key("PMWARNS", value): await event.edit( - f"PM Warns Set to {value}.\nNew users will have {value} chances in PMs before getting banned.", - buttons=get_back_button("cbs_pmcstm"), + fmtmsg( + "PM Warnings ", + msgs=f"New users will have {value} chances in PMs before getting banned.", + foot=f"Currently: {value}", + ), + buttons=get_back_button(_menu("pm_customisation")), + parse_mode="html", ) else: await event.edit( - f"Something went wrong, please check your {HNDLR}logs!", - buttons=get_back_button("cbs_pmcstm"), + fmtmsg( + "Error ", msgs=f"Something went wrong, please check your {HNDLR}logs." + ), + buttons=get_back_button(_menu("pm_customisation")), + parse_mode="html", ) -@callback("pmmed", owner=True) +@callback(_handler("pm_media"), owner=True) async def media(event): await event.delete() pru = event.sender_id @@ -948,15 +1666,20 @@ async def media(event): name = "PM Media" async with event.client.conversation(pru) as conv: await conv.send_message( - "**PM Media**\nSend me a pic/gif/sticker/link to set as pmpermit media.\n\nUse /cancel to terminate the operation.", + fmtmsg( + name, + msgs="Send a photo, GIF, sticker, or link for the PM Permit media.\n\nSend /cancel to stop.", + ), + parse_mode="html", ) response = await conv.get_response() try: themssg = response.message - if themssg == "/cancel": + if _is_cancel(response): return await conv.send_message( - "Operation cancelled!!", - buttons=get_back_button("cbs_pmcstm"), + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(_menu("pm_customisation")), + parse_mode="html", ) except BaseException as er: LOGS.exception(er) @@ -971,175 +1694,243 @@ async def media(event): url = response.file.id else: try: - url = uploader.upload_file(media) + x = upl(media) + url = f"https://graph.org/{x[0]}" remove(media) except BaseException as er: LOGS.exception(er) return await conv.send_message( - "Terminated.", - buttons=get_back_button("cbs_pmcstm"), + fmtmsg("Terminated ", msgs="The operation was terminated."), + buttons=get_back_button(_menu("pm_customisation")), + parse_mode="html", ) await setit(event, var, url) await conv.send_message( - f"{name} has been set.", - buttons=get_back_button("cbs_pmcstm"), + fmtmsg(f"{name} Changed ", msgs=f"New value: {url}"), + buttons=get_back_button(_menu("pm_customisation")), + parse_mode="html", ) -@callback("delpmmed", owner=True) +@callback(_handler("del_pm_media"), owner=True) async def dell(event): try: udB.del_key("PMPIC") return await event.edit( - get_string("clst_5"), buttons=get_back_button("cbs_pmcstm") + fmtmsg( + "PM Media ", + msgs="PM media has been deleted.", + foot="Currently: Not set", + ), + buttons=get_back_button(_menu("pm_customisation")), + parse_mode="html", ) except BaseException as er: LOGS.exception(er) return await event.edit( - get_string("clst_4"), - buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]], + fmtmsg("Error ", msgs="Something went wrong."), + buttons=get_back_button(START_SETTER, " Settings"), + parse_mode="html", ) -@callback("apon", owner=True) -async def apon(event): +@callback(_handler("auto_ap_on"), owner=True) +async def auto_ap_on(event): var = "AUTOAPPROVE" await setit(event, var, "True") await event.edit( - "Done!! AUTOAPPROVE Started!!", - buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_apauto")]], + fmtmsg( + "Auto Approve ", + msgs="AUTOAPPROVE has been started.", + foot="Currently: On", + ), + buttons=get_back_button(_menu("apauto")), + parse_mode="html", ) -@callback("apof", owner=True) -async def apof(event): +@callback(_handler("auto_ap_off"), owner=True) +async def auto_ap_off(event): try: udB.set_key("AUTOAPPROVE", "False") return await event.edit( - "Done! AUTOAPPROVE Stopped!!", - buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_apauto")]], + fmtmsg( + "Auto Approve ", + msgs="AUTOAPPROVE has been stopped.", + foot="Currently: Off", + ), + buttons=get_back_button(_menu("apauto")), + parse_mode="html", ) except BaseException as er: LOGS.exception(er) return await event.edit( - get_string("clst_4"), - buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]], + fmtmsg("Error ", msgs="Something went wrong."), + buttons=get_back_button(START_SETTER, " Settings"), + parse_mode="html", ) -@callback("pml", owner=True) +@callback(_handler("pm_logger"), owner=True) async def l_vcs(event): BT = ( - [Button.inline("PMLOGGER OFF", data="pmlogof")] + _row(("PM Logger Off", _tok("pm_logger_off"), "danger")) if udB.get_key("PMLOG") - else [Button.inline("PMLOGGER ON", data="pmlog")] + else _row(("PM Logger On", _tok("pm_logger_on"), "success")) ) await event.edit( - "PMLOGGER This Will Forward Ur Pm to Ur Private Group -", + fmtmsg( + "PM Logger", + msgs="This will forward your PMs to your private group.", + foot=f"Currently: {_toggle('PMLOG')}", + ), buttons=[ BT, - [Button.inline("PᴍLᴏɢɢᴇʀ Gʀᴏᴜᴘ", "abs_pmlgg")], - [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")], + _row(("PM Logger Group", _conv("pm_logger_group"), "primary")), + get_back_button(_menu("pm_customisation")), ], ) -@callback("pmlog", owner=True) +@callback(_handler("pm_logger_on"), owner=True) async def pmlog(event): await setit(event, "PMLOG", "True") await event.edit( - "Done!! PMLOGGER Started!!", - buttons=[[Button.inline("« Bᴀᴄᴋ", data="pml")]], + fmtmsg("PM Logger", msgs="PM Logger is on.", foot="Currently: On"), + buttons=get_back_button(_tok("pm_logger")), + parse_mode="html", ) -@callback("pmlogof", owner=True) +@callback(_handler("pm_logger_off"), owner=True) async def pmlogof(event): try: udB.del_key("PMLOG") return await event.edit( - "Done! PMLOGGER Stopped!!", - buttons=[[Button.inline("« Bᴀᴄᴋ", data="pml")]], + fmtmsg("PM Logger", msgs="PM Logger is off.", foot="Currently: Off"), + buttons=get_back_button(_tok("pm_logger")), + parse_mode="html", ) except BaseException as er: LOGS.exception(er) return await event.edit( - get_string("clst_4"), - buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]], + fmtmsg("Error ", msgs="Something went wrong."), + buttons=get_back_button(START_SETTER, " Settings"), + parse_mode="html", ) -@callback("pmon", owner=True) +@callback(_handler("pm_permit_on"), owner=True) async def pmonn(event): var = "PMSETTING" await setit(event, var, "True") await event.edit( - "Done! PMPermit has been turned on!!", - buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")]], + fmtmsg("PM Permit", msgs="PM Permit is on.", foot="Currently: On"), + buttons=get_back_button(_menu("pm_settings")), + parse_mode="html", ) -@callback("pmoff", owner=True) +@callback(_handler("pm_permit_off"), owner=True) async def pmofff(event): var = "PMSETTING" await setit(event, var, "False") await event.edit( - "Done! PMPermit has been turned off!!", - buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")]], + fmtmsg("PM Permit", msgs="PM Permit is off.", foot="Currently: Off"), + buttons=get_back_button(_menu("pm_settings")), + parse_mode="html", ) -@callback("botmew", owner=True) +@callback(_handler("bot_welcome_media"), owner=True) async def hhh(e): async with e.client.conversation(e.chat_id) as conv: - await conv.send_message("Send Any Media to keep at your Bot's welcome ") + await conv.send_message( + fmtmsg( + "Bot Welcome Media ", + msgs="Send any media to keep at your bot's welcome.", + ), + parse_mode="html", + ) msg = await conv.get_response() if not msg.media or msg.text.startswith("/"): return await conv.send_message( - "Terminated!", buttons=get_back_button("cbs_chatbot") + fmtmsg("Terminated ", msgs="The operation was terminated."), + buttons=get_back_button(_menu("chatbot")), + parse_mode="html", ) udB.set_key("STARTMEDIA", msg.file.id) - await conv.send_message("Done!", buttons=get_back_button("cbs_chatbot")) + await conv.send_message( + fmtmsg("Bot Welcome Media ", msgs="Media has been saved."), + buttons=get_back_button(_menu("chatbot")), + parse_mode="html", + ) -@callback("botinfe", owner=True) +@callback(_handler("bot_info_text"), owner=True) async def hhh(e): async with e.client.conversation(e.chat_id) as conv: await conv.send_message( - "Send message to set to Display, when user Press Info button in Bot Welcome!\n\nsend `False` to completely remove that button.." + fmtmsg( + "Bot Info Text ℹ", + msgs="Send the message to display when a user presses the Info button in Bot Welcome.\n\nSend False to completely remove that button.", + ), + parse_mode="html", ) msg = await conv.get_response() if msg.media or msg.text.startswith("/"): return await conv.send_message( - "Terminated!", buttons=get_back_button("cbs_chatbot") + fmtmsg("Terminated ", msgs="The operation was terminated."), + buttons=get_back_button(_menu("chatbot")), + parse_mode="html", ) udB.set_key("BOT_INFO_START", msg.text) - await conv.send_message("Done!", buttons=get_back_button("cbs_chatbot")) + await conv.send_message( + fmtmsg("Bot Info Text ", msgs="Text has been saved."), + buttons=get_back_button(_menu("chatbot")), + parse_mode="html", + ) -@callback("pmfs", owner=True) +@callback(_handler("bot_fsub"), owner=True) async def heheh(event): Ll = [] err = "" async with event.client.conversation(event.chat_id) as conv: await conv.send_message( - "• Send The Chat Id(s), which you want user to Join Before using Chat/Pm Bot\n\n• Send /clear to disable PmBot Force sub..\n• • Send /cancel to stop this process.." + fmtmsg( + "Force Subscribe ", + msgs="Send the chat ID(s) the user must join before using Chat/PM Bot.\n\nSend /clear to disable PMBot Force Subscribe.\nSend /cancel to stop this process.", + ), + parse_mode="html", ) await conv.send_message( - "Example : \n`-1001234567\n-100778888`\n\nFor Multiple Chat(s)." + fmtmsg("Example", msgs="-1001234567\n-100778888\n\nFor multiple chats."), + parse_mode="html", ) try: msg = await conv.get_response() except AsyncTimeOut: - return await conv.send_message("**• TimeUp!**\nStart from /start back.") + return await conv.send_message( + fmtmsg("Time Up ", msgs="Start from /start back."), + parse_mode="html", + ) if not msg.text or msg.text.startswith("/"): - timyork = "Cancelled!" if msg.text == "/clear": udB.del_key("PMBOT_FSUB") - timyork = "Done! Force Subscribe Stopped\nRestart your Bot!" + return await conv.send_message( + fmtmsg( + "Force Subscribe ", + msgs="Force Subscribe has been stopped and applies to the next incoming message.", + ), + buttons=get_back_button(_menu("chatbot")), + parse_mode="html", + ) return await conv.send_message( - "Cancelled!", buttons=get_back_button("cbs_chatbot") + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(_menu("chatbot")), + parse_mode="html", ) for chat in msg.message.split("\n"): if chat.startswith("-") or chat.isdigit(): @@ -1150,14 +1941,24 @@ async def heheh(event): except Exception as er: err += f"**{chat}** : {er}\n" if err: - return await conv.send_message(err) + return await conv.send_message( + fmtmsg("Error ", msgs=err), + parse_mode="html", + ) + # Keep the existing database representation; pmbot now parses this + # legacy literal safely and reads it fresh for each incoming message. udB.set_key("PMBOT_FSUB", str(Ll)) await conv.send_message( - "Done!\nRestart Your Bot.", buttons=get_back_button("cbs_chatbot") + fmtmsg( + "Force Subscribe ", + msgs="Done. The setting applies to the next incoming message.", + ), + buttons=get_back_button(_menu("chatbot")), + parse_mode="html", ) -@callback("bwel", owner=True) +@callback(_handler("bot_welcome"), owner=True) async def name(event): await event.delete() pru = event.sender_id @@ -1165,40 +1966,51 @@ async def name(event): name = "Bot Welcome Message:" async with event.client.conversation(pru) as conv: await conv.send_message( - "**BOT WELCOME MSG**\nEnter the msg which u want to show when someone start your assistant Bot.\nYou Can use `{me}` , `{mention}` Parameters Too\nUse /cancel to terminate the operation.", + fmtmsg( + name, + msgs="Enter the message to show when someone starts your assistant bot.\nYou can use {me} and {mention} parameters too.\nUse /cancel to terminate the operation.", + ), + parse_mode="html", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message - if themssg == "/cancel": + if _is_cancel(response): return await conv.send_message( - "Cancelled!!", - buttons=get_back_button("cbs_chatbot"), + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(_menu("chatbot")), + parse_mode="html", ) await setit(event, var, themssg) await conv.send_message( - f"{name} changed to {themssg}", - buttons=get_back_button("cbs_chatbot"), + fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"), + buttons=get_back_button(_menu("chatbot")), + parse_mode="html", ) -@callback("onchbot", owner=True) +@callback(_handler("chatbot_on"), owner=True) async def chon(event): var = "PMBOT" await setit(event, var, "True") - Loader(path="assistant/pmbot.py", key="PM Bot").load() + await AsyncPluginLoader(path="assistant/pmbot.py", key="PM Bot").load_all(log=False) if AST_PLUGINS.get("pmbot"): for i, e in AST_PLUGINS["pmbot"]: event.client.remove_event_handler(i) for i, e in AST_PLUGINS["pmbot"]: event.client.add_event_handler(i, events.NewMessage(**e)) await event.edit( - "Done! Now u Can Chat With People Via This Bot", - buttons=[Button.inline("« Bᴀᴄᴋ", data="cbs_chatbot")], + fmtmsg( + "Chat Bot ", + msgs="Now you can chat with people via this bot.", + foot="Currently: On", + ), + buttons=get_back_button(_menu("chatbot")), + parse_mode="html", ) -@callback("ofchbot", owner=True) +@callback(_handler("chatbot_off"), owner=True) async def chon(event): var = "PMBOT" await setit(event, var, "False") @@ -1206,12 +2018,17 @@ async def chon(event): for i, e in AST_PLUGINS["pmbot"]: event.client.remove_event_handler(i) await event.edit( - "Done! Chat People Via This Bot Stopped.", - buttons=[Button.inline("« Bᴀᴄᴋ", data="cbs_chatbot")], + fmtmsg( + "Chat Bot ", + msgs="Chat with people via this bot has been stopped.", + foot="Currently: Off", + ), + buttons=get_back_button(_menu("chatbot")), + parse_mode="html", ) -@callback("inli_pic", owner=True) +@callback(_handler("inline_pic"), owner=True) async def media(event): await event.delete() pru = event.sender_id @@ -1219,15 +2036,20 @@ async def media(event): name = "Inline Media" async with event.client.conversation(pru) as conv: await conv.send_message( - "**Inline Media**\nSend me a pic/gif/ or link to set as inline media.\n\nUse /cancel to terminate the operation.", + fmtmsg( + name, + msgs="Send me a pic/gif/link to set as inline media.\n\nUse /cancel to terminate the operation.", + ), + parse_mode="html", ) response = await conv.get_response() try: themssg = response.message - if themssg == "/cancel": + if _is_cancel(response): return await conv.send_message( - "Operation cancelled!!", - buttons=get_back_button("setter"), + fmtmsg("Cancelled ", msgs="Nothing was changed."), + buttons=get_back_button(START_SETTER, " Settings"), + parse_mode="html", ) except BaseException as er: LOGS.exception(er) @@ -1240,46 +2062,52 @@ async def media(event): url = text_to_url(response) else: try: - url = uploader.upload_file(media) + x = upl(media) + url = f"https://graph.org/{x[0]}" remove(media) except BaseException as er: LOGS.exception(er) return await conv.send_message( - "Terminated.", - buttons=get_back_button("setter"), + fmtmsg("Terminated ", msgs="The operation was terminated."), + buttons=get_back_button(START_SETTER, " Settings"), + parse_mode="html", ) await setit(event, var, url) await conv.send_message( - f"{name} has been set.", - buttons=get_back_button("setter"), + fmtmsg(f"{name} Changed ", msgs=f"New value: {url}"), + buttons=get_back_button(START_SETTER, " Settings"), + parse_mode="html", ) FD_MEDIA = {} -@callback(re.compile("fd(.*)"), owner=True) +@callback(FDROID_PATTERN, owner=True) async def fdroid_dler(event): uri = event.data_match.group(1).decode("utf-8") if FD_MEDIA.get(uri): return await event.edit(file=FD_MEDIA[uri]) - await event.answer("• Starting Download •", alert=True) - await event.edit("• Downloading.. •") + await event.answer(" Starting Download ", alert=True) + await event.edit( + fmtmsg("Downloading "), + parse_mode="html", + ) URL = f"https://f-droid.org/packages/{uri}" - conte = await async_searcher(URL, re_content=True) + conte = await fns.async_searcher(URL, re_content=True) BSC = bs(conte, "html.parser", from_encoding="utf-8") dl_ = BSC.find("p", "package-version-download").find("a")["href"] title = BSC.find("h3", "package-name").text.strip() thumb = BSC.find("img", "package-icon")["src"] if thumb.startswith("/"): thumb = f"https://f-droid.org{thumb}" - thumb, _ = await fast_download(thumb, filename=f"{uri}.png") + thumb, _ = await fns.fast_download(thumb, filename=f"{uri}.png") s_time = time.time() - file, _ = await fast_download( + file, _ = await fns.fast_download( dl_, filename=f"{title}.apk", - progress_callback=lambda d, t: asyncio.get_event_loop().create_task( - progress( + progress_callback=lambda d, t: asyncio.get_running_loop().create_task( + fns.progress( d, t, event, @@ -1293,10 +2121,13 @@ async def fdroid_dler(event): n_file = await event.client.fast_uploader( file, show_progress=True, event=event, message="Uploading...", to_delete=True ) - buttons = Button.switch_inline("Search Back", query="fdroid", same_peer=True) + buttons = ikm([("Search Again", "switch_inline", "fdroid", True, "green")]) + caption = fmtmsg( + f" {title} ", data={"APK": rawhtml(f'{title}')} + ) try: msg = await event.edit( - f"**• [{title}]({URL}) •**", file=n_file, thumb=thumb, buttons=buttons + f"** [{title}]({URL}) **", file=n_file, thumb=thumb, buttons=buttons ) except Exception as er: LOGS.exception(er) @@ -1304,15 +2135,24 @@ async def fdroid_dler(event): msg = await event.client.edit_message( await event.get_input_chat(), event.message_id, - f"**• [{title}]({URL}) •**", + f"** [{title}]({URL}) **", buttons=buttons, thumb=thumb, file=n_file, ) except Exception as er: - os.remove(thumb) + remove(thumb) LOGS.exception(er) - return await event.edit(f"**ERROR**: `{er}`", buttons=buttons) + return await event.edit( + fmtmsg("Error ", msgs=str(er)), + buttons=buttons, + parse_mode="html", + ) if msg and hasattr(msg, "media"): FD_MEDIA.update({uri: msg.media}) - os.remove(thumb) + remove(thumb) + + +@callback("noop") +async def _noop(event): + await event.answer() diff --git a/assistant/games.py b/assistant/games.py index 0542f60f8c4d96dd4f0eef786ab4ac71e79f890c..c8d6c4bce73337dec871c47960b0c33cc308b2c4 100644 --- a/assistant/games.py +++ b/assistant/games.py @@ -1,49 +1,97 @@ # Ultroid - UserBot -# Copyright (C) 2021-2026 TeamUltroid +# Copyright (C) 2021-2024 TeamUltroid # # This file is a part of < https://github.com/TeamUltroid/Ultroid/ > # PLease read the GNU Affero General Public License in # . """ -• `{i}akinator` | `/akinator` - Start akinator game from Userbot/Assistant +{i}akinator | /akinator + Start akinator game from Userbot/Assistant -• `/startgame` - Open Portal for Games +/startgame + Open Portal for Games """ import asyncio -import re, uuid, operator +import html +import re +import operator +import uuid +from html import unescape from random import choice, shuffle -from akipy.async_akipy import Akinator +try: + from akipy.async_akipy import Akinator, akipyLOGS +except ImportError: + from akipy.async_akinator import Akinator + import logging + + akipyLOGS = logging.getLogger("akipy") from telethon.errors.rpcerrorlist import BotMethodInvalidError from telethon.events import Raw +from telethon.tl import types from telethon.tl.types import InputMediaPoll, Poll, PollAnswer, UpdateMessagePollVote from pyUltroid._misc._decorators import ultroid_cmd -from logging import getLogger -from html import unescape -from telethon.tl.types import TextWithEntities -from pyUltroid.fns.helper import inline_mention -from pyUltroid.fns.tools import async_searcher -from telethon.errors import ChatSendStickersForbiddenError +from custom.tg import ikm +from custom.fmt import fmtmsg, rawhtml from . import * # Ensure this import matches your project structure +from ._cbs import cb, cb_str, cb_exact_pattern, cb_pattern +from pyUltroid.fns import fns games = {} aki_photo = "https://graph.org/file/3cc8825c029fd0cab9edc.jpg" -akipyLOGS = getLogger("akipy") +#: assistant:games:aki:: reused verbatim as both the inline +#: query text (eiagx/akina) and the resulting button/callback data +#: (doai), so it's built once here rather than three separate times. +AKI_PREFIX = cb_str("assistant", "games", "aki") +AKI_CALLBACK_PATTERN = cb_pattern("assistant", "games", "aki") +AKI_TEXT_PATTERN = re.compile(re.escape(AKI_PREFIX) + r":(.*)") + +TRIVIA_CAT = cb("assistant", "games", "trivia", "cat") +DELIT = cb("assistant", "games", "delit") + + +def _akinator_result(name, description): + """Build a safe HTML result without interpreting provider text as markup.""" + body = f"It's {html.escape(str(name))}\n{html.escape(str(description))}" + return fmtmsg("Akinator Result", msgs=rawhtml(body)) + + +def _aka_buttons(ch, mid): + """Akinator answer keyboard for game (ch, mid) (used by both the + first question in doai and every follow-up in okah).""" + + def _a(ans): + return cb("assistant", "games", "aka", ch, mid, ans) + + return ikm( + [ + [ + ("Yes", _a("Yes"), "primary"), + ("No", _a("No"), "primary"), + ("Idk", _a("Idk"), "primary"), + ], + [ + ("Probably", _a("Probably"), "primary"), + ("Probably Not", _a("Probably Not"), "primary"), + ], + ], + icon=False, + ) + @ultroid_cmd(pattern="akinator") async def akina(e): sta = Akinator() games[e.chat_id] = {e.id: sta} LOGS.info(f"Game started for chat {e.chat_id} with ID {e.id}.") + query = f"{AKI_PREFIX}:{e.chat_id}:{e.id}" try: - m = await e.client.inline_query(asst.me.username, f"aki_{e.chat_id}_{e.id}") + m = await e.client.inline_query(asst.me.username, query) await m[0].click(e.chat_id) akipyLOGS.info(f"Clicked inline result for chat {e.chat_id}") except BotMethodInvalidError as err: @@ -51,7 +99,7 @@ async def akina(e): await asst.send_file( e.chat_id, aki_photo, - buttons=Button.inline(get_string("aki_2"), data=f"aki_{e.chat_id}_{e.id}"), + buttons=ikm([[(get_string("aki_2"), query, "primary")]], icon=False), ) except Exception as er: akipyLOGS.error(f"Unexpected error: {er}") @@ -65,28 +113,29 @@ async def _akokk(e): await akina(e) -@callback(re.compile("aki_(.*)"), owner=True) +@callback(AKI_CALLBACK_PATTERN, owner=True) async def doai(e): - adt = e.pattern_match.group(1).strip().decode("utf-8") - dt = adt.split("_") - ch = int(dt[0]) - mid = int(dt[1]) + adt = e.data_match.group(1).decode("utf-8") + ch, mid = adt.split(":") + ch = int(ch) + mid = int(mid) await e.edit(get_string("com_1")) try: await games[ch][mid].start_game(child_mode=False) - bts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Yes", "No", "Idk"]] - cts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Probably", "Probably Not"]] - bts = [bts, cts] - await e.edit(f"Q. {games[ch][mid].question}", buttons=bts) + bts = _aka_buttons(ch, mid) + await e.edit( + fmtmsg("Akinator ", msgs=f"Q. {games[ch][mid].question}"), + buttons=bts, + parse_mode="html", + ) except KeyError: return await e.answer(get_string("aki_1"), alert=True) -@callback(re.compile("aka_(.*)"), owner=True) +@callback(cb_pattern("assistant", "games", "aka"), owner=True) async def okah(e): try: - mk = e.pattern_match.group(1).decode("utf-8").split("_") - #akipyLOGS.info(f"Parsed values: {mk}") + mk = e.data_match.group(1).decode("utf-8").split(":") if len(mk) < 3: akipyLOGS.error("Pattern match did not return enough parts.") @@ -102,30 +151,34 @@ async def okah(e): # Check for the final guess in the API response if gm.name_proposition and gm.description_proposition: gm.win = True - text = f"It's {gm.name_proposition}\n{gm.description_proposition}" - await e.edit(text, file=gm.photo) + text = _akinator_result(gm.name_proposition, gm.description_proposition) + await e.edit(text, file=gm.photo, parse_mode="html") else: # Game is not won yet, continue asking questions - buttons = [ - [Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Yes", "No", "Idk"]], - [Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Probably", "Probably Not"]], - ] - await e.edit(gm.question, buttons=buttons) + buttons = _aka_buttons(ch, mid) + await e.edit( + fmtmsg("Akinator ", msgs=gm.question), + buttons=buttons, + parse_mode="html", + ) except KeyError: await e.answer(get_string("aki_3")) except Exception as ex: - akipyLOGS.error(f"An unexpected error occurred: {ex}") + akipyLOGS.exception(f"An unexpected error occurred: {ex}") + try: + await e.answer("The game could not continue. Start a new game.", alert=True) + except Exception: + pass -@in_pattern(re.compile("aki_?(.*)"), owner=True) +@in_pattern(AKI_TEXT_PATTERN, owner=True) async def eiagx(e): - bts = Button.inline(get_string("aki_2"), data=e.text) + bts = ikm([[(get_string("aki_2"), e.text, "primary")]], icon=False) ci = types.InputWebDocument(aki_photo, 0, "image/jpeg", []) ans = [ await e.builder.article( "Akinator", - type="photo", content=ci, text="Akinator", thumb=ci, @@ -138,18 +191,26 @@ async def eiagx(e): # ----------------------- Main Command ------------------- # -GIMAGE = "https://graph.org/file/1c51015bae5205a65fd69.jpg" +GIMAGES = [ + "https://graph.org/file/1c51015bae5205a65fd69.jpg", + "https://imgwhale.xyz/3xyr322l64j9590", +] + @asst_cmd(pattern="startgame", owner=True) async def magic(event): - buttons = [ - [Button.inline("Trivia Quiz", "trzia")], - [Button.inline("Cancel ❌", "delit")], - ] + buttons = ikm( + [ + [("Trivia Quiz ", TRIVIA_CAT, "primary")], + [("Cancel ", DELIT, "danger")], + ], + icon=False, + ) await event.reply( - get_string("games_1"), - file=GIMAGE, + fmtmsg("SarahUB Games ", msgs=get_string("games_1")), + file=choice(GIMAGES), buttons=buttons, + parse_mode="html", ) @@ -169,27 +230,34 @@ CONGO_STICKER = [ "CAADAgADiwMAAsSraAuoe2BwYu1sdQI", ] +TRIVIA_PATTERN = cb_pattern("assistant", "games", "trivia") +CTDOWN_PATTERN = cb_pattern("assistant", "games", "ctdown") -@callback("delit", owner=True) + +@callback(cb_exact_pattern("assistant", "games", "delit"), owner=True) async def delete_it(event): await event.delete() -@callback(re.compile("ctdown(.*)"), owner=True) +@callback(CTDOWN_PATTERN, owner=True) async def ct_spam(e): n = e.data_match.group(1).decode("utf-8") await e.answer(f"Wait {n} seconds..", alert=True) -@callback(re.compile("trzia(.*)"), owner=True) +@callback(TRIVIA_PATTERN, owner=True) async def choose_cata(event): - match = event.data_match.group(1).decode("utf-8") - if not match: + tail = event.data_match.group(1).decode("utf-8") + parts = tail.split(":") + action = parts[0] + rest = parts[1:] + + if action == "cat": if TR_BTS.get("category"): buttons = TR_BTS["category"] else: req = ( - await async_searcher( + await fns.async_searcher( "https://opentdb.com/api_category.php", re_json=True ) )["trivia_categories"] @@ -198,39 +266,99 @@ async def choose_cata(event): name = i["name"] if ":" in name: name = name.split(":")[1] - btt.append(Button.inline(name, f"trziad_{i['id']}")) - buttons = list(zip(btt[::2], btt[1::2])) + btt.append( + ( + name, + cb("assistant", "games", "trivia", "diff", i["id"]), + "primary", + ) + ) + buttons_data = list(zip(btt[::2], btt[1::2])) if len(btt) % 2 == 1: - buttons.append((btt[-1],)) - buttons.append([Button.inline("Cancel ❌", "delit")]) + buttons_data.append([btt[-1]]) + buttons_data.append([("Cancel ", DELIT, "danger")]) + buttons = ikm(buttons_data, icon=False) TR_BTS.update({"category": buttons}) - text = get_string("games_2") - elif match[0] == "d": - cat = match[1:] - buttons = [[Button.inline(i, f"trziac{cat}_{i}") for i in DIFI_KEYS]] - buttons.append(get_back_button("trzia")) - text = get_string("games_3") - elif match[0] == "c": - m = match[1:] - buttons = [[Button.inline(str(i), f"trziat{m}_{i}") for i in range(10, 70, 20)]] - text = get_string("games_4") - elif match[0] == "t": - m_ = match[1:] - buttons = [ - [Button.inline(str(i), f"trzias{m_}_{i}") for i in [10, 30, 60, 120]] - ] - text = get_string("games_5") - elif match[0] == "s": + text = fmtmsg("Trivia Setup ", msgs=get_string("games_2")) + elif action == "diff": + cat = rest[0] + buttons = ikm( + [ + [ + ( + "Easy ", + cb("assistant", "games", "trivia", "num", cat, "Easy"), + "primary", + ), + ( + "Medium ", + cb("assistant", "games", "trivia", "num", cat, "Medium"), + "primary", + ), + ( + "Hard ", + cb("assistant", "games", "trivia", "num", cat, "Hard"), + "primary", + ), + ], + [("Back", TRIVIA_CAT, None)], + ], + icon=False, + ) + text = fmtmsg("Difficulty Selection ", msgs=get_string("games_3")) + elif action == "num": + cat, diff = rest + buttons = ikm( + [ + [ + ( + f"{i} Questions", + cb("assistant", "games", "trivia", "time", cat, diff, i), + "primary", + ) + for i in range(10, 70, 20) + ], + [("Back", TRIVIA_CAT, None)], + ], + icon=False, + ) + text = fmtmsg("Number of Questions ", msgs=get_string("games_4")) + elif action == "time": + cat, diff, num = rest + buttons = ikm( + [ + [ + ( + f"{i}s", + cb("assistant", "games", "trivia", "start", cat, diff, num, i), + "primary", + ) + for i in [10, 30, 60, 120] + ], + [("Back", TRIVIA_CAT, None)], + ], + icon=False, + ) + text = fmtmsg("Time Limit per Question ", msgs=get_string("games_5")) + elif action == "start": + cat, le, nu, in_ = rest chat = event.chat_id - cat, le, nu, in_ = match[2:].split("_") - msg = await event.edit(get_string("games_6").format(le, nu)) + msg = await event.edit( + fmtmsg("Trivia Quiz ", msgs=get_string("games_6").format(le, nu)), + parse_mode="html", + ) for i in reversed(range(5)): - msg = await msg.edit(buttons=Button.inline(f"{i} ⏰", f"ctdown{i}")) + msg = await msg.edit( + buttons=ikm( + [[(f"{i}", cb("assistant", "games", "ctdown", i), None)]], + icon=False, + ) + ) await asyncio.sleep(1) await msg.edit( - msg.text + "\n\n• Send /cancel to stop the Quiz...", buttons=None + msg.text + "\n\n Send /cancel to stop the Quiz...", buttons=None ) - qsss = await async_searcher( + qsss = await fns.async_searcher( f"https://opentdb.com/api.php?amount={nu}&category={cat}&difficulty={le.lower()}", re_json=True, ) @@ -244,10 +372,10 @@ async def choose_cata(event): if TRIVIA_CHATS[chat].get("cancel") is not None: break ansi = str(uuid.uuid1()).split("-")[0].encode() - opts = [PollAnswer(TextWithEntities(unescape(q["correct_answer"]), entities=[]), ansi)] + opts = [PollAnswer(unescape(q["correct_answer"]), ansi)] [ opts.append( - PollAnswer(TextWithEntities(unescape(a), entities=[]), str(uuid.uuid1()).split("-")[0].encode()) + PollAnswer(unescape(a), str(uuid.uuid1()).split("-")[0].encode()) ) for a in q["incorrect_answers"] ] @@ -255,10 +383,7 @@ async def choose_cata(event): poll = InputMediaPoll( Poll( 0, - TextWithEntities( - f"[{copper+1}]. " + unescape(q["question"]), - entities=[] - ), + f"[{copper + 1}]. " + unescape(q["question"]), answers=opts, public_voters=True, quiz=True, @@ -273,51 +398,50 @@ async def choose_cata(event): await asyncio.sleep(int(in_)) if not TRIVIA_CHATS[chat]: await event.respond( - "No-One Got Any Score in the Quiz!\nBetter Luck Next Time!" + fmtmsg( + "Quiz Finished ", + msgs="No-One Got Any Score in the Quiz!\nBetter Luck Next Time!", + ), + parse_mode="html", ) else: try: await event.respond(file=choice(CONGO_STICKER)) except ChatSendStickersForbiddenError: pass - LBD = "🎯 **Scoreboard of the Quiz.**\n\n" + LBD = {} TRC = TRIVIA_CHATS[chat] if "cancel" in TRC.keys(): del TRC["cancel"] for userid, user_score in dict( sorted(TRC.items(), key=operator.itemgetter(1), reverse=True) ).items(): - user = inline_mention(await event.client.get_entity(userid)) - LBD += f"••• {user} - {user_score}\n" - await event.respond(LBD) + user_entity = await event.client.get_entity(userid) + LBD[get_display_name(user_entity)] = f"{user_score} Points" + + await event.respond( + fmtmsg(" Quiz Scoreboard", data=LBD), + parse_mode="html", + ) del TRIVIA_CHATS[chat] list_ = list(POLLS.copy().keys()) for key in list_: if POLLS[key]["chat"] == chat: del POLLS[key] return - await event.edit(text, buttons=buttons) + await event.edit(text, buttons=buttons, parse_mode="html") @asst.on( Raw(UpdateMessagePollVote, func=lambda x: TRIVIA_CHATS and POLLS.get(x.poll_id)) ) -async def pollish(eve: UpdateMessagePollVote): +async def pollish(eve): if POLLS.get(eve.poll_id)["chat"] not in TRIVIA_CHATS.keys(): return - if not eve.options: - # Consider as correct answer if no options selected - chat = POLLS.get(eve.poll_id)["chat"] - user = eve.peer.user_id - if not TRIVIA_CHATS.get(chat, {}).get(user): - TRIVIA_CHATS[chat][user] = 1 - else: - TRIVIA_CHATS[chat][user] += 1 - return if POLLS[eve.poll_id]["answer"] != eve.options[0]: return chat = POLLS.get(eve.poll_id)["chat"] - user = eve.peer.user_id + user = eve.user_id if not TRIVIA_CHATS.get(chat, {}).get(user): TRIVIA_CHATS[chat][user] = 1 else: diff --git a/assistant/initial.py b/assistant/initial.py index abf334b2827859034f7a3eb9a0c2a154f015dc23..9e846b0aa78a2a1cd6136c9576de5751b5661643 100644 --- a/assistant/initial.py +++ b/assistant/initial.py @@ -1,84 +1,91 @@ # Ultroid - UserBot -# Copyright (C) 2021-2026 TeamUltroid +# Copyright (C) 2021-2023 TeamUltroid # # This file is a part of < https://github.com/TeamUltroid/Ultroid/ > # PLease read the GNU Affero General Public License in # . -import re +import html from . import * +from ._cbs import cb, cb_pattern +from custom.tg import ikm -STRINGS = { - 1: """🎇 **Thanks for Deploying Ultroid Userbot!** - -• Here, are the Some Basic stuff from, where you can Know, about its Usage.""", - 2: """🎉** About Ultroid** - -🧿 Ultroid is Pluggable and powerful Telethon Userbot, made in Python from Scratch. It is Aimed to Increase Security along with Addition of Other Useful Features. - -❣ Made by **@TeamUltroid**""", - 3: """**💡• FAQs •** --> [Username Tracker](https://t.me/UltroidUpdates/24) --> [Keeping Custom Addons Repo](https://t.me/UltroidUpdates/28) --> [Disabling Deploy message](https://t.me/UltroidUpdates/27) --> [Setting up TimeZone](https://t.me/UltroidUpdates/22) --> [About Inline PmPermit](https://t.me/UltroidUpdates/21) --> [About Dual Mode](https://t.me/UltroidUpdates/18) --> [Custom Thumbnail](https://t.me/UltroidUpdates/13) --> [About FullSudo](https://t.me/UltroidUpdates/11) --> [Setting Up PmBot](https://t.me/UltroidUpdates/2) --> [Also Check](https://t.me/UltroidUpdates/14) - -**• To Know About Updates** - - Join @TeamUltroid.""", - 4: f"""• `To Know All Available Commands` - - - `{HNDLR}help` - - `{HNDLR}cmds`""", - 5: """• **For Any Other Query or Suggestion** - - Move to **@UltroidSupportChat**. - -• Thanks for Reaching till END.""", +STRINGS = { + 1: ( + "Welcome to Ultroid\n\n" + "Your userbot is online. This short guide covers the first commands, " + "help, and support." + ), + 2: ( + "About Ultroid\n\n" + "Ultroid is a modular Telegram userbot built with Telethon. Its plugins " + "add tools for messaging, moderation, media, and automation.\n\n" + 'Maintained by TeamUltroid.' + ), + 3: ( + "Quick links\n\n" + 'Username tracker\n' + 'Custom add-ons\n' + 'Time zone setup\n' + 'Inline PMPermit\n' + 'Dual mode\n' + 'Private-message bot\n' + 'More guides' + ), + 4: ( + "Find commands\n\n" + f"{html.escape(HNDLR)}help opens the help menu.\n" + f"{html.escape(HNDLR)}help <plugin> shows a plugin's " + "commands.\n" + f"{html.escape(HNDLR)}cmds opens the complete command index." + ), + 5: ( + "Need a hand?\n\n" + "For questions, suggestions, and troubleshooting, visit " + 'Ultroid Support.\n\n' + "You're all set." + ), } +PAGE_COUNT = len(STRINGS) +PAGE_PATTERN = cb_pattern("assistant", "initial") -@callback(re.compile("initft_(\\d+)")) -async def init_depl(e): - CURRENT = int(e.data_match.group(1)) - if CURRENT == 5: - return await e.edit( - STRINGS[5], - buttons=Button.inline("<< Back", "initbk_4"), - link_preview=False, + +def _page_buttons(current): + rows = [] + if current > 1: + rows.append( + ("Previous", cb("assistant", "initial", "prev", current - 1), "primary") + ) + if current < PAGE_COUNT: + rows.append( + ("Next", cb("assistant", "initial", "next", current + 1), "primary") ) + elif current == PAGE_COUNT: + rows.append(("Back to start", cb("assistant", "initial", "prev", 1), None)) + return ikm([rows], icon=False) if rows else [] - await e.edit( - STRINGS[CURRENT], - buttons=[ - Button.inline("<<", f"initbk_{str(CURRENT - 1)}"), - Button.inline(">>", f"initft_{str(CURRENT + 1)}"), - ], + +async def _render_page(event, current): + current = max(1, min(int(current), PAGE_COUNT)) + await event.edit( + STRINGS[current], + buttons=_page_buttons(current), link_preview=False, + parse_mode="html", ) -@callback(re.compile("initbk_(\\d+)")) -async def ineiq(e): - CURRENT = int(e.data_match.group(1)) - if CURRENT == 1: - return await e.edit( - STRINGS[1], - buttons=Button.inline("Start Back >>", "initft_2"), - link_preview=False, - ) - - await e.edit( - STRINGS[CURRENT], - buttons=[ - Button.inline("<<", f"initbk_{str(CURRENT - 1)}"), - Button.inline(">>", f"initft_{str(CURRENT + 1)}"), - ], - link_preview=False, - ) +@callback(PAGE_PATTERN) +async def init_depl(event): + """Render the guide page named by the callback payload.""" + try: + payload = event.data.decode("utf-8").split(":") + current = int(payload[-1]) + except (AttributeError, UnicodeDecodeError, ValueError, IndexError): + return await event.answer("This guide page could not be opened.", alert=True) + if not 1 <= current <= PAGE_COUNT: + return await event.answer("This guide page no longer exists.", alert=True) + await _render_page(event, current) diff --git a/assistant/inlinestuff.py b/assistant/inlinestuff.py index 5c157a6bb2692c81f32c9c6d12e14a99991e7002..f568946c307ae1cbaa078777a147bf98105d0657 100644 --- a/assistant/inlinestuff.py +++ b/assistant/inlinestuff.py @@ -1,39 +1,134 @@ # Ultroid - UserBot -# Copyright (C) 2021-2026 TeamUltroid +# Copyright (C) 2021-2023 TeamUltroid # # This file is a part of < https://github.com/TeamUltroid/Ultroid/ > # PLease read the GNU Affero General Public License in # . import base64 +import hashlib import inspect +import os from datetime import datetime from html import unescape from random import choice -from re import compile as re_compile from bs4 import BeautifulSoup as bs from telethon import Button from telethon.tl.alltlobjects import LAYER, tlobjects -from telethon.tl.types import DocumentAttributeAudio as Audio from telethon.tl.types import InputWebDocument as wb -from pyUltroid.fns.misc import google_search -from pyUltroid.fns.tools import ( - _webupload_cache, - async_searcher, - get_ofox, - saavn_search, - webuploader, +from custom.rich import resolve_style +from pyUltroid import LOGS, asst +from pyUltroid._core.buttonkit import button as rich_button +from pyUltroid._core.events import InlineResultBuilder +from pyUltroid._core.inlineresults import InlineResults +from pyUltroid._core.richmsg import RichBlocks, rich_markup_from_blocks +from pyUltroid._core.webupload import ( + MENU_SERVICES, + SERVICE_LABELS, + UploadResult, ) +from pyUltroid.fns import fns +from pyUltroid.fns.tools import _webupload_cache +from strings import get_string + +from . import InlinePlugin, _ult_cache, callback, in_pattern +from ._cbs import cb, cb_pattern + +# +# C8 inline result restyle helpers. +# +# InlineResults.article_rich() (pyUltroid/_core/inlineresults.py) emits only +# native RichMessage articles. Missing rich-message constructors or invalid +# content are hard errors; this path never falls back to a plain article. +# Block rendering delegates to pyUltroid._core.richmsg, so table() and +# expandable() blocks use the same native model as other rich-message callers. +# +# _rich_article below additionally preserves inline-result thumb=/content= +# metadata on the native RichMessage result. +# + + +async def _rich_article( + ires, + title, + blocks, + *, + description=None, + url=None, + id=None, + buttons=None, + thumb=None, + content=None, + rtl=False, +): + """Build one article_rich inline result from a :class:RichBlocks. + + Converts *blocks* to native RichMarkup while preserving its file vector, + then passes the complete payload to InlineResults.article_rich. Local + media that has not already been uploaded to Telegram is rejected by the + layer-230 engine; it is never silently dropped. thumb/content are assigned + directly on the pinned InputBotInlineResult schema. + """ + payload = rich_markup_from_blocks(blocks, format="html") + result = await ires.article_rich( + title, + payload, + format="html", + description=description, + url=url, + id=id, + buttons=buttons, + rtl=rtl, + ) + changed = False + if thumb is not None: + result.thumb = thumb + changed = True + if content is not None: + result.content = content + changed = True + if changed and id is None: + result.id = hashlib.sha256(bytes(result)).hexdigest() + return result + + +def _styled(text, *, data=None, url=None, preset=None): + """Style one button via buttonkit.button (bg-colour presets). + + Falls back to a plain telethon.Button if styling itself raises for + any reason custom.rich.button already degrades style/icon + internally (see its docstring), this is a belt-and-suspenders probe so + callers below never lose a button entirely over styling. + """ + try: + return rich_button(text, data=data, url=url, preset=preset) + except Exception: + return ( + Button.url(text, url=url) + if url is not None + else Button.inline(text, data=data) + ) + + +def _styled_switch(text, query, *, same_peer=True, preset=None): + """Style a switch_inline (search-again / share / fork) button.""" + try: + style, icon = resolve_style(preset=preset) + return Button.switch_inline( + text, query=query, same_peer=same_peer, style=style, icon=icon + ) + except Exception: + return Button.switch_inline(text, query=query, same_peer=same_peer) -from . import * -from . import _ult_cache SUP_BUTTONS = [ [ - Button.url("• Repo •", url="https://github.com/TeamUltroid/Ultroid"), - Button.url("• Support •", url="t.me/UltroidSupportChat"), + _styled( + " Repo ", url="https://github.com/TeamUltroid/Ultroid", preset="primary" + ), + _styled(" Support ", url="t.me/UltroidSupportChat", preset="default"), ], ] @@ -50,17 +145,24 @@ apis = [ @in_pattern("ofox", owner=True) async def _(e): + ires = InlineResults(e) try: match = e.text.split(" ", maxsplit=1)[1] except IndexError: - kkkk = e.builder.article( - title="Enter Device Codename", + blocks = ( + RichBlocks().header("OFoxRecovery").paragraph("You didn't search anything") + ) + kkkk = await _rich_article( + ires, + "Enter Device Codename", + blocks, thumb=wb(ofox, 0, "image/jpeg", []), - text="**OFᴏx🦊Rᴇᴄᴏᴠᴇʀʏ**\n\nYou didn't search anything", - buttons=Button.switch_inline("Sᴇᴀʀᴄʜ Aɢᴀɪɴ", query="ofox ", same_peer=True), + buttons=_styled_switch( + "Search Again", "ofox ", same_peer=True, preset="default" + ), ) return await e.answer([kkkk]) - device, releases = await get_ofox(match) + device, releases = await fns.get_ofox(match) if device.get("detail") is None: fox = [] fullname = device["full_name"] @@ -71,27 +173,36 @@ async def _(e): for data in releases["data"]: release = data["type"] version = data["version"] - size = humanbytes(data["size"]) + size = fns.humanbytes(data["size"]) release_date = datetime.utcfromtimestamp(data["date"]).strftime("%Y-%m-%d") - text = f"[­]({ofox})**OrangeFox Recovery For**\n\n" - text += f"` Full Name: {fullname}`\n" - text += f"` Codename: {codename}`\n" - text += f"` Maintainer: {maintainer}`\n" - text += f"` Build Type: {release}`\n" - text += f"` Version: {version}`\n" - text += f"` Size: {size}`\n" - text += f"` Build Date: {release_date}`" + blocks = ( + RichBlocks() + .header(f"OrangeFox Recovery For {fullname}") + .table( + [ + ["Field", "Value"], + ["Full Name", fullname], + ["Codename", codename], + ["Maintainer", maintainer], + ["Build Type", release], + ["Version", version], + ["Size", size], + ["Build Date", release_date], + ], + caption="Device Details", + ) + ) fox.append( - await e.builder.article( - title=f"{fullname}", + await _rich_article( + ires, + fullname, + blocks, description=f"{version}\n{release_date}", - text=text, thumb=wb(ofox, 0, "image/jpeg", []), - link_preview=True, buttons=[ - Button.url("Dᴏᴡɴʟᴏᴀᴅ", url=f"{link}"), - Button.switch_inline( - "Sᴇᴀʀᴄʜ Aɢᴀɪɴ", query="ofox ", same_peer=True + _styled("Download", url=link, preset="primary"), + _styled_switch( + "Search Again", "ofox ", same_peer=True, preset="default" ), ], ) @@ -105,74 +216,152 @@ async def _(e): ) +#: emoji icon shown on each fl2lnk service button (presentation-only real +#: custom-emoji document ids are deployment-specific, see buttonkit.py). +_FL_SERVICE_ICONS = { + "catbox": "", + "litterbox": "", + "file.io": "", + "0x0.st": "", + "transfer": "", + "uguu": "", + "filebin": "", + "siasky": "", +} + + @in_pattern("fl2lnk ?(.*)", owner=True) -async def _(e): - match = e.pattern_match.group(1) +async def fl2lnk_command(event): + match = event.pattern_match.group(1) + if not match or ":" not in match: + await event.respond( + "Invalid format. Please provide chat ID and message ID in the format 'chat_id:message_id'." + ) + return + chat_id, msg_id = match.split(":") - filename = _webupload_cache[int(chat_id)][int(msg_id)] + try: + filename = _webupload_cache[int(chat_id)][int(msg_id)] + except (KeyError, ValueError): + await event.respond("File not found or invalid chat ID/message ID.") + return + if "/" in filename: filename = filename.split("/")[-1] - __cache = f"{chat_id}:{msg_id}" - buttons = [ - [ - Button.inline("anonfiles", data=f"flanonfiles//{__cache}"), - Button.inline("transfer", data=f"fltransfer//{__cache}"), - ], - [ - Button.inline("bayfiles", data=f"flbayfiles//{__cache}"), - Button.inline("x0.at", data=f"flx0.at//{__cache}"), - ], - [ - Button.inline("file.io", data=f"flfile.io//{__cache}"), - Button.inline("siasky", data=f"flsiasky//{__cache}"), - ], - ] + + ires = InlineResults(event) + buttons = [] + row_btns = [] + for key in MENU_SERVICES: + icon = _FL_SERVICE_ICONS.get(key, "") + row_btns.append( + _styled( + f"{icon} {SERVICE_LABELS.get(key, key)}", + data=cb("assistant", "fl2lnk", key, chat_id, msg_id), + preset="primary", + ) + ) + if len(row_btns) == 2: + buttons.append(row_btns) + row_btns = [] + if row_btns: + buttons.append(row_btns) + try: - lnk = [ - await e.builder.article( - title=f"Upload {filename}", - text=f"**File:**\n{filename}", + blocks = RichBlocks().header(" Upload File").paragraph(filename) + articles = [ + await _rich_article( + ires, + f"Upload {filename}", + blocks, buttons=buttons, ) ] - except BaseException as er: - LOGS.exception(er) - lnk = [ - await e.builder.article( - title="fl2lnk", - text="File not found", - ) - ] - await e.answer(lnk, switch_pm="File to Link.", switch_pm_param="start") + except Exception as e: + LOGS.exception(e) + blocks = ( + RichBlocks() + .header("fl2lnk") + .paragraph("File not found or error in processing.") + ) + articles = [await _rich_article(ires, "fl2lnk", blocks)] + await event.answer(articles, switch_pm="File to Link.", switch_pm_param="start") -@callback( - re_compile( - "fl(.*)", - ), - owner=True, -) -async def _(e): - t = (e.data).decode("UTF-8") - data = t[2:] - host = data.split("//")[0] - chat_id, msg_id = data.split("//")[1].split(":") - filename = _webupload_cache[int(chat_id)][int(msg_id)] - if "/" in filename: - filename = filename.split("/")[-1] - await e.edit(f"Uploading `{filename}` on {host}") - link = (await webuploader(chat_id, msg_id, host)).strip().replace("\n", "") - await e.edit(f"Uploaded `{filename}` on {host}.", buttons=Button.url("View", link)) + +@callback(cb_pattern("assistant", "fl2lnk"), owner=True) +async def fl_callback(event): + tail = event.data_match.group(1).decode("utf-8") + parts = tail.split(":") + if len(parts) != 3: + await event.respond("Invalid callback data format.") + return + + host, chat_id, msg_id = parts + + try: + filename = _webupload_cache[int(chat_id)][int(msg_id)] + except (KeyError, ValueError): + await event.respond("File not found or invalid chat ID/message ID.") + return + + disp = filename.split("/")[-1] if "/" in filename else filename + label = SERVICE_LABELS.get(host, host) + + import time as _time + + state = {"pct": -1, "t": 0.0} + + async def on_progress(sent, total): + pct = round(sent / total * 100) if total else 0 + now = _time.time() + if pct - state["pct"] >= 5 or now - state["t"] >= 1.5 or sent >= total: + state["pct"] = pct + state["t"] = now + try: + await event.edit(f" Uploading {disp} on {label}... {pct}%") + except Exception: + pass + + await event.edit(f" Uploading {disp} on {label}...") + result = await fns.webupload_result( + int(chat_id), int(msg_id), host, on_progress=on_progress + ) + + if isinstance(result, UploadResult): + text = f"**Uploaded** {disp} **on** {label}." + buttons = [[_styled(" View", url=result.url, preset="primary")]] + if result.delete_url: + text += f"\n Delete: {result.delete_url}" + if result.delete_note: + text += f" ({result.delete_note})" + if result.expires: + text += f"\n Expires: {result.expires}" + await event.edit(text, buttons=buttons, link_preview=False) + try: + os.remove(f"resources/downloads/{disp}") + except FileNotFoundError: + pass + else: + await event.edit(f"Failed to upload {disp} on {label}. Error: {result}") @in_pattern("repo", owner=True) async def repo(e): + ires = InlineResults(e) + blocks = ( + RichBlocks() + .header("Ultroid Userbot") + .list(["Userbot", "Telethon"]) + .paragraph(" **ULTROID USERBOT** ") + ) res = [ - await e.builder.article( - title="Ultroid Userbot", + await _rich_article( + ires, + "Ultroid Userbot", + blocks, description="Userbot | Telethon", thumb=wb(ultpic, 0, "image/jpeg", []), - text="• **ULTROID USERBOT** •", buttons=SUP_BUTTONS, ), ] @@ -188,18 +377,18 @@ async def gsearch(q_event): [], switch_pm="Google Search. Enter a query!", switch_pm_param="start" ) searcher = [] - gresults = await google_search(match) + gresults = await fns.google_search(match) for i in gresults: try: title = i["title"] link = i["link"] desc = i["description"] searcher.append( - await q_event.builder.article( + await InlineResultBuilder(q_event).article( title=title, description=desc, thumb=wb(gugirl, 0, "image/jpeg", []), - text=f"**Google Search**\n\n**• Title •**\n`{title}`\n\n**• Description •**\n`{desc}`", + text=f"**Google Search**\n\n** Title **\n{title}\n\n** Description **\n{desc}", link_preview=False, buttons=[ [Button.url("Link", url=f"{link}")], @@ -234,31 +423,31 @@ async def _(e): start = 0 * 3 + 1 da = base64.b64decode(choice(apis)).decode("ascii") url = f"https://www.googleapis.com/customsearch/v1?key={da}&cx=25b3b50edb928435b&q={quer}&start={start}" - data = await async_searcher(url, re_json=True) + data = await fns.async_searcher(url, re_json=True) search_items = data.get("items", []) modss = [] for a in search_items: title = a.get("title") desc = a.get("snippet") link = a.get("link") - text = f"**••Tɪᴛʟᴇ••** `{title}`\n\n" - text += f"**Dᴇsᴄʀɪᴘᴛɪᴏɴ** `{desc}`" + text = f"** Title ** {title}\n\n" + text += f"**Description** {desc}" modss.append( - await e.builder.article( + await InlineResultBuilder(e).article( title=title, description=desc, text=text, link_preview=True, buttons=[ - [Button.url("Dᴏᴡɴʟᴏᴀᴅ", url=f"{link}")], + [Button.url("Download", url=f"{link}")], [ Button.switch_inline( - "Mᴏʀᴇ Mᴏᴅs", + "More Mods", query="mods ", same_peer=True, ), Button.switch_inline( - "Sʜᴀʀᴇ", + "Share", query=f"mods {quer}", same_peer=False, ), @@ -296,34 +485,29 @@ async def _(e): pass foles = [] url = PLAY_API + f.replace(" ", "+") - aap = await async_searcher(url, re_json=True) + aap = await fns.async_searcher(url, re_json=True) + ires = InlineResults(e) for z in aap["results"][:50]: url = "https://play.google.com/store/apps/details?id=" + z["appId"] name = z["title"] desc = unescape(z["summary"])[:300].replace("
", "\n") + "..." dev = z["developer"]["devId"] - text = f"**• App Name •** [{name}]({url})\n" - text += f"**• Developer •** `{dev}`\n" - text += f"**• Description •**\n`{desc}`" + blocks = RichBlocks().header(name).list([f"Developer: {dev}"]).paragraph(desc) foles.append( - await e.builder.article( - title=name, + await _rich_article( + ires, + name, + blocks, description=dev, thumb=wb(z["icon"], 0, "image/jpeg", []), - text=text, - link_preview=True, buttons=[ - [Button.url("Link", url=url)], + [_styled("Link", url=url, preset="primary")], [ - Button.switch_inline( - "More Apps", - query="app ", - same_peer=True, + _styled_switch( + "More Apps", "app ", same_peer=True, preset="default" ), - Button.switch_inline( - "Sʜᴀʀᴇ", - query=f"app {f}", - same_peer=False, + _styled_switch( + "Share", f"app {f}", same_peer=False, preset="default" ), ], ], @@ -343,35 +527,52 @@ PISTON_LANGS = {} @in_pattern("run", owner=True) async def piston_run(event): + ires = InlineResults(event) try: lang = event.text.split()[1] code = event.text.split(maxsplit=2)[2] except IndexError: - result = await event.builder.article( - title="Bad Query", + blocks = ( + RichBlocks() + .header("Bad Query") + .paragraph("Usage: [Language] [code]") + .code(f'@{asst.me.username} run python print("hello world")') + .paragraph("Language List: https://graph.org/Ultroid-09-01-6") + ) + result = await _rich_article( + ires, + "Bad Query", + blocks, description="Usage: [Language] [code]", thumb=wb( "https://graph.org/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", [] ), - text=f'**Inline Usage**\n\n`@{asst.me.username} run python print("hello world")`\n\n[Language List](https://graph.org/Ultroid-09-01-6)', ) return await event.answer([result]) if not PISTON_LANGS: - se = await async_searcher(f"{PISTON_URI}runtimes", re_json=True) + se = await fns.async_searcher(f"{PISTON_URI}runtimes", re_json=True) PISTON_LANGS.update({lang.pop("language"): lang for lang in se}) if lang in PISTON_LANGS.keys(): version = PISTON_LANGS[lang]["version"] else: - result = await event.builder.article( - title="Unsupported Language", + blocks = ( + RichBlocks() + .header("Unsupported Language") + .paragraph("Usage: [Language] [code]") + .code(f'@{asst.me.username} run python print("hello world")') + .paragraph("Language List: https://graph.org/Ultroid-09-01-6") + ) + result = await _rich_article( + ires, + "Unsupported Language", + blocks, description="Usage: [Language] [code]", thumb=wb( "https://graph.org/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", [] ), - text=f'**Inline Usage**\n\n`@{asst.me.username} run python print("hello world")`\n\n[Language List](https://graph.org/Ultroid-09-01-6)', ) return await event.answer([result]) - output = await async_searcher( + output = await fns.async_searcher( f"{PISTON_URI}execute", post=True, json={ @@ -385,16 +586,25 @@ async def piston_run(event): output = output["run"]["output"] or get_string("instu_4") if len(output) > 3000: output = f"{output[:3000]}..." - result = await event.builder.article( - title="Result", + blocks = ( + RichBlocks() + .header("Result") + .table([["Field", "Value"], ["Language", lang]]) + .code(code, lang=lang) + .header("Output", level=3) + .code(output) + ) + result = await _rich_article( + ires, + "Result", + blocks, description=output, - text=f"• **Language:**\n`{lang}`\n\n• **Code:**\n`{code}`\n\n• **Result:**\n`{output}`", thumb=wb( "https://graph.org/file/871ee4a481f58117dccc4.jpg", 0, "image/jpeg", [] ), - buttons=Button.switch_inline("Fork", query=event.text, same_peer=True), + buttons=_styled_switch("Fork", event.text, same_peer=True, preset="default"), ) - await event.answer([result], switch_pm="• Piston •", switch_pm_param="start") + await event.answer([result], switch_pm=" Piston ", switch_pm_param="start") FDROID_ = {} @@ -410,36 +620,43 @@ async def do_magic(event): ) if FDROID_.get(match): return await event.answer( - FDROID_[match], switch_pm=f"• Results for {match}", switch_pm_param="start" + FDROID_[match], switch_pm=f" Results for {match}", switch_pm_param="start" ) link = "https://search.f-droid.org/?q=" + match.replace(" ", "+") - content = await async_searcher(link, re_content=True) + content = await fns.async_searcher(link, re_content=True) BSC = bs(content, "html.parser", from_encoding="utf-8") ress = [] + ires = InlineResults(event) for dat in BSC.find_all("a", "package-header")[:10]: image = dat.find("img", "package-icon")["src"] if image.endswith("/"): image = "https://graph.org/file/a8dd4a92c5a53a89d0eff.jpg" title = dat.find("h4", "package-name").text.strip() desc = dat.find("span", "package-summary").text.strip() - text = f"• **Name :** `{title}`\n\n" - text += f"• **Description :** `{desc}`\n" - text += f"• **License :** `{dat.find('span', 'package-license').text.strip()}`" + license_ = dat.find("span", "package-license").text.strip() + blocks = ( + RichBlocks().header(title).list([f"License: {license_}"]).paragraph(desc) + ) imga = wb(image, 0, "image/jpeg", []) ress.append( - await event.builder.article( - title=title, - type="photo", + await _rich_article( + ires, + title, + blocks, description=desc, - text=text, - content=imga, thumb=imga, - include_media=True, + content=imga, buttons=[ - Button.inline( - "• Download •", "fd" + dat["href"].split("packages/")[-1] + _styled( + " Download ", + data=cb( + "assistant", "fdroid", dat["href"].split("packages/")[-1] + ), + preset="primary", + ), + _styled_switch( + " Share ", event.text, same_peer=False, preset="default" ), - Button.switch_inline("• Share •", query=event.text), ], ) ) @@ -467,40 +684,46 @@ async def twitter_search(event): try: return await event.answer( _ult_cache["twitter"][match], - switch_pm="• Twitter Search •", + switch_pm=" Twitter Search ", switch_pm_param="start", ) except KeyError: pass headers = {"Authorization": f"bearer {choice(_bearer_collected)}"} - res = await async_searcher( + res = await fns.async_searcher( f"https://api.twitter.com/1.1/users/search.json?q={match}", headers=headers, re_json=True, ) reso = [] + ires = InlineResults(event) for user in res: thumb = wb(user["profile_image_url_https"], 0, "image/jpeg", []) - if user.get("profile_banner_url"): - url = user["profile_banner_url"] - text = f"[\xad]({url})• **Name :** `{user['name']}`\n" - else: - text = f"• **Name :** `{user['name']}`\n" - text += f"• **Description :** `{user['description']}`\n" - text += f"• **Username :** `@{user['screen_name']}`\n" - text += f"• **Followers :** `{user['followers_count']}` • **Following :** `{user['friends_count']}`\n" pro_ = "https://twitter.com/" + user["screen_name"] - text += f"• **Link :** [Click Here]({pro_})\n_" + blocks = ( + RichBlocks() + .header(user["name"]) + .table( + [ + ["Field", "Value"], + ["Username", f"@{user['screen_name']}"], + ["Followers", str(user["followers_count"])], + ["Following", str(user["friends_count"])], + ] + ) + .paragraph(user["description"] or "") + ) reso.append( - await event.builder.article( - title=user["name"], + await _rich_article( + ires, + user["name"], + blocks, description=user["description"], url=pro_, - text=text, thumb=thumb, ) ) - swi_ = f"🐦 Showing {len(reso)} Results!" if reso else "No User Found :(" + swi_ = f" Showing {len(reso)} Results!" if reso else "No User Found :(" await event.answer(reso, switch_pm=swi_, switch_pm_param="start") if _ult_cache.get("twitter"): _ult_cache["twitter"].update({match: reso}) @@ -508,60 +731,24 @@ async def twitter_search(event): _ult_cache.update({"twitter": {match: reso}}) -_savn_cache = {} +# Saavn defunct inline handler removed @in_pattern("saavn", owner=True) async def savn_s(event): - try: - query = event.text.split(maxsplit=1)[1].lower() - except IndexError: - return await event.answer( - [], switch_pm="Enter Query to search 🔍", switch_pm_param="start" - ) - if query in _savn_cache: - return await event.answer( - _savn_cache[query], - switch_pm=f"Showing Results for {query}", - switch_pm_param="start", - ) - results = await saavn_search(query) - swi = "🎵 Saavn Search" if results else "No Results Found!" - res = [] - for song in results: - thumb = wb(song["image"], 0, "image/jpeg", []) - text = f"• **Title :** {song['title']}" - text += f"\n• **Year :** {song['year']}" - text += f"\n• **Lang :** {song['language']}" - text += f"\n• **Artist :** {song['artists']}" - text += f"\n• **Release Date :** {song['release_date']}" - res.append( - await event.builder.article( - title=song["title"], - description=song["artists"], - type="audio", - text=text, - include_media=True, - buttons=Button.switch_inline( - "Search Again 🔍", query="saavn", same_peer=True - ), - thumb=thumb, - content=wb( - song["url"], - 0, - "audio/mp4", - [ - Audio( - title=song["title"], - duration=int(song["duration"]), - performer=song["artists"], - ) - ], - ), - ) - ) - await event.answer(res, switch_pm=swi, switch_pm_param="start") - _savn_cache.update({query: res}) + """Saavn music service defunct inline search removed.""" + ires = InlineResults(event) + blocks = ( + RichBlocks() + .header(" Saavn Search") + .paragraph("This inline search is no longer available.") + ) + notice = await _rich_article(ires, "Saavn is no longer available", blocks) + return await event.answer( + [notice], + switch_pm=" Saavn is no longer available", + switch_pm_param="start", + ) @in_pattern("tl", owner=True) @@ -569,33 +756,33 @@ async def inline_tl(ult): try: match = ult.text.split(maxsplit=1)[1] except IndexError: - text = f"**Telegram TlObjects Searcher.**\n__(Don't use if you don't know what it is!)__\n\n• Example Usage\n`@{asst.me.username} tl GetFullUserRequest`" + text = f"**Telegram TlObjects Searcher.**\n__(Don't use if you don't know what it is!)__\n\n Example Usage\n@{asst.me.username} tl GetFullUserRequest" return await ult.answer( [ - await ult.builder.article( + await InlineResultBuilder(ult).article( title="How to Use?", description="Tl Searcher by Ultroid", url="https://t.me/TeamUltroid", text=text, ) ], - switch_pm="Tl Search 🔍", + switch_pm="Tl Search ", switch_pm_param="start", ) res = [] for key in tlobjects.values(): if match.lower() in key.__name__.lower(): tyyp = "Function" if "tl.functions." in str(key) else "Type" - text = f"**Name:** `{key.__name__}`\n" - text += f"**Category:** `{tyyp}`\n" - text += f"\n`from {key.__module__} import {key.__name__}`\n\n" + text = f"**Name:** {key.__name__}\n" + text += f"**Category:** {tyyp}\n" + text += f"\nfrom {key.__module__} import {key.__name__}\n\n" if args := str(inspect.signature(key))[1:][:-1]: text += "**Parameter:**\n" for para in args.split(","): - text += " " * 4 + "`" + para + "`\n" - text += f"\n**Layer:** `{LAYER}`" + text += " " * 4 + "" + para + "\n" + text += f"\n**Layer:** {LAYER}" res.append( - await ult.builder.article( + await InlineResultBuilder(ult).article( title=key.__name__, description=tyyp, url="https://t.me/TeamUltroid", @@ -608,16 +795,16 @@ async def inline_tl(ult): InlinePlugin.update( { - "Pʟᴀʏ Sᴛᴏʀᴇ Aᴘᴘs": "app telegram", - "Mᴏᴅᴅᴇᴅ Aᴘᴘs": "mods minecraft", - "Sᴇᴀʀᴄʜ Oɴ Gᴏᴏɢʟᴇ": "go TeamUltroid", - "WʜɪSᴘᴇʀ": "wspr @username Hello🎉", - "YᴏᴜTᴜʙᴇ Dᴏᴡɴʟᴏᴀᴅᴇʀ": "yt Ed Sheeran Perfect", + "Play Store Apps": "app telegram", + "Modded Apps": "mods minecraft", + "Search On Google": "go TeamUltroid", + "WhiSper": "wspr @username Hello", + "YouTube Downloader": "yt Ed Sheeran Perfect", "Piston Eval": "run javascript console.log('Hello Ultroid')", - "OʀᴀɴɢᴇFᴏx🦊": "ofox beryllium", - "Tᴡɪᴛᴛᴇʀ Usᴇʀ": "twitter theultroid", - "Fᴅʀᴏɪᴅ Sᴇᴀʀᴄʜ": "fdroid telegram", - "Sᴀᴀᴠɴ sᴇᴀʀᴄʜ": "saavn", - "Tʟ Sᴇᴀʀᴄʜ": "tl", + "OrangeFox": "ofox beryllium", + "Twitter User": "twitter theultroid", + "Fdroid Search": "fdroid telegram", + "Saavn search": "saavn", + "Tl Search": "tl", } ) diff --git a/assistant/localization.py b/assistant/localization.py index 7abbdadef60a61e2106b5cc0c286d08ed0fcd5de..a1234f93b4e838913cfe53c4c23560b701c4d316 100644 --- a/assistant/localization.py +++ b/assistant/localization.py @@ -1,47 +1,117 @@ # Ultroid - UserBot -# Copyright (C) 2021-2026 TeamUltroid +# Copyright (C) 2021-2023 TeamUltroid # # This file is a part of < https://github.com/TeamUltroid/Ultroid/ > -# PLease read the GNU Affero General Public License in -# . +# Please read the GNU Affero General Public License in +# . -import re +from custom.tg import ikm +from pyUltroid._core.richmsg import edit_rich from . import ( - Button, ULTConfig, callback, get_back_button, get_languages, - get_string, udB, ) +from ._cbs import cb, cb_exact_pattern, cb_pattern +from .rich_pages import callback_edit_target, rich_page +LANG_MENU = cb_exact_pattern("assistant", "lang", "menu") +LANG_SET_PATTERN = cb_pattern("assistant", "lang", "set") +MAIN_MENU = cb("assistant", "start", "mainmenu") -@callback("lang", owner=True) + +def _language_key(raw: str, languages: dict) -> str | None: + """Resolve a callback token against the currently supported locale keys.""" + key = str(raw or "").strip() + if key in languages: + return key + return next( + ( + candidate + for candidate in languages + if candidate.casefold() == key.casefold() + ), + None, + ) + + +async def _edit_language(event, blocks, buttons): + """Edit this callback's message through the native RichMessage path.""" + peer, message = callback_edit_target(event) + return await edit_rich( + event.client, + peer, + message, + blocks, + format="html", + buttons=buttons, + link_preview=False, + ) + + +@callback(LANG_MENU, owner=True) async def setlang(event): languages = get_languages() - tultd = [ - Button.inline( - f"{languages[ult]['natively']} [{ult.lower()}]", - data=f"set_{ult}", + current = str(getattr(ULTConfig, "lang", "en") or "en").casefold() + entries = [ + ( + f"{languages[code]['natively']} [{code.casefold()}]", + cb("assistant", "lang", "set", code), + "success" if code.casefold() == current else None, ) - for ult in languages + for code in languages ] - buttons = list(zip(tultd[::2], tultd[1::2])) - if len(tultd) % 2 == 1: - buttons.append((tultd[-1],)) - buttons.append([Button.inline("« Back", data="mainmenu")]) - await event.edit(get_string("ast_4"), buttons=buttons) + rows = [list(pair) for pair in zip(entries[::2], entries[1::2])] + if len(entries) % 2: + rows.append([entries[-1]]) + rows.append([("Back", MAIN_MENU, None)]) + await _edit_language( + event, + rich_page( + "Language", + [ + ( + f"{languages[code]['natively']} [{code.casefold()}]", + "Currently selected" if code.casefold() == current else "Choose this language", + ) + for code in languages + ], + description="Choose the language used by the assistant.", + columns=("Language", "Status"), + total=len(languages), + ), + ikm(rows, icon=False), + ) -@callback(re.compile(b"set_(.*)"), owner=True) +@callback(LANG_SET_PATTERN, owner=True) async def settt(event): - lang = event.data_match.group(1).decode("UTF-8") + try: + raw = event.data_match.group(1).decode("utf-8") + except (AttributeError, UnicodeDecodeError, IndexError): + return await event.answer("That language selection is invalid.", alert=True) + languages = get_languages() + lang = _language_key(raw, languages) + if lang is None: + return await event.answer("That language is no longer available.", alert=True) + ULTConfig.lang = lang - udB.del_key("language") if lang == "en" else udB.set_key("language", lang) - await event.edit( - f"Your language has been set to {languages[lang]['natively']} [{lang}].", - buttons=get_back_button("lang"), + udB.del_key("language") if lang.casefold() == "en" else udB.set_key( + "language", lang + ) + name = str(languages[lang].get("natively") or lang) + await _edit_language( + event, + rich_page( + "Language updated", + [("Language", f"{name} [{lang}]")], + description="The assistant language has been updated.", + columns=("Setting", "Current value"), + total=1, + ), + get_back_button(cb("assistant", "lang", "menu")), ) diff --git a/assistant/ludo_arcade.py b/assistant/ludo_arcade.py new file mode 100644 index 0000000000000000000000000000000000000000..3b388bc474bd162dc3b46c3c8352ee8d973e2bd6 --- /dev/null +++ b/assistant/ludo_arcade.py @@ -0,0 +1,228 @@ +"""Shared native group Ludo with locked, revisioned, ephemeral table sessions.""" +from __future__ import annotations + +import asyncio +import copy +import re +import secrets +import time +from dataclasses import dataclass, field + +from telethon.errors import FloodWaitError, MessageNotModifiedError, RPCError +from telethon.tl import types as t + +from pyUltroid._core.ludo_arcade import Ludo +from pyUltroid._core.ludo_visuals import ( + board_block, + legend_block, + player_blocks, + seat_label, + status_blocks, +) +from pyUltroid._core.matrix_arcade import button, paragraph, row, text, title +from pyUltroid._core.richdebug import rpc_identifier, trace_rich_rpc +from pyUltroid._core.richmsg import edit_rich, send_rich +from pyUltroid._misc._assistant import asst_cmd, callback + +PATTERN = re.compile(r"^lu:(?:new|[a-f0-9]{12}:[0-9]{1,9}:(?:join|leave|start|cancel|roll|move[0-3]|resign|skip|rematch|cancelok|resignok|back))$") +TTL = 60 * 60 +CAPACITY = 64 +EDIT_TIMEOUT = 8.0 + + +@dataclass +class Table: + """Bind one shared game to its exact group and bot message.""" + token: str + chat: int + game: Ludo + message: int | None = None + revision: int = 0 + touched: float = field(default_factory=time.monotonic) + confirmation: tuple[int, str, float] | None = None + lock: asyncio.Lock = field(default_factory=asyncio.Lock) + + def control(self, label, action): + """Build an exact-revision native callback control.""" + control = button(label, f"lu:{self.token}:{self.revision}:{action}") + if action in {"start", "join", "rematch"}: + control.style = t.RichButtonStyle(bg_success=True) + elif action in {"cancelok", "resignok"}: + control.style = t.RichButtonStyle(bg_danger=True) + elif action == "roll" or action.startswith("move"): + control.style = t.RichButtonStyle(bg_primary=True) + return control + + +TABLES: dict[str, Table] = {} + + +def prune(): + """Expire idle tables without evicting locked edits or touching persistence.""" + now = time.monotonic() + for token, table in list(TABLES.items()): + if now - table.touched >= TTL and not table.lock.locked(): + del TABLES[token] + + +def render(table): + """Compose native board cells, readable player cards and nested controls.""" + game, ctl = table.game, table.control + blocks = [title("🎲 LUDO / THE COLOUR COURT"), *status_blocks(game)] + if game.status == "lobby": + blocks += [paragraph("2–4 humans · four tokens each · no AI opponent"), + row(ctl("+ Join table", "join"), ctl("− Leave seat", "leave")), + row(ctl("▶ Start · host", "start"))] + elif game.status == "playing": + moves = game.legal_moves() + seat = game.active + if game.dice is None: + blocks.append(row(ctl(f"🎲 Roll · {seat_label(seat)}", "roll"))) + elif moves: + # Two controls per row keeps legal token labels legible on phones. + for start in range(0, len(moves), 2): + blocks.append(row(*(ctl(f"{seat_label(seat).split()[0]} {chr(65 + seat)}{i + 1} · Move", f"move{i}") + for i in moves[start:start + 2]))) + else: + blocks.append(row(ctl("↺ Rematch lobby · host", "rematch"))) + blocks += [paragraph("Track positions use shared squares 0–51. Your token cards below stay readable even if the full board scrolls sideways."), + t.PageBlockDetails([board_block(game), legend_block()], text("✦ Open the cross board / 15 × 15 cells"), open=False), + *player_blocks(game)] + management = [] + if game.status == "playing": + management += [row(ctl("◷ Skip AFK turn", "skip")), + t.PageBlockDetails([paragraph("Resigning removes your tokens. Closing ends the table for everyone. Both require confirmation."), + row(ctl("⚑ Resign", "resign")), + row(ctl("■ Close · host", "cancel"))], + text("⚑ Leave / close table"), open=False)] + elif game.status == "lobby": + management.append(row(ctl("■ Close table · host", "cancel"))) + if management: + blocks.append(t.PageBlockDetails(management, text("Table controls / more"), open=False)) + if table.confirmation: + actor, action, _deadline = table.confirmation + blocks += [paragraph(f"Player {actor}: confirm {action}. This confirmation expires in 20 seconds."), + row(ctl(f"Confirm {action}", action + "ok"), ctl("Keep playing", "back"))] + if game.events: + blocks.append(t.PageBlockDetails([paragraph(item) for item in game.events[-6:]], + text("Arena feed / last six events"), open=False)) + blocks += [t.PageBlockDetails([ + t.PageBlockDetails([paragraph("Six releases a token; roll then choose one legal token. Four tokens must reach home exactly. Six, capture or a token finishing grants a bonus roll. Three consecutive sixes forfeit the third roll (earlier moves stand)."), + paragraph("Safe star squares cannot be captured. Two allied tokens form a blockade: opponents cannot cross or land on it. No legal move passes automatically. Home lanes are private. This is the arcade's documented Ludo variant, not every regional ruleset.")], text("🎲 Movement / captures / home"), open=False), + t.PageBlockDetails([paragraph("Only the current player may roll or move. Seated players can skip a turn after 90 seconds with no successful turn action; there is no background timer. Resigning removes that seat's tokens. The host can close a table only after confirmation."), + paragraph("One table per group. New controls supersede old controls. Idle tables expire after one hour; restart clears all games. Rematches reopen a lobby and everyone must join again. No stakes, prizes, database writes or external inference.")], text("🛡 Turn access / table safety"), open=False), + ], text("📖 Rules / safety / controls"), open=False), + t.PageBlockFooter(text(f"Native Layer 230 · table {table.token} · revision {table.revision} · /ludo"))] + return t.InputRichMessage(blocks) + + +async def launch(event): + """Reserve one new table in a group without editing any existing message.""" + if not getattr(event, "is_group", False) or not event.sender_id or event.sender_id <= 0: + raise ValueError("Ludo is for human players in group chats. Add the assistant to your group and send /ludo there") + prune() + if any(table.chat == event.chat_id for table in TABLES.values()): + raise ValueError("This group already has a Ludo table. Use its current controls, or let it expire after one hour idle") + if len(TABLES) >= CAPACITY: + raise ValueError("All Ludo tables are occupied. Try later") + table = Table(secrets.token_hex(6), event.chat_id, Ludo(event.sender_id, now=time.monotonic())) + TABLES[table.token] = table + try: + async with table.lock: + result = await asyncio.wait_for(send_rich(event.client, table.chat, render(table)), EDIT_TIMEOUT) + table.message = result if isinstance(result, int) else getattr(result, "id", None) + if not isinstance(table.message, int) or not table.message: + raise ValueError("Telegram returned no table message reference; do not replay the send") + return result + except BaseException: + TABLES.pop(table.token, None) + raise + + +@asst_cmd(pattern="ludo") +async def ludo(event): + """Open a native shared Ludo lobby for this group's human players.""" + try: + return await launch(event) + except ValueError as error: + return await send_rich(event.client, event.chat_id, t.InputRichMessage([title("Ludo table"), paragraph(str(error))])) + + +async def commit(event, table, candidate): + """Publish the candidate before committing state, expiring ambiguous edits.""" + candidate.revision = table.revision + 1 + try: + await asyncio.wait_for(edit_rich(event.client, table.chat, table.message, render(candidate)), EDIT_TIMEOUT) + except asyncio.TimeoutError: + TABLES.pop(table.token, None) + raise ValueError("Telegram did not confirm the edit. This table expired rather than replaying an uncertain turn") from None + except MessageNotModifiedError: + return False + table.game, table.revision, table.confirmation = candidate.game, candidate.revision, candidate.confirmation + table.touched = time.monotonic() + return True + + +def candidate_for(table): + """Copy mutable game state while retaining the live table's single lock.""" + return Table(table.token, table.chat, copy.deepcopy(table.game), table.message, + table.revision, table.touched, table.confirmation, table.lock) + + +@callback(PATTERN) +async def ludo_callback(event): + """Allow group participants while rejecting stale, copied and illegal turns.""" + try: + data = event.data.decode("ascii", "strict") + except (AttributeError, UnicodeDecodeError): + return + if not PATTERN.fullmatch(data): + return + try: + if not getattr(event, "is_group", False) or not event.sender_id or event.sender_id <= 0: + raise ValueError("Use Ludo controls as a human player inside the original group") + if data == "lu:new": + await launch(event) + return await event.answer("Ludo lobby opened") + _, token, revision, action = data.split(":") + prune() + table = TABLES.get(token) + if table is None: + raise ValueError("Table expired or the bot restarted. Send /ludo for a new lobby") + if (table.chat, table.message) != (event.chat_id, event.message_id): + raise ValueError("These controls belong to another group or message") + if table.lock.locked(): + return await event.answer("A turn is updating; use the newest controls in a moment") + async with table.lock: + if int(revision) != table.revision: + raise ValueError("Old board. Use the newest controls on this table") + candidate = candidate_for(table) + now = time.monotonic() + if action in {"cancel", "resign"}: + if action == "cancel" and event.sender_id != candidate.game.host: + raise ValueError("Only the host may close this table") + if action == "resign" and (candidate.game.status != "playing" or not any(p.user == event.sender_id and not p.resigned and not p.finished for p in candidate.game.players)): + raise ValueError("Only a seated player in a running game can resign") + candidate.confirmation = (event.sender_id, action, now + 20) + elif action.endswith("ok"): + expected = (event.sender_id, action[:-2]) + pending = candidate.confirmation + if not pending or pending[:2] != expected or now > pending[2]: + raise ValueError("That confirmation expired or belongs to another player") + candidate.game.apply(action[:-2], event.sender_id, now=now) + candidate.confirmation = None + elif action == "back": + if not candidate.confirmation or candidate.confirmation[0] != event.sender_id: + raise ValueError("Only the player who requested confirmation may dismiss it") + candidate.confirmation = None + else: + candidate.game.apply(action, event.sender_id, now=now) + candidate.confirmation = None + await commit(event, table, candidate) + return await event.answer() + except ValueError as error: + return await event.answer(str(error), alert=True) + except (RPCError, TypeError, asyncio.TimeoutError) as error: + trace_rich_rpc("assistant.ludo", error=error, request_kind="edit", target_kind="peer", outcome="rejected") + detail = "Telegram rate-limited this table; try later" if isinstance(error, FloodWaitError) else f"Native update rejected ({rpc_identifier(error) if isinstance(error, RPCError) else 'LOCAL_VALIDATION_ERROR'}). No move was replayed" + return await event.answer(detail, alert=True) diff --git a/assistant/manager/__init__.py b/assistant/manager/__init__.py index e16967cd56d3ec7cc5474a4825bd5c396404384a..69c528d352acf627ac254993e41a1f89f3e78978 100644 --- a/assistant/manager/__init__.py +++ b/assistant/manager/__init__.py @@ -1,11 +1,19 @@ # Ultroid - UserBot -# Copyright (C) 2021-2026 TeamUltroid +# Copyright (C) 2021-2023 TeamUltroid # # This file is a part of < https://github.com/TeamUltroid/Ultroid/ > # PLease read the GNU Affero General Public License in # . +"""Group-manager plugin namespace. + +The manager modules intentionally import this namespace with ``from . import +*``. Re-export the assistant runtime names exactly as before, and make that +existing public surface explicit for loader and static-audit tooling. +""" + from pyUltroid._misc._decorators import ultroid_cmd -from pyUltroid.fns.helper import inline_mention from .. import * + +__all__ = tuple(name for name in globals() if not name.startswith("_")) diff --git a/assistant/manager/_help.py b/assistant/manager/_help.py index caf0701822cec6f2a8322d966afb022f9d998c30..d3ec21958e914c9ff8600a4a10751792e83ee666 100644 --- a/assistant/manager/_help.py +++ b/assistant/manager/_help.py @@ -1,134 +1,222 @@ # Ultroid - UserBot -# Copyright (C) 2021-2026 TeamUltroid +# Copyright (C) 2021-2023 TeamUltroid # # This file is a part of < https://github.com/TeamUltroid/Ultroid/ > # PLease read the GNU Affero General Public License in # . -from . import * - -START = """ -🪅 **Help Menu** 🪅 - -✘ /start : Check I am Alive or not. -✘ /help : Get This Message. -✘ /repo : Get Bot's Repo.. - -🧑‍💻 Join **@TeamUltroid** -""" - -ADMINTOOLS = """✘ **AdminTools** ✘ - -• /pin : Pins the Replied Message -• /pinned : Get Pinned message in chat. -• /unpin : Unpin the Replied message -• /unpin all : Unpin all Pinned Messages. - -• /ban (username/id/reply) : Ban the User -• /unban (username/id/reply) : UnBan the User. - -• /mute (username/id/reply) : Mute the User. -• /unmute (username/id/reply) : Unmute the User. - -• /tban (username/id/reply) (time) : Temporary ban a user -• /tmute (username/id/reply) (time) : temporary Mutes a User. - -• /purge (purge messages) - -• /setgpic (reply photo) : keep Chat Photo of Group. -• /delgpic : remove current chat Photo.""" - -UTILITIES = """ -✘ ** Utilities ** ✘ - -• /info (reply/username/id) : get detailed info of user. -• /id : get chat/user id. -• /tr : Translate Languages.. -• /q : Create Quotes. - -• /paste (reply file/text) : paste content on Spaceb.in -• /meaning (text) : Get Meaning of that Word. -• /google (query) : Search Something on Google.. +"""Assistant help menu for group administration and utility commands.""" -• /suggest (query/reply) : Creates a Yes / No Poll. -""" - -LOCKS = """ -✘ ** Locks ** ✘ - -• /lock (query) : lock particular content in chat. -• /unlock (query) : Unlock some content. - -• All Queries -- `msgs` : for messages. -- `inlines` : for inline queries. -- `media` : for all medias. -- `games` : for games. -- `sticker` : for stickers. -- `polls` : for polls. -- `gif` : for gifs. -- `pin` : for pins. -- `changeinfo` : for change info right. -""" - -MISC = """ -✘ **Misc** ✘ - -• /joke : Get Random Jokes. -• /decide : Decide Something.. - -**✘ Stickertools ✘** -• /kang : add sticker to your pack. -• /listpack : get all of yours pack.. -""" - -STRINGS = {"Admintools": ADMINTOOLS, "locks": LOCKS, "Utils": UTILITIES, "Misc": MISC} - -MNGE = udB.get_key("MNGR_EMOJI") or "•" +from . import * +from .._cbs import cb, cb_exact_pattern, cb_pattern +from ..rich_pages import edit_callback_page, rich_page +from pyUltroid._core.richmsg import send_rich + +HELP_SECTIONS = { + "Admintools": [ + ("/pin ", "Pin the replied-to message."), + ("/pinned", "Show the current pinned message."), + ("/unpin ", "Unpin the replied-to message."), + ("/unpin all", "Remove all pinned messages."), + ("/ban [reason]", "Ban a user by reply, ID, or username."), + ("/unban ", "Unban a user."), + ("/mute ", "Mute a user."), + ("/unmute ", "Unmute a user."), + ("/tban