github-actions[bot] commited on
Commit
c0e9d84
·
1 Parent(s): 33e38a7

Automated sync from GitHub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.dockerignore ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # SarahUB — Docker build context exclusions
3
+ # Everything listed here is omitted from the image build context, which keeps
4
+ # the image small and — critically — keeps secrets and local runtime state out
5
+ # of the built layers.
6
+ # =============================================================================
7
+
8
+ # ---- Secrets / local runtime state (MUST never be baked into an image) ----
9
+ .env
10
+ .env.*
11
+ !.env.sample
12
+ *.session
13
+ *.session-journal
14
+ asst.session
15
+ *.localdb.json
16
+ ultroid.json
17
+ ultroid.localdb.json
18
+
19
+ # ---- Version control ----
20
+ .git
21
+ .gitignore
22
+ .github
23
+
24
+ # ---- Python ----
25
+ .venv/
26
+ venv/
27
+ **/__pycache__/
28
+ *.py[cod]
29
+ *.egg-info/
30
+ .pytest_cache/
31
+ .mypy_cache/
32
+ build/
33
+ dist/
34
+
35
+ # ---- Node ----
36
+ node_modules/
37
+
38
+ # ---- Logs, caches, and generated artifacts ----
39
+ *.log
40
+ vc.log
41
+ *.tar.xz
42
+ *.tar.xz.md5
43
+
44
+ # ---- Tests (not needed at runtime) ----
45
+ tests/
.env.sample DELETED
@@ -1,13 +0,0 @@
1
- # Don't use quotes( " and ' )
2
-
3
- API_ID=
4
- API_HASH=
5
- SESSION=
6
-
7
-
8
- # [OPTIONAL]
9
-
10
- REDIS_URI=
11
- REDIS_PASSWORD=
12
- LOG_CHANNEL=
13
- BOT_TOKEN=
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore CHANGED
@@ -1,47 +1,42 @@
1
- .env
2
- *.session-journal
3
  *.session
4
- build
5
- test*
6
- *.mp3
7
- *.webm
8
- *.webp
9
- *.mp4
10
- *.tgs
11
- *.txt
12
- /*.jpg
13
- /*.png
14
- /*.mp4
15
- *.log
16
- target/npmlist.json
17
- package-lock.json
18
- ultroid.json
19
- resources/extras/thumbnail.jpg
20
- resources/auth/
21
 
22
- # Directories
23
- addons/
24
- vcbot/
 
 
 
 
 
 
25
  __pycache__/
26
- venv/
 
 
 
 
27
  node_modules/
28
- glitch_me/
29
- src/glitch-me
30
- .idea/
 
31
  .vscode/
32
- temp/
33
- bin-debug/
34
- bin-release/
35
- [Oo]bj/
36
- [Bb]in/
37
- .settings/
38
- *.swf
39
- *.air
40
- *.ipa
41
- *.apk
42
 
43
- # temporary files
44
- *.raw
 
 
 
 
 
 
 
45
 
46
- # fly.io configs
47
- fly.toml
 
 
 
1
+ # Session files
 
2
  *.session
3
+ *.session-journal
4
+ asst.session
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ # Environment files
7
+ .env
8
+ .venv
9
+ venv
10
+ env/
11
+ .env.*
12
+ !.env.sample
13
+
14
+ # Python caches
15
  __pycache__/
16
+ *.pyc
17
+ *.pyo
18
+ *.pyd
19
+
20
+ # Node/JavaScript dependencies
21
  node_modules/
22
+ dist/
23
+ build/
24
+
25
+ # IDE files
26
  .vscode/
27
+ .idea/
 
 
 
 
 
 
 
 
 
28
 
29
+ # Local cache/temporary files
30
+ .cache/
31
+ *.log
32
+ ultroid.json
33
+ ultroid.localdb.json
34
+ resources/error_cards/
35
+ addons/
36
+ mehrama.mp3
37
+ pr-body-phase0-3.md
38
 
39
+ # local agent/runtime artifacts
40
+ opencode.jsonc
41
+ env.txt
42
+ .codegraph/
CODE_OF_CONDUCT.md DELETED
@@ -1,128 +0,0 @@
1
- # Contributor Covenant Code of Conduct
2
-
3
- ## Our Pledge
4
-
5
- We as members, contributors, and leaders pledge to make participation in our
6
- community a harassment-free experience for everyone, regardless of age, body
7
- size, visible or invisible disability, ethnicity, sex characteristics, gender
8
- identity and expression, level of experience, education, socio-economic status,
9
- nationality, personal appearance, race, religion, or sexual identity
10
- and orientation.
11
-
12
- We pledge to act and interact in ways that contribute to an open, welcoming,
13
- diverse, inclusive, and healthy community.
14
-
15
- ## Our Standards
16
-
17
- Examples of behavior that contributes to a positive environment for our
18
- community include:
19
-
20
- * Demonstrating empathy and kindness toward other people
21
- * Being respectful of differing opinions, viewpoints, and experiences
22
- * Giving and gracefully accepting constructive feedback
23
- * Accepting responsibility and apologizing to those affected by our mistakes,
24
- and learning from the experience
25
- * Focusing on what is best not just for us as individuals, but for the
26
- overall community
27
-
28
- Examples of unacceptable behavior include:
29
-
30
- * The use of sexualized language or imagery, and sexual attention or
31
- advances of any kind
32
- * Trolling, insulting or derogatory comments, and personal or political attacks
33
- * Public or private harassment
34
- * Publishing others' private information, such as a physical or email
35
- address, without their explicit permission
36
- * Other conduct which could reasonably be considered inappropriate in a
37
- professional setting
38
-
39
- ## Enforcement Responsibilities
40
-
41
- Community leaders are responsible for clarifying and enforcing our standards of
42
- acceptable behavior and will take appropriate and fair corrective action in
43
- response to any behavior that they deem inappropriate, threatening, offensive,
44
- or harmful.
45
-
46
- Community leaders have the right and responsibility to remove, edit, or reject
47
- comments, commits, code, wiki edits, issues, and other contributions that are
48
- not aligned to this Code of Conduct, and will communicate reasons for moderation
49
- decisions when appropriate.
50
-
51
- ## Scope
52
-
53
- This Code of Conduct applies within all community spaces, and also applies when
54
- an individual is officially representing the community in public spaces.
55
- Examples of representing our community include using an official e-mail address,
56
- posting via an official social media account, or acting as an appointed
57
- representative at an online or offline event.
58
-
59
- ## Enforcement
60
-
61
- Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
- reported to the community leaders responsible for enforcement at
63
- teamultroid@ultroid.tech.
64
- All complaints will be reviewed and investigated promptly and fairly.
65
-
66
- All community leaders are obligated to respect the privacy and security of the
67
- reporter of any incident.
68
-
69
- ## Enforcement Guidelines
70
-
71
- Community leaders will follow these Community Impact Guidelines in determining
72
- the consequences for any action they deem in violation of this Code of Conduct:
73
-
74
- ### 1. Correction
75
-
76
- **Community Impact**: Use of inappropriate language or other behavior deemed
77
- unprofessional or unwelcome in the community.
78
-
79
- **Consequence**: A private, written warning from community leaders, providing
80
- clarity around the nature of the violation and an explanation of why the
81
- behavior was inappropriate. A public apology may be requested.
82
-
83
- ### 2. Warning
84
-
85
- **Community Impact**: A violation through a single incident or series
86
- of actions.
87
-
88
- **Consequence**: A warning with consequences for continued behavior. No
89
- interaction with the people involved, including unsolicited interaction with
90
- those enforcing the Code of Conduct, for a specified period of time. This
91
- includes avoiding interactions in community spaces as well as external channels
92
- like social media. Violating these terms may lead to a temporary or
93
- permanent ban.
94
-
95
- ### 3. Temporary Ban
96
-
97
- **Community Impact**: A serious violation of community standards, including
98
- sustained inappropriate behavior.
99
-
100
- **Consequence**: A temporary ban from any sort of interaction or public
101
- communication with the community for a specified period of time. No public or
102
- private interaction with the people involved, including unsolicited interaction
103
- with those enforcing the Code of Conduct, is allowed during this period.
104
- Violating these terms may lead to a permanent ban.
105
-
106
- ### 4. Permanent Ban
107
-
108
- **Community Impact**: Demonstrating a pattern of violation of community
109
- standards, including sustained inappropriate behavior, harassment of an
110
- individual, or aggression toward or disparagement of classes of individuals.
111
-
112
- **Consequence**: A permanent ban from any sort of public interaction within
113
- the community.
114
-
115
- ## Attribution
116
-
117
- This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
- version 2.0, available at
119
- https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120
-
121
- Community Impact Guidelines were inspired by [Mozilla's code of conduct
122
- enforcement ladder](https://github.com/mozilla/diversity).
123
-
124
- [homepage]: https://www.contributor-covenant.org
125
-
126
- For answers to common questions about this code of conduct, see the FAQ at
127
- https://www.contributor-covenant.org/faq. Translations are available at
128
- https://www.contributor-covenant.org/translations.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
CONTRIBUTING.md DELETED
@@ -1,23 +0,0 @@
1
- # Welcome To Contributing Guide
2
- Any contribution done to this repository will be appreciated! 🎉
3
-
4
- ### About Ultroid
5
- - **Ultroid** is Telegram Userbot, which allow you to perform many task easily.
6
- - It's base core is a pip package named [`pyUltroid`](https://GitHub.com/TeamUltroid/pyUltroid).
7
- - This repository, contains Ultroid's official plugin files.
8
- - moreover, Ultroid User also have an option to get more plugins available at [`UltroidAddons`](https://github.com/TeamUltroid/UltroidAddons)
9
-
10
- ### Issues
11
- - Search for existing Similar issues.
12
- - You can open a issue first before contributing, If it contain some major changes like `bug fixes` or `feature addition`.
13
- - If you are busy or getting trouble while making changes, you can just open the issue (explaining it).
14
-
15
- ### Contributing
16
- - You can [fork](https://github.com/TeamUltroid/Ultroid/fork) this repository.
17
- - You can commits your changes now.
18
- - You can [Git-Squash](https://docs.github.com/en/get-started/using-git/about-git-rebase) your commits, if they are more. [Optional]
19
- - 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).
20
- - Make sure that, your `Pull Request` contain an explaining title and issue number if it closes any open issue.
21
-
22
- ### Thanks
23
- - Congrats! 💫 you have successfully made your Contribution to Ultroid.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dockerfile CHANGED
@@ -1,20 +1,187 @@
1
- # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
- # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
4
- # PLease read the GNU Affero General Public License in <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
5
 
6
- FROM theteamultroid/ultroid:main
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- # set timezone
9
- ENV TZ=Asia/Kolkata
10
- RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
11
 
12
- COPY installer.sh .
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- RUN bash installer.sh
 
 
 
 
 
 
 
15
 
16
- # changing workdir
17
- WORKDIR "/root/TeamUltroid"
18
 
19
- # start the bot with a dummy web server in the background to satisfy Hugging Face
20
- CMD ["bash", "-c", "python3 -m http.server 7860 & bash startup"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
 
 
 
2
 
3
+ # =============================================================================
4
+ # SarahUB — container image (CUDA / GPU variant)
5
+ # =============================================================================
6
+ # Build tunables are declared as ARGs below so they can be overridden at
7
+ # build time without editing this file.
8
+ #
9
+ # Secrets/env vars are consumed at BUILD time. Easiest way: export them in
10
+ # your shell, then pass the ARG by name with no value (Docker forwards the
11
+ # matching shell env var automatically):
12
+ #
13
+ # export GIT_TOKEN=<PAT>
14
+ # docker build --build-arg TZ=Europe/London \
15
+ # --build-arg GIT_TOKEN --build-arg PYTHON_VERSION=3.11 .
16
+ #
17
+ # Or pass the value inline:
18
+ # docker build --build-arg GIT_TOKEN="$GIT_TOKEN" .
19
+ # =============================================================================
20
 
21
+ # Base image is the only tunable the FROM instruction itself needs.
22
+ ARG BASE_IMAGE=nvidia/cuda:12.5.1-cudnn-devel-ubuntu22.04
23
+ FROM ${BASE_IMAGE}
24
 
25
+ # -----------------------------------------------------------------------------
26
+ # Build-time tunables (defaults mirror the original hardcoded values)
27
+ # -----------------------------------------------------------------------------
28
+ ARG TZ=Asia/Kolkata
29
+ ARG APP_USER=sarah
30
+ ARG APP_HOME=/sarah
31
+ ARG MINICONDA_DIR=${APP_HOME}/miniconda
32
+ ARG CONDA_ENV=py311
33
+ ARG PYTHON_VERSION=3.11
34
+ ARG NODE_URL=https://deb.nodesource.com/setup_current.x
35
+ ARG MINIFORGE_URL=https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-x86_64.sh
36
+ ARG REPO_OWNER=Mahesh953-hub
37
+ ARG REPO_NAME=SarahUB
38
+ ARG REPO_BRANCH=main
39
+ ARG GIT_TOKEN
40
+ ARG EXPOSE_PORT=7860
41
 
42
+ # -----------------------------------------------------------------------------
43
+ # Environment
44
+ # -----------------------------------------------------------------------------
45
+ ENV DEBIAN_FRONTEND=noninteractive \
46
+ TZ=${TZ} \
47
+ CONDA_AUTO_UPDATE_CONDA=false \
48
+ PYTHONUNBUFFERED=1 \
49
+ GIT_TOKEN=${GIT_TOKEN}
50
 
51
+ RUN export TZ=${TZ}
 
52
 
53
+ # -----------------------------------------------------------------------------
54
+ # System dependencies
55
+ # -----------------------------------------------------------------------------
56
+ RUN apt-get update \
57
+ && apt-get install -y --no-install-recommends \
58
+ curl \
59
+ ca-certificates \
60
+ sudo \
61
+ git \
62
+ wget \
63
+ zip \
64
+ unzip \
65
+ neofetch \
66
+ gnupg2 \
67
+ libnss3 \
68
+ libx11-xcb1 \
69
+ libxcursor1 \
70
+ libxi6 \
71
+ libgtk-3-0 \
72
+ libnspr4 \
73
+ libdbus-1-3 \
74
+ libatk1.0-0 \
75
+ libatk-bridge2.0-0 \
76
+ libgl1-mesa-glx \
77
+ libcups2 \
78
+ libdrm2 \
79
+ libxkbcommon0 \
80
+ libatspi2.0-0 \
81
+ libxcomposite1 \
82
+ libxdamage1 \
83
+ libxfixes3 \
84
+ libxrandr2 \
85
+ libgbm1 \
86
+ libasound2 \
87
+ gosu \
88
+ p7zip-full \
89
+ mediainfo \
90
+ procps \
91
+ htop \
92
+ vim \
93
+ nano \
94
+ bzip2 \
95
+ build-essential \
96
+ libsndfile-dev \
97
+ software-properties-common \
98
+ && rm -rf /var/lib/apt/lists/*
99
+
100
+ # -----------------------------------------------------------------------------
101
+ # Node.js — builds the web setup server's frontend
102
+ # -----------------------------------------------------------------------------
103
+ RUN curl -fsSL ${NODE_URL} | bash - \
104
+ && apt-get install -y nodejs
105
+
106
+ # -----------------------------------------------------------------------------
107
+ # Non-root runtime user
108
+ # -----------------------------------------------------------------------------
109
+ RUN useradd -m -s /bin/bash ${APP_USER} \
110
+ && echo "${APP_USER} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/90-${APP_USER}
111
+
112
+ USER ${APP_USER}
113
+ ENV HOME=${APP_HOME}
114
+ WORKDIR ${APP_HOME}
115
+
116
+ # -----------------------------------------------------------------------------
117
+ # Miniforge (conda + mamba, conda-forge) + Python environment
118
+ # -----------------------------------------------------------------------------
119
+ ENV PATH=${MINICONDA_DIR}/bin:$PATH
120
+
121
+ RUN curl -sL -o ${APP_HOME}/miniforge.sh ${MINIFORGE_URL} \
122
+ && bash ${APP_HOME}/miniforge.sh -b -p ${MINICONDA_DIR} \
123
+ && rm ${APP_HOME}/miniforge.sh \
124
+ && ${MINICONDA_DIR}/bin/mamba create -y -n ${CONDA_ENV} python=${PYTHON_VERSION} \
125
+ && ${MINICONDA_DIR}/bin/mamba clean -afy
126
+
127
+ ENV PATH=${MINICONDA_DIR}/envs/${CONDA_ENV}/bin:${MINICONDA_DIR}/bin:$PATH
128
+
129
+ # -----------------------------------------------------------------------------
130
+ # Application source — cloned so the container keeps `.git` and start.sh's
131
+ # `git pull` can keep the deployment updatable. `GIT_TOKEN` is only injected
132
+ # when provided (e.g. for a private fork): `--build-arg GIT_TOKEN=<PAT>`.
133
+ # -----------------------------------------------------------------------------
134
+ RUN echo "Better logs#2"
135
+
136
+ RUN if [ -n "${GIT_TOKEN}" ]; then \
137
+ GIT_URL="https://${GIT_TOKEN}@github.com/${REPO_OWNER}/${REPO_NAME}.git"; \
138
+ else \
139
+ GIT_URL="https://github.com/${REPO_OWNER}/${REPO_NAME}.git"; \
140
+ fi \
141
+ && git clone --branch "${REPO_BRANCH}" --single-branch "${GIT_URL}" "${APP_HOME}/${REPO_NAME}"
142
+
143
+ WORKDIR ${APP_HOME}/${REPO_NAME}
144
+
145
+ RUN ls -all && git pull
146
+
147
+ RUN chown -R ${APP_USER}:${APP_USER} ${APP_HOME}
148
+
149
+ # -----------------------------------------------------------------------------
150
+ # Python dependencies
151
+ # `res*/st*/op*` expands to `resources/startup/optional-requirements.txt`.
152
+ # -----------------------------------------------------------------------------
153
+ RUN echo "I want rebuild!!!!"
154
+
155
+ # Core deps MUST succeed. The database drivers are pinned explicitly so a
156
+ # midway `requirements.txt` failure can no longer fall through the old `|| true`
157
+ # and ship an image whose Redis/Mongo/SQL clients are silently missing (that
158
+ # made the app fall back to LocalDB even when MONGO_URI was set). With this
159
+ # split, a broken core install fails the build instead.
160
+ RUN pip install --no-cache-dir -U pip \
161
+ && pip install --no-cache-dir requests dnspython redis pymongo psycopg2-binary \
162
+ && pip install --no-cache-dir fastapi uvicorn nest-asyncio \
163
+ && pip install --no-cache-dir -r requirements.txt
164
+
165
+ # Optional extras for local deploys (git deps + heavy native builds) can fail
166
+ # without breaking the bot, so THIS line alone is allowed to fail.
167
+ RUN pip install --no-cache-dir -r res*/st*/op* || true
168
+
169
+ # -----------------------------------------------------------------------------
170
+ # FFmpeg — pulled from a prebuilt static image (needs root to write /usr/local)
171
+ # -----------------------------------------------------------------------------
172
+ USER root
173
+ COPY --from=mwader/static-ffmpeg:latest /ffmpeg /ffprobe /usr/local/bin/
174
+
175
+ # -----------------------------------------------------------------------------
176
+ # Permissions + final runtime user
177
+ # -----------------------------------------------------------------------------
178
+ USER ${APP_USER}
179
+ RUN chmod -R 755 ${APP_HOME} \
180
+ && chmod +x ${APP_HOME}/${REPO_NAME}/start.sh
181
+
182
+ USER ${APP_USER}
183
+ WORKDIR ${APP_HOME}/${REPO_NAME}
184
+
185
+ EXPOSE ${EXPOSE_PORT}
186
+
187
+ CMD ["./start.sh"]
akipy/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 advnpzn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
akipy/VENDORING.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Vendored Akinator wrapper
2
+
3
+ This package is the `akipy` 0.1.2 source from <https://github.com/ufoptg/akipy>
4
+ (commit `2af0027d05ef32a89aa6dede27a7bde4d8c4ad0e`), retained here to keep
5
+ SarahUB's asynchronous Akinator feature intact without installing its stale
6
+ `httpx>=0.25,<0.26` distribution requirement. The upstream wrapper uses only
7
+ ordinary `httpx` client APIs; SarahUB declares the shared `httpx>=0.28.1`
8
+ dependency required by Gemini and tests the async game/transport path against
9
+ that client version.
10
+
11
+ The upstream MIT license and copyright notice are in `LICENSE`.
akipy/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ akipy - A Python wrapper library for Akinator
3
+
4
+ :copyright: (c) 2024, advnpzn
5
+ :license: MIT, see LICENSE for more details.
6
+ """
7
+
8
+ from .akinator import Akinator
9
+ from .exceptions import *
akipy/akinator.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MIT License
3
+
4
+ Copyright (c) 2024 advnpzn
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+
24
+ """
25
+ import json
26
+ import re
27
+ import httpx
28
+
29
+ from .dicts import HEADERS, THEME_ID, THEMES, LANG_MAP
30
+ from .exceptions import InvalidLanguageError, CantGoBackAnyFurther
31
+ from .utils import get_answer_id, request_handler
32
+
33
+
34
+ class Akinator:
35
+ """
36
+ The Akinator Class represents the Akinator Game.
37
+ You need to create an instance of this class to get started.
38
+ """
39
+
40
+ def __init__(self):
41
+ self.photo = None
42
+ self.pseudo = None
43
+ self.uri = None
44
+ self.theme = None
45
+ self.session = None
46
+ self.signature = None
47
+ self.child_mode = False
48
+ self.lang = None
49
+ self.available_themes = None
50
+ self.theme = None
51
+
52
+ self.question = None
53
+ self.progression = None
54
+ self.step = None
55
+ self.akitude = None
56
+ self.step_last_proposition = ""
57
+
58
+ self.win = False
59
+ self.name_proposition = None
60
+ self.description_proposition = None
61
+ self.completion = None
62
+
63
+ def start_game(self, language: str = "en", child_mode: bool = False):
64
+ """
65
+ Start the Akinator game with specified language and child mode.
66
+ :param language: Language code or name
67
+ :param child_mode: Whether to enable child mode
68
+ :return: None
69
+ """
70
+ self.__get_region(lang=language)
71
+ self.__initialise()
72
+
73
+ def answer(self, option):
74
+ url = f"{self.uri}/answer"
75
+ data = {
76
+ "step": self.step,
77
+ "progression": self.progression,
78
+ "sid": self.theme,
79
+ "cm": str(self.child_mode).lower(),
80
+ "answer": get_answer_id(option),
81
+ "step_last_proposition": self.step_last_proposition,
82
+ "session": self.session,
83
+ "signature": self.signature,
84
+ }
85
+
86
+ try:
87
+ req = request_handler(url=url, method='POST', data=data)
88
+ resp = req.json()
89
+
90
+ if "id_proposition" in resp:
91
+ self.__update(action="win", resp=resp)
92
+ else:
93
+ self.__update(action="answer", resp=resp)
94
+ self.completion = resp.get('completion')
95
+ except Exception as e:
96
+ raise e
97
+
98
+ def back(self):
99
+ if self.step == 1:
100
+ raise CantGoBackAnyFurther("Cannot go back further.")
101
+ else:
102
+ url = f"{self.uri}/cancel_answer"
103
+ data = {
104
+ "step": self.step,
105
+ "progression": self.progression,
106
+ "sid": self.theme,
107
+ "cm": str(self.child_mode).lower(),
108
+ "session": self.session,
109
+ "signature": self.signature,
110
+ }
111
+
112
+ try:
113
+ req = request_handler(url=url, method='POST', data=data)
114
+ resp = req.json()
115
+ self.__update(action="back", resp=resp)
116
+ except Exception as e:
117
+ raise e
118
+
119
+ def __update(self, action: str, resp):
120
+ if action in ["answer", "back"]:
121
+ self.akitude = resp.get('akitude')
122
+ self.step = resp.get('step')
123
+ self.progression = resp.get('progression')
124
+ self.question = resp.get('question')
125
+ elif action == "win":
126
+ self.win = True
127
+ self.name_proposition = resp.get('name_proposition')
128
+ self.description_proposition = resp.get('description_proposition')
129
+ self.pseudo = resp.get('pseudo')
130
+ self.photo = resp.get('photo')
131
+
132
+ def __get_region(self, lang):
133
+ try:
134
+ lang = LANG_MAP.get(lang, lang) # Get mapped language if available
135
+ if len(lang) > 2 and lang not in LANG_MAP.values():
136
+ raise InvalidLanguageError(lang)
137
+ except Exception:
138
+ raise InvalidLanguageError(lang)
139
+
140
+ url = f"https://{lang}.akinator.com"
141
+ try:
142
+ req = request_handler(url=url, method='GET')
143
+ if req.status_code != 200:
144
+ raise httpx.HTTPStatusError(f"HTTP status error: {req.status_code}")
145
+ self.uri = url
146
+ self.lang = lang
147
+ self.available_themes = THEMES.get(lang, [])
148
+ self.theme = THEME_ID.get(self.available_themes[0])
149
+ except Exception as e:
150
+ raise e
151
+
152
+ def __initialise(self):
153
+ url = f"{self.uri}/game"
154
+ data = {
155
+ "sid": self.theme,
156
+ "cm": str(self.child_mode).lower()
157
+ }
158
+ try:
159
+ req = request_handler(url=url, method='POST', data=data).text
160
+ match = re.findall(r"[a-zA-Z0-9+/]+==", req)
161
+
162
+ if len(match) >= 2:
163
+ self.session = match[0]
164
+ self.signature = match[1]
165
+
166
+ match = re.search(r'<div class="bubble-body"><p class="question-text" id="question-label">(.*?)</p></div>', req)
167
+ self.question = match.group(1) if match else None
168
+ self.progression = "0.00000"
169
+ self.step = 0
170
+ except Exception as e:
171
+ raise httpx.HTTPStatusError(f"Failed to initialise: {e}")
akipy/async_akipy/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """
2
+ akipy - A Python wrapper library for Akinator
3
+
4
+ :copyright: (c) 2024, advnpzn
5
+ :license: MIT, see LICENSE for more details.
6
+ """
7
+
8
+ from .async_akinator import Akinator, akipyLOGS
akipy/async_akipy/async_akinator.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MIT License
3
+
4
+ Copyright (c) 2024 advnpzn
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+
24
+ """
25
+ import json
26
+ import re
27
+ import asyncio
28
+ import logging
29
+
30
+ try:
31
+ import httpx
32
+ except ImportError:
33
+ raise ImportError('httpx is not installed')
34
+
35
+ from ..dicts import HEADERS, THEME_ID, THEMES, LANG_MAP
36
+ from ..exceptions import InvalidLanguageError, CantGoBackAnyFurther
37
+ from ..utils import get_answer_id, async_request_handler
38
+
39
+ akipyLOGS = logging.getLogger("Aᴋɪɴᴀᴛᴏʀ")
40
+
41
+ class Akinator:
42
+ """
43
+ The ``Akinator`` Class represents the Akinator Game.
44
+ You need to create an Instance of this Class to get started.
45
+ """
46
+
47
+ def __init__(self):
48
+ self.photo = None
49
+ self.pseudo = None
50
+ self.uri = None
51
+ self.theme = None
52
+ self.session = None
53
+ self.signature = None
54
+ self.identifiant = None
55
+ self.child_mode = False
56
+ self.lang = None
57
+ self.available_themes = None
58
+
59
+ self.question = None
60
+ self.progression = None
61
+ self.step = None
62
+ self.akitude = None
63
+ self.step_last_proposition = ""
64
+
65
+ self.win = False
66
+ self.name_proposition = None
67
+ self.description_proposition = None
68
+ self.completion = None
69
+
70
+ async def __update(self, action: str, resp):
71
+ if action == "answer":
72
+ self.akitude = resp.get('akitude')
73
+ self.step = resp.get('step')
74
+ self.progression = resp.get('progression')
75
+ self.question = resp.get('question')
76
+ elif action == "back":
77
+ self.akitude = resp.get('akitude')
78
+ self.step = resp.get('step')
79
+ self.progression = resp.get('progression')
80
+ self.question = resp.get('question')
81
+ elif action == "win":
82
+ self.win = True
83
+ self.name_proposition = resp.get('name_proposition')
84
+ self.description_proposition = resp.get('description_proposition')
85
+ self.pseudo = resp.get('pseudo')
86
+ self.photo = resp.get('photo')
87
+
88
+ async def __get_region(self, lang):
89
+ try:
90
+ if len(lang) > 2:
91
+ lang = LANG_MAP.get(lang)
92
+ else:
93
+ assert lang in LANG_MAP.values(), "Invalid language code"
94
+ except AssertionError as e:
95
+ raise InvalidLanguageError(lang) from e
96
+ url = f"https://{lang}.akinator.com"
97
+ try:
98
+ req = await async_request_handler(url=url, method='GET')
99
+ req.raise_for_status()
100
+ self.uri = url
101
+ self.lang = lang
102
+
103
+ self.available_themes = THEMES.get(lang)
104
+ self.theme = THEME_ID.get(self.available_themes[0])
105
+ except httpx.HTTPStatusError as e:
106
+ raise httpx.HTTPStatusError(f"HTTP error occurred: {e}") from e
107
+ except Exception as e:
108
+ raise Exception(f"An error occurred while getting region: {e}") from e
109
+
110
+ async def __initialise(self):
111
+ url = f"{self.uri}/game"
112
+ data = {
113
+ "sid": self.theme,
114
+ "cm": str(self.child_mode).lower()
115
+ }
116
+ try:
117
+ req = await async_request_handler(url=url, method='POST', data=data)
118
+ req.raise_for_status()
119
+ match = re.findall(r"[a-zA-Z0-9+/]+==", req.text)[-2:]
120
+
121
+ self.session = match[0]
122
+ self.signature = match[1]
123
+
124
+ # Extract identifiant
125
+ identifiant_match = re.search(r'\$\(\'#identifiant\'\)\.val\([\'"](.*?)[\'"]\);', req.text)
126
+ self.identifiant = identifiant_match.group(1) if identifiant_match else None
127
+
128
+ match = re.search(r'<div class="bubble-body"><p class="question-text" id="question-label">(.*?)</p></div>', req.text)
129
+ if match:
130
+ self.question = match.group(1)
131
+ self.progression = "0.00000"
132
+ self.step = 0
133
+ except httpx.HTTPStatusError as e:
134
+ raise httpx.HTTPStatusError(f"HTTP error occurred: {e}") from e
135
+ except Exception as e:
136
+ raise Exception(f"An error occurred while initializing: {e}") from e
137
+
138
+ async def start_game(self, language: str = "en", child_mode: bool = False):
139
+ """
140
+ This method is responsible for actually starting the game scene.
141
+ You can pass the following parameters to set your language preference and as well as the Child Mode.
142
+ If language is not set, English is used by default. Child Mode is set to ``False`` by default.
143
+ :param language: "en"
144
+ :param child_mode: False
145
+ :return: None
146
+ """
147
+ await self.__get_region(lang=language)
148
+ await self.__initialise()
149
+
150
+ async def answer(self, option):
151
+ url = f"{self.uri}/answer"
152
+ data = {
153
+ "step": self.step,
154
+ "progression": self.progression,
155
+ "sid": self.theme,
156
+ "cm": str(self.child_mode).lower(),
157
+ "answer": get_answer_id(option),
158
+ "step_last_proposition": self.step_last_proposition,
159
+ "session": self.session,
160
+ "signature": self.signature,
161
+ "identifiant": self.identifiant,
162
+ }
163
+
164
+ try:
165
+ req = await async_request_handler(url=url, method='POST', data=data)
166
+ req.raise_for_status()
167
+ resp = req.json()
168
+ #akipyLOGS.info(f"API Response: {resp}")
169
+
170
+ if "id_proposition" in resp:
171
+ await self.__update(action="win", resp=resp)
172
+ else:
173
+ await self.__update(action="answer", resp=resp)
174
+
175
+ akipyLOGS.info(f"Updated question: {self.question}")
176
+ self.completion = resp.get('completion')
177
+ except httpx.HTTPStatusError as e:
178
+ raise httpx.HTTPStatusError(f"HTTP error occurred: {e}") from e
179
+ except Exception as e:
180
+ raise Exception(f"An error occurred while answering: {e}") from e
181
+
182
+ async def back(self):
183
+ if self.step == 1:
184
+ raise CantGoBackAnyFurther
185
+ else:
186
+ url = f"{self.uri}/cancel_answer"
187
+ data = {
188
+ "step": self.step,
189
+ "progression": self.progression,
190
+ "sid": self.theme,
191
+ "cm": str(self.child_mode).lower(),
192
+ "session": self.session,
193
+ "signature": self.signature,
194
+ "identifiant": self.identifiant,
195
+ }
196
+
197
+ try:
198
+ req = await async_request_handler(url=url, method='POST', data=data)
199
+ req.raise_for_status()
200
+ resp = req.json()
201
+ await self.__update(action="back", resp=resp)
202
+ except httpx.HTTPStatusError as e:
203
+ raise httpx.HTTPStatusError(f"HTTP error occurred: {e}") from e
204
+ except Exception as e:
205
+ raise Exception(f"An error occurred while going back: {e}") from e
akipy/dicts.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ HEADERS = {
2
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
3
+ "Accept-Encoding": "gzip, deflate",
4
+ "Accept-Language": "en-US,en;q=0.9",
5
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/81.0.4044.92 "
6
+ "Chrome/81.0.4044.92 Safari/537.36",
7
+ "x-requested-with": "XMLHttpRequest",
8
+ }
9
+
10
+ LANG_MAP = {
11
+ "english": "en",
12
+ "arabic": "ar",
13
+ "chinese": "cn",
14
+ "german": "de",
15
+ "spanish": "es",
16
+ "french": "fr",
17
+ "hebrew": "il",
18
+ "italian": "it",
19
+ "japanese": "jp",
20
+ "korean": "kr",
21
+ "dutch": "nl",
22
+ "polish": "pl",
23
+ "portuguese": "pt",
24
+ "russian": "ru",
25
+ "turkish": "tr",
26
+ "indonesian": "id"
27
+ }
28
+
29
+ THEME_ID = {
30
+ "c": 1,
31
+ "a": 14,
32
+ "o": 2
33
+ }
34
+
35
+ """
36
+ c - characters
37
+ a - animals
38
+ o - objects
39
+ """
40
+
41
+ THEMES = {
42
+ "en": ["c", "a", "o"],
43
+ "ar": ["c"],
44
+ "cn": ["c"],
45
+ "de": ["c", "a"],
46
+ "es": ["c", "a"],
47
+ "fr": ["c", "a", "o"],
48
+ "il": ["c"],
49
+ "it": ["c", "a"],
50
+ "jp": ["c", "a"],
51
+ "kr": ["c"],
52
+ "nl": ["c"],
53
+ "pl": ["c"],
54
+ "pt": ["c"],
55
+ "ru": ["c"],
56
+ "tr": ["c"],
57
+ "id": ["c"],
58
+ }
59
+
60
+ ANSWERS = {
61
+ 0: ["yes", "y", '0'],
62
+ 1: ["no", "n", '1'],
63
+ 2: ["i", "idk", "i dont know", "i don't know", '2'],
64
+ 3: ["p", "probably", '3'],
65
+ 4: ["pn", "probably not", '4'],
66
+ }
67
+
akipy/exceptions.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ class InvalidLanguageError(ValueError):
2
+ """Raise when the user input language is invalid or not supported by Akinator"""
3
+ pass
4
+
5
+
6
+ class CantGoBackAnyFurther(Exception):
7
+ """Raises when the user is in the first question and tries to go back further"""
8
+ pass
akipy/utils.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Optional
2
+ import httpx
3
+
4
+ from .dicts import ANSWERS, HEADERS
5
+
6
+ def request_handler(url: str, method: str, data: Optional[dict] = None) -> httpx.Response:
7
+ if method == 'GET':
8
+ return httpx.get(url, headers=HEADERS, timeout=30.0)
9
+ elif method == 'POST':
10
+ return httpx.post(url, headers=HEADERS, data=data, timeout=30.0)
11
+ else:
12
+ raise ValueError(f"Unsupported HTTP method: {method}")
13
+
14
+ async def async_request_handler(url: str, method: str, data: Optional[dict] = None) -> httpx.Response:
15
+ async with httpx.AsyncClient() as client:
16
+ if method == 'GET':
17
+ return await client.get(url, headers=HEADERS, timeout=30.0)
18
+ elif method == 'POST':
19
+ return await client.post(url, headers=HEADERS, data=data, timeout=30.0)
20
+ else:
21
+ raise ValueError(f"Unsupported HTTP method: {method}")
22
+
23
+ def get_answer_id(ans):
24
+ for key, values in ANSWERS.items():
25
+ if ans.lower() in values:
26
+ return key
27
+ return None
app.json DELETED
@@ -1,56 +0,0 @@
1
- {
2
- "name": "Ultroid UserBot",
3
- "description": "Pluggable telegram userbot, made in python using Telethon.",
4
- "logo": "https://graph.org/file/031957757a4f6a5191040.jpg",
5
- "keywords": [
6
- "Telethon",
7
- "telegram",
8
- "userbot",
9
- "python",
10
- "ultroid"
11
- ],
12
- "repository": "https://github.com/TeamUltroid/Ultroid",
13
- "website": "https://ultroid.tech",
14
- "success_url": "https://t.me/TeamUltroid",
15
- "stack": "container",
16
- "env": {
17
- "API_ID": {
18
- "description": "You api id, from my.telegram.org or @ScrapperRoBot.",
19
- "value": "",
20
- "required": false
21
- },
22
- "API_HASH": {
23
- "description": "You api hash, from my.telegram.org or @ScrapperRoBot.",
24
- "value": "",
25
- "required": false
26
- },
27
- "SESSION": {
28
- "description": "Session String (telethon or pyrogram) for your telegram user account. The userbot will NOT work without a session string!!",
29
- "value": ""
30
- },
31
- "REDIS_URI": {
32
- "description": "Redis endpoint URL, from redislabs.com",
33
- "value": ""
34
- },
35
- "REDIS_PASSWORD": {
36
- "description": "Redis endpoint password, from redislabs.com",
37
- "value": ""
38
- },
39
- "HEROKU_API": {
40
- "description": "Heroku API token. Mandatory for Heroku Deploy...",
41
- "value": "",
42
- "required": false
43
- },
44
- "HEROKU_APP_NAME": {
45
- "description": "Name of your Heroku app, given in the first blank on this page. To be added if deploying to heroku ONLY.",
46
- "value": "",
47
- "required": false
48
- }
49
- },
50
- "formation": {
51
- "ultroid": {
52
- "quantity": 1,
53
- "size": "eco"
54
- }
55
- }
56
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
assistant/__init__.py CHANGED
@@ -1,21 +1,38 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
 
 
8
  from telethon import Button, custom
 
 
9
 
 
10
  from plugins import ATRA_COL, InlinePlugin
11
- from pyUltroid import *
12
- from pyUltroid import _ult_cache
13
  from pyUltroid._misc import owner_and_sudos
 
 
14
  from pyUltroid._misc._assistant import asst_cmd, callback, in_pattern
15
- from pyUltroid.fns.helper import *
16
- from pyUltroid.fns.tools import get_stored_file
 
 
17
  from strings import get_languages, get_string
 
18
 
 
 
 
 
 
 
 
 
19
  OWNER_NAME = ultroid_bot.full_name
20
  OWNER_ID = ultroid_bot.uid
21
 
@@ -27,8 +44,48 @@ async def setit(event, name, value):
27
  udB.set_key(name, value)
28
  except BaseException as er:
29
  LOGS.exception(er)
30
- return await event.edit("`Something Went Wrong`")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
 
33
- def get_back_button(name):
34
- return [Button.inline("« Bᴀᴄᴋ", data=f"{name}")]
 
 
 
 
 
 
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
+ import unicodedata
9
+
10
  from telethon import Button, custom
11
+ from telethon.errors.rpcerrorlist import ChatSendStickersForbiddenError
12
+ from telethon.utils import get_display_name
13
 
14
+ from custom.tg import ikm
15
  from plugins import ATRA_COL, InlinePlugin
16
+ from pyUltroid import HNDLR, LOGS, ULTConfig, asst, udB, ultroid_bot, _ult_cache
 
17
  from pyUltroid._misc import owner_and_sudos
18
+ from pyUltroid._misc._decorators import ultroid_cmd
19
+ from pyUltroid._misc._wrappers import eod
20
  from pyUltroid._misc._assistant import asst_cmd, callback, in_pattern
21
+ from pyUltroid.configs import Var
22
+ from pyUltroid.fns import fns
23
+ from pyUltroid.fns.tools import _webupload_cache
24
+ from pyUltroid.version import ultroid_version
25
  from strings import get_languages, get_string
26
+ from pyUltroid.dB import db as dbs
27
 
28
+ # The twelve submodules reach these through from . import *, so this module
29
+ # is the facade. Two rules keep that safe, and both are pinned by
30
+ # tests/test_assistant_facade.py:
31
+ # 1. nothing below imports a submodule of assistant - a package __init__
32
+ # always finishes before any submodule body runs, which is what makes
33
+ # the star import deterministic rather than lucky;
34
+ # 2. pyUltroid is reached by explicit import, never by star, so the
35
+ # names the facade re-exports are provable instead of accidental.
36
  OWNER_NAME = ultroid_bot.full_name
37
  OWNER_ID = ultroid_bot.uid
38
 
 
44
  udB.set_key(name, value)
45
  except BaseException as er:
46
  LOGS.exception(er)
47
+ return await event.edit("Something Went Wrong")
48
+
49
+
50
+ def _clean_nav_label(label):
51
+ out = []
52
+ for char in str(label or ""):
53
+ if ord(char) in {
54
+ 0x00AB,
55
+ 0x00BB,
56
+ 0x2039,
57
+ 0x203A,
58
+ 0x25C0,
59
+ 0x25B6,
60
+ 0x2190,
61
+ 0x2192,
62
+ 0x2022,
63
+ 0x00B7,
64
+ 0xFE0E,
65
+ 0xFE0F,
66
+ 0x200D,
67
+ 0x20E3,
68
+ }:
69
+ out.append(" ")
70
+ continue
71
+ try:
72
+ name = unicodedata.name(char)
73
+ except ValueError:
74
+ name = ""
75
+ if name.startswith("LATIN LETTER SMALL CAPITAL "):
76
+ out.append(name.rsplit(" ", 1)[-1].lower())
77
+ elif unicodedata.category(char) in {"So", "Sk"}:
78
+ out.append(" ")
79
+ else:
80
+ out.append(char)
81
+ return " ".join("".join(out).split())
82
 
83
 
84
+ def get_back_button(name, label="Back", style="primary"):
85
+ """Build a blue, glyph-free navigation row targeting name a destination's own
86
+ callback data (from assistant._cbs.cb, or a legacy bare token).
87
+ Reusing the destination's own data *is* the back-navigation mechanism:
88
+ the click is a real callback-query round trip dispatched straight to
89
+ that destination's handler (see assistant/_cbs.py).
90
+ """
91
+ return ikm([(_clean_nav_label(label), name, style)], icon=False)[0]
assistant/_cbs.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
+ #
4
+ # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
+ # PLease read the GNU Affero General Public License in
6
+ # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
+
8
+ """Structured callback-data model ("cbs") for assistant/.
9
+
10
+ Every inline button assistant/-side code sends carries callback data (or, for
11
+ @in_pattern results, an inline-query string) that some @callback /
12
+ @in_pattern handler must consume. Before this module, that data was a
13
+ grab-bag of ad-hoc prefixes (cbs_, abs_, aki_, hlp_, bare
14
+ atoms like "setter"...) with no single place documenting which handler
15
+ owns which prefix a classic "button times out, nobody knows why" trap: a
16
+ button emits data with no registered handler, or a handler's pattern has no
17
+ button that ever emits it.
18
+
19
+ This module gives every assistant/ callback datum one of three shapes:
20
+
21
+ 1. help:<plugin>:<data> the group-manager help menu
22
+ (assistant/manager/_help.py); paged button indexation.
23
+ 2. assistant:<name>:<tail> everything else living in assistant/
24
+ and assistant/manager/ (menus, convo flows, games, ytdl helpers,
25
+ standalone alert-and-return buttons all of it). <name> is the
26
+ owning module's short name (callbacks, games, lang, start,
27
+ ...); <tail> is that module's own sub-format (colon-joined further,
28
+ free-form, whatever the handler needs).
29
+ 3. **Standalones** call-and-cut buttons that only event.answer(...) an
30
+ alert or delete the message, with no further navigation/state. They are
31
+ *not* a fourth colon-prefix: they use the same assistant:<name>:<tail>
32
+ shape as namespace 2.
33
+
34
+ Symmetry rule
35
+ --------------
36
+ Every callback data a button *emits* must have a matching @callback
37
+ pattern that *consumes* it, and vice versa. Emitters use :func:cb /
38
+ :func:cb_str; handlers use :func:cb_pattern / :func:cb_exact_pattern.
39
+ tests/test_assistant_cbs_symmetry.py statically scans every literal
40
+ call site of these four functions and fails on any one-sided
41
+ namespace:name prefix.
42
+
43
+ Cross-boundary tokens
44
+ ----------------------
45
+ A handful of callback datas cross the assistant/ <-> plugins/ (or
46
+ pyUltroid core) boundary e.g. the group-manager help menu's "back to
47
+ plugin help" button is emitted by plugins/_help.py but consumed by
48
+ assistant/manager/_help.py. These tokens are **fully migrated** to the
49
+ colon model: both sides build/handle the same literal cb(...) segments,
50
+ with the primitives imported from the dependency-free leaf
51
+ pyUltroid._core._cbs (re-exported below) so no side introduces an
52
+ import-order cycle. The symmetry audit
53
+ (tests/test_assistant_cbs_symmetry.py) scans the participating files
54
+ across both layers and pins the migrated prefixes so a silent
55
+ re-literalization can't slip through.
56
+
57
+ Back-navigation
58
+ ----------------
59
+ Every " Back" button targets a real, already-registered destination token
60
+ (e.g. assistant:callbacks:menu:otvars has its own @callback handler).
61
+ Reusing that destination's own callback data as the back button's data is
62
+ not a workaround a button click is a *real* Telegram callback-query round
63
+ trip, dispatched by Telethon exactly as if the destination button itself had
64
+ been clicked. No in-process redispatch engine is needed, and the symmetry
65
+ rule is satisfied automatically (the "emitter" is just every
66
+ get_back_button() call site, the "handler" is the destination's own
67
+ handler).
68
+ """
69
+
70
+ from pyUltroid._core._cbs import ( # noqa: F401 (re-export)
71
+ SEP,
72
+ _clean,
73
+ cb,
74
+ cb_pattern,
75
+ cb_exact_pattern,
76
+ cb_str,
77
+ )
78
+
79
+ __all__ = [
80
+ "SEP",
81
+ "_clean",
82
+ "cb",
83
+ "cb_str",
84
+ "cb_pattern",
85
+ "cb_exact_pattern",
86
+ ]
assistant/agent.py ADDED
@@ -0,0 +1,1164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ultroid - UserBot
2
+ # Copyright (C) 2021-2024 TeamUltroid
3
+ #
4
+ # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
+ # PLease read the GNU Affero General Public License in
6
+ # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
+
8
+ """/agent - a full agent-configuration menu tree for the assistant bot.
9
+
10
+ This module owns the assistant:agent:* callback-data namespace (see
11
+ assistant/_cbs.py). One @asst_cmd(pattern="agent") entry point opens a
12
+ primary-blue dashboard; from there six coloured-button sections branch out,
13
+ each driven by @callback handlers over the colon callback model:
14
+
15
+ * menu:<key> - screen navigation (one MENU_PATTERN handler)
16
+ * conv:<field>:<id> - conversation-style value entry (CONV_PATTERN)
17
+ * act:<name>[:<id>] - real side-effects / fetches (ACT_PATTERN)
18
+
19
+ Every button is built with cb(...) through the _menu/_conv/_act
20
+ wrappers below, and every wrapper call is paired with one of those three
21
+ cb_pattern(...) handlers - no dead buttons, no dead handlers (verified by
22
+ tests/test_assistant_cbs_symmetry.py, which resolves these wrappers).
23
+
24
+ Menu tree (each level owns the next; back pops one level)
25
+ ---------
26
+ home
27
+ llama llama:<ollama|llamacpp|lmstudio|tgi|vllm>
28
+ base/model/ctx/temp/sys + fetch-models (real GET)
29
+ cloud cloud:<openai|gemini|anthropic|openrouter|groq>
30
+ key(model/masked)/model/sys/base + validate-key (real GET)
31
+ claude key(masked)/default-model/fallback + fetch-modelspaste URL (real GET)
32
+ keys masked credentials readout + clear (llama/cloud/claude/all)
33
+ modules importability probe of openai/anthropic/httpx/aiohttp/requests
34
+ act:syscheck Python/platform/memory + endpoint reachability (real GET)
35
+
36
+ Persisted udB keys (namespace AGENT_*)
37
+ ------------------------------------------
38
+ Local LLM : AGENT_LLAMA_<PROV>_BASE|MODEL|CTX|TEMP|SYS
39
+ Cloud AI : AGENT_CLOUD_<PROV>_KEY|MODEL|SYS|BASE
40
+ Claude : AGENT_CLAUDE_KEY|MODEL|FALLBACK
41
+
42
+ Real network calls (vs. key-gated)
43
+ ----------------------------------
44
+ * Llama "Fetch Models" - REAL GET, no key: Ollama {base}/api/tags;
45
+ OpenAI-compatible servers (llama.cpp/LM Studio/TGI/vLLM) {base}/v1/models.
46
+ * Cloud "Validate Key" - REAL authenticated GET per provider
47
+ (OpenAI/Anthropic/OpenRouter/Groq/Gemini). Requires a stored key.
48
+ * Claude "Fetch Models URL" - REAL GET api.anthropic.com/v1/models
49
+ (x-api-key). Requires a stored key; result pasted via get_paste +
50
+ make_html_telegraph.
51
+ * "Check System" reachability - REAL GET (short timeout) against each
52
+ configured provider host.
53
+
54
+ All network calls go through async_searcher (the repo's standard async GET
55
+ helper, also used by callbackstuffs.py) wrapped in asyncio.wait_for with
56
+ a timeout and try/except, so the event loop is never blocked and the module
57
+ imports cleanly even when an optional client library is absent (the modules
58
+ probe uses importlib.util.find_spec, never an import).
59
+ """
60
+
61
+ import asyncio
62
+ import html
63
+ import platform
64
+ from datetime import datetime, timezone
65
+
66
+ from custom.tg import ikm
67
+ from pyUltroid._core.richmsg import RichMarkup, send_rich
68
+ from pyUltroid.agent import agent
69
+ from pyUltroid.fns import fns
70
+
71
+ from . import *
72
+ from ._cbs import cb, cb_pattern
73
+ from .rich_pages import body_page, edit_callback_page, rich_page
74
+
75
+ # --------------------------------------------------------------------#
76
+ # Callback-data wrappers. _menu/_conv/_act are the emitter side;
77
+ # MENU/CONV/ACT_PATTERN are the three handler prefixes that consume them. The
78
+ # static symmetry audit (tests/test_assistant_cbs_symmetry.py) resolves these
79
+ # one-line wrappers, so a single pattern handler covers every key under it.
80
+
81
+
82
+ def _menu(*parts):
83
+ return cb("assistant", "agent", "menu", *parts)
84
+
85
+
86
+ def _conv(*parts):
87
+ return cb("assistant", "agent", "conv", *parts)
88
+
89
+
90
+ def _act(*parts):
91
+ return cb("assistant", "agent", "act", *parts)
92
+
93
+
94
+ MENU_PATTERN = cb_pattern("assistant", "agent", "menu")
95
+ CONV_PATTERN = cb_pattern("assistant", "agent", "conv")
96
+ ACT_PATTERN = cb_pattern("assistant", "agent", "act")
97
+
98
+ # --------------------------------------------------------------------#
99
+ # Provider registries + persistence helpers.
100
+
101
+ #: Local LLM servers. api selects the model-list endpoint shape:
102
+ #: ollama -> {base}/api/tags; openai -> {base}/v1/models.
103
+ LLAMA_PROVIDERS = {
104
+ "ollama": {
105
+ "label": "Ollama",
106
+ "default_base": "http://localhost:11434",
107
+ "api": "ollama",
108
+ },
109
+ "llamacpp": {
110
+ "label": "llama.cpp",
111
+ "default_base": "http://localhost:8080",
112
+ "api": "openai",
113
+ },
114
+ "lmstudio": {
115
+ "label": "LM Studio",
116
+ "default_base": "http://localhost:1234/v1",
117
+ "api": "openai",
118
+ },
119
+ "tgi": {
120
+ "label": "TGI / WebUI",
121
+ "default_base": "http://localhost:5000/v1",
122
+ "api": "openai",
123
+ },
124
+ "vllm": {
125
+ "label": "vLLM",
126
+ "default_base": "http://localhost:8000/v1",
127
+ "api": "openai",
128
+ },
129
+ }
130
+
131
+ #: Cloud LLM providers (provider id -> display label).
132
+ CLOUD_PROVIDERS = {
133
+ "openai": "OpenAI-compatible",
134
+ "gemini": "Google Gemini",
135
+ "anthropic": "Anthropic",
136
+ "apimix": "apmix.ai",
137
+ "openrouter": "OpenRouter",
138
+ "groq": "Groq",
139
+ "xai": "xAI (Grok)",
140
+ "meta_llama": "Meta Llama API",
141
+ }
142
+
143
+ #: Host roots used only for the (key-gated) reachability probe in "check system".
144
+ CLOUD_HOSTS = {
145
+ "openai": "https://api.openai.com",
146
+ "gemini": "https://generativelanguage.googleapis.com",
147
+ "anthropic": "https://api.anthropic.com",
148
+ "apimix": "https://api.apmix.ai",
149
+ "openrouter": "https://openrouter.ai",
150
+ "groq": "https://api.groq.com",
151
+ "xai": "https://api.x.ai",
152
+ "meta_llama": "https://api.llama.com",
153
+ }
154
+
155
+ #: Optional AI client libraries probed by the "modules" screen.
156
+ MODULES = [
157
+ ("openai", "openai", 'pip install "openai>=1.40"'),
158
+ ("anthropic", "anthropic", "pip install anthropic"),
159
+ ("httpx", "httpx", "pip install httpx"),
160
+ ("aiohttp", "aiohttp", "pip install aiohttp"),
161
+ ("requests", "requests", "pip install requests"),
162
+ ]
163
+
164
+ #: Conversation-field metadata: field -> (label, prompt, validator).
165
+ #: validator is None | "int" | "float".
166
+ _CONV_FIELDS = {
167
+ "llama_base": (
168
+ "Base URL",
169
+ "Send the base URL of the local server (e.g. http://localhost:11434). Use /cancel to abort.",
170
+ None,
171
+ ),
172
+ "llama_model": (
173
+ "Model",
174
+ "Send the model name to use (e.g. llama3, qwen2.5:7b). Use /cancel to abort.",
175
+ None,
176
+ ),
177
+ "llama_ctx": (
178
+ "Context Window",
179
+ "Send the context window size in tokens (e.g. 4096). Use /cancel to abort.",
180
+ "int",
181
+ ),
182
+ "llama_temp": (
183
+ "Temperature",
184
+ "Send the sampling temperature, 0.0 2.0 (e.g. 0.7). Use /cancel to abort.",
185
+ "float",
186
+ ),
187
+ "llama_sys": (
188
+ "System Prompt",
189
+ "Send the system prompt text. Use /cancel to abort.",
190
+ None,
191
+ ),
192
+ "cloud_key": (
193
+ "API Key",
194
+ "Send the API key for this cloud provider. Use /cancel to abort.",
195
+ None,
196
+ ),
197
+ "cloud_model": (
198
+ "Model",
199
+ "Send the model id (e.g. gpt-4o-mini, gemini-1.5-pro). Use /cancel to abort.",
200
+ None,
201
+ ),
202
+ "cloud_sys": (
203
+ "System Prompt",
204
+ "Send the system prompt text. Use /cancel to abort.",
205
+ None,
206
+ ),
207
+ "cloud_base": (
208
+ "Base URL",
209
+ "Send the OpenAI-compatible base URL (e.g. https://api.openai.com/v1). Use /cancel to abort.",
210
+ None,
211
+ ),
212
+ "claude_key": (
213
+ "Anthropic API Key",
214
+ "Send your Anthropic API key (sk-ant-...). Use /cancel to abort.",
215
+ None,
216
+ ),
217
+ "claude_model": (
218
+ "Default Model",
219
+ "Send the default Claude model id (e.g. claude-3-5-sonnet-20241022). Use /cancel to abort.",
220
+ None,
221
+ ),
222
+ "claude_fallback": (
223
+ "Fallback Model",
224
+ "Send the fallback Claude model id. Use /cancel to abort.",
225
+ None,
226
+ ),
227
+ }
228
+
229
+ #: Fields whose value may be echoed back in the convo confirmation (non-secret,
230
+ #: short). Keys and system prompts are never echoed.
231
+ _ECHO_FIELDS = {
232
+ "llama_base",
233
+ "llama_model",
234
+ "llama_ctx",
235
+ "llama_temp",
236
+ "cloud_model",
237
+ "cloud_base",
238
+ "claude_model",
239
+ "claude_fallback",
240
+ }
241
+
242
+
243
+ def _agent_var(field, scope=""):
244
+ """Build a udB key from a convo field (llama_base) + optional
245
+ provider scope (ollama) -> AGENT_LLAMA_OLLAMA_BASE."""
246
+ section, _, suffix = field.partition("_")
247
+ base = f"AGENT_{section.upper()}"
248
+ if scope:
249
+ base = f"{base}_{scope.upper()}"
250
+ return f"{base}_{suffix.upper()}"
251
+
252
+
253
+ def _has_value(value):
254
+ """True when a setting is explicitly present, including a stored False/0."""
255
+ return value is not None and not (isinstance(value, str) and not value.strip())
256
+
257
+
258
+ def _state_style(value):
259
+ """Use green only for a configured value; leave unset controls unstyled."""
260
+ return "success" if _has_value(value) else None
261
+
262
+
263
+ def _back_btn(*current):
264
+ """Back button for the screen at menu path current.
265
+
266
+ Destination is the parent path - same segments minus the last one
267
+ (llama/<prov> -> llama -> home).
268
+ """
269
+ parent = current[:-1] or ("home",)
270
+ return ("Back", _menu(*parent), None)
271
+
272
+
273
+ def _conv_back(field, scope):
274
+ """Destination token for a convo flow's " Back" button - re-opens the
275
+ provider screen the field belongs to."""
276
+ section = field.split("_", 1)[0]
277
+ if section == "llama":
278
+ return _menu("llama", scope)
279
+ if section == "cloud":
280
+ return _menu("cloud", scope)
281
+ return _menu("claude")
282
+
283
+
284
+ def _mask(value):
285
+ """Mask a secret for display - never echoes the raw value back."""
286
+ if not value:
287
+ return "not set"
288
+ s = str(value)
289
+ if len(s) <= 8:
290
+ return "****"
291
+ return f"{s[:4]}****{s[-4:]}"
292
+
293
+
294
+ def _settings_page(title, description, rows, details=None):
295
+ """Build a native RichMessage settings table with consistent page chrome."""
296
+ page = rich_page(
297
+ title,
298
+ rows,
299
+ description=description,
300
+ columns=("Setting", "Current value"),
301
+ total=len(rows),
302
+ )
303
+ if not details:
304
+ return page
305
+ detail_title, detail_text = details
306
+ expandable = (
307
+ f"</table><blockquote expandable><b>{html.escape(str(detail_title))}</b>\n"
308
+ f"{html.escape(str(detail_text))}</blockquote><hr>"
309
+ )
310
+ return RichMarkup(page.text.replace("</table><hr>", expandable), "html")
311
+
312
+
313
+ # --------------------------------------------------------------------#
314
+ # Network helper. async_searcher is the repo's standard async GET (used by
315
+ # callbackstuffs.py too); asyncio.wait_for enforces the timeout so a
316
+ # hung host can never block the event loop. Returns (ok, status, body):
317
+ # ok=True -> (status, parsed-json-or-None) for any HTTP status (host reached)
318
+ # ok=False -> (None, "timed out" | "<ExceptionClass>") on timeout / conn error.
319
+
320
+
321
+ async def _http_get(url, headers=None, timeout=10):
322
+ async def _eval(resp):
323
+ status = resp.status
324
+ try:
325
+ body = await resp.json()
326
+ except Exception:
327
+ body = None
328
+ return status, body
329
+
330
+ try:
331
+ status, body = await asyncio.wait_for(
332
+ fns.async_searcher(url, headers=headers, evaluate=_eval),
333
+ timeout=timeout,
334
+ )
335
+ return True, status, body
336
+ except TimeoutError:
337
+ return False, None, "timed out"
338
+ except Exception as e:
339
+ return False, None, f"{e.__class__.__name__}"
340
+
341
+
342
+ def _validate_spec(prov, key, base):
343
+ """Return (url, headers) for a real lightweight authenticated "whoami"
344
+ request, or (None, None) when no safe validation endpoint is known."""
345
+ if prov == "openai":
346
+ b = (base or "https://api.openai.com/v1").rstrip("/")
347
+ return f"{b}/models", {"Authorization": f"Bearer {key}"}
348
+ if prov == "gemini":
349
+ return (
350
+ f"https://generativelanguage.googleapis.com/v1beta/models?key={key}",
351
+ {},
352
+ )
353
+ if prov == "anthropic":
354
+ return (
355
+ "https://api.anthropic.com/v1/models",
356
+ {"x-api-key": key, "anthropic-version": "2023-06-01"},
357
+ )
358
+ if prov == "openrouter":
359
+ return "https://openrouter.ai/api/v1/key", {"Authorization": f"Bearer {key}"}
360
+ if prov == "groq":
361
+ return "https://api.groq.com/openai/v1/models", {
362
+ "Authorization": f"Bearer {key}"
363
+ }
364
+ if prov == "xai":
365
+ return "https://api.x.ai/v1/models", {"Authorization": f"Bearer {key}"}
366
+ if prov == "meta_llama":
367
+ return "https://api.llama.com/v1/models", {"Authorization": f"Bearer {key}"}
368
+ return None, None
369
+
370
+
371
+ def _validate_hint(prov, body):
372
+ """A non-sensitive hint from a successful validation (model count / key
373
+ label) - never includes the key itself."""
374
+ try:
375
+ if prov == "openrouter" and isinstance(body, dict):
376
+ d = body.get("data", {}) or {}
377
+ parts = []
378
+ if d.get("label"):
379
+ parts.append(f"label: {d['label']}")
380
+ if d.get("usage") is not None:
381
+ parts.append(f"usage: {d['usage']}")
382
+ return f" ({', '.join(parts)})" if parts else ""
383
+ if isinstance(body, dict):
384
+ data = body.get("data") or body.get("models") or []
385
+ if isinstance(data, list) and data:
386
+ return f" ({len(data)} models listed)"
387
+ except Exception:
388
+ pass
389
+ return ""
390
+
391
+
392
+ def _probe_modules():
393
+ """Real importability probe - uses find_spec (no import side effects),
394
+ so the module imports fine even when a library is missing."""
395
+ import importlib.util
396
+
397
+ return {name: importlib.util.find_spec(name) is not None for name, _, _ in MODULES}
398
+
399
+
400
+ def _mem_info():
401
+ """Best-effort memory readout: psutil if available, else /proc/meminfo,
402
+ else a clear 'unavailable' note."""
403
+ try:
404
+ import psutil
405
+
406
+ vm = psutil.virtual_memory()
407
+ return (
408
+ f"{vm.percent}% used - {vm.available // (1024**2)} MB free / "
409
+ f"{vm.total // (1024**2)} MB total"
410
+ )
411
+ except Exception:
412
+ pass
413
+ try:
414
+ with open("/proc/meminfo") as f:
415
+ d = {}
416
+ for line in f:
417
+ k, _, v = line.partition(":")
418
+ d[k.strip()] = v.strip().split()[0]
419
+ total = int(d["MemTotal"]) // 1024
420
+ avail = int(d["MemAvailable"]) // 1024
421
+ pct = (100 * (total - avail) / total) if total else 0
422
+ return f"{pct:.0f}% used - {avail} MB free / {total} MB total"
423
+ except Exception:
424
+ return "unavailable (install psutil for details)"
425
+
426
+
427
+ def _collect_endpoints():
428
+ """Endpoints to probe in "check system": user-configured local bases + the
429
+ hosts of cloud/Claude providers that actually have a stored key."""
430
+ eps = []
431
+ for pid, info in LLAMA_PROVIDERS.items():
432
+ base = udB.get_key(_agent_var("llama_base", pid))
433
+ if base:
434
+ eps.append((f"Llama - {info['label']}", base.rstrip("/")))
435
+ for pid in CLOUD_PROVIDERS:
436
+ if udB.get_key(_agent_var("cloud_key", pid)):
437
+ if pid == "openai":
438
+ b = (
439
+ udB.get_key(_agent_var("cloud_base", pid))
440
+ or "https://api.openai.com/v1"
441
+ ).rstrip("/")
442
+ host = b.rsplit("/v1", 1)[0] if "/v1" in b else b
443
+ eps.append((f"Cloud - {CLOUD_PROVIDERS[pid]}", host))
444
+ else:
445
+ eps.append((f"Cloud - {CLOUD_PROVIDERS[pid]}", CLOUD_HOSTS[pid]))
446
+ if udB.get_key("AGENT_CLAUDE_KEY"):
447
+ eps.append(("Claude - Anthropic", "https://api.anthropic.com"))
448
+ if not eps:
449
+ eps.append(("Ollama (default)", LLAMA_PROVIDERS["ollama"]["default_base"]))
450
+ return eps
451
+
452
+
453
+ # --------------------------------------------------------------------#
454
+ # Menu renderers - each returns native RichMarkup plus callback buttons.
455
+
456
+
457
+ def _home():
458
+ primary = agent().config_default_provider()
459
+ primary_label = (
460
+ CLOUD_PROVIDERS.get(primary)
461
+ or (LLAMA_PROVIDERS.get(primary) or {}).get("label")
462
+ or primary
463
+ )
464
+ text = _settings_page(
465
+ "Agent Config",
466
+ "Configure local and cloud models, manage keys, inspect installed modules, and run a system health check.",
467
+ [
468
+ ("Version", f"v{ultroid_version}"),
469
+ ("Primary provider", primary_label if primary else "Automatic routing"),
470
+ ("Native RichMessage engine", "Available for this assistant bot"),
471
+ ],
472
+ )
473
+ buttons = ikm(
474
+ [
475
+ [
476
+ ("Llama / Local", _menu("llama"), "primary"),
477
+ ("Cloud AI", _menu("cloud"), "primary"),
478
+ ],
479
+ [
480
+ ("Claude (Anthropic)", _menu("claude"), "primary"),
481
+ ("Keys", _menu("keys"), "primary"),
482
+ ],
483
+ [
484
+ ("Modules", _menu("modules"), "primary"),
485
+ ("Check System", _act("syscheck"), "primary"),
486
+ ],
487
+ [("Close", _act("close"), None)],
488
+ ],
489
+ icon=False,
490
+ )
491
+ return text, buttons
492
+
493
+
494
+ def _llama_menu():
495
+ rows = []
496
+ items = list(LLAMA_PROVIDERS.items())
497
+ while items:
498
+ a = items.pop(0)
499
+ row = [(a[1]["label"], _menu("llama", a[0]), "primary")]
500
+ if items:
501
+ b = items.pop(0)
502
+ row.append((b[1]["label"], _menu("llama", b[0]), "primary"))
503
+ rows.append(row)
504
+ rows.append([_back_btn("llama")])
505
+ text = _settings_page(
506
+ "Llama / Local",
507
+ "Choose a local inference server. Each server keeps its own URL, model, context, temperature, and prompt.",
508
+ [
509
+ (
510
+ info["label"],
511
+ (
512
+ f"{udB.get_key(_agent_var('llama_base', pid)) or info['default_base']} · "
513
+ f"{udB.get_key(_agent_var('llama_model', pid)) or 'model not set'}"
514
+ ),
515
+ )
516
+ for pid, info in LLAMA_PROVIDERS.items()
517
+ ],
518
+ )
519
+ return text, ikm(rows, icon=False)
520
+
521
+
522
+ def _llama_prov(prov):
523
+ info = LLAMA_PROVIDERS.get(prov)
524
+ if not info:
525
+ return body_page("Llama", "<p>Unknown provider.</p>"), ikm(
526
+ [[_back_btn("llama", prov)]], icon=False
527
+ )
528
+ stored_base = udB.get_key(_agent_var("llama_base", prov))
529
+ base = stored_base or info["default_base"]
530
+ model = udB.get_key(_agent_var("llama_model", prov))
531
+ context = udB.get_key(_agent_var("llama_ctx", prov))
532
+ temperature = udB.get_key(_agent_var("llama_temp", prov))
533
+ system_prompt = udB.get_key(_agent_var("llama_sys", prov))
534
+ text = _settings_page(
535
+ f"Llama · {info['label']}",
536
+ "Settings for this local inference endpoint. Fetch Models checks the live server without changing configuration.",
537
+ [
538
+ ("Base URL", base),
539
+ ("Model", model or "Not set"),
540
+ ("Context window", context if _has_value(context) else "Not set"),
541
+ ("Temperature", temperature if _has_value(temperature) else "Not set"),
542
+ ("API protocol", info["api"]),
543
+ ],
544
+ details=("System prompt", system_prompt or "Not set"),
545
+ )
546
+ buttons = ikm(
547
+ [
548
+ [
549
+ ("Base URL", _conv("llama_base", prov), _state_style(stored_base)),
550
+ ("Model", _conv("llama_model", prov), _state_style(model)),
551
+ ],
552
+ [
553
+ ("Context", _conv("llama_ctx", prov), _state_style(context)),
554
+ ("Temperature", _conv("llama_temp", prov), _state_style(temperature)),
555
+ ],
556
+ [("System Prompt", _conv("llama_sys", prov), _state_style(system_prompt))],
557
+ [("Fetch Models", _act("llama_fetch", prov), None)],
558
+ [_back_btn("llama", prov)],
559
+ ],
560
+ icon=False,
561
+ )
562
+ return text, buttons
563
+
564
+
565
+ def _llama_prov_buttons(prov):
566
+ return ikm([[_back_btn("llama", prov)]], icon=False)
567
+
568
+
569
+ def _cloud_menu():
570
+ rows = []
571
+ items = list(CLOUD_PROVIDERS.items())
572
+ while items:
573
+ a = items.pop(0)
574
+ row = [(a[1], _menu("cloud", a[0]), "primary")]
575
+ if items:
576
+ b = items.pop(0)
577
+ row.append((b[1], _menu("cloud", b[0]), "primary"))
578
+ rows.append(row)
579
+ rows.append([_back_btn("cloud")])
580
+ text = _settings_page(
581
+ "Cloud AI",
582
+ "Store keys securely, choose a model and prompt, validate credentials, and select a primary provider.",
583
+ [
584
+ (
585
+ label,
586
+ "configured · "
587
+ + str(udB.get_key(_agent_var("cloud_model", pid)) or "model not set")
588
+ if udB.get_key(_agent_var("cloud_key", pid))
589
+ else "not configured",
590
+ )
591
+ for pid, label in CLOUD_PROVIDERS.items()
592
+ ],
593
+ )
594
+ return text, ikm(rows, icon=False)
595
+
596
+
597
+ def _provider_pin_label(provider: str) -> str:
598
+ """Label for a provider's pin button, including its current state."""
599
+ if not udB.get_key("AGENT_CLOUD_%s_KEY" % provider.upper()):
600
+ return "Not configured"
601
+ if agent().config_default_provider() == provider:
602
+ return "Primary for .ai/.ask"
603
+ return "Set as primary"
604
+
605
+
606
+ def _cloud_prov(prov):
607
+ label = CLOUD_PROVIDERS.get(prov, prov)
608
+ key = udB.get_key(_agent_var("cloud_key", prov))
609
+ stored_base = udB.get_key(_agent_var("cloud_base", prov))
610
+ base = stored_base
611
+ if not base and prov == "openai":
612
+ base = "https://api.openai.com/v1"
613
+ model = udB.get_key(_agent_var("cloud_model", prov))
614
+ system_prompt = udB.get_key(_agent_var("cloud_sys", prov))
615
+ data = [
616
+ ("API key", _mask(key)),
617
+ ("Model", model or "Not set"),
618
+ (
619
+ "Primary for .ai/.ask",
620
+ "Yes" if agent().config_default_provider() == prov else "No",
621
+ ),
622
+ ]
623
+ if prov == "openai":
624
+ data.insert(2, ("Base URL", base or "Not set"))
625
+ text = _settings_page(
626
+ f"Cloud · {label}",
627
+ "Credentials are masked. Validate Key performs a read-only authenticated provider check.",
628
+ data,
629
+ details=("System prompt", system_prompt or "Not set"),
630
+ )
631
+ rows = [
632
+ [
633
+ ("API Key", _conv("cloud_key", prov), _state_style(key)),
634
+ ("Model", _conv("cloud_model", prov), _state_style(model)),
635
+ ],
636
+ [("System Prompt", _conv("cloud_sys", prov), _state_style(system_prompt))],
637
+ ]
638
+ if prov == "openai":
639
+ rows.insert(
640
+ 1,
641
+ [("Base URL", _conv("cloud_base", prov), _state_style(stored_base))],
642
+ )
643
+ if _has_value(key):
644
+ rows.append([("Validate Key", _act("cloud_validate", prov), "success")])
645
+ pinned = agent().config_default_provider() == prov
646
+ rows.append(
647
+ [
648
+ (
649
+ _provider_pin_label(prov),
650
+ _act("cloud_primary", prov),
651
+ "success" if pinned else None,
652
+ )
653
+ ]
654
+ )
655
+ rows.append([_back_btn("cloud", prov)])
656
+ buttons = ikm(rows, icon=False)
657
+ return text, buttons
658
+
659
+
660
+ def _cloud_prov_buttons(prov):
661
+ return ikm([[_back_btn("cloud", prov)]], icon=False)
662
+
663
+
664
+ def _claude_menu():
665
+ key = udB.get_key("AGENT_CLAUDE_KEY")
666
+ model = udB.get_key("AGENT_CLAUDE_MODEL")
667
+ fallback = udB.get_key("AGENT_CLAUDE_FALLBACK")
668
+ text = _settings_page(
669
+ "Claude · Anthropic",
670
+ "Configure model selection and fallback. Fetch Models checks Anthropic's live catalog and returns shareable specs.",
671
+ [
672
+ ("API key", _mask(key)),
673
+ ("Default model", model or "Not set"),
674
+ ("Fallback model", fallback or "Not set"),
675
+ ],
676
+ )
677
+ buttons = ikm(
678
+ [
679
+ [
680
+ ("API Key", _conv("claude_key"), _state_style(key)),
681
+ ("Default Model", _conv("claude_model"), _state_style(model)),
682
+ ],
683
+ [("Fallback Model", _conv("claude_fallback"), _state_style(fallback))],
684
+ [("Fetch Models", _act("claude_fetch"), None)],
685
+ [_back_btn("claude")],
686
+ ],
687
+ icon=False,
688
+ )
689
+ return text, buttons
690
+
691
+
692
+ def _claude_menu_buttons():
693
+ return ikm([[_back_btn("claude")]], icon=False)
694
+
695
+
696
+ def _keys_menu():
697
+ rows = []
698
+ for pid, label in CLOUD_PROVIDERS.items():
699
+ k = udB.get_key(_agent_var("cloud_key", pid))
700
+ rows.append((f"Cloud · {label}", _mask(k) if k else "Not set"))
701
+ ck = udB.get_key("AGENT_CLAUDE_KEY")
702
+ rows.append(("Claude · Anthropic", _mask(ck) if ck else "Not set"))
703
+ configured = [
704
+ LLAMA_PROVIDERS[p]["label"]
705
+ for p in LLAMA_PROVIDERS
706
+ if udB.get_key(_agent_var("llama_base", p))
707
+ ]
708
+ rows.append(("Local LLM endpoints", ", ".join(configured) if configured else "None configured"))
709
+ text = _settings_page(
710
+ "Credentials",
711
+ "Keys are shown masked and never echoed in full. Use the buttons to clear a provider section.",
712
+ rows,
713
+ )
714
+ buttons = ikm(
715
+ [
716
+ [
717
+ ("Clear Llama", _act("keys_clear", "llama"), "danger"),
718
+ ("Clear Cloud", _act("keys_clear", "cloud"), "danger"),
719
+ ],
720
+ [
721
+ ("Clear Claude", _act("keys_clear", "claude"), "danger"),
722
+ ("Clear All", _act("keys_clear", "all"), "danger"),
723
+ ],
724
+ [_back_btn("keys")],
725
+ ],
726
+ icon=False,
727
+ )
728
+ return text, buttons
729
+
730
+
731
+ def _modules_menu():
732
+ probe = _probe_modules()
733
+ rows = []
734
+ for name, label, install in MODULES:
735
+ rows.append(
736
+ (label, "Installed" if probe[name] else f"Missing · {install}")
737
+ )
738
+ text = _settings_page(
739
+ "AI Modules",
740
+ "Importability of optional AI client libraries. Missing modules affect only the features that use them.",
741
+ rows,
742
+ )
743
+ buttons = ikm([[_back_btn("modules")]], icon=False)
744
+ return text, buttons
745
+
746
+
747
+ def _render_menu(key):
748
+ """Dispatch a menu:<path...> callback to its screen renderer.
749
+
750
+ key is the path below assistant:agent:menu: - every level owns
751
+ the next (llama -> llama:<prov>), so back is always the parent
752
+ path (see :func:_back_btn).
753
+ """
754
+ levels = key.split(":") if key else []
755
+ if levels == ["home"]:
756
+ return _home()
757
+ if levels == ["llama"]:
758
+ return _llama_menu()
759
+ if len(levels) == 2 and levels[0] == "llama":
760
+ return _llama_prov(levels[1])
761
+ if levels == ["cloud"]:
762
+ return _cloud_menu()
763
+ if len(levels) == 2 and levels[0] == "cloud":
764
+ return _cloud_prov(levels[1])
765
+ if levels == ["claude"]:
766
+ return _claude_menu()
767
+ if levels == ["keys"]:
768
+ return _keys_menu()
769
+ if levels == ["modules"]:
770
+ return _modules_menu()
771
+ return None, None
772
+
773
+
774
+ # --------------------------------------------------------------------#
775
+ # Action bodies - real network fetches / probes. Each returns (text, buttons).
776
+
777
+
778
+ async def _llama_fetch(prov):
779
+ info = LLAMA_PROVIDERS.get(prov)
780
+ if not info:
781
+ return (
782
+ f"<b>Llama</b>\n\nUnknown provider.",
783
+ ikm([[_back_btn("llama", prov)]], icon=False),
784
+ )
785
+ base = (udB.get_key(_agent_var("llama_base", prov)) or info["default_base"]).rstrip(
786
+ "/"
787
+ )
788
+ if info["api"] == "ollama":
789
+ url = f"{base}/api/tags"
790
+ elif base.endswith("/v1"):
791
+ # OpenAI-compatible servers whose configured base already carries the
792
+ # /v1 prefix (LM Studio, TGI and vLLM defaults do): appending another
793
+ # one doubled the prefix and every fetch 404'd.
794
+ url = f"{base}/models"
795
+ else:
796
+ url = f"{base}/v1/models"
797
+ ok, status, body = await _http_get(url, timeout=10)
798
+ head = f"Llama - {info['label']} - Models"
799
+ if not ok:
800
+ return (
801
+ f"<b>{head}</b>\n\nUnreachable - needs a running provider at "
802
+ f"<code>{html.escape(url)}</code>.\n\nReason: <code>{html.escape(str(body))}</code>",
803
+ _llama_prov_buttons(prov),
804
+ )
805
+ if status != 200:
806
+ return (
807
+ f"<b>{head}</b>\n\nServer responded HTTP {status} at "
808
+ f"<code>{html.escape(url)}</code>. Is the right provider running there?",
809
+ _llama_prov_buttons(prov),
810
+ )
811
+ if info["api"] == "ollama":
812
+ models = (body or {}).get("models", []) or []
813
+ lines = []
814
+ for m in models[:30]:
815
+ det = m.get("details", {}) or {}
816
+ lines.append(
817
+ f"- <b>{html.escape(str(m.get('name', '?')))}</b> - "
818
+ f"{html.escape(str(det.get('parameter_size', '?')))} - "
819
+ f"{html.escape(str(det.get('quantization_level', '?')))}"
820
+ )
821
+ else:
822
+ models = (body or {}).get("data", []) or []
823
+ lines = [f"- <b>{html.escape(str(m.get('id', '?')))}</b>" for m in models[:30]]
824
+ count = len(models)
825
+ if not lines:
826
+ msg = "No models returned by the server."
827
+ else:
828
+ msg = (
829
+ f"Fetched {count} model(s) from <code>{html.escape(url)}</code>:\n\n"
830
+ + "\n".join(lines)
831
+ )
832
+ if count > 30:
833
+ msg += f"\n... and {count - 30} more"
834
+ return f"<b>{head}</b>\n\n{msg}", _llama_prov_buttons(prov)
835
+
836
+
837
+ async def _cloud_validate(prov):
838
+ label = CLOUD_PROVIDERS.get(prov, prov)
839
+ back = _cloud_prov_buttons(prov)
840
+ head = f"Cloud - {label} - Validate"
841
+ key = udB.get_key(_agent_var("cloud_key", prov))
842
+ if not key:
843
+ return (
844
+ f"<b>{head}</b>\n\nNo API key set for this provider. Set one first.",
845
+ back,
846
+ )
847
+ base = udB.get_key(_agent_var("cloud_base", prov)) if prov == "openai" else None
848
+ url, headers = _validate_spec(prov, key, base)
849
+ if url is None:
850
+ return (
851
+ f"<b>{head}</b>\n\nNo safe validation endpoint is known for this "
852
+ f"provider. Validate by sending a real completion request with your key.",
853
+ back,
854
+ )
855
+ ok, status, body = await _http_get(url, headers=headers, timeout=12)
856
+ if not ok:
857
+ return (
858
+ f"<b>{head}</b>\n\nCould not reach provider.\nReason: "
859
+ f"<code>{html.escape(str(status or body))}</code>",
860
+ back,
861
+ )
862
+ if status == 200:
863
+ return (
864
+ f"<b>{head}</b>\n\nKey is valid. Provider authenticated the request."
865
+ + html.escape(_validate_hint(prov, body)),
866
+ back,
867
+ )
868
+ if status in (401, 403):
869
+ return (
870
+ f"<b>{head}</b>\n\nProvider rejected the key (HTTP {status}). "
871
+ f"Check the key and try again.",
872
+ back,
873
+ )
874
+ return f"<b>{head}</b>\n\nUnexpected response (HTTP {status}).", back
875
+
876
+
877
+ async def _claude_fetch():
878
+ back = _claude_menu_buttons()
879
+ head = f"Claude - Models"
880
+ key = udB.get_key("AGENT_CLAUDE_KEY")
881
+ if not key:
882
+ return (
883
+ f"<b>{head}</b>\n\nNo Anthropic API key set. Set one first "
884
+ f"(Claude API Key).",
885
+ back,
886
+ )
887
+ ok, status, body = await _http_get(
888
+ "https://api.anthropic.com/v1/models",
889
+ headers={"x-api-key": key, "anthropic-version": "2023-06-01"},
890
+ timeout=12,
891
+ )
892
+ if not ok:
893
+ return (
894
+ f"<b>{head}</b>\n\nCould not reach Anthropic.\nReason: "
895
+ f"<code>{html.escape(str(status or body))}</code>",
896
+ back,
897
+ )
898
+ if status != 200:
899
+ msg = f"Anthropic rejected the request (HTTP {status})."
900
+ if status in (401, 403):
901
+ msg += " Check your API key."
902
+ return f"<b>{head}</b>\n\n{msg}", back
903
+ data = (body or {}).get("data", []) or []
904
+ if not data:
905
+ return f"<b>{head}</b>\n\nNo models returned.", back
906
+
907
+ # Plaintext specs for the paste.
908
+ specs = [
909
+ f"Anthropic Models - fetched {datetime.now(timezone.utc).isoformat(timespec='seconds')}",
910
+ "",
911
+ ]
912
+ for m in data:
913
+ specs.append(f"- {m.get('id', '?')}")
914
+ if m.get("display_name"):
915
+ specs.append(f" display_name: {m['display_name']}")
916
+ if m.get("created_at"):
917
+ specs.append(f" created_at: {m['created_at']}")
918
+ if m.get("type"):
919
+ specs.append(f" type: {m['type']}")
920
+ specs_text = "\n".join(specs)
921
+
922
+ paste_url = None
923
+ try:
924
+ okp, pkey = await fns.get_paste(specs_text, extension="txt")
925
+ if okp and pkey:
926
+ paste_url = f"https://spaceb.in/{pkey}"
927
+ except Exception:
928
+ paste_url = None
929
+
930
+ tele_url = None
931
+ try:
932
+ tele_url = await fns.make_html_telegraph(
933
+ "Anthropic Models", f"<pre>{html.escape(specs_text)}</pre>"
934
+ )
935
+ except Exception:
936
+ tele_url = None
937
+
938
+ summary = "\n".join(f"- {html.escape(str(m.get('id', '?')))}" for m in data[:20])
939
+ if len(data) > 20:
940
+ summary += f"\n... and {len(data) - 20} more"
941
+ body_html = f"Fetched {len(data)} model(s):\n\n{summary}"
942
+ if not paste_url and not tele_url:
943
+ body_html += "\n\n( Paste generation failed - full list shown above. )"
944
+
945
+ rows = []
946
+ url_row = []
947
+ if paste_url:
948
+ url_row.append(("Specs Paste", "url", paste_url, "primary"))
949
+ if tele_url:
950
+ url_row.append(("Telegraph", "url", tele_url, "primary"))
951
+ if url_row:
952
+ rows.append(url_row)
953
+ rows.append([_back_btn("claude")])
954
+ return f"<b>{head}</b>\n\n{body_html}", ikm(rows, icon=False)
955
+
956
+
957
+ async def _keys_clear(scope):
958
+ cleared = []
959
+
960
+ def _del(var):
961
+ if udB.get_key(var):
962
+ udB.del_key(var)
963
+ cleared.append(var)
964
+
965
+ if scope in ("llama", "all"):
966
+ for pid in LLAMA_PROVIDERS:
967
+ for f in ("BASE", "MODEL", "CTX", "TEMP", "SYS"):
968
+ _del(f"AGENT_LLAMA_{pid.upper()}_{f}")
969
+ if scope in ("cloud", "all"):
970
+ for pid in CLOUD_PROVIDERS:
971
+ for f in ("KEY", "MODEL", "SYS", "BASE"):
972
+ _del(f"AGENT_CLOUD_{pid.upper()}_{f}")
973
+ if scope in ("claude", "all"):
974
+ for f in ("KEY", "MODEL", "FALLBACK"):
975
+ _del(f"AGENT_CLAUDE_{f}")
976
+ # A pin that outlives its key is a trap: .ai would keep forcing a
977
+ # provider that can no longer authenticate. Drop the pin when the
978
+ # provider it points at just lost its credentials.
979
+ try:
980
+ pinned = agent().config_default_provider()
981
+ if pinned and not agent().config_ready(pinned):
982
+ agent().config_use_default(None)
983
+ except Exception:
984
+ pass
985
+ msg = (
986
+ f"Cleared {len(cleared)} stored credential(s)."
987
+ if cleared
988
+ else "Nothing to clear - no credentials stored for this section."
989
+ )
990
+ return (
991
+ f"<b>Credentials - Cleared</b>\n\n{msg}",
992
+ ikm([[_back_btn("keys")]], icon=False),
993
+ )
994
+
995
+
996
+ async def _syscheck():
997
+ py = platform.python_version()
998
+ plat = platform.platform()
999
+ mem = _mem_info()
1000
+ endpoints = _collect_endpoints()
1001
+
1002
+ async def _one(label, url):
1003
+ ok, _status, body = await _http_get(url, timeout=6)
1004
+ if ok:
1005
+ return label, url, "reachable"
1006
+ return label, url, f"{html.escape(str(body))}"
1007
+
1008
+ reach = (
1009
+ await asyncio.gather(*[_one(label, url) for label, url in endpoints])
1010
+ if endpoints
1011
+ else []
1012
+ )
1013
+
1014
+ lines = [
1015
+ f"Python: <code>{html.escape(py)}</code>",
1016
+ f"Platform: <code>{html.escape(plat)}</code>",
1017
+ f"Memory: <code>{html.escape(mem)}</code>",
1018
+ "",
1019
+ "<b>Endpoint reachability:</b>",
1020
+ ]
1021
+ if reach:
1022
+ for label, url, state in reach:
1023
+ lines.append(
1024
+ f"- {html.escape(label)} - {state} (<code>{html.escape(url)}</code>)"
1025
+ )
1026
+ else:
1027
+ lines.append("- No provider endpoints configured yet.")
1028
+ return (
1029
+ f"<b>System Check</b>\n\n" + "\n".join(lines),
1030
+ ikm([[_back_btn("home")]], icon=False),
1031
+ )
1032
+
1033
+
1034
+ # --------------------------------------------------------------------#
1035
+ # Handlers. CallbackQuery.Event has no .buttons and event.client is the
1036
+ # assistant bot (event.client._bot self-references it); all state is read
1037
+ # from udB, so no get_message() is needed and routing stays on the bot.
1038
+
1039
+
1040
+ @asst_cmd(pattern="agent", owner=True)
1041
+ async def _agent_cmd(event):
1042
+ text, buttons = _home()
1043
+ await send_rich(
1044
+ event.client,
1045
+ event.chat_id,
1046
+ text,
1047
+ buttons=buttons,
1048
+ reply_to=event.id,
1049
+ link_preview=False,
1050
+ )
1051
+
1052
+
1053
+ @callback(MENU_PATTERN, owner=True)
1054
+ async def _menu_handler(event):
1055
+ key = event.data_match.group(1).decode("utf-8")
1056
+ text, buttons = _render_menu(key)
1057
+ if text is None:
1058
+ # A dead path (stale button after a reload of the module tree) must
1059
+ # not just swallow the click; tell the owner and land on home.
1060
+ text, buttons = _home()
1061
+ try:
1062
+ await event.answer(
1063
+ "That screen no longer exists; reopened home.", alert=True
1064
+ )
1065
+ except Exception:
1066
+ pass
1067
+ await edit_callback_page(event, text, buttons)
1068
+ return
1069
+ await event.answer()
1070
+ await edit_callback_page(event, text, buttons)
1071
+
1072
+
1073
+ @callback(CONV_PATTERN, owner=True)
1074
+ async def _conv_handler(event):
1075
+ key = event.data_match.group(1).decode("utf-8")
1076
+ field, _, scope = key.partition(":")
1077
+ meta = _CONV_FIELDS.get(field)
1078
+ if not meta:
1079
+ return
1080
+ label, prompt, validator = meta
1081
+ var = _agent_var(field, scope)
1082
+ back = _conv_back(field, scope)
1083
+ try:
1084
+ await event.answer("Enter a value in the chat.")
1085
+ await event.delete()
1086
+ except Exception:
1087
+ pass
1088
+ async with event.client.conversation(event.sender_id, timeout=120) as conv:
1089
+ await conv.send_message(prompt)
1090
+ try:
1091
+ response = await conv.get_response()
1092
+ except TimeoutError:
1093
+ return await conv.send_message(
1094
+ "Timed out. Please try again.", buttons=get_back_button(back)
1095
+ )
1096
+ value = response.message
1097
+ value_text = str(value).strip()
1098
+ cancel_command = (
1099
+ value_text.split(maxsplit=1)[0].split("@", 1)[0] if value_text else ""
1100
+ )
1101
+ if cancel_command.casefold() == "/cancel":
1102
+ return await conv.send_message("Cancelled.", buttons=get_back_button(back))
1103
+ if validator:
1104
+ try:
1105
+ value = float(value) if validator == "float" else int(value)
1106
+ if validator == "float" and not 0 <= value <= 2:
1107
+ raise ValueError("out of range")
1108
+ except (ValueError, TypeError):
1109
+ return await conv.send_message(
1110
+ f"Invalid value for {label}.",
1111
+ buttons=get_back_button(back),
1112
+ )
1113
+ await setit(event, var, value)
1114
+ if field in _ECHO_FIELDS:
1115
+ shown = f"{value}"
1116
+ elif field.endswith("_key"):
1117
+ shown = " - (masked)"
1118
+ else:
1119
+ shown = "saved"
1120
+ await conv.send_message(
1121
+ f"{label} set to {shown}.", buttons=get_back_button(back)
1122
+ )
1123
+
1124
+
1125
+ @callback(ACT_PATTERN, owner=True)
1126
+ async def _act_handler(event):
1127
+ key = event.data_match.group(1).decode("utf-8")
1128
+ action, _, rest = key.partition(":")
1129
+ if action == "close":
1130
+ try:
1131
+ return await event.delete()
1132
+ except Exception:
1133
+ return await event.answer("Could not close.", alert=True)
1134
+ await event.answer("Working...")
1135
+ if action == "syscheck":
1136
+ text, buttons = await _syscheck()
1137
+ elif action == "llama_fetch":
1138
+ text, buttons = await _llama_fetch(rest)
1139
+ elif action == "cloud_validate":
1140
+ text, buttons = await _cloud_validate(rest)
1141
+ elif action == "cloud_primary":
1142
+ try:
1143
+ if agent().config_default_provider() == rest:
1144
+ agent().config_use_default(None)
1145
+ text, buttons = _cloud_prov(rest)
1146
+ else:
1147
+ agent().config_use_default(rest, require_configured=True)
1148
+ text, buttons = _cloud_prov(rest)
1149
+ except (KeyError, ValueError) as exc:
1150
+ text = body_page(
1151
+ "Primary provider",
1152
+ f"<p>Could not set {html.escape(CLOUD_PROVIDERS.get(rest, rest))} as primary: "
1153
+ f"{html.escape(str(exc))}</p>",
1154
+ )
1155
+ buttons = _cloud_prov_buttons(rest)
1156
+ elif action == "claude_fetch":
1157
+ text, buttons = await _claude_fetch()
1158
+ elif action == "keys_clear":
1159
+ text, buttons = await _keys_clear(rest)
1160
+ else:
1161
+ return
1162
+ if isinstance(text, str):
1163
+ text = body_page("Agent result", text)
1164
+ await edit_callback_page(event, text, buttons)
assistant/agent_bridge.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Routes the user's answer back to whatever the agent is waiting on.
2
+
3
+ This is the half of the ask bridge that was missing: the tool half lives in
4
+ :mod:pyUltroid.agent._interactive and puts a styled keyboard on the Bot, but
5
+ a tap on that keyboard and a typed reply both have to arrive back here to
6
+ settle the future the tool is blocked on.
7
+
8
+ Two handlers, both deliberately unfiltered:
9
+
10
+ * every CallbackQuery is offered to the bridge, which claims only the
11
+ data it minted and ignores the rest - the assistant's own menu buttons share
12
+ the same dispatcher, so this must be a filter and not a pattern;
13
+ * every private inbound text message is offered as a typed answer to the
14
+ oldest open question in that chat, and is otherwise left completely alone,
15
+ so the PM bot and the session threads keep owning their own flows.
16
+
17
+ The client note matters: Telegram does not deliver a callback query for a
18
+ message the *User* account sent itself. That is why the question goes out on
19
+ the Bot in the first place, and why this file binds bot=asst.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Any
25
+
26
+ from telethon import events
27
+
28
+ from pyUltroid import asst
29
+ from pyUltroid.startup.logger import LOGS
30
+ from pyUltroid.agent._bridge import AskBridge, shared_bridge
31
+ from pyUltroid.agent._telegram import text_of
32
+
33
+ __res_tags__ = ["ai", "agent", "bridge"]
34
+ _REGISTERED = False
35
+
36
+
37
+ def _bridge() -> AskBridge:
38
+ """The process-wide bridge, bound to the bot that paints the keyboards."""
39
+ bridge = shared_bridge()
40
+ bridge.attach(bot=asst)
41
+ return bridge
42
+
43
+
44
+ async def on_ask_callback(event: Any) -> None:
45
+ """Settle the question whose button was tapped."""
46
+ data = getattr(event, "data", None)
47
+ if not data:
48
+ return
49
+ bridge = _bridge()
50
+ if not bridge.owns(data):
51
+ return
52
+ try:
53
+ outcome = bridge.resolve_callback(data)
54
+ except Exception as exc: # noqa: BLE001 - one bad tap must not kill the bot
55
+ LOGS.exception("[agent/bridge] callback resolve failed: %s", exc)
56
+ return
57
+ if outcome is None:
58
+ return
59
+ # The keyboard has served its purpose; take it off the message so a second
60
+ # tap cannot re-answer a question that is already settled.
61
+ try:
62
+ await event.delete()
63
+ except Exception: # noqa: BLE001 - deleting is cosmetic
64
+ pass
65
+ LOGS.info(
66
+ "[agent/bridge] answered %r via button after %.1fs",
67
+ outcome.question[:60],
68
+ outcome.waited,
69
+ )
70
+ raise events.StopPropagation
71
+
72
+
73
+ async def on_ask_reply(event: Any) -> None:
74
+ """Settle the oldest open question in this chat with typed text."""
75
+ bridge = _bridge()
76
+ if bridge.pending == 0:
77
+ return
78
+ text = text_of(getattr(event, "message", event), "").strip()
79
+ if not text:
80
+ return
81
+ try:
82
+ outcome = bridge.submit_text(event.chat_id, text)
83
+ except Exception as exc: # noqa: BLE001
84
+ LOGS.exception("[agent/bridge] text resolve failed: %s", exc)
85
+ return
86
+ if outcome is not None:
87
+ LOGS.info(
88
+ "[agent/bridge] answered %r by text after %.1fs",
89
+ outcome.question[:60],
90
+ outcome.waited,
91
+ )
92
+ raise events.StopPropagation
93
+
94
+
95
+ def register() -> None:
96
+ """Bind the clients and attach both handlers to the bot."""
97
+ global _REGISTERED
98
+ if _REGISTERED or asst is None:
99
+ return
100
+ _bridge()
101
+ asst.add_event_handler(on_ask_callback, events.CallbackQuery())
102
+ asst.add_event_handler(
103
+ on_ask_reply,
104
+ events.NewMessage(incoming=True, func=lambda e: bool(e.is_private)),
105
+ )
106
+ _REGISTERED = True
107
+ LOGS.info("[agent/bridge] ask bridge wired to the assistant bot")
108
+
109
+
110
+ register()
assistant/ai_dm.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Agent sessions in the assistant bot's DM, one reply thread per session.
2
+
3
+ A session-start card anchors a reply thread. Replies to that anchor continue
4
+ only that session; ordinary private messages and commands remain available to
5
+ the PM bot and other assistant handlers.
6
+
7
+ Session metadata is stored under ``AGENT_DM_SESSIONS_<user_id>`` and each
8
+ conversation uses a typed ``dm:<user_id>:<anchor>`` key, keeping sessions
9
+ separate across users and restarts.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ import time
16
+ from typing import Any
17
+
18
+ from telethon import events
19
+
20
+ from pyUltroid import asst
21
+ from pyUltroid._core.richmsg import (
22
+ RichBlocks,
23
+ client_can_send_rich_message,
24
+ send_rich,
25
+ )
26
+ from pyUltroid._misc._assistant import asst_cmd
27
+ from pyUltroid.agent import AgentRequest, agent
28
+ from pyUltroid.agent import controls as ai_controls
29
+ from pyUltroid.agent._chatkey import DmSessionKey
30
+ from pyUltroid.agent._delivery import DeliveryError as _DeliveryError
31
+ from pyUltroid.agent._delivery import DeliveryStrategy as _SessionDelivery
32
+ from pyUltroid.agent._reporting import report_run
33
+ from pyUltroid.agent._sessions import SessionStoreError
34
+ from pyUltroid.startup.logger import LOGS as _LOGS
35
+
36
+ __res_tags__ = ["ai", "agent", "sessions"]
37
+
38
+ # Only strip a command at the beginning of the message. Never remove text that
39
+ # merely happens to contain "/ai" later in the user's prompt.
40
+ _AI_PREFIX = re.compile(r"^/ai(?:@\w+)?(?:\s+|$)", re.IGNORECASE)
41
+
42
+
43
+ async def send_session_card(user_id: Any, title: str) -> Any:
44
+ """Send the session-start card; its message is the session anchor."""
45
+ blocks = (
46
+ RichBlocks()
47
+ .header("AI session", level=3)
48
+ .header(str(title), level=4)
49
+ .paragraph(
50
+ "Reply to this message to continue this session. "
51
+ "Each session has its own conversation history."
52
+ )
53
+ )
54
+ return await send_rich(asst, user_id, blocks)
55
+
56
+
57
+ async def _send_session_list(event: Any, sessions: list[dict]) -> Any:
58
+ """Render a readable, consistently indented session index."""
59
+ items = []
60
+ for session in sessions:
61
+ when = time.strftime("%Y-%m-%d %H:%M", time.gmtime(session.get("created", 0)))
62
+ title = str(session.get("title") or "Untitled session")
63
+ anchor = session.get("anchor")
64
+ items.append(f"{title} — {when} (reply to message {anchor})")
65
+
66
+ blocks = RichBlocks().header("Your AI sessions", level=2).list(items)
67
+ return await send_rich(
68
+ event.client,
69
+ event.chat_id,
70
+ blocks,
71
+ reply_to=event,
72
+ link_preview=False,
73
+ )
74
+
75
+
76
+ @asst_cmd("ai")
77
+ async def dm_ai_cmd(event):
78
+ """Start an AI session or continue the session card being replied to."""
79
+ if not event.is_private:
80
+ return
81
+ user_id = event.sender_id
82
+ prompt = _AI_PREFIX.sub("", (event.raw_text or "").strip(), count=1).strip()
83
+
84
+ reply = await event.get_reply_message()
85
+ session = _session_for_reply(user_id, reply) if reply is not None else None
86
+
87
+ if session is None:
88
+ title = (prompt or "New session")[:60]
89
+ card = await send_session_card(user_id, title)
90
+ try:
91
+ agent().session_create(user_id, card.id, title)
92
+ except SessionStoreError:
93
+ return await event.reply(
94
+ "This session could not be saved, so it cannot be continued later. "
95
+ "Please try again."
96
+ )
97
+ anchor = card.id
98
+ else:
99
+ anchor = session["anchor"]
100
+
101
+ if not prompt:
102
+ return await event.reply(
103
+ "Reply to the session card with a prompt, or send /ai <prompt> "
104
+ "to start a new session."
105
+ )
106
+
107
+ await _run_session(event, user_id, anchor, prompt)
108
+
109
+
110
+ @asst_cmd("sessions")
111
+ async def dm_sessions_cmd(event):
112
+ """List this user's AI sessions in the assistant bot's private chat."""
113
+ if not event.is_private:
114
+ return
115
+ sessions = agent().session_list(event.sender_id)
116
+ if not sessions:
117
+ return await event.reply("No sessions yet. Start one with /ai <prompt>.")
118
+ return await _send_session_list(event, sessions)
119
+
120
+
121
+ @asst.on(
122
+ events.NewMessage(
123
+ incoming=True,
124
+ func=lambda event: (
125
+ event.is_private
126
+ and event.is_reply
127
+ and bool((event.raw_text or "").strip())
128
+ and not (event.raw_text or "").lstrip().startswith("/")
129
+ ),
130
+ )
131
+ )
132
+ async def dm_thread_handler(event):
133
+ """Continue only the session associated with the replied-to anchor."""
134
+ user_id = event.sender_id
135
+ session = agent().session_find(user_id, event.reply_to_msg_id)
136
+ if session is None:
137
+ session = _session_for_reply(user_id, await event.get_reply_message())
138
+ if session is None:
139
+ return
140
+ anchor = session["anchor"]
141
+ try:
142
+ await _run_session(event, user_id, anchor, (event.raw_text or "").strip())
143
+ except Exception: # noqa: BLE001 - outer Telegram handler boundary
144
+ _LOGS.error("[agent/dm] session reply failed")
145
+ try:
146
+ await event.reply(
147
+ "This AI session could not process that reply. "
148
+ "Try again or start a new session."
149
+ )
150
+ except Exception: # noqa: BLE001 - failure notice is best-effort
151
+ _LOGS.error("[agent/dm] session error notice could not be sent")
152
+ raise events.StopPropagation
153
+
154
+
155
+ async def _run_session(event: Any, user_id: Any, anchor: int, prompt: str) -> None:
156
+ """Run one agent turn and deliver it in the session's reply thread."""
157
+ key = DmSessionKey(user_id, anchor).value
158
+ controls = ai_controls.get_controls(f"dm:{user_id}")
159
+ started = time.time()
160
+ delivery = _SessionDelivery(event, anchor=anchor)
161
+ rich_allowed = await client_can_send_rich_message(event.client)
162
+ try:
163
+ status = await delivery.placeholder()
164
+ except _DeliveryError as exc:
165
+ return await event.reply(
166
+ f"Could not open session {anchor}: delivery failed at {exc.phase}. "
167
+ "Start a new session with /ai <prompt>."
168
+ )
169
+
170
+ try:
171
+ response = await agent().runtime_run(
172
+ AgentRequest(
173
+ prompt=prompt,
174
+ chat_id=key,
175
+ origin="dm-session",
176
+ user_id=user_id,
177
+ is_private=True,
178
+ use_tools=ai_controls.dm_tools_enabled(user_id, controls),
179
+ max_rounds=controls["rounds"],
180
+ model=controls["model"],
181
+ temperature=controls["temp"],
182
+ use_cache=True,
183
+ rich_messages_allowed=rich_allowed,
184
+ timeout_seconds=105.0,
185
+ )
186
+ )
187
+ except Exception: # noqa: BLE001 - report unexpected runtime/provider failures
188
+ _LOGS.error("[agent/dm] runtime failed")
189
+ try:
190
+ await delivery.render(
191
+ status,
192
+ "This session could not complete the request. Please try again.",
193
+ )
194
+ except _DeliveryError:
195
+ _LOGS.error("[agent/dm] runtime failure notice could not be delivered")
196
+ return
197
+
198
+ report_run(
199
+ origin="dm-session",
200
+ chat_id=event.chat_id,
201
+ user=getattr(getattr(event, "sender", None), "username", None),
202
+ provider=response.provider,
203
+ model=response.model,
204
+ prompt=prompt,
205
+ tools_used=list(getattr(response, "tools_used", None) or []),
206
+ duration=time.time() - started,
207
+ ok=response.ok,
208
+ error=getattr(response, "error", None),
209
+ )
210
+ try:
211
+ await delivery.render(status, response)
212
+ except _DeliveryError as exc:
213
+ await event.reply(
214
+ f"Could not deliver response {anchor}: delivery failed at {exc.phase}."
215
+ )
216
+
217
+
218
+ def _session_for_reply(user_id: Any, reply: Any) -> dict | None:
219
+ """Resolve replies to either a session anchor or a result in its thread."""
220
+ store = agent()
221
+ message_id = getattr(reply, "id", None)
222
+ session = store.session_find(user_id, message_id)
223
+ if session is not None:
224
+ return session
225
+ header = getattr(reply, "reply_to", None)
226
+ # Telethon retains thread root metadata on replies even when the directly
227
+ # replied-to result has scrolled out of cache.
228
+ for candidate in (
229
+ getattr(reply, "reply_to_top_id", None),
230
+ getattr(header, "reply_to_top_id", None),
231
+ getattr(reply, "reply_to_msg_id", None),
232
+ getattr(header, "reply_to_msg_id", None),
233
+ ):
234
+ if candidate:
235
+ session = store.session_find(user_id, candidate)
236
+ if session is not None:
237
+ return session
238
+ return None
assistant/callbackstuffs.py CHANGED
@@ -1,5 +1,5 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
@@ -7,11 +7,11 @@
7
 
8
  import ast
9
  import asyncio
10
- import re
11
- import sys
12
  import time
 
13
  from asyncio.exceptions import TimeoutError as AsyncTimeOut
14
- from os import execl, remove
 
15
  from random import choice
16
 
17
  from bs4 import BeautifulSoup as bs
@@ -20,22 +20,295 @@ try:
20
  from pyUltroid.fns.gDrive import GDriveManager
21
  except ImportError:
22
  GDriveManager = None
23
- from telethon import Button, events
24
- from catbox import CatboxUploader
 
25
  from telethon.tl.types import MessageMediaWebPage
26
  from telethon.utils import get_peer_id
27
 
28
- from pyUltroid.fns.helper import fast_download, progress
29
- from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
30
- from pyUltroid.startup.loader import Loader
 
 
31
 
32
  from . import *
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- # --------------------------------------------------------------------#
35
- telegraph = telegraph_client()
36
- GDrive = GDriveManager() if GDriveManager else None
37
- uploader = CatboxUploader()
38
- # --------------------------------------------------------------------#
39
 
40
  def text_to_url(event):
41
  """function to get media url (with|without) Webpage"""
@@ -46,190 +319,333 @@ def text_to_url(event):
46
  return event.text
47
 
48
 
49
- # --------------------------------------------------------------------#
50
-
51
  _buttons = {
52
- "otvars": {
53
- "text": "Other Variables to set for @TeamUltroid:",
54
- "buttons": [
55
- [
56
- Button.inline("Tᴀɢ Lᴏɢɢᴇʀ", data="taglog"),
57
- Button.inline("SᴜᴘᴇʀFʙᴀɴ", data="cbs_sfban"),
58
- ],
59
- [
60
- Button.inline("Sudo Mode", data="sudo"),
61
- Button.inline("Handler", data="hhndlr"),
62
- ],
63
- [
64
- Button.inline("Extra Plugins", data="plg"),
65
- Button.inline("Addons", data="eaddon"),
66
- ],
67
  [
68
- Button.inline("Emoji in Help", data="emoj"),
69
- Button.inline("Set gDrive", data="gdrive"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  ],
 
 
 
 
 
 
 
 
71
  [
72
- Button.inline("Inline Pic", data="inli_pic"),
73
- Button.inline("Sudo HNDLR", data="shndlr"),
 
74
  ],
75
- [Button.inline("Dual Mode", "cbs_oofdm")],
76
- [Button.inline("« Back", data="setter")],
77
- ],
78
- },
79
- "sfban": {
80
- "text": "SuperFban Settings:",
81
- "buttons": [
82
- [Button.inline("FBᴀɴ Gʀᴏᴜᴘ", data="sfgrp")],
83
- [Button.inline("Exᴄʟᴜᴅᴇ Fᴇᴅs", data="abs_sfexf")],
84
- [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")],
85
- ],
86
  },
87
  "apauto": {
88
  "text": "This'll auto approve on outgoing messages",
89
- "buttons": [
90
- [Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ ON", data="apon")],
91
- [Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ OFF", data="apof")],
92
- [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")],
93
- ],
94
- },
95
- "alvcstm": {
96
- "text": f"Customise your {HNDLR}alive. Choose from the below options -",
97
- "buttons": [
98
- [Button.inline("Aʟɪᴠᴇ Tᴇxᴛ", data="abs_alvtx")],
99
- [Button.inline("Aʟɪᴠᴇ ᴍᴇᴅɪᴀ", data="alvmed")],
100
- [Button.inline("Dᴇʟᴇᴛᴇ Aʟɪᴠᴇ Mᴇᴅɪᴀ", data="delmed")],
101
- [Button.inline("« Bᴀᴄᴋ", data="setter")],
102
- ],
103
- },
104
- "pmcstm": {
105
- "text": "Customise your PMPERMIT Settings -",
106
- "buttons": [
107
  [
108
- Button.inline("Pᴍ Tᴇxᴛ", data="pmtxt"),
109
- Button.inline("Pᴍ Mᴇᴅɪᴀ", data="pmmed"),
 
110
  ],
 
 
 
 
 
 
 
 
111
  [
112
- Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ", data="cbs_apauto"),
113
- Button.inline("PMLOGGER", data="pml"),
 
 
114
  ],
 
 
 
 
 
 
 
115
  [
116
- Button.inline("Sᴇᴛ Wᴀʀɴs", data="swarn"),
117
- Button.inline("Dᴇʟᴇᴛᴇ Pᴍ Mᴇᴅɪᴀ", data="delpmmed"),
 
 
 
 
 
 
 
 
 
 
 
 
118
  ],
119
- [Button.inline("PMPermit Type", data="cbs_pmtype")],
120
- [Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")],
121
- ],
122
  },
123
- "pmtype": {
124
- "text": "Select the type of PMPermit needed.",
125
- "buttons": [
126
- [Button.inline("Inline", data="inpm_in")],
127
- [Button.inline("Normal", data="inpm_no")],
128
- [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")],
129
- ],
 
 
 
 
 
 
 
130
  },
131
- "ppmset": {
132
- "text": "PMPermit Settings:",
133
- "buttons": [
134
- [Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oɴ", data="pmon")],
135
- [Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oғғ", data="pmoff")],
136
- [Button.inline("Cᴜsᴛᴏᴍɪᴢᴇ PMPᴇʀᴍɪᴛ", data="cbs_pmcstm")],
137
- [Button.inline("« Bᴀᴄᴋ", data="setter")],
138
- ],
 
 
 
 
 
139
  },
140
  "chatbot": {
141
- "text": "From This Feature U can chat with ppls Via ur Assistant Bot.\n[More info](https://t.me/UltroidUpdates/2)",
142
- "buttons": [
 
 
 
 
 
 
 
143
  [
144
- Button.inline("Cʜᴀᴛ Bᴏᴛ Oɴ", data="onchbot"),
145
- Button.inline("Cʜᴀᴛ Bᴏᴛ Oғғ", data="ofchbot"),
 
 
 
 
 
 
 
 
 
146
  ],
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  [
148
- Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ", data="bwel"),
149
- Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ Mᴇᴅɪᴀ", data="botmew"),
150
  ],
151
- [Button.inline("Bᴏᴛ Iɴғᴏ Tᴇxᴛ", data="botinfe")],
152
- [Button.inline("Fᴏʀᴄᴇ Sᴜʙsᴄʀɪʙᴇ", data="pmfs")],
153
- [Button.inline("« Bᴀ��ᴋ", data="setter")],
154
- ],
155
- },
156
- "vcb": {
157
- "text": "From This Feature U can play songs in group voice chat\n\n[moreinfo](https://t.me/UltroidUpdates/4)",
158
- "buttons": [
159
- [Button.inline("VC Sᴇssɪᴏɴ", data="abs_vcs")],
160
- [Button.inline("« Bᴀᴄᴋ", data="setter")],
161
- ],
162
  },
163
- "oofdm": {
164
- "text": "About [Dual Mode](https://t.me/UltroidUpdates/18)",
165
- "buttons": [
 
 
 
 
 
 
166
  [
167
- Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oɴ", "dmof"),
168
- Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oғғ", "dmof"),
 
 
 
 
169
  ],
170
- [Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Hɴᴅʟʀ", "dmhn")],
171
- [Button.inline("« Back", data="cbs_otvars")],
172
- ],
173
  },
174
  "apiset": {
175
- "text": get_string("ast_1"),
176
- "buttons": [
177
- [Button.inline("Remove.bg API", data="abs_rmbg")],
178
- [Button.inline("DEEP API", data="abs_dapi")],
179
- [Button.inline("OCR API", data="abs_oapi")],
180
- [Button.inline("« Back", data="setter")],
181
- ],
 
 
 
 
 
 
 
 
 
182
  },
183
  }
184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  _convo = {
186
- "rmbg": {
187
  "var": "RMBG_API",
188
  "name": "Remove.bg API Key",
189
  "text": get_string("ast_2"),
190
- "back": "cbs_apiset",
191
  },
192
- "dapi": {
193
  "var": "DEEP_AI",
194
  "name": "Deep AI Api Key",
195
  "text": "Get Your Deep Api from deepai.org and send here.",
196
- "back": "cbs_apiset",
197
  },
198
- "oapi": {
199
  "var": "OCR_API",
200
  "name": "Ocr Api Key",
201
  "text": "Get Your OCR api from ocr.space and send that Here.",
202
- "back": "cbs_apiset",
 
 
 
 
 
 
203
  },
204
- "pmlgg": {
205
  "var": "PMLOGGROUP",
206
  "name": "Pm Log Group",
207
  "text": "Send chat id of chat which you want to save as Pm log Group.",
208
- "back": "pml",
209
  },
210
- "vcs": {
211
  "var": "VC_SESSION",
212
  "name": "Vc Session",
213
  "text": "**Vc session**\nEnter the New session u generated for vc bot.\n\nUse /cancel to terminate the operation.",
214
- "back": "cbs_vcb",
215
  },
216
- "settag": {
217
  "var": "TAG_LOG",
218
  "name": "Tag Log Group",
219
- "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.",
220
- "back": "taglog",
221
  },
222
- "alvtx": {
223
  "var": "ALIVE_TEXT",
224
  "name": "Alive Text",
225
  "text": "**Alive Text**\nEnter the new alive text.\n\nUse /cancel to terminate the operation.",
226
- "back": "cbs_alvcstm",
227
  },
228
- "sfexf": {
229
  "var": "EXCLUDE_FED",
230
  "name": "Excluded Fed",
231
- "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.",
232
- "back": "cbs_sfban",
233
  },
234
  }
235
 
@@ -237,189 +653,265 @@ _convo = {
237
  TOKEN_FILE = "resources/auths/auth_token.txt"
238
 
239
 
240
- @callback(
241
- re.compile(
242
- "sndplug_(.*)",
243
- ),
244
- owner=True,
245
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  async def send(eve):
247
- key, name = (eve.data_match.group(1)).decode("UTF-8").split("_")
248
- thumb = "resources/extras/inline.jpg"
249
- await eve.answer("■ Sending ■")
250
- data = f"uh_{key}_"
251
- index = None
252
- if "|" in name:
253
- name, index = name.split("|")
254
- key = "plugins" if key == "Official" else key.lower()
255
- plugin = f"{key}/{name}.py"
256
- _ = f"pasta-{plugin}"
 
 
 
257
  if index is not None:
258
- data += f"|{index}"
259
- _ += f"|{index}"
260
- buttons = [
261
- [
262
- Button.inline(
263
- "« Pᴀsᴛᴇ »",
264
- data=_,
265
- )
266
- ],
267
- [
268
- Button.inline("« Bᴀᴄᴋ", data=data),
269
- ],
270
- ]
271
  try:
272
- await eve.edit(file=plugin, thumb=thumb, buttons=buttons)
273
- except Exception as er:
274
- await eve.answer(str(er), alert=True)
 
 
 
 
 
 
 
 
 
 
275
 
276
 
277
  heroku_api, app_name = Var.HEROKU_API, Var.HEROKU_APP_NAME
278
 
279
 
280
- @callback("updatenow", owner=True)
281
  async def update(eve):
282
- repo = Repo()
283
- ac_br = repo.active_branch
284
- ups_rem = repo.remote("upstream")
285
- if heroku_api:
286
- import heroku3
287
 
288
- try:
289
- heroku = heroku3.from_key(heroku_api)
290
- heroku_app = None
291
- heroku_applications = heroku.apps()
292
- except BaseException as er:
293
- LOGS.exception(er)
294
- return await eve.edit("`Wrong HEROKU_API.`")
295
- for app in heroku_applications:
296
- if app.name == app_name:
297
- heroku_app = app
298
- if not heroku_app:
299
- await eve.edit("`Wrong HEROKU_APP_NAME.`")
300
- repo.__del__()
301
- return
302
- await eve.edit(get_string("clst_1"))
303
- ups_rem.fetch(ac_br)
304
- repo.git.reset("--hard", "FETCH_HEAD")
305
- heroku_git_url = heroku_app.git_url.replace(
306
- "https://", f"https://api:{heroku_api}@"
307
- )
308
 
309
- if "heroku" in repo.remotes:
310
- remote = repo.remote("heroku")
311
- remote.set_url(heroku_git_url)
312
- else:
313
- remote = repo.create_remote("heroku", heroku_git_url)
314
- try:
315
- remote.push(refspec=f"HEAD:refs/heads/{ac_br}", force=True)
316
- except GitCommandError as error:
317
- await eve.edit(f"`Here is the error log:\n{error}`")
318
- repo.__del__()
319
- return
320
- await eve.edit("`Successfully Updated!\nRestarting, please wait...`")
321
- else:
322
- await eve.edit(get_string("clst_1"))
323
- call_back()
324
- await bash("git pull && pip3 install -r requirements.txt")
325
- await bash("pip3 install -r requirements.txt --break-system-packages")
326
- execl(sys.executable, sys.executable, "-m", "pyUltroid")
327
-
328
- @callback(re.compile("changes(.*)"), owner=True)
329
- async def changes(okk):
330
- match = okk.data_match.group(1).decode("utf-8")
331
- await okk.answer(get_string("clst_3"))
332
- repo = Repo.init()
333
- button = [[Button.inline("Update Now", data="updatenow")]]
334
- changelog, tl_chnglog = await gen_chlog(
335
- repo, f"HEAD..upstream/{repo.active_branch}"
336
  )
337
- cli = "\n\nClick the below button to update!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
  if not match:
339
  try:
340
  if len(tl_chnglog) > 700:
341
  tl_chnglog = f"{tl_chnglog[:700]}..."
342
- button.append([Button.inline("View Complete", "changesall")])
343
- await okk.edit("• Writing Changelogs 📝 •")
344
- img = await Carbon(
 
 
 
 
 
 
 
 
 
 
 
 
345
  file_name="changelog",
346
  code=tl_chnglog,
347
  backgroundColor=choice(ATRA_COL),
348
  language="md",
349
  )
350
- return await okk.edit(
351
- f"**• Ultroid Userbot •**{cli}", file=img, buttons=button
 
 
 
352
  )
353
  except Exception as er:
354
  LOGS.exception(er)
355
- changelog_str = changelog + cli
 
 
 
356
  if len(changelog_str) > 1024:
357
- await okk.edit(get_string("upd_4"))
 
 
 
358
  await asyncio.sleep(2)
359
  with open("ultroid_updates.txt", "w+") as file:
360
  file.write(tl_chnglog)
361
- await okk.edit(
362
- get_string("upd_5"),
363
  file="ultroid_updates.txt",
364
  buttons=button,
365
  )
366
  remove("ultroid_updates.txt")
367
  return
368
- await okk.edit(
369
- changelog_str,
 
 
 
 
370
  buttons=button,
371
  parse_mode="html",
372
  )
373
 
374
 
375
- @callback(
376
- re.compile(
377
- "pasta-(.*)",
378
- ),
379
- owner=True,
380
- )
381
  async def _(e):
 
382
  ok = (e.data_match.group(1)).decode("UTF-8")
383
  index = None
384
  if "|" in ok:
385
  ok, index = ok.split("|")
386
- with open(ok, "r") as hmm:
387
- _, data = await get_paste(hmm.read())
388
- if not data.get("link"):
 
 
389
  return await e.answer(key[:30], alert=True)
390
- if not key.startswith("http"):
391
- link, raw = data["link"], data["raw"]
392
- else:
393
- link = key
394
- raw = f"{key}/raw"
395
  if ok.startswith("addons"):
396
  key = "Addons"
397
- elif ok.startswith("vcbot"):
398
  key = "VCBot"
399
  else:
400
  key = "Official"
401
- data = f"uh_{key}_"
402
- if index is not None:
403
- data += f"|{index}"
 
404
  await e.edit(
405
  "",
406
- buttons=[
407
- [Button.url("Lɪɴᴋ", link), Button.url("Rᴀᴡ", raw)],
408
- [Button.inline("« Bᴀᴄᴋ", data=data)],
409
- ],
 
 
 
 
 
 
410
  )
411
 
412
 
413
- @callback(re.compile("cbs_(.*)"), owner=True)
414
  async def _edit_to(event):
415
  match = event.data_match.group(1).decode("utf-8")
416
- data = _buttons.get(match)
417
- if not data:
418
  return
419
- await event.edit(data["text"], buttons=data["buttons"], link_preview=False)
 
 
 
 
 
 
 
 
 
 
 
420
 
421
 
422
- @callback(re.compile("abs_(.*)"), owner=True)
423
  async def convo_handler(event: events.CallbackQuery):
424
  match = event.data_match.group(1).decode("utf-8")
425
  if not _convo.get(match):
@@ -428,44 +920,93 @@ async def convo_handler(event: events.CallbackQuery):
428
  get_ = _convo[match]
429
  back = get_["back"]
430
  async with event.client.conversation(event.sender_id) as conv:
431
- await conv.send_message(get_["text"])
432
- response = await conv.get_response()
433
- themssg = response.message
 
 
 
 
 
 
 
 
 
 
434
  try:
435
  themssg = ast.literal_eval(themssg)
436
  except Exception:
437
  pass
438
- if themssg == "/cancel":
439
- return await conv.send_message(
440
- "Cancelled!!",
 
 
 
 
 
 
 
441
  buttons=get_back_button(back),
 
442
  )
443
  await setit(event, get_["var"], themssg)
444
- await conv.send_message(
445
- f"{get_['name']} changed to `{themssg}`",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446
  buttons=get_back_button(back),
 
447
  )
448
 
449
 
450
- @callback("authorise", owner=True)
451
  async def _(e):
452
  if not e.is_private:
453
  return
 
 
 
 
 
454
  url = GDrive._create_token_file()
455
- await e.edit("Go to the below link and send the code!")
 
 
 
456
  async with asst.conversation(e.sender_id) as conv:
457
  await conv.send_message(url)
458
  code = await conv.get_response()
459
  if GDrive._create_token_file(code=code.text):
460
  await conv.send_message(
461
- "`Success!\nYou are all set to use Google Drive with Ultroid Userbot.`",
462
- buttons=Button.inline("Main Menu", data="setter"),
 
 
 
 
463
  )
464
  else:
465
- await conv.send_message("Wrong code! Click authorise again.")
 
 
 
466
 
467
 
468
- @callback("folderid", owner=True, func=lambda x: x.is_private)
469
  async def _(e):
470
  if not e.is_private:
471
  return
@@ -479,48 +1020,75 @@ async def _(e):
479
  )
480
  await e.delete()
481
  async with asst.conversation(e.sender_id, timeout=150) as conv:
482
- await conv.send_message(msg)
 
 
 
483
  repl = await conv.get_response()
484
  id = repl.text
485
  if id.startswith("https"):
486
  id = id.split("?id=")[-1]
487
  udB.set_key("GDRIVE_FOLDER_ID", id)
488
  await repl.reply(
489
- "`Success.`",
490
- buttons=get_back_button("gdrive"),
 
491
  )
492
 
493
 
494
- @callback("gdrive", owner=True)
495
  async def _(e):
496
  if not e.is_private:
497
  return
498
  await e.edit(
499
- "Click Authorise and send the code.\n\nYou can use your own CLIENT ID and SECRET by [this](https://t.me/UltroidUpdates/37)",
500
- buttons=[
 
 
 
 
 
 
 
 
501
  [
502
- Button.inline("Folder ID", data="folderid"),
503
- Button.inline("Authorise", data="authorise"),
 
 
 
504
  ],
505
- [Button.inline("« Back", data="cbs_otvars")],
506
- ],
507
  link_preview=False,
508
  )
509
 
510
 
511
- @callback("dmof", owner=True)
512
  async def rhwhe(e):
513
- if udB.get_key("DUAL_MODE"):
514
- udB.del_key("DUAL_MODE")
515
- key = "Off"
516
- else:
517
- udB.set_key("DUAL_MODE", "True")
518
- key = "On"
519
- Msg = f"Dual Mode : {key}"
520
- await e.edit(Msg, buttons=get_back_button("cbs_otvars"))
 
 
 
 
 
 
 
 
 
 
 
 
521
 
522
 
523
- @callback("dmhn", owner=True)
524
  async def hndlrr(event):
525
  await event.delete()
526
  pru = event.sender_id
@@ -529,59 +1097,75 @@ async def hndlrr(event):
529
  CH = udB.get_key(var) or "/"
530
  async with event.client.conversation(pru) as conv:
531
  await conv.send_message(
532
- 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.",
 
 
 
 
533
  )
534
  response = conv.wait_event(events.NewMessage(chats=pru))
535
  response = await response
536
  themssg = response.message.message
537
- if themssg == "/cancel":
538
  await conv.send_message(
539
- "Cancelled!!",
540
- buttons=get_back_button("cbs_otvars"),
 
541
  )
542
  elif len(themssg) > 1:
543
  await conv.send_message(
544
- "Incorrect Handler",
545
- buttons=get_back_button("cbs_otvars"),
 
546
  )
547
  else:
548
  await setit(event, var, themssg)
549
  await conv.send_message(
550
- f"{name} changed to {themssg}",
551
- buttons=get_back_button("cbs_otvars"),
 
552
  )
553
 
554
 
555
- @callback("emoj", owner=True)
556
- async def emoji(event):
557
  await event.delete()
558
  pru = event.sender_id
559
  var = "EMOJI_IN_HELP"
560
- name = f"Emoji in `{HNDLR}help` menu"
561
  async with event.client.conversation(pru) as conv:
562
- await conv.send_message("Send emoji u want to set 🙃.\n\nUse /cancel to cancel.")
 
 
 
 
 
 
563
  response = conv.wait_event(events.NewMessage(chats=pru))
564
  response = await response
565
  themssg = response.message.message
566
- if themssg == "/cancel":
567
  await conv.send_message(
568
- "Cancelled!!",
569
- buttons=get_back_button("cbs_otvars"),
 
570
  )
571
  elif themssg.startswith(("/", HNDLR)):
572
  await conv.send_message(
573
- "Incorrect Emoji",
574
- buttons=get_back_button("cbs_otvars"),
 
575
  )
576
  else:
577
  await setit(event, var, themssg)
578
  await conv.send_message(
579
- f"{name} changed to {themssg}\n",
580
- buttons=get_back_button("cbs_otvars"),
 
581
  )
582
 
583
 
584
- @callback("plg", owner=True)
585
  async def pluginch(event):
586
  await event.delete()
587
  pru = event.sender_id
@@ -589,66 +1173,86 @@ async def pluginch(event):
589
  name = "Plugin Channel"
590
  async with event.client.conversation(pru) as conv:
591
  await conv.send_message(
592
- "Send id or username of a channel from where u want to install all plugins\n\nOur Channel~ @ultroidplugins\n\nUse /cancel to cancel.",
 
 
 
 
593
  )
594
  response = conv.wait_event(events.NewMessage(chats=pru))
595
  response = await response
596
  themssg = response.message.message
597
- if themssg == "/cancel":
598
  await conv.send_message(
599
- "Cancelled!!",
600
- buttons=get_back_button("cbs_otvars"),
 
601
  )
602
  elif themssg.startswith(("/", HNDLR)):
603
  await conv.send_message(
604
- "Incorrect channel",
605
- buttons=get_back_button("cbs_otvars"),
 
606
  )
607
  else:
608
  await setit(event, var, themssg)
609
  await conv.send_message(
610
- f"{name} changed to {themssg}\n After Setting All Things Do Restart",
611
- buttons=get_back_button("cbs_otvars"),
 
 
 
 
 
612
  )
613
 
614
 
615
- @callback("hhndlr", owner=True)
616
  async def hndlrr(event):
617
  await event.delete()
618
  pru = event.sender_id
619
  var = "HNDLR"
620
- name = "Handler/ Trigger"
621
  async with event.client.conversation(pru) as conv:
622
  await conv.send_message(
623
- f"Send The Symbol Which u want as Handler/Trigger to use bot\nUr Current Handler is [ `{HNDLR}` ]\n\n use /cancel to cancel.",
 
 
 
 
 
624
  )
625
  response = conv.wait_event(events.NewMessage(chats=pru))
626
  response = await response
627
  themssg = response.message.message
628
- if themssg == "/cancel":
629
  await conv.send_message(
630
- "Cancelled!!",
631
- buttons=get_back_button("cbs_otvars"),
 
632
  )
633
  elif len(themssg) > 1:
634
  await conv.send_message(
635
- "Incorrect Handler",
636
- buttons=get_back_button("cbs_otvars"),
 
637
  )
638
  elif themssg.startswith(("/", "#", "@")):
639
  await conv.send_message(
640
- "This cannot be used as handler",
641
- buttons=get_back_button("cbs_otvars"),
 
642
  )
643
  else:
644
  await setit(event, var, themssg)
645
  await conv.send_message(
646
- f"{name} changed to {themssg}",
647
- buttons=get_back_button("cbs_otvars"),
 
648
  )
649
 
650
 
651
- @callback("shndlr", owner=True)
652
  async def hndlrr(event):
653
  await event.delete()
654
  pru = event.sender_id
@@ -656,153 +1260,215 @@ async def hndlrr(event):
656
  name = "Sudo Handler"
657
  async with event.client.conversation(pru) as conv:
658
  await conv.send_message(
659
- "Send The Symbol Which u want as Sudo Handler/Trigger to use bot\n\n use /cancel to cancel."
 
 
 
 
 
660
  )
661
 
662
  response = conv.wait_event(events.NewMessage(chats=pru))
663
  response = await response
664
  themssg = response.message.message
665
- if themssg == "/cancel":
666
  await conv.send_message(
667
- "Cancelled!!",
668
- buttons=get_back_button("cbs_otvars"),
 
669
  )
670
  elif len(themssg) > 1:
671
  await conv.send_message(
672
- "Incorrect Handler",
673
- buttons=get_back_button("cbs_otvars"),
 
674
  )
675
  elif themssg.startswith(("/", "#", "@")):
676
  await conv.send_message(
677
- "This cannot be used as handler",
678
- buttons=get_back_button("cbs_otvars"),
 
679
  )
680
  else:
681
  await setit(event, var, themssg)
682
  await conv.send_message(
683
- f"{name} changed to {themssg}",
684
- buttons=get_back_button("cbs_otvars"),
 
685
  )
686
 
687
 
688
- @callback("taglog", owner=True)
689
- async def tagloggrr(e):
690
- BUTTON = [
691
- [Button.inline("SET TAG LOG", data="abs_settag")],
692
- [Button.inline("DELETE TAG LOG", data="deltag")],
693
- get_back_button("cbs_otvars"),
694
- ]
 
 
 
695
  await e.edit(
696
- "Choose Options",
 
 
 
 
697
  buttons=BUTTON,
 
698
  )
699
 
700
 
701
- @callback("deltag", owner=True)
702
  async def _(e):
703
  udB.del_key("TAG_LOG")
704
- await e.answer("Done!!! Tag Logger has been turned Off")
 
 
 
 
 
 
 
 
705
 
706
 
707
- @callback("eaddon", owner=True)
708
  async def pmset(event):
709
  BT = (
710
- [Button.inline("Aᴅᴅᴏɴs Oғғ", data="edof")]
711
  if udB.get_key("ADDONS")
712
- else [Button.inline("Aᴅᴅᴏɴs Oɴ", data="edon")]
713
  )
714
 
715
  await event.edit(
716
- "ADDONS~ Extra Plugins:",
 
 
 
 
717
  buttons=[
718
  BT,
719
- [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")],
720
  ],
 
721
  )
722
 
723
 
724
- @callback("edon", owner=True)
725
  async def eddon(event):
726
  var = "ADDONS"
727
  await setit(event, var, "True")
728
  await event.edit(
729
- "Done! ADDONS has been turned on!!\n\n After Setting All Things Do Restart",
730
- buttons=get_back_button("eaddon"),
 
 
 
 
 
731
  )
732
 
733
 
734
- @callback("edof", owner=True)
735
  async def eddof(event):
736
  udB.set_key("ADDONS", "False")
737
  await event.edit(
738
- "Done! ADDONS has been turned off!! After Setting All Things Do Restart",
739
- buttons=get_back_button("eaddon"),
 
 
 
 
 
740
  )
741
 
742
 
743
- @callback("sudo", owner=True)
744
  async def pmset(event):
745
  BT = (
746
- [Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ Oғғ", data="ofsudo")]
747
  if udB.get_key("SUDO")
748
- else [Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ Oɴ", data="onsudo")]
749
  )
750
 
751
  await event.edit(
752
- f"SUDO MODE ~ Some peoples can use ur Bot which u selected. To know More use `{HNDLR}help sudo`",
 
 
 
 
753
  buttons=[
754
  BT,
755
- [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")],
756
  ],
 
757
  )
758
 
759
 
760
- @callback("onsudo", owner=True)
761
  async def eddon(event):
762
  var = "SUDO"
763
  await setit(event, var, "True")
764
  await event.edit(
765
- "Done! SUDO MODE has been turned on!!\n\n After Setting All Things Do Restart",
766
- buttons=get_back_button("sudo"),
 
 
 
 
 
767
  )
768
 
769
 
770
- @callback("ofsudo", owner=True)
771
  async def eddof(event):
772
  var = "SUDO"
773
  await setit(event, var, "False")
774
  await event.edit(
775
- "Done! SUDO MODE has been turned off!! After Setting All Things Do Restart",
776
- buttons=get_back_button("sudo"),
 
 
 
 
 
777
  )
778
 
779
 
780
- @callback("sfgrp", owner=True)
781
- async def sfgrp(event):
782
  await event.delete()
783
  name = "FBan Group ID"
784
  var = "FBAN_GROUP_ID"
785
  pru = event.sender_id
786
  async with asst.conversation(pru) as conv:
787
  await conv.send_message(
788
- f"Make a group, add @MissRose_Bot, send `{HNDLR}id`, copy that and send it here.\nUse /cancel to go back.",
 
 
 
 
 
789
  )
790
  response = conv.wait_event(events.NewMessage(chats=pru))
791
  response = await response
792
  themssg = response.message.message
793
- if themssg == "/cancel":
794
  return await conv.send_message(
795
- "Cancelled!!",
796
- buttons=get_back_button("cbs_sfban"),
 
797
  )
798
  await setit(event, var, themssg)
799
  await conv.send_message(
800
- f"{name} changed to {themssg}",
801
- buttons=get_back_button("cbs_sfban"),
 
802
  )
803
 
804
 
805
- @callback("alvmed", owner=True)
806
  async def media(event):
807
  await event.delete()
808
  pru = event.sender_id
@@ -810,15 +1476,20 @@ async def media(event):
810
  name = "Alive Media"
811
  async with event.client.conversation(pru) as conv:
812
  await conv.send_message(
813
- "**Alive Media**\nSend me a pic/gif/media to set as alive media.\n\nUse /cancel to terminate the operation.",
 
 
 
 
814
  )
815
  response = await conv.get_response()
816
  try:
817
  themssg = response.message
818
- if themssg == "/cancel":
819
  return await conv.send_message(
820
- "Operation cancelled!!",
821
- buttons=get_back_button("cbs_alvcstm"),
 
822
  )
823
  except BaseException as er:
824
  LOGS.exception(er)
@@ -833,57 +1504,77 @@ async def media(event):
833
  else:
834
  media = await event.client.download_media(response, "alvpc")
835
  try:
836
- url = uploader.upload_file(media)
 
837
  remove(media)
838
  except BaseException as er:
839
  LOGS.exception(er)
840
  return await conv.send_message(
841
- "Terminated.",
842
- buttons=get_back_button("cbs_alvcstm"),
 
843
  )
844
  await setit(event, var, url)
845
  await conv.send_message(
846
- f"{name} has been set.",
847
- buttons=get_back_button("cbs_alvcstm"),
 
848
  )
849
 
850
 
851
- @callback("delmed", owner=True)
852
  async def dell(event):
853
  try:
854
  udB.del_key("ALIVE_PIC")
855
  return await event.edit(
856
- get_string("clst_5"), buttons=get_back_button("cbs_alabs_vcstm")
 
 
 
 
 
 
857
  )
858
  except BaseException as er:
859
  LOGS.exception(er)
860
  return await event.edit(
861
- get_string("clst_4"),
862
- buttons=get_back_button("cbs_alabs_vcstm"),
 
863
  )
864
 
865
 
866
- @callback("inpm_in", owner=True)
867
  async def inl_on(event):
868
  var = "INLINE_PM"
869
  await setit(event, var, "True")
870
  await event.edit(
871
- "Done!! PMPermit type has been set to inline!",
872
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_pmtype")]],
 
 
 
 
 
873
  )
874
 
875
 
876
- @callback("inpm_no", owner=True)
877
  async def inl_on(event):
878
  var = "INLINE_PM"
879
  await setit(event, var, "False")
880
  await event.edit(
881
- "Done!! PMPermit type has been set to normal!",
882
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_pmtype")]],
 
 
 
 
 
883
  )
884
 
885
 
886
- @callback("pmtxt", owner=True)
887
  async def name(event):
888
  await event.delete()
889
  pru = event.sender_id
@@ -891,56 +1582,83 @@ async def name(event):
891
  name = "PM Text"
892
  async with event.client.conversation(pru) as conv:
893
  await conv.send_message(
894
- "**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.",
 
 
 
 
895
  )
896
  response = conv.wait_event(events.NewMessage(chats=pru))
897
  response = await response
898
  themssg = response.message.message
899
- if themssg == "/cancel":
900
  return await conv.send_message(
901
- "Cancelled!!",
902
- buttons=get_back_button("cbs_pmcstm"),
 
903
  )
904
  if len(themssg) > 4090:
905
  return await conv.send_message(
906
- "Message too long!\nGive a shorter message please!!",
907
- buttons=get_back_button("cbs_pmcstm"),
 
 
 
908
  )
909
  await setit(event, var, themssg)
910
  await conv.send_message(
911
- f"{name} changed to {themssg}\n\nAfter Setting All Things Do restart",
912
- buttons=get_back_button("cbs_pmcstm"),
 
 
 
 
913
  )
914
 
915
 
916
- @callback("swarn", owner=True)
917
  async def name(event):
918
- m = range(1, 10)
919
- tultd = [Button.inline(f"{x}", data=f"wrns_{x}") for x in m]
920
- lst = list(zip(tultd[::3], tultd[1::3], tultd[2::3]))
921
- lst.append([Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")])
 
 
922
  await event.edit(
923
- "Select the number of warnings for a user before getting blocked in PMs.",
 
 
 
 
924
  buttons=lst,
 
925
  )
926
 
927
 
928
- @callback(re.compile(b"wrns_(.*)"), owner=True)
929
  async def set_wrns(event):
930
  value = int(event.data_match.group(1).decode("UTF-8"))
931
  if dn := udB.set_key("PMWARNS", value):
932
  await event.edit(
933
- f"PM Warns Set to {value}.\nNew users will have {value} chances in PMs before getting banned.",
934
- buttons=get_back_button("cbs_pmcstm"),
 
 
 
 
 
935
  )
936
  else:
937
  await event.edit(
938
- f"Something went wrong, please check your {HNDLR}logs!",
939
- buttons=get_back_button("cbs_pmcstm"),
 
 
 
940
  )
941
 
942
 
943
- @callback("pmmed", owner=True)
944
  async def media(event):
945
  await event.delete()
946
  pru = event.sender_id
@@ -948,15 +1666,20 @@ async def media(event):
948
  name = "PM Media"
949
  async with event.client.conversation(pru) as conv:
950
  await conv.send_message(
951
- "**PM Media**\nSend me a pic/gif/sticker/link to set as pmpermit media.\n\nUse /cancel to terminate the operation.",
 
 
 
 
952
  )
953
  response = await conv.get_response()
954
  try:
955
  themssg = response.message
956
- if themssg == "/cancel":
957
  return await conv.send_message(
958
- "Operation cancelled!!",
959
- buttons=get_back_button("cbs_pmcstm"),
 
960
  )
961
  except BaseException as er:
962
  LOGS.exception(er)
@@ -971,175 +1694,243 @@ async def media(event):
971
  url = response.file.id
972
  else:
973
  try:
974
- url = uploader.upload_file(media)
 
975
  remove(media)
976
  except BaseException as er:
977
  LOGS.exception(er)
978
  return await conv.send_message(
979
- "Terminated.",
980
- buttons=get_back_button("cbs_pmcstm"),
 
981
  )
982
  await setit(event, var, url)
983
  await conv.send_message(
984
- f"{name} has been set.",
985
- buttons=get_back_button("cbs_pmcstm"),
 
986
  )
987
 
988
 
989
- @callback("delpmmed", owner=True)
990
  async def dell(event):
991
  try:
992
  udB.del_key("PMPIC")
993
  return await event.edit(
994
- get_string("clst_5"), buttons=get_back_button("cbs_pmcstm")
 
 
 
 
 
 
995
  )
996
  except BaseException as er:
997
  LOGS.exception(er)
998
  return await event.edit(
999
- get_string("clst_4"),
1000
- buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]],
 
1001
  )
1002
 
1003
 
1004
- @callback("apon", owner=True)
1005
- async def apon(event):
1006
  var = "AUTOAPPROVE"
1007
  await setit(event, var, "True")
1008
  await event.edit(
1009
- "Done!! AUTOAPPROVE Started!!",
1010
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_apauto")]],
 
 
 
 
 
1011
  )
1012
 
1013
 
1014
- @callback("apof", owner=True)
1015
- async def apof(event):
1016
  try:
1017
  udB.set_key("AUTOAPPROVE", "False")
1018
  return await event.edit(
1019
- "Done! AUTOAPPROVE Stopped!!",
1020
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_apauto")]],
 
 
 
 
 
1021
  )
1022
  except BaseException as er:
1023
  LOGS.exception(er)
1024
  return await event.edit(
1025
- get_string("clst_4"),
1026
- buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]],
 
1027
  )
1028
 
1029
 
1030
- @callback("pml", owner=True)
1031
  async def l_vcs(event):
1032
  BT = (
1033
- [Button.inline("PMLOGGER OFF", data="pmlogof")]
1034
  if udB.get_key("PMLOG")
1035
- else [Button.inline("PMLOGGER ON", data="pmlog")]
1036
  )
1037
 
1038
  await event.edit(
1039
- "PMLOGGER This Will Forward Ur Pm to Ur Private Group -",
 
 
 
 
1040
  buttons=[
1041
  BT,
1042
- [Button.inline("PᴍLᴏɢɢᴇʀ Gʀᴏᴜᴘ", "abs_pmlgg")],
1043
- [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")],
1044
  ],
1045
  )
1046
 
1047
 
1048
- @callback("pmlog", owner=True)
1049
  async def pmlog(event):
1050
  await setit(event, "PMLOG", "True")
1051
  await event.edit(
1052
- "Done!! PMLOGGER Started!!",
1053
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="pml")]],
 
1054
  )
1055
 
1056
 
1057
- @callback("pmlogof", owner=True)
1058
  async def pmlogof(event):
1059
  try:
1060
  udB.del_key("PMLOG")
1061
  return await event.edit(
1062
- "Done! PMLOGGER Stopped!!",
1063
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="pml")]],
 
1064
  )
1065
  except BaseException as er:
1066
  LOGS.exception(er)
1067
  return await event.edit(
1068
- get_string("clst_4"),
1069
- buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]],
 
1070
  )
1071
 
1072
 
1073
- @callback("pmon", owner=True)
1074
  async def pmonn(event):
1075
  var = "PMSETTING"
1076
  await setit(event, var, "True")
1077
  await event.edit(
1078
- "Done! PMPermit has been turned on!!",
1079
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")]],
 
1080
  )
1081
 
1082
 
1083
- @callback("pmoff", owner=True)
1084
  async def pmofff(event):
1085
  var = "PMSETTING"
1086
  await setit(event, var, "False")
1087
  await event.edit(
1088
- "Done! PMPermit has been turned off!!",
1089
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")]],
 
1090
  )
1091
 
1092
 
1093
- @callback("botmew", owner=True)
1094
  async def hhh(e):
1095
  async with e.client.conversation(e.chat_id) as conv:
1096
- await conv.send_message("Send Any Media to keep at your Bot's welcome ")
 
 
 
 
 
 
1097
  msg = await conv.get_response()
1098
  if not msg.media or msg.text.startswith("/"):
1099
  return await conv.send_message(
1100
- "Terminated!", buttons=get_back_button("cbs_chatbot")
 
 
1101
  )
1102
  udB.set_key("STARTMEDIA", msg.file.id)
1103
- await conv.send_message("Done!", buttons=get_back_button("cbs_chatbot"))
 
 
 
 
1104
 
1105
 
1106
- @callback("botinfe", owner=True)
1107
  async def hhh(e):
1108
  async with e.client.conversation(e.chat_id) as conv:
1109
  await conv.send_message(
1110
- "Send message to set to Display, when user Press Info button in Bot Welcome!\n\nsend `False` to completely remove that button.."
 
 
 
 
1111
  )
1112
  msg = await conv.get_response()
1113
  if msg.media or msg.text.startswith("/"):
1114
  return await conv.send_message(
1115
- "Terminated!", buttons=get_back_button("cbs_chatbot")
 
 
1116
  )
1117
  udB.set_key("BOT_INFO_START", msg.text)
1118
- await conv.send_message("Done!", buttons=get_back_button("cbs_chatbot"))
 
 
 
 
1119
 
1120
 
1121
- @callback("pmfs", owner=True)
1122
  async def heheh(event):
1123
  Ll = []
1124
  err = ""
1125
  async with event.client.conversation(event.chat_id) as conv:
1126
  await conv.send_message(
1127
- "• 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.."
 
 
 
 
1128
  )
1129
  await conv.send_message(
1130
- "Example : \n`-1001234567\n-100778888`\n\nFor Multiple Chat(s)."
 
1131
  )
1132
  try:
1133
  msg = await conv.get_response()
1134
  except AsyncTimeOut:
1135
- return await conv.send_message("**• TimeUp!**\nStart from /start back.")
 
 
 
1136
  if not msg.text or msg.text.startswith("/"):
1137
- timyork = "Cancelled!"
1138
  if msg.text == "/clear":
1139
  udB.del_key("PMBOT_FSUB")
1140
- timyork = "Done! Force Subscribe Stopped\nRestart your Bot!"
 
 
 
 
 
 
 
1141
  return await conv.send_message(
1142
- "Cancelled!", buttons=get_back_button("cbs_chatbot")
 
 
1143
  )
1144
  for chat in msg.message.split("\n"):
1145
  if chat.startswith("-") or chat.isdigit():
@@ -1150,14 +1941,24 @@ async def heheh(event):
1150
  except Exception as er:
1151
  err += f"**{chat}** : {er}\n"
1152
  if err:
1153
- return await conv.send_message(err)
 
 
 
 
 
1154
  udB.set_key("PMBOT_FSUB", str(Ll))
1155
  await conv.send_message(
1156
- "Done!\nRestart Your Bot.", buttons=get_back_button("cbs_chatbot")
 
 
 
 
 
1157
  )
1158
 
1159
 
1160
- @callback("bwel", owner=True)
1161
  async def name(event):
1162
  await event.delete()
1163
  pru = event.sender_id
@@ -1165,40 +1966,51 @@ async def name(event):
1165
  name = "Bot Welcome Message:"
1166
  async with event.client.conversation(pru) as conv:
1167
  await conv.send_message(
1168
- "**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.",
 
 
 
 
1169
  )
1170
  response = conv.wait_event(events.NewMessage(chats=pru))
1171
  response = await response
1172
  themssg = response.message.message
1173
- if themssg == "/cancel":
1174
  return await conv.send_message(
1175
- "Cancelled!!",
1176
- buttons=get_back_button("cbs_chatbot"),
 
1177
  )
1178
  await setit(event, var, themssg)
1179
  await conv.send_message(
1180
- f"{name} changed to {themssg}",
1181
- buttons=get_back_button("cbs_chatbot"),
 
1182
  )
1183
 
1184
 
1185
- @callback("onchbot", owner=True)
1186
  async def chon(event):
1187
  var = "PMBOT"
1188
  await setit(event, var, "True")
1189
- Loader(path="assistant/pmbot.py", key="PM Bot").load()
1190
  if AST_PLUGINS.get("pmbot"):
1191
  for i, e in AST_PLUGINS["pmbot"]:
1192
  event.client.remove_event_handler(i)
1193
  for i, e in AST_PLUGINS["pmbot"]:
1194
  event.client.add_event_handler(i, events.NewMessage(**e))
1195
  await event.edit(
1196
- "Done! Now u Can Chat With People Via This Bot",
1197
- buttons=[Button.inline("« Bᴀᴄᴋ", data="cbs_chatbot")],
 
 
 
 
 
1198
  )
1199
 
1200
 
1201
- @callback("ofchbot", owner=True)
1202
  async def chon(event):
1203
  var = "PMBOT"
1204
  await setit(event, var, "False")
@@ -1206,12 +2018,17 @@ async def chon(event):
1206
  for i, e in AST_PLUGINS["pmbot"]:
1207
  event.client.remove_event_handler(i)
1208
  await event.edit(
1209
- "Done! Chat People Via This Bot Stopped.",
1210
- buttons=[Button.inline("« Bᴀᴄᴋ", data="cbs_chatbot")],
 
 
 
 
 
1211
  )
1212
 
1213
 
1214
- @callback("inli_pic", owner=True)
1215
  async def media(event):
1216
  await event.delete()
1217
  pru = event.sender_id
@@ -1219,15 +2036,20 @@ async def media(event):
1219
  name = "Inline Media"
1220
  async with event.client.conversation(pru) as conv:
1221
  await conv.send_message(
1222
- "**Inline Media**\nSend me a pic/gif/ or link to set as inline media.\n\nUse /cancel to terminate the operation.",
 
 
 
 
1223
  )
1224
  response = await conv.get_response()
1225
  try:
1226
  themssg = response.message
1227
- if themssg == "/cancel":
1228
  return await conv.send_message(
1229
- "Operation cancelled!!",
1230
- buttons=get_back_button("setter"),
 
1231
  )
1232
  except BaseException as er:
1233
  LOGS.exception(er)
@@ -1240,46 +2062,52 @@ async def media(event):
1240
  url = text_to_url(response)
1241
  else:
1242
  try:
1243
- url = uploader.upload_file(media)
 
1244
  remove(media)
1245
  except BaseException as er:
1246
  LOGS.exception(er)
1247
  return await conv.send_message(
1248
- "Terminated.",
1249
- buttons=get_back_button("setter"),
 
1250
  )
1251
  await setit(event, var, url)
1252
  await conv.send_message(
1253
- f"{name} has been set.",
1254
- buttons=get_back_button("setter"),
 
1255
  )
1256
 
1257
 
1258
  FD_MEDIA = {}
1259
 
1260
 
1261
- @callback(re.compile("fd(.*)"), owner=True)
1262
  async def fdroid_dler(event):
1263
  uri = event.data_match.group(1).decode("utf-8")
1264
  if FD_MEDIA.get(uri):
1265
  return await event.edit(file=FD_MEDIA[uri])
1266
- await event.answer("• Starting Download •", alert=True)
1267
- await event.edit("• Downloading.. •")
 
 
 
1268
  URL = f"https://f-droid.org/packages/{uri}"
1269
- conte = await async_searcher(URL, re_content=True)
1270
  BSC = bs(conte, "html.parser", from_encoding="utf-8")
1271
  dl_ = BSC.find("p", "package-version-download").find("a")["href"]
1272
  title = BSC.find("h3", "package-name").text.strip()
1273
  thumb = BSC.find("img", "package-icon")["src"]
1274
  if thumb.startswith("/"):
1275
  thumb = f"https://f-droid.org{thumb}"
1276
- thumb, _ = await fast_download(thumb, filename=f"{uri}.png")
1277
  s_time = time.time()
1278
- file, _ = await fast_download(
1279
  dl_,
1280
  filename=f"{title}.apk",
1281
- progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
1282
- progress(
1283
  d,
1284
  t,
1285
  event,
@@ -1293,10 +2121,13 @@ async def fdroid_dler(event):
1293
  n_file = await event.client.fast_uploader(
1294
  file, show_progress=True, event=event, message="Uploading...", to_delete=True
1295
  )
1296
- buttons = Button.switch_inline("Search Back", query="fdroid", same_peer=True)
 
 
 
1297
  try:
1298
  msg = await event.edit(
1299
- f"**• [{title}]({URL}) •**", file=n_file, thumb=thumb, buttons=buttons
1300
  )
1301
  except Exception as er:
1302
  LOGS.exception(er)
@@ -1304,15 +2135,24 @@ async def fdroid_dler(event):
1304
  msg = await event.client.edit_message(
1305
  await event.get_input_chat(),
1306
  event.message_id,
1307
- f"**• [{title}]({URL}) •**",
1308
  buttons=buttons,
1309
  thumb=thumb,
1310
  file=n_file,
1311
  )
1312
  except Exception as er:
1313
- os.remove(thumb)
1314
  LOGS.exception(er)
1315
- return await event.edit(f"**ERROR**: `{er}`", buttons=buttons)
 
 
 
 
1316
  if msg and hasattr(msg, "media"):
1317
  FD_MEDIA.update({uri: msg.media})
1318
- os.remove(thumb)
 
 
 
 
 
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
 
7
 
8
  import ast
9
  import asyncio
 
 
10
  import time
11
+ import unicodedata
12
  from asyncio.exceptions import TimeoutError as AsyncTimeOut
13
+ from os import remove
14
+ from pathlib import Path
15
  from random import choice
16
 
17
  from bs4 import BeautifulSoup as bs
 
20
  from pyUltroid.fns.gDrive import GDriveManager
21
  except ImportError:
22
  GDriveManager = None
23
+ from telegraph import upload_file as upl
24
+ from telethon import events
25
+ from telethon.tl import types
26
  from telethon.tl.types import MessageMediaWebPage
27
  from telethon.utils import get_peer_id
28
 
29
+ from custom.fmt import fmtmsg, rawhtml
30
+ from pyUltroid._core.loader import AsyncPluginLoader
31
+ from pyUltroid._core.richmsg import send_rich
32
+ from pyUltroid.fns import fns
33
+ from pyUltroid.ultroid import core
34
 
35
  from . import *
36
+ from ._cbs import cb, cb_exact_pattern, cb_pattern
37
+ from .rich_pages import edit_callback_page, rich_page
38
+ telegraph = fns.telegraph_client()
39
+
40
+ try:
41
+ GDrive = GDriveManager() if GDriveManager else None
42
+ except Exception:
43
+ GDrive = None
44
+
45
+
46
+ def _tok(*parts):
47
+ return cb("assistant", "callbacks", *parts)
48
+
49
+
50
+ def _handler(*parts):
51
+ return cb_exact_pattern("assistant", "callbacks", *parts)
52
+
53
+
54
+ def _menu(key):
55
+ return cb("assistant", "callbacks", "menu", key)
56
+
57
+
58
+ def _conv(key):
59
+ return cb("assistant", "callbacks", "conv", key)
60
+
61
+
62
+ def _message_text(message):
63
+ if isinstance(message, str):
64
+ return message
65
+ value = getattr(message, "raw_text", None)
66
+ if value is None:
67
+ value = getattr(message, "message", None)
68
+ if not isinstance(value, str):
69
+ value = getattr(value, "message", None)
70
+ return str(value or "")
71
+
72
+
73
+ def _is_cancel(message):
74
+ text = _message_text(message).strip()
75
+ command = text.split(maxsplit=1)[0].split("@", 1)[0] if text else ""
76
+ return command.casefold() == "/cancel"
77
+
78
+
79
+ def _row(*btns):
80
+ return ikm([list(btns)], icon=False)[0]
81
+
82
+
83
+ def _toggle(key):
84
+ value = udB.get_key(key)
85
+ if value is True or (isinstance(value, str) and value.lower() == "true"):
86
+ return "On"
87
+ return "Off"
88
+
89
+
90
+ def _val(key):
91
+ value = udB.get_key(key)
92
+ if value is None or value == "":
93
+ return "Not set"
94
+ return str(value)
95
+
96
+
97
+ def _mask_val(key):
98
+ value = udB.get_key(key)
99
+ if value is None or value == "":
100
+ return "Not set"
101
+ return "Set (hidden)"
102
+
103
+
104
+ def _plain(text):
105
+ """Remove common Markdown delimiters before showing text in a plain field."""
106
+ value = str(text)
107
+ for delimiter in ("**", "__", "~~", "`"):
108
+ value = value.replace(delimiter, "")
109
+ return value
110
+
111
+
112
+ _BUTTON_VALUE_KEYS = {
113
+ "taglogger": "TAG_LOG",
114
+ "help_emoji": "EMOJI_IN_HELP",
115
+ "plugins": "PLUGIN_CHANNEL",
116
+ "handler": "HNDLR",
117
+ "sudo_handler": "SUDO_HNDLR",
118
+ "addons": "ADDONS",
119
+ "edon": "ADDONS",
120
+ "edof": "ADDONS",
121
+ "sudo": "SUDO",
122
+ "onsudo": "SUDO",
123
+ "ofsudo": "SUDO",
124
+ "fbangroup": "FBAN_GROUP_ID",
125
+ "excludefeds": "EXCLUDE_FED",
126
+ "alive_text": "ALIVE_TEXT",
127
+ "alive_media": "ALIVE_PIC",
128
+ "pm_txt": "PM_TEXT",
129
+ "set_pm_warns": "PMWARNS",
130
+ "pm_media": "PMPIC",
131
+ "pm_logger": "PMLOG",
132
+ "pm_logger_group": "PMLOGGROUP",
133
+ "pm_inline": "INLINE_PM",
134
+ "pm_normal": "INLINE_PM",
135
+ "auto_ap_on": "AUTOAPPROVE",
136
+ "auto_ap_off": "AUTOAPPROVE",
137
+ "pm_permit_on": "PMSETTING",
138
+ "pm_permit_off": "PMSETTING",
139
+ "bot_welcome": "STARTMSG",
140
+ "bot_welcome_media": "STARTMEDIA",
141
+ "bot_info_text": "BOT_INFO_START",
142
+ "bot_fsub": "PMBOT_FSUB",
143
+ "chatbot_on": "PMBOT",
144
+ "chatbot_off": "PMBOT",
145
+ "vc_session": "VC_SESSION",
146
+ "dual_mode": "DUAL_MODE",
147
+ "dual_mode_on": "DUAL_MODE",
148
+ "dual_mode_off": "DUAL_MODE",
149
+ "dual_mode_handler": "DUAL_HNDLR",
150
+ "rmbg_key_set": "RMBG_API",
151
+ "deep_key_set": "DEEP_AI",
152
+ "ocr_key_set": "OCR_API",
153
+ "serp_key_set": "SERPAPI",
154
+ }
155
+ _BUTTON_GROUP_KEYS = {
156
+ "othervars": (
157
+ "TAG_LOG",
158
+ "SUDO",
159
+ "HNDLR",
160
+ "PLUGIN_CHANNEL",
161
+ "ADDONS",
162
+ "EMOJI_IN_HELP",
163
+ "INLINE_PIC",
164
+ "SUDO_HNDLR",
165
+ "DUAL_MODE",
166
+ ),
167
+ "superfban": ("FBAN_GROUP_ID", "EXCLUDE_FED"),
168
+ "alive_customisation": ("ALIVE_TEXT", "ALIVE_PIC"),
169
+ "pm_customisation": ("PM_TEXT", "PMPIC", "PMLOG", "PMWARNS", "INLINE_PM"),
170
+ "pm_type": ("INLINE_PM",),
171
+ "apauto": ("AUTOAPPROVE",),
172
+ "pm_settings": ("PMSETTING",),
173
+ "chatbot": ("PMBOT", "STARTMSG", "STARTMEDIA", "BOT_INFO_START", "PMBOT_FSUB"),
174
+ "vc_menu": ("VC_SESSION",),
175
+ "dual_mode": ("DUAL_MODE", "DUAL_HNDLR"),
176
+ "apiset": ("RMBG_API", "DEEP_AI", "OCR_API", "SERPAPI"),
177
+ }
178
+ _TOGGLE_BUTTONS = {
179
+ "edon": ("ADDONS", True),
180
+ "edof": ("ADDONS", False),
181
+ "onsudo": ("SUDO", True),
182
+ "ofsudo": ("SUDO", False),
183
+ "auto_ap_on": ("AUTOAPPROVE", True),
184
+ "auto_ap_off": ("AUTOAPPROVE", False),
185
+ "pm_permit_on": ("PMSETTING", True),
186
+ "pm_permit_off": ("PMSETTING", False),
187
+ "chatbot_on": ("PMBOT", True),
188
+ "chatbot_off": ("PMBOT", False),
189
+ "pm_inline": ("INLINE_PM", True),
190
+ "pm_normal": ("INLINE_PM", False),
191
+ "dual_mode_on": ("DUAL_MODE", True),
192
+ "dual_mode_off": ("DUAL_MODE", False),
193
+ "pm_logger_on": ("PMLOG", True),
194
+ "pm_logger_off": ("PMLOG", False),
195
+ }
196
+ _DESTRUCTIVE_BUTTONS = {"deltag", "del_alive_media", "del_pm_media"}
197
+
198
+
199
+ def _has_saved_value(value):
200
+ return value is not None and value != "" and value != []
201
+
202
+
203
+ def _enabled(value):
204
+ return value is True or (
205
+ isinstance(value, str) and value.strip().lower() in {"true", "on", "1", "yes"}
206
+ )
207
+
208
+
209
+ def _button_action(data):
210
+ if isinstance(data, bytes):
211
+ data = data.decode("utf-8", "ignore")
212
+ return str(data or "").rstrip(":").split(":")[-1].lower()
213
+
214
+
215
+ def _menu_label(text):
216
+ out = []
217
+ for char in str(text or ""):
218
+ if ord(char) in {
219
+ 0x00AB,
220
+ 0x00BB,
221
+ 0x2039,
222
+ 0x203A,
223
+ 0x25C0,
224
+ 0x25B6,
225
+ 0x2190,
226
+ 0x2192,
227
+ 0x2022,
228
+ 0x00B7,
229
+ 0xFE0E,
230
+ 0xFE0F,
231
+ 0x200D,
232
+ 0x20E3,
233
+ }:
234
+ out.append(" ")
235
+ continue
236
+ try:
237
+ name = unicodedata.name(char)
238
+ except ValueError:
239
+ name = ""
240
+ if name.startswith("LATIN LETTER SMALL CAPITAL "):
241
+ out.append(name.rsplit(" ", 1)[-1].lower())
242
+ elif unicodedata.category(char) in {"So", "Sk"}:
243
+ out.append(" ")
244
+ else:
245
+ out.append(char)
246
+ return " ".join("".join(out).split())
247
+
248
+
249
+ def _menu_button_style(data, label=None):
250
+ action = _button_action(data)
251
+ if _menu_label(label).lower() == "back":
252
+ return "primary"
253
+ if action in _DESTRUCTIVE_BUTTONS:
254
+ return "danger"
255
+ if action in _TOGGLE_BUTTONS:
256
+ key, desired = _TOGGLE_BUTTONS[action]
257
+ value = udB.get_key(key)
258
+ return (
259
+ "success"
260
+ if _has_saved_value(value) and _enabled(value) is desired
261
+ else None
262
+ )
263
+ key = _BUTTON_VALUE_KEYS.get(action)
264
+ if key and _has_saved_value(udB.get_key(key)):
265
+ return "success"
266
+ keys = _BUTTON_GROUP_KEYS.get(action, ())
267
+ return "success" if any(_has_saved_value(udB.get_key(k)) for k in keys) else None
268
+
269
+
270
+ def _refresh_menu_buttons(buttons):
271
+ rows = []
272
+ for row in buttons or []:
273
+ converted = []
274
+ for btn in row:
275
+ legacy_callback = getattr(types, "KeyboardButtonCallback", None)
276
+ inline_button = getattr(types, "KeyboardInlineButton", None)
277
+ callback_type = getattr(types, "InlineButtonTypeCallback", None)
278
+ button_type = getattr(btn, "type", None)
279
+ is_callback = legacy_callback is not None and isinstance(
280
+ btn, legacy_callback
281
+ )
282
+ is_callback = is_callback or (
283
+ inline_button is not None
284
+ and callback_type is not None
285
+ and isinstance(btn, inline_button)
286
+ and isinstance(button_type, callback_type)
287
+ )
288
+ if is_callback:
289
+ data = getattr(btn, "data", None) or getattr(button_type, "data", None)
290
+ converted.append(
291
+ (
292
+ _menu_label(btn.text),
293
+ data,
294
+ _menu_button_style(data, btn.text),
295
+ )
296
+ )
297
+ else:
298
+ converted.append(btn)
299
+ rows.append(converted)
300
+ return ikm(rows, icon=False)
301
+
302
+
303
+ START_SETTER = cb("assistant", "start", "setter")
304
+
305
+ MENU_PATTERN = cb_pattern("assistant", "callbacks", "menu")
306
+ CONV_PATTERN = cb_pattern("assistant", "callbacks", "conv")
307
+ CHANGES_PATTERN = cb_pattern("assistant", "callbacks", "changes")
308
+ WRNS_PATTERN = cb_pattern("assistant", "callbacks", "pm_warns")
309
+ PASTA_PATTERN = cb_pattern("assistant", "callbacks", "paste")
310
+ FDROID_PATTERN = cb_pattern("assistant", "fdroid")
311
 
 
 
 
 
 
312
 
313
  def text_to_url(event):
314
  """function to get media url (with|without) Webpage"""
 
319
  return event.text
320
 
321
 
 
 
322
  _buttons = {
323
+ "othervars": {
324
+ "head": "Other Variables ",
325
+ "body": "Configure the remaining variables for your Ultroid assistant.",
326
+ "buttons": ikm(
 
 
 
 
 
 
 
 
 
 
 
327
  [
328
+ [
329
+ ("Tag Logger", _tok("taglogger"), "person", "blue"),
330
+ ("SuperFban", _menu("superfban"), "blue"),
331
+ ],
332
+ [
333
+ ("Sudo Mode", _tok("sudo"), "blue"),
334
+ ("Handler", _tok("handler"), "blue"),
335
+ ],
336
+ [
337
+ ("Extra Plugins", _tok("plugins"), "blue"),
338
+ ("Addons", _tok("addons"), "blue"),
339
+ ],
340
+ [
341
+ ("Emoji in Help", _tok("help_emoji"), "blue"),
342
+ ("Set gDrive", _tok("gdrive"), "blue"),
343
+ ],
344
+ [
345
+ ("Inline Pic", _tok("inline_pic"), "blue"),
346
+ ("Sudo HNDLR", _tok("sudo_handler"), "blue"),
347
+ ],
348
+ [("Dual Mode", _menu("dual_mode"), "blue")],
349
+ [("Back", START_SETTER, None)],
350
  ],
351
+ icon=False,
352
+ ),
353
+ },
354
+ "superfban": {
355
+ "head": "SuperFban Settings ",
356
+ "body": "SuperFban bans spammers across federations for your channel.",
357
+ "foot": lambda: f"Currently: FBan group {_val('FBAN_GROUP_ID')}",
358
+ "buttons": ikm(
359
  [
360
+ [("FBan Group", _tok("fbangroup"), "blue")],
361
+ [("Exclude Feds", _conv("excludefeds"), "blue")],
362
+ [("Back", _menu("othervars"), None)],
363
  ],
364
+ icon=False,
365
+ ),
 
 
 
 
 
 
 
 
 
366
  },
367
  "apauto": {
368
  "text": "This'll auto approve on outgoing messages",
369
+ "head": "Auto Approve ",
370
+ "body": "Automatically approve incoming private messages.",
371
+ "foot": lambda: f"Currently: {_toggle('AUTOAPPROVE')}",
372
+ "buttons": ikm(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  [
374
+ [("Auto Approve ON", _tok("auto_ap_on"), "green")],
375
+ [("Auto Approve OFF", _tok("auto_ap_off"), "danger")],
376
+ [("Back", _menu("pm_customisation"), None)],
377
  ],
378
+ icon=False,
379
+ ),
380
+ },
381
+ "alive_customisation": {
382
+ "head": "Alive Customisation ",
383
+ "body": f"Customise your {HNDLR}alive. Choose from the options below.",
384
+ "foot": lambda: f"Currently: alive text {_val('ALIVE_TEXT')}",
385
+ "buttons": ikm(
386
  [
387
+ [("Alive Text", _conv("alive_text"), "blue")],
388
+ [("Alive media", _tok("alive_media"), "blue")],
389
+ [("Delete Alive Media", _tok("del_alive_media"), "danger")],
390
+ [("Back", START_SETTER, None)],
391
  ],
392
+ icon=False,
393
+ ),
394
+ },
395
+ "pm_customisation": {
396
+ "head": "PM Permit Settings",
397
+ "body": "Customise your PMPERMIT settings below.",
398
+ "buttons": ikm(
399
  [
400
+ [
401
+ ("PM Text", _tok("pm_txt"), "blue"),
402
+ ("PM Media", _tok("pm_media"), "blue"),
403
+ ],
404
+ [
405
+ ("Auto Approve", _menu("apauto"), "green"),
406
+ ("PM Logger", _tok("pm_logger"), "blue"),
407
+ ],
408
+ [
409
+ ("Set Warns", _tok("set_pm_warns"), "green"),
410
+ ("Delete PM Media", _tok("del_pm_media"), "danger"),
411
+ ],
412
+ [("PM Permit Type", _menu("pm_type"), "blue")],
413
+ [("Back", _menu("pm_settings"), None)],
414
  ],
415
+ icon=False,
416
+ ),
 
417
  },
418
+ "pm_type": {
419
+ "head": "PM Permit Type",
420
+ "body": "Choose how the PM Permit guard handles incoming private messages.",
421
+ "foot": lambda: (
422
+ f"Currently: {'Inline' if udB.get_key('INLINE_PM') in (True, 'True') else 'Normal'}"
423
+ ),
424
+ "buttons": ikm(
425
+ [
426
+ [("Inline", _tok("pm_inline"), "green")],
427
+ [("Normal", _tok("pm_normal"), "blue")],
428
+ [("Back", _menu("pm_customisation"), None)],
429
+ ],
430
+ icon=False,
431
+ ),
432
  },
433
+ "pm_settings": {
434
+ "head": "PM Permit",
435
+ "body": "Control the PM Permit guard for incoming private messages.",
436
+ "foot": lambda: f"Currently: {_toggle('PMSETTING')}",
437
+ "buttons": ikm(
438
+ [
439
+ [("Turn PM Permit On", _tok("pm_permit_on"), "success")],
440
+ [("Turn PM Permit Off", _tok("pm_permit_off"), "danger")],
441
+ [("Customize PM Permit", _menu("pm_customisation"))],
442
+ [("Back", START_SETTER, None)],
443
+ ],
444
+ icon=False,
445
+ ),
446
  },
447
  "chatbot": {
448
+ "head": "Chat Bot ",
449
+ "body": "Chat with people through your assistant bot.",
450
+ "data": {
451
+ "More info": rawhtml(
452
+ '<a href="https://t.me/UltroidUpdates/2">t.me/UltroidUpdates/2</a>'
453
+ )
454
+ },
455
+ "foot": lambda: f"Currently: {_toggle('PMBOT')}",
456
+ "buttons": ikm(
457
  [
458
+ [
459
+ ("Chat Bot On", _tok("chatbot_on"), "success"),
460
+ ("Chat Bot Off", _tok("chatbot_off"), "danger"),
461
+ ],
462
+ [
463
+ ("Bot Welcome", _tok("bot_welcome"), "blue"),
464
+ ("Bot Welcome Media", _tok("bot_welcome_media"), "blue"),
465
+ ],
466
+ [("Bot Info Text", _tok("bot_info_text"), "blue")],
467
+ [("Force Subscribe", _tok("bot_fsub"), "blue")],
468
+ [("Back", START_SETTER, None)],
469
  ],
470
+ icon=False,
471
+ ),
472
+ },
473
+ "vc_menu": {
474
+ "head": "VC Song Bot ",
475
+ "body": "Play songs in group voice chat.",
476
+ "data": {
477
+ "More info": rawhtml(
478
+ '<a href="https://t.me/UltroidUpdates/4">t.me/UltroidUpdates/4</a>'
479
+ )
480
+ },
481
+ "foot": lambda: f"Currently: session {_mask_val('VC_SESSION')}",
482
+ "buttons": ikm(
483
  [
484
+ [("VC Session", _conv("vc_session"), "blue")],
485
+ [("Back", START_SETTER, None)],
486
  ],
487
+ icon=False,
488
+ ),
 
 
 
 
 
 
 
 
 
489
  },
490
+ "dual_mode": {
491
+ "head": "Dual Mode ",
492
+ "data": {
493
+ "About": rawhtml(
494
+ '<a href="https://t.me/UltroidUpdates/18">t.me/UltroidUpdates/18</a>'
495
+ )
496
+ },
497
+ "foot": lambda: f"Currently: {_toggle('DUAL_MODE')}",
498
+ "buttons": ikm(
499
  [
500
+ [
501
+ ("Dual Mode On", _tok("dual_mode_on"), "success"),
502
+ ("Dual Mode Off", _tok("dual_mode_off"), "danger"),
503
+ ],
504
+ [("Dual Mode Handler", _tok("dual_mode_handler"), "blue")],
505
+ [("Back", _menu("othervars"), None)],
506
  ],
507
+ icon=False,
508
+ ),
 
509
  },
510
  "apiset": {
511
+ "head": "API Keys ",
512
+ "body": get_string("ast_1"),
513
+ "foot": lambda: (
514
+ f"Keys set: "
515
+ f"{sum(1 for k in ('RMBG_API', 'DEEP_AI', 'OCR_API', 'SERPAPI') if udB.get_key(k))}/4"
516
+ ),
517
+ "buttons": ikm(
518
+ [
519
+ [("Remove.bg API", _conv("rmbg_key_set"), "blue")],
520
+ [("DEEP API", _conv("deep_key_set"), "blue")],
521
+ [("OCR API", _conv("ocr_key_set"), "blue")],
522
+ [("SERP API", _conv("serp_key_set"), "blue")],
523
+ [("Back", START_SETTER, None)],
524
+ ],
525
+ icon=False,
526
+ ),
527
  },
528
  }
529
 
530
+ _MENU_BUTTON_DESCRIPTIONS = {
531
+ "remove.bg api": "Set or replace the API key; its value stays hidden.",
532
+ "deep api": "Set or replace the DeepAI key; its value stays hidden.",
533
+ "ocr api": "Set or replace the OCR key; its value stays hidden.",
534
+ "serp api": "Set or replace the search key; its value stays hidden.",
535
+ "chat bot on": "Enable the private-message chat bot.",
536
+ "chat bot off": "Disable the private-message chat bot.",
537
+ "bot welcome": "Edit the welcome message shown by the bot.",
538
+ "bot welcome media": "Set the media shown with the welcome message.",
539
+ "bot info text": "Edit the information shown from the Info button.",
540
+ "force subscribe": "Set the channel or group membership requirement.",
541
+ "alive text": "Edit the assistant's alive message.",
542
+ "alive media": "Set media for the alive message.",
543
+ "delete alive media": "Remove the saved alive media.",
544
+ "turn pm permit on": "Enable the incoming private-message guard.",
545
+ "turn pm permit off": "Disable the incoming private-message guard.",
546
+ "customize pm permit": "Open text, media, logging, and approval options.",
547
+ "tag logger": "Choose the chat used for tag logs.",
548
+ "superfban": "Configure federated-ban group settings.",
549
+ "sudo mode": "Manage sudo access.",
550
+ "handler": "Change the assistant command prefix.",
551
+ "extra plugins": "Choose the source for additional plugins.",
552
+ "addons": "Enable or disable add-on plugins.",
553
+ "emoji in help": "Configure emoji labels in the help menu.",
554
+ "set gdrive": "Configure Google Drive access.",
555
+ "inline pic": "Set or clear the inline result picture.",
556
+ "sudo hndlr": "Change the sudo command prefix.",
557
+ "dual mode": "Configure dual-client routing and its handler.",
558
+ "vc session": "Set the voice-chat bot session; its value stays hidden.",
559
+ "fban group": "Set the group used by federated-ban actions.",
560
+ "exclude feds": "Set the federations excluded from these actions.",
561
+ "auto approve": "Choose whether outgoing messages are auto-approved.",
562
+ "pm logger": "Enable or configure private-message logging.",
563
+ "set warns": "Set the private-message warning limit.",
564
+ "delete pm media": "Remove the saved PM Permit media.",
565
+ "pm permit type": "Choose normal or inline PM Permit handling.",
566
+ "inline": "Use inline PM Permit responses.",
567
+ "normal": "Use normal PM Permit responses.",
568
+ "dual mode on": "Enable dual-client mode.",
569
+ "dual mode off": "Disable dual-client mode.",
570
+ "dual mode handler": "Set the dual-client command handler.",
571
+ }
572
+
573
+
574
+ def _menu_table_rows(menu):
575
+ """Describe visible submenu buttons without rendering stored values."""
576
+ rows = []
577
+ for button_row in menu.get("buttons", ()):
578
+ for button in button_row:
579
+ label = getattr(button, "text", None)
580
+ if label is None:
581
+ try:
582
+ label = button[0]
583
+ except (IndexError, TypeError):
584
+ continue
585
+ label = _menu_label(label)
586
+ if label.casefold() == "back":
587
+ continue
588
+ purpose = _MENU_BUTTON_DESCRIPTIONS.get(
589
+ label.casefold(), "Open or update this setting."
590
+ )
591
+ rows.append((label, purpose))
592
+ return rows
593
+
594
+
595
  _convo = {
596
+ "rmbg_key_set": {
597
  "var": "RMBG_API",
598
  "name": "Remove.bg API Key",
599
  "text": get_string("ast_2"),
600
+ "back": _menu("apiset"),
601
  },
602
+ "deep_key_set": {
603
  "var": "DEEP_AI",
604
  "name": "Deep AI Api Key",
605
  "text": "Get Your Deep Api from deepai.org and send here.",
606
+ "back": _menu("apiset"),
607
  },
608
+ "ocr_key_set": {
609
  "var": "OCR_API",
610
  "name": "Ocr Api Key",
611
  "text": "Get Your OCR api from ocr.space and send that Here.",
612
+ "back": _menu("apiset"),
613
+ },
614
+ "serp_key_set": {
615
+ "var": "SERPAPI",
616
+ "name": "Serp Api Key",
617
+ "text": "Get Your SERP api from https://serpapi.com/users/sign_in and send that Here.",
618
+ "back": _menu("apiset"),
619
  },
620
+ "pm_logger_group": {
621
  "var": "PMLOGGROUP",
622
  "name": "Pm Log Group",
623
  "text": "Send chat id of chat which you want to save as Pm log Group.",
624
+ "back": _tok("pm_logger"),
625
  },
626
+ "vc_session": {
627
  "var": "VC_SESSION",
628
  "name": "Vc Session",
629
  "text": "**Vc session**\nEnter the New session u generated for vc bot.\n\nUse /cancel to terminate the operation.",
630
+ "back": _menu("vc_menu"),
631
  },
632
+ "set_pm_logger": {
633
  "var": "TAG_LOG",
634
  "name": "Tag Log Group",
635
+ "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.",
636
+ "back": _tok("taglogger"),
637
  },
638
+ "alive_text": {
639
  "var": "ALIVE_TEXT",
640
  "name": "Alive Text",
641
  "text": "**Alive Text**\nEnter the new alive text.\n\nUse /cancel to terminate the operation.",
642
+ "back": _menu("alive_customisation"),
643
  },
644
+ "excludefeds": {
645
  "var": "EXCLUDE_FED",
646
  "name": "Excluded Fed",
647
+ "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.",
648
+ "back": _menu("superfban"),
649
  },
650
  }
651
 
 
653
  TOKEN_FILE = "resources/auths/auth_token.txt"
654
 
655
 
656
+ def _plugin_source_path(key, name, *, repo_root=None, registry=None):
657
+ """Resolve a plugin source file inside its allowed repository directory."""
658
+ repo_root = (
659
+ Path(repo_root).resolve()
660
+ if repo_root is not None
661
+ else Path(__file__).resolve().parents[1]
662
+ )
663
+ roots = {
664
+ "Official": ("plugins",),
665
+ "Addons": ("addons",),
666
+ "VCBot": ("vc", "plugins"),
667
+ }.get(key, ())
668
+ if not roots:
669
+ return None
670
+
671
+ if registry is None:
672
+ registry = getattr(core, "registry", None)
673
+ manifest = registry.get(name) if registry is not None else None
674
+ manifest_path = getattr(manifest, "path", None)
675
+ if manifest_path:
676
+ candidate = Path(manifest_path)
677
+ if not candidate.is_absolute():
678
+ candidate = repo_root / candidate
679
+ candidate = candidate.resolve()
680
+ if (
681
+ candidate.suffix == ".py"
682
+ and candidate.is_file()
683
+ and any(candidate.is_relative_to(repo_root / folder) for folder in roots)
684
+ ):
685
+ return candidate
686
+
687
+ normalized = str(name or "").replace("\\", "/").strip("/").removesuffix(".py")
688
+ candidates = []
689
+ for folder in roots:
690
+ prefix = f"{folder}/"
691
+ dotted_prefix = f"{folder}."
692
+ if normalized.startswith(prefix):
693
+ relative = normalized[len(prefix) :]
694
+ elif normalized.startswith(dotted_prefix):
695
+ relative = normalized[len(dotted_prefix) :].replace(".", "/")
696
+ else:
697
+ relative = normalized
698
+ relative = relative.replace(".", "/")
699
+ if not relative.endswith(".py"):
700
+ relative += ".py"
701
+ candidate = (repo_root / folder / relative).resolve()
702
+ if (
703
+ candidate.suffix == ".py"
704
+ and candidate.is_file()
705
+ and candidate.is_relative_to(repo_root / folder)
706
+ ):
707
+ candidates.append(candidate)
708
+ return candidates[0] if candidates else None
709
+
710
+
711
+ @callback(cb_pattern("assistant", "inline", "send_plugin"), owner=True)
712
  async def send(eve):
713
+ key, _, rest = (eve.data_match.group(1)).decode("UTF-8").partition(":")
714
+ name, index = rest.rsplit(":", 1) if ":" in rest else (rest, None)
715
+ plugin = _plugin_source_path(key, name)
716
+ if plugin is None:
717
+ return await eve.answer("The plugin source file is unavailable.", alert=True)
718
+ user_id = getattr(eve, "sender_id", None) or getattr(
719
+ getattr(eve, "query", None), "user_id", None
720
+ )
721
+ if user_id is None:
722
+ return await eve.answer(
723
+ "I could not identify the requesting account.", alert=True
724
+ )
725
+ paste_ref = plugin.relative_to(Path(__file__).resolve().parents[1]).as_posix()
726
  if index is not None:
727
+ paste_ref = f"{paste_ref}|{index}"
728
+ buttons = ikm(
729
+ [[("Paste", cb("assistant", "callbacks", "paste", paste_ref), "primary")]],
730
+ icon=False,
731
+ )
 
 
 
 
 
 
 
 
732
  try:
733
+ await eve.client.send_file(
734
+ user_id,
735
+ file=str(plugin),
736
+ caption=f"{name} source",
737
+ buttons=buttons,
738
+ )
739
+ except Exception:
740
+ LOGS.exception("Unable to deliver plugin source")
741
+ return await eve.answer(
742
+ "I could not send the source in a private message. Open the assistant bot and try again.",
743
+ alert=True,
744
+ )
745
+ return await eve.answer("Source sent in your private chat.", alert=True)
746
 
747
 
748
  heroku_api, app_name = Var.HEROKU_API, Var.HEROKU_APP_NAME
749
 
750
 
751
+ @callback(_handler("updatenow"), owner=True)
752
  async def update(eve):
753
+ from pyUltroid.updater import up as update_engine
 
 
 
 
754
 
755
+ await eve.edit(
756
+ fmtmsg("Updating ", msgs=_plain(get_string("clst_1"))),
757
+ parse_mode="html",
758
+ )
759
+ msg_id = getattr(eve, "message_id", None) or getattr(
760
+ getattr(eve, "message", None), "id", 0
761
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
762
 
763
+ state = await update_engine.engine.apply(
764
+ restart_notice=("bot", eve.chat_id, msg_id),
765
+ )
766
+ text = _plain(state.summary())
767
+ foot = (
768
+ "Core files changed restarting in 3s"
769
+ if (state.status == "done" and state.needs_restart)
770
+ else ""
771
+ )
772
+ await eve.edit(
773
+ fmtmsg("Update", msgs=text, foot=foot),
774
+ parse_mode="html",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
775
  )
776
+
777
+
778
+ @callback(CHANGES_PATTERN, owner=True)
779
+ async def changes(event):
780
+ from pyUltroid.updater import up as update_engine
781
+
782
+ match = event.data_match.group(1).decode("utf-8")
783
+ await event.answer(get_string("clst_3"))
784
+ diff = await update_engine.engine.check()
785
+ button = [_row(("Update Now", _tok("updatenow"), "green"))]
786
+ if not (diff and diff.has_changes):
787
+ return await event.edit(
788
+ fmtmsg("Updates ", msgs="Already up-to-date."),
789
+ buttons=button,
790
+ parse_mode="html",
791
+ )
792
+ tl_chnglog = diff.changelog_text(max_entries=len(diff.commits))
793
+ head = f"Ultroid {ultroid_version} updates for {diff.branch}"
794
  if not match:
795
  try:
796
  if len(tl_chnglog) > 700:
797
  tl_chnglog = f"{tl_chnglog[:700]}..."
798
+ button.append(
799
+ _row(
800
+ (
801
+ "View Complete",
802
+ cb("assistant", "callbacks", "changes", "all"),
803
+ "primary",
804
+ )
805
+ )
806
+ )
807
+
808
+ await event.edit(
809
+ fmtmsg("Updates ", msgs="Writing changelogs"),
810
+ parse_mode="html",
811
+ )
812
+ img = await fns.Carbon(
813
  file_name="changelog",
814
  code=tl_chnglog,
815
  backgroundColor=choice(ATRA_COL),
816
  language="md",
817
  )
818
+ return await event.edit(
819
+ fmtmsg(" Ultroid Userbot "),
820
+ file=img,
821
+ buttons=button,
822
+ parse_mode="html",
823
  )
824
  except Exception as er:
825
  LOGS.exception(er)
826
+ changelog_str = (
827
+ f"{head}:\n\n{_plain(diff.changelog_text(10))}"
828
+ "\n\nClick the below button to update!"
829
+ )
830
  if len(changelog_str) > 1024:
831
+ await event.edit(
832
+ fmtmsg("Updates ", msgs=_plain(get_string("upd_4"))),
833
+ parse_mode="html",
834
+ )
835
  await asyncio.sleep(2)
836
  with open("ultroid_updates.txt", "w+") as file:
837
  file.write(tl_chnglog)
838
+ await event.edit(
839
+ fmtmsg("Updates ", msgs=_plain(get_string("upd_5"))),
840
  file="ultroid_updates.txt",
841
  buttons=button,
842
  )
843
  remove("ultroid_updates.txt")
844
  return
845
+ await event.edit(
846
+ fmtmsg(
847
+ head,
848
+ msgs=_plain(diff.changelog_text(10)),
849
+ foot="Click the below button to update!",
850
+ ),
851
  buttons=button,
852
  parse_mode="html",
853
  )
854
 
855
 
856
+ @callback(PASTA_PATTERN, owner=True)
 
 
 
 
 
857
  async def _(e):
858
+
859
  ok = (e.data_match.group(1)).decode("UTF-8")
860
  index = None
861
  if "|" in ok:
862
  ok, index = ok.split("|")
863
+ with open(ok) as hmm:
864
+ _, key = await fns.get_paste(hmm.read())
865
+ link = f"https://spaceb.in/{key}"
866
+ raw = f"https://spaceb.in/api/v1/documents/{key}/raw"
867
+ if not _:
868
  return await e.answer(key[:30], alert=True)
 
 
 
 
 
869
  if ok.startswith("addons"):
870
  key = "Addons"
871
+ elif ok.startswith(("vcbot", "vc/")):
872
  key = "VCBot"
873
  else:
874
  key = "Official"
875
+
876
+ data = cb(
877
+ "assistant", "inline", "help_menu", key, index if index is not None else "0"
878
+ )
879
  await e.edit(
880
  "",
881
+ buttons=ikm(
882
+ [
883
+ [
884
+ ("Link", "url", link, "green", "link"),
885
+ ("Raw", "url", raw, "green", "play"),
886
+ ],
887
+ [("Back", data, None)],
888
+ ],
889
+ icon=False,
890
+ ),
891
  )
892
 
893
 
894
+ @callback(MENU_PATTERN, owner=True)
895
  async def _edit_to(event):
896
  match = event.data_match.group(1).decode("utf-8")
897
+ menu = _buttons.get(match)
898
+ if not menu:
899
  return
900
+ rows = _menu_table_rows(menu)
901
+ await edit_callback_page(
902
+ event,
903
+ rich_page(
904
+ _menu_label(menu["head"]),
905
+ rows,
906
+ description=_plain(menu.get("body", "")),
907
+ columns=("Button", "What it does"),
908
+ total=len(rows),
909
+ ),
910
+ buttons=_refresh_menu_buttons(menu["buttons"]),
911
+ )
912
 
913
 
914
+ @callback(CONV_PATTERN, owner=True)
915
  async def convo_handler(event: events.CallbackQuery):
916
  match = event.data_match.group(1).decode("utf-8")
917
  if not _convo.get(match):
 
920
  get_ = _convo[match]
921
  back = get_["back"]
922
  async with event.client.conversation(event.sender_id) as conv:
923
+ prompt = await send_rich(
924
+ event.client,
925
+ conv.chat_id,
926
+ rich_page(
927
+ get_["name"],
928
+ [("Instructions", _plain(get_["text"]))],
929
+ columns=("Step", "What to do"),
930
+ total=1,
931
+ ),
932
+ link_preview=False,
933
+ )
934
+ response = await conv.get_response(prompt)
935
+ themssg = _message_text(response)
936
  try:
937
  themssg = ast.literal_eval(themssg)
938
  except Exception:
939
  pass
940
+ if _is_cancel(response):
941
+ return await send_rich(
942
+ event.client,
943
+ conv.chat_id,
944
+ rich_page(
945
+ "Settings cancelled",
946
+ [("Result", "Nothing was changed.")],
947
+ columns=("Status", "Details"),
948
+ total=1,
949
+ ),
950
  buttons=get_back_button(back),
951
+ link_preview=False,
952
  )
953
  await setit(event, get_["var"], themssg)
954
+ secret_setting = get_["var"] in {
955
+ "RMBG_API",
956
+ "DEEP_AI",
957
+ "OCR_API",
958
+ "SERPAPI",
959
+ "VC_SESSION",
960
+ }
961
+ shown_value = "Set (hidden)" if secret_setting else _plain(themssg)
962
+ await send_rich(
963
+ event.client,
964
+ conv.chat_id,
965
+ rich_page(
966
+ f"{get_['name']} updated",
967
+ [("Result", shown_value)],
968
+ columns=("Setting", "Status"),
969
+ total=1,
970
+ ),
971
  buttons=get_back_button(back),
972
+ link_preview=False,
973
  )
974
 
975
 
976
+ @callback(_handler("authorise"), owner=True)
977
  async def _(e):
978
  if not e.is_private:
979
  return
980
+ if not GDrive:
981
+ return await e.edit(
982
+ fmtmsg("Error ", msgs="Google Drive is not available right now."),
983
+ parse_mode="html",
984
+ )
985
  url = GDrive._create_token_file()
986
+ await e.edit(
987
+ fmtmsg("Google Drive ", msgs="Go to the below link and send the code!"),
988
+ parse_mode="html",
989
+ )
990
  async with asst.conversation(e.sender_id) as conv:
991
  await conv.send_message(url)
992
  code = await conv.get_response()
993
  if GDrive._create_token_file(code=code.text):
994
  await conv.send_message(
995
+ fmtmsg(
996
+ "Success ",
997
+ msgs="You are all set to use Google Drive with Ultroid Userbot.",
998
+ ),
999
+ buttons=_row(("Main Menu", START_SETTER, "primary")),
1000
+ parse_mode="html",
1001
  )
1002
  else:
1003
+ await conv.send_message(
1004
+ fmtmsg("Error ", msgs="Wrong code! Click authorise again."),
1005
+ parse_mode="html",
1006
+ )
1007
 
1008
 
1009
+ @callback(_handler("folderid"), owner=True, func=lambda x: x.is_private)
1010
  async def _(e):
1011
  if not e.is_private:
1012
  return
 
1020
  )
1021
  await e.delete()
1022
  async with asst.conversation(e.sender_id, timeout=150) as conv:
1023
+ await conv.send_message(
1024
+ fmtmsg("Google Drive Folder ", msgs=msg),
1025
+ parse_mode="html",
1026
+ )
1027
  repl = await conv.get_response()
1028
  id = repl.text
1029
  if id.startswith("https"):
1030
  id = id.split("?id=")[-1]
1031
  udB.set_key("GDRIVE_FOLDER_ID", id)
1032
  await repl.reply(
1033
+ fmtmsg("Success ", msgs="Folder ID saved."),
1034
+ buttons=get_back_button(_tok("gdrive")),
1035
+ parse_mode="html",
1036
  )
1037
 
1038
 
1039
+ @callback(_handler("gdrive"), owner=True)
1040
  async def _(e):
1041
  if not e.is_private:
1042
  return
1043
  await e.edit(
1044
+ fmtmsg(
1045
+ "Google Drive ",
1046
+ msgs="Click Authorise and send the code.\n\nYou can use your own CLIENT ID and SECRET.",
1047
+ data={
1048
+ "More info": rawhtml(
1049
+ '<a href="https://t.me/UltroidUpdates/37">t.me/UltroidUpdates/37</a>'
1050
+ )
1051
+ },
1052
+ ),
1053
+ buttons=ikm(
1054
  [
1055
+ [
1056
+ ("Folder ID", _tok("folderid"), "blue"),
1057
+ ("Authorise", _tok("authorise"), "green"),
1058
+ ],
1059
+ [("Back", _menu("othervars"), None)],
1060
  ],
1061
+ icon=False,
1062
+ ),
1063
  link_preview=False,
1064
  )
1065
 
1066
 
1067
+ @callback(_handler("dual_mode_on"), owner=True)
1068
  async def rhwhe(e):
1069
+ udB.set_key("DUAL_MODE", "True")
1070
+ await e.edit(
1071
+ fmtmsg(
1072
+ "Dual Mode ", msgs="Dual Mode has been turned on.", foot="Currently: On"
1073
+ ),
1074
+ buttons=get_back_button(_menu("othervars")),
1075
+ parse_mode="html",
1076
+ )
1077
+
1078
+
1079
+ @callback(_handler("dual_mode_off"), owner=True)
1080
+ async def rhwheoff(e):
1081
+ udB.del_key("DUAL_MODE")
1082
+ await e.edit(
1083
+ fmtmsg(
1084
+ "Dual Mode ", msgs="Dual Mode has been turned off.", foot="Currently: Off"
1085
+ ),
1086
+ buttons=get_back_button(_menu("othervars")),
1087
+ parse_mode="html",
1088
+ )
1089
 
1090
 
1091
+ @callback(_handler("dual_mode_handler"), owner=True)
1092
  async def hndlrr(event):
1093
  await event.delete()
1094
  pru = event.sender_id
 
1097
  CH = udB.get_key(var) or "/"
1098
  async with event.client.conversation(pru) as conv:
1099
  await conv.send_message(
1100
+ fmtmsg(
1101
+ name,
1102
+ msgs=f"Send the symbol you want as Handler/Trigger for your assistant bot.\nCurrent Handler is {CH}.\n\nUse /cancel to cancel.",
1103
+ ),
1104
+ parse_mode="html",
1105
  )
1106
  response = conv.wait_event(events.NewMessage(chats=pru))
1107
  response = await response
1108
  themssg = response.message.message
1109
+ if _is_cancel(response):
1110
  await conv.send_message(
1111
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
1112
+ buttons=get_back_button(_menu("othervars")),
1113
+ parse_mode="html",
1114
  )
1115
  elif len(themssg) > 1:
1116
  await conv.send_message(
1117
+ fmtmsg("Error ", msgs="Incorrect Handler."),
1118
+ buttons=get_back_button(_menu("othervars")),
1119
+ parse_mode="html",
1120
  )
1121
  else:
1122
  await setit(event, var, themssg)
1123
  await conv.send_message(
1124
+ fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"),
1125
+ buttons=get_back_button(_menu("othervars")),
1126
+ parse_mode="html",
1127
  )
1128
 
1129
 
1130
+ @callback(_handler("help_emoji"), owner=True)
1131
+ async def help_emoji(event):
1132
  await event.delete()
1133
  pru = event.sender_id
1134
  var = "EMOJI_IN_HELP"
1135
+ name = f"Emoji in {HNDLR}help menu"
1136
  async with event.client.conversation(pru) as conv:
1137
+ await conv.send_message(
1138
+ fmtmsg(
1139
+ name,
1140
+ msgs="Send the emoji you want to set .\n\nUse /cancel to cancel.",
1141
+ ),
1142
+ parse_mode="html",
1143
+ )
1144
  response = conv.wait_event(events.NewMessage(chats=pru))
1145
  response = await response
1146
  themssg = response.message.message
1147
+ if _is_cancel(response):
1148
  await conv.send_message(
1149
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
1150
+ buttons=get_back_button(_menu("othervars")),
1151
+ parse_mode="html",
1152
  )
1153
  elif themssg.startswith(("/", HNDLR)):
1154
  await conv.send_message(
1155
+ fmtmsg("Error ", msgs="Incorrect Emoji."),
1156
+ buttons=get_back_button(_menu("othervars")),
1157
+ parse_mode="html",
1158
  )
1159
  else:
1160
  await setit(event, var, themssg)
1161
  await conv.send_message(
1162
+ fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"),
1163
+ buttons=get_back_button(_menu("othervars")),
1164
+ parse_mode="html",
1165
  )
1166
 
1167
 
1168
+ @callback(_handler("plugins"), owner=True)
1169
  async def pluginch(event):
1170
  await event.delete()
1171
  pru = event.sender_id
 
1173
  name = "Plugin Channel"
1174
  async with event.client.conversation(pru) as conv:
1175
  await conv.send_message(
1176
+ fmtmsg(
1177
+ name,
1178
+ msgs="Send the id or username of the channel to install plugins from.\n\nOur Channel: @ultroidplugins\n\nUse /cancel to cancel.",
1179
+ ),
1180
+ parse_mode="html",
1181
  )
1182
  response = conv.wait_event(events.NewMessage(chats=pru))
1183
  response = await response
1184
  themssg = response.message.message
1185
+ if _is_cancel(response):
1186
  await conv.send_message(
1187
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
1188
+ buttons=get_back_button(_menu("othervars")),
1189
+ parse_mode="html",
1190
  )
1191
  elif themssg.startswith(("/", HNDLR)):
1192
  await conv.send_message(
1193
+ fmtmsg("Error ", msgs="Incorrect channel."),
1194
+ buttons=get_back_button(_menu("othervars")),
1195
+ parse_mode="html",
1196
  )
1197
  else:
1198
  await setit(event, var, themssg)
1199
  await conv.send_message(
1200
+ fmtmsg(
1201
+ f"{name} Changed ",
1202
+ msgs=f"New value: {themssg}",
1203
+ foot="Restart after setting all things.",
1204
+ ),
1205
+ buttons=get_back_button(_menu("othervars")),
1206
+ parse_mode="html",
1207
  )
1208
 
1209
 
1210
+ @callback(_handler("handler"), owner=True)
1211
  async def hndlrr(event):
1212
  await event.delete()
1213
  pru = event.sender_id
1214
  var = "HNDLR"
1215
+ name = "Handler/Trigger"
1216
  async with event.client.conversation(pru) as conv:
1217
  await conv.send_message(
1218
+ fmtmsg(
1219
+ name,
1220
+ msgs=f"Send the symbol you want as Handler/Trigger to use the bot.\nUse /cancel to cancel.",
1221
+ foot=lambda: f"Current Handler is {_val('HNDLR')}",
1222
+ ),
1223
+ parse_mode="html",
1224
  )
1225
  response = conv.wait_event(events.NewMessage(chats=pru))
1226
  response = await response
1227
  themssg = response.message.message
1228
+ if _is_cancel(response):
1229
  await conv.send_message(
1230
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
1231
+ buttons=get_back_button(_menu("othervars")),
1232
+ parse_mode="html",
1233
  )
1234
  elif len(themssg) > 1:
1235
  await conv.send_message(
1236
+ fmtmsg("Error ", msgs="Incorrect Handler."),
1237
+ buttons=get_back_button(_menu("othervars")),
1238
+ parse_mode="html",
1239
  )
1240
  elif themssg.startswith(("/", "#", "@")):
1241
  await conv.send_message(
1242
+ fmtmsg("Error ", msgs="This cannot be used as handler."),
1243
+ buttons=get_back_button(_menu("othervars")),
1244
+ parse_mode="html",
1245
  )
1246
  else:
1247
  await setit(event, var, themssg)
1248
  await conv.send_message(
1249
+ fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"),
1250
+ buttons=get_back_button(_menu("othervars")),
1251
+ parse_mode="html",
1252
  )
1253
 
1254
 
1255
+ @callback(_handler("sudo_handler"), owner=True)
1256
  async def hndlrr(event):
1257
  await event.delete()
1258
  pru = event.sender_id
 
1260
  name = "Sudo Handler"
1261
  async with event.client.conversation(pru) as conv:
1262
  await conv.send_message(
1263
+ fmtmsg(
1264
+ name,
1265
+ msgs="Send the symbol you want as Sudo Handler/Trigger to use the bot.\n\nUse /cancel to cancel.",
1266
+ foot=f" Prohibited Values: /, #, @.",
1267
+ ),
1268
+ parse_mode="html",
1269
  )
1270
 
1271
  response = conv.wait_event(events.NewMessage(chats=pru))
1272
  response = await response
1273
  themssg = response.message.message
1274
+ if _is_cancel(response):
1275
  await conv.send_message(
1276
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
1277
+ buttons=get_back_button(_menu("othervars")),
1278
+ parse_mode="html",
1279
  )
1280
  elif len(themssg) > 1:
1281
  await conv.send_message(
1282
+ fmtmsg("Error ", msgs="Incorrect Handler."),
1283
+ buttons=get_back_button(_menu("othervars")),
1284
+ parse_mode="html",
1285
  )
1286
  elif themssg.startswith(("/", "#", "@")):
1287
  await conv.send_message(
1288
+ fmtmsg("Error ", msgs="This cannot be used as handler."),
1289
+ buttons=get_back_button(_menu("othervars")),
1290
+ parse_mode="html",
1291
  )
1292
  else:
1293
  await setit(event, var, themssg)
1294
  await conv.send_message(
1295
+ fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"),
1296
+ buttons=get_back_button(_menu("othervars")),
1297
+ parse_mode="html",
1298
  )
1299
 
1300
 
1301
+ @callback(_handler("taglogger"), owner=True)
1302
+ async def tagloggergrr(e):
1303
+ BUTTON = ikm(
1304
+ [
1305
+ [("SET TAG LOG", _conv("set_pm_logger"))],
1306
+ [("DELETE TAG LOG", _tok("deltag"), "danger")],
1307
+ ],
1308
+ icon=False,
1309
+ )
1310
+ BUTTON.append(get_back_button(_menu("othervars")))
1311
  await e.edit(
1312
+ fmtmsg(
1313
+ "Tag Logger ",
1314
+ msgs="Choose whether to set or delete the tag log group.",
1315
+ foot=f"Currently: {_val('TAG_LOG')}",
1316
+ ),
1317
  buttons=BUTTON,
1318
+ parse_mode="html",
1319
  )
1320
 
1321
 
1322
+ @callback(_handler("deltag"), owner=True)
1323
  async def _(e):
1324
  udB.del_key("TAG_LOG")
1325
+ await e.edit(
1326
+ fmtmsg(
1327
+ "Tag Logger ",
1328
+ msgs="Tag Logger has been turned off.",
1329
+ foot="Currently: Off",
1330
+ ),
1331
+ buttons=get_back_button(_menu("othervars")),
1332
+ parse_mode="html",
1333
+ )
1334
 
1335
 
1336
+ @callback(_handler("addons"), owner=True)
1337
  async def pmset(event):
1338
  BT = (
1339
+ _row(("Addons Off", _tok("edof"), "danger"))
1340
  if udB.get_key("ADDONS")
1341
+ else _row(("Addons On", _tok("edon"), "success"))
1342
  )
1343
 
1344
  await event.edit(
1345
+ fmtmsg(
1346
+ "Addons ",
1347
+ msgs="Extra plugins can be enabled or disabled here.",
1348
+ foot=f"Currently: {_toggle('ADDONS')}",
1349
+ ),
1350
  buttons=[
1351
  BT,
1352
+ get_back_button(_menu("othervars")),
1353
  ],
1354
+ parse_mode="html",
1355
  )
1356
 
1357
 
1358
+ @callback(_handler("edon"), owner=True)
1359
  async def eddon(event):
1360
  var = "ADDONS"
1361
  await setit(event, var, "True")
1362
  await event.edit(
1363
+ fmtmsg(
1364
+ "Addons ",
1365
+ msgs="ADDONS has been turned on.\nAfter setting all things, restart.",
1366
+ foot="Currently: On",
1367
+ ),
1368
+ buttons=get_back_button(_tok("addons")),
1369
+ parse_mode="html",
1370
  )
1371
 
1372
 
1373
+ @callback(_handler("edof"), owner=True)
1374
  async def eddof(event):
1375
  udB.set_key("ADDONS", "False")
1376
  await event.edit(
1377
+ fmtmsg(
1378
+ "Addons ",
1379
+ msgs="ADDONS has been turned off.\nAfter setting all things, restart.",
1380
+ foot="Currently: Off",
1381
+ ),
1382
+ buttons=get_back_button(_tok("addons")),
1383
+ parse_mode="html",
1384
  )
1385
 
1386
 
1387
+ @callback(_handler("sudo"), owner=True)
1388
  async def pmset(event):
1389
  BT = (
1390
+ _row(("Sudo Mode Off", _tok("ofsudo"), "danger"))
1391
  if udB.get_key("SUDO")
1392
+ else _row(("Sudo Mode On", _tok("onsudo"), "success"))
1393
  )
1394
 
1395
  await event.edit(
1396
+ fmtmsg(
1397
+ "Sudo Mode ",
1398
+ msgs=f"Some people you select can use your bot.\nUse {HNDLR}help sudo to know more.",
1399
+ foot=f"Currently: {_toggle('SUDO')}",
1400
+ ),
1401
  buttons=[
1402
  BT,
1403
+ get_back_button(_menu("othervars")),
1404
  ],
1405
+ parse_mode="html",
1406
  )
1407
 
1408
 
1409
+ @callback(_handler("onsudo"), owner=True)
1410
  async def eddon(event):
1411
  var = "SUDO"
1412
  await setit(event, var, "True")
1413
  await event.edit(
1414
+ fmtmsg(
1415
+ "Sudo Mode ",
1416
+ msgs="SUDO MODE has been turned on.\nAfter setting all things, restart.",
1417
+ foot="Currently: On",
1418
+ ),
1419
+ buttons=get_back_button(_tok("sudo")),
1420
+ parse_mode="html",
1421
  )
1422
 
1423
 
1424
+ @callback(_handler("ofsudo"), owner=True)
1425
  async def eddof(event):
1426
  var = "SUDO"
1427
  await setit(event, var, "False")
1428
  await event.edit(
1429
+ fmtmsg(
1430
+ "Sudo Mode ",
1431
+ msgs="SUDO MODE has been turned off.\nAfter setting all things, restart.",
1432
+ foot="Currently: Off",
1433
+ ),
1434
+ buttons=get_back_button(_tok("sudo")),
1435
+ parse_mode="html",
1436
  )
1437
 
1438
 
1439
+ @callback(_handler("fbangroup"), owner=True)
1440
+ async def fbangroup(event):
1441
  await event.delete()
1442
  name = "FBan Group ID"
1443
  var = "FBAN_GROUP_ID"
1444
  pru = event.sender_id
1445
  async with asst.conversation(pru) as conv:
1446
  await conv.send_message(
1447
+ fmtmsg(
1448
+ name,
1449
+ msgs=f"Make a group, add @MissRose_Bot, send {HNDLR}id, copy that and send it here.\nUse /cancel to go back.",
1450
+ foot=f"Current value: {_val('FBAN_GROUP_ID')}",
1451
+ ),
1452
+ parse_mode="html",
1453
  )
1454
  response = conv.wait_event(events.NewMessage(chats=pru))
1455
  response = await response
1456
  themssg = response.message.message
1457
+ if _is_cancel(response):
1458
  return await conv.send_message(
1459
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
1460
+ buttons=get_back_button(_menu("superfban")),
1461
+ parse_mode="html",
1462
  )
1463
  await setit(event, var, themssg)
1464
  await conv.send_message(
1465
+ fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"),
1466
+ buttons=get_back_button(_menu("superfban")),
1467
+ parse_mode="html",
1468
  )
1469
 
1470
 
1471
+ @callback(_handler("alive_media"), owner=True)
1472
  async def media(event):
1473
  await event.delete()
1474
  pru = event.sender_id
 
1476
  name = "Alive Media"
1477
  async with event.client.conversation(pru) as conv:
1478
  await conv.send_message(
1479
+ fmtmsg(
1480
+ name,
1481
+ msgs="Send me a pic/gif/media to set as alive media.\n\nUse /cancel to terminate the operation.",
1482
+ ),
1483
+ parse_mode="html",
1484
  )
1485
  response = await conv.get_response()
1486
  try:
1487
  themssg = response.message
1488
+ if _is_cancel(response):
1489
  return await conv.send_message(
1490
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
1491
+ buttons=get_back_button(_menu("alive_customisation")),
1492
+ parse_mode="html",
1493
  )
1494
  except BaseException as er:
1495
  LOGS.exception(er)
 
1504
  else:
1505
  media = await event.client.download_media(response, "alvpc")
1506
  try:
1507
+ x = upl(media)
1508
+ url = f"https://graph.org/{x[0]}"
1509
  remove(media)
1510
  except BaseException as er:
1511
  LOGS.exception(er)
1512
  return await conv.send_message(
1513
+ fmtmsg("Terminated ", msgs="The operation was terminated."),
1514
+ buttons=get_back_button(_menu("alive_customisation")),
1515
+ parse_mode="html",
1516
  )
1517
  await setit(event, var, url)
1518
  await conv.send_message(
1519
+ fmtmsg(f"{name} Changed ", msgs=f"New value: {url}"),
1520
+ buttons=get_back_button(_menu("alive_customisation")),
1521
+ parse_mode="html",
1522
  )
1523
 
1524
 
1525
+ @callback(_handler("del_alive_media"), owner=True)
1526
  async def dell(event):
1527
  try:
1528
  udB.del_key("ALIVE_PIC")
1529
  return await event.edit(
1530
+ fmtmsg(
1531
+ "Alive Media ",
1532
+ msgs="Alive media has been deleted.",
1533
+ foot="Currently: Not set",
1534
+ ),
1535
+ buttons=get_back_button(_menu("alive_customisation")),
1536
+ parse_mode="html",
1537
  )
1538
  except BaseException as er:
1539
  LOGS.exception(er)
1540
  return await event.edit(
1541
+ fmtmsg("Error ", msgs="Something went wrong."),
1542
+ buttons=get_back_button(_menu("alive_customisation")),
1543
+ parse_mode="html",
1544
  )
1545
 
1546
 
1547
+ @callback(_handler("pm_inline"), owner=True)
1548
  async def inl_on(event):
1549
  var = "INLINE_PM"
1550
  await setit(event, var, "True")
1551
  await event.edit(
1552
+ fmtmsg(
1553
+ "PM Permit Type",
1554
+ msgs="PM Permit type has been set to inline.",
1555
+ foot="Currently: Inline",
1556
+ ),
1557
+ buttons=get_back_button(_menu("pm_type")),
1558
+ parse_mode="html",
1559
  )
1560
 
1561
 
1562
+ @callback(_handler("pm_normal"), owner=True)
1563
  async def inl_on(event):
1564
  var = "INLINE_PM"
1565
  await setit(event, var, "False")
1566
  await event.edit(
1567
+ fmtmsg(
1568
+ "PM Permit Type",
1569
+ msgs="PM Permit type has been set to normal.",
1570
+ foot="Currently: Normal",
1571
+ ),
1572
+ buttons=get_back_button(_menu("pm_type")),
1573
+ parse_mode="html",
1574
  )
1575
 
1576
 
1577
+ @callback(_handler("pm_txt"), owner=True)
1578
  async def name(event):
1579
  await event.delete()
1580
  pru = event.sender_id
 
1582
  name = "PM Text"
1583
  async with event.client.conversation(pru) as conv:
1584
  await conv.send_message(
1585
+ fmtmsg(
1586
+ name,
1587
+ msgs="Enter the new PM Permit message.\n\nYou can use {name}, {fullname}, {count}, {mention}, and {username} placeholders.\n\nSend /cancel to stop.",
1588
+ ),
1589
+ parse_mode="html",
1590
  )
1591
  response = conv.wait_event(events.NewMessage(chats=pru))
1592
  response = await response
1593
  themssg = response.message.message
1594
+ if _is_cancel(response):
1595
  return await conv.send_message(
1596
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
1597
+ buttons=get_back_button(_menu("pm_customisation")),
1598
+ parse_mode="html",
1599
  )
1600
  if len(themssg) > 4090:
1601
  return await conv.send_message(
1602
+ fmtmsg(
1603
+ "Error ", msgs="Message too long!\nGive a shorter message please."
1604
+ ),
1605
+ buttons=get_back_button(_menu("pm_customisation")),
1606
+ parse_mode="html",
1607
  )
1608
  await setit(event, var, themssg)
1609
  await conv.send_message(
1610
+ fmtmsg(
1611
+ f"{name} Changed ",
1612
+ msgs=f"New value: {themssg}\n\nAfter setting all things, restart.",
1613
+ ),
1614
+ buttons=get_back_button(_menu("pm_customisation")),
1615
+ parse_mode="html",
1616
  )
1617
 
1618
 
1619
+ @callback(_handler("set_pm_warns"), owner=True)
1620
  async def name(event):
1621
+ btns = [
1622
+ (f"{x}", cb("assistant", "callbacks", "pm_warns", x), "primary")
1623
+ for x in range(1, 10)
1624
+ ]
1625
+ lst = ikm([btns[i : i + 3] for i in range(0, len(btns), 3)], icon=False)
1626
+ lst.append(get_back_button(_menu("pm_customisation")))
1627
  await event.edit(
1628
+ fmtmsg(
1629
+ "PM Warnings ",
1630
+ msgs="Select the number of warnings for a user before getting blocked in PMs.",
1631
+ foot=f"Currently: {_val('PMWARNS')}",
1632
+ ),
1633
  buttons=lst,
1634
+ parse_mode="html",
1635
  )
1636
 
1637
 
1638
+ @callback(WRNS_PATTERN, owner=True)
1639
  async def set_wrns(event):
1640
  value = int(event.data_match.group(1).decode("UTF-8"))
1641
  if dn := udB.set_key("PMWARNS", value):
1642
  await event.edit(
1643
+ fmtmsg(
1644
+ "PM Warnings ",
1645
+ msgs=f"New users will have {value} chances in PMs before getting banned.",
1646
+ foot=f"Currently: {value}",
1647
+ ),
1648
+ buttons=get_back_button(_menu("pm_customisation")),
1649
+ parse_mode="html",
1650
  )
1651
  else:
1652
  await event.edit(
1653
+ fmtmsg(
1654
+ "Error ", msgs=f"Something went wrong, please check your {HNDLR}logs."
1655
+ ),
1656
+ buttons=get_back_button(_menu("pm_customisation")),
1657
+ parse_mode="html",
1658
  )
1659
 
1660
 
1661
+ @callback(_handler("pm_media"), owner=True)
1662
  async def media(event):
1663
  await event.delete()
1664
  pru = event.sender_id
 
1666
  name = "PM Media"
1667
  async with event.client.conversation(pru) as conv:
1668
  await conv.send_message(
1669
+ fmtmsg(
1670
+ name,
1671
+ msgs="Send a photo, GIF, sticker, or link for the PM Permit media.\n\nSend /cancel to stop.",
1672
+ ),
1673
+ parse_mode="html",
1674
  )
1675
  response = await conv.get_response()
1676
  try:
1677
  themssg = response.message
1678
+ if _is_cancel(response):
1679
  return await conv.send_message(
1680
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
1681
+ buttons=get_back_button(_menu("pm_customisation")),
1682
+ parse_mode="html",
1683
  )
1684
  except BaseException as er:
1685
  LOGS.exception(er)
 
1694
  url = response.file.id
1695
  else:
1696
  try:
1697
+ x = upl(media)
1698
+ url = f"https://graph.org/{x[0]}"
1699
  remove(media)
1700
  except BaseException as er:
1701
  LOGS.exception(er)
1702
  return await conv.send_message(
1703
+ fmtmsg("Terminated ", msgs="The operation was terminated."),
1704
+ buttons=get_back_button(_menu("pm_customisation")),
1705
+ parse_mode="html",
1706
  )
1707
  await setit(event, var, url)
1708
  await conv.send_message(
1709
+ fmtmsg(f"{name} Changed ", msgs=f"New value: {url}"),
1710
+ buttons=get_back_button(_menu("pm_customisation")),
1711
+ parse_mode="html",
1712
  )
1713
 
1714
 
1715
+ @callback(_handler("del_pm_media"), owner=True)
1716
  async def dell(event):
1717
  try:
1718
  udB.del_key("PMPIC")
1719
  return await event.edit(
1720
+ fmtmsg(
1721
+ "PM Media ",
1722
+ msgs="PM media has been deleted.",
1723
+ foot="Currently: Not set",
1724
+ ),
1725
+ buttons=get_back_button(_menu("pm_customisation")),
1726
+ parse_mode="html",
1727
  )
1728
  except BaseException as er:
1729
  LOGS.exception(er)
1730
  return await event.edit(
1731
+ fmtmsg("Error ", msgs="Something went wrong."),
1732
+ buttons=get_back_button(START_SETTER, " Settings"),
1733
+ parse_mode="html",
1734
  )
1735
 
1736
 
1737
+ @callback(_handler("auto_ap_on"), owner=True)
1738
+ async def auto_ap_on(event):
1739
  var = "AUTOAPPROVE"
1740
  await setit(event, var, "True")
1741
  await event.edit(
1742
+ fmtmsg(
1743
+ "Auto Approve ",
1744
+ msgs="AUTOAPPROVE has been started.",
1745
+ foot="Currently: On",
1746
+ ),
1747
+ buttons=get_back_button(_menu("apauto")),
1748
+ parse_mode="html",
1749
  )
1750
 
1751
 
1752
+ @callback(_handler("auto_ap_off"), owner=True)
1753
+ async def auto_ap_off(event):
1754
  try:
1755
  udB.set_key("AUTOAPPROVE", "False")
1756
  return await event.edit(
1757
+ fmtmsg(
1758
+ "Auto Approve ",
1759
+ msgs="AUTOAPPROVE has been stopped.",
1760
+ foot="Currently: Off",
1761
+ ),
1762
+ buttons=get_back_button(_menu("apauto")),
1763
+ parse_mode="html",
1764
  )
1765
  except BaseException as er:
1766
  LOGS.exception(er)
1767
  return await event.edit(
1768
+ fmtmsg("Error ", msgs="Something went wrong."),
1769
+ buttons=get_back_button(START_SETTER, " Settings"),
1770
+ parse_mode="html",
1771
  )
1772
 
1773
 
1774
+ @callback(_handler("pm_logger"), owner=True)
1775
  async def l_vcs(event):
1776
  BT = (
1777
+ _row(("PM Logger Off", _tok("pm_logger_off"), "danger"))
1778
  if udB.get_key("PMLOG")
1779
+ else _row(("PM Logger On", _tok("pm_logger_on"), "success"))
1780
  )
1781
 
1782
  await event.edit(
1783
+ fmtmsg(
1784
+ "PM Logger",
1785
+ msgs="This will forward your PMs to your private group.",
1786
+ foot=f"Currently: {_toggle('PMLOG')}",
1787
+ ),
1788
  buttons=[
1789
  BT,
1790
+ _row(("PM Logger Group", _conv("pm_logger_group"), "primary")),
1791
+ get_back_button(_menu("pm_customisation")),
1792
  ],
1793
  )
1794
 
1795
 
1796
+ @callback(_handler("pm_logger_on"), owner=True)
1797
  async def pmlog(event):
1798
  await setit(event, "PMLOG", "True")
1799
  await event.edit(
1800
+ fmtmsg("PM Logger", msgs="PM Logger is on.", foot="Currently: On"),
1801
+ buttons=get_back_button(_tok("pm_logger")),
1802
+ parse_mode="html",
1803
  )
1804
 
1805
 
1806
+ @callback(_handler("pm_logger_off"), owner=True)
1807
  async def pmlogof(event):
1808
  try:
1809
  udB.del_key("PMLOG")
1810
  return await event.edit(
1811
+ fmtmsg("PM Logger", msgs="PM Logger is off.", foot="Currently: Off"),
1812
+ buttons=get_back_button(_tok("pm_logger")),
1813
+ parse_mode="html",
1814
  )
1815
  except BaseException as er:
1816
  LOGS.exception(er)
1817
  return await event.edit(
1818
+ fmtmsg("Error ", msgs="Something went wrong."),
1819
+ buttons=get_back_button(START_SETTER, " Settings"),
1820
+ parse_mode="html",
1821
  )
1822
 
1823
 
1824
+ @callback(_handler("pm_permit_on"), owner=True)
1825
  async def pmonn(event):
1826
  var = "PMSETTING"
1827
  await setit(event, var, "True")
1828
  await event.edit(
1829
+ fmtmsg("PM Permit", msgs="PM Permit is on.", foot="Currently: On"),
1830
+ buttons=get_back_button(_menu("pm_settings")),
1831
+ parse_mode="html",
1832
  )
1833
 
1834
 
1835
+ @callback(_handler("pm_permit_off"), owner=True)
1836
  async def pmofff(event):
1837
  var = "PMSETTING"
1838
  await setit(event, var, "False")
1839
  await event.edit(
1840
+ fmtmsg("PM Permit", msgs="PM Permit is off.", foot="Currently: Off"),
1841
+ buttons=get_back_button(_menu("pm_settings")),
1842
+ parse_mode="html",
1843
  )
1844
 
1845
 
1846
+ @callback(_handler("bot_welcome_media"), owner=True)
1847
  async def hhh(e):
1848
  async with e.client.conversation(e.chat_id) as conv:
1849
+ await conv.send_message(
1850
+ fmtmsg(
1851
+ "Bot Welcome Media ",
1852
+ msgs="Send any media to keep at your bot's welcome.",
1853
+ ),
1854
+ parse_mode="html",
1855
+ )
1856
  msg = await conv.get_response()
1857
  if not msg.media or msg.text.startswith("/"):
1858
  return await conv.send_message(
1859
+ fmtmsg("Terminated ", msgs="The operation was terminated."),
1860
+ buttons=get_back_button(_menu("chatbot")),
1861
+ parse_mode="html",
1862
  )
1863
  udB.set_key("STARTMEDIA", msg.file.id)
1864
+ await conv.send_message(
1865
+ fmtmsg("Bot Welcome Media ", msgs="Media has been saved."),
1866
+ buttons=get_back_button(_menu("chatbot")),
1867
+ parse_mode="html",
1868
+ )
1869
 
1870
 
1871
+ @callback(_handler("bot_info_text"), owner=True)
1872
  async def hhh(e):
1873
  async with e.client.conversation(e.chat_id) as conv:
1874
  await conv.send_message(
1875
+ fmtmsg(
1876
+ "Bot Info Text ℹ",
1877
+ msgs="Send the message to display when a user presses the Info button in Bot Welcome.\n\nSend False to completely remove that button.",
1878
+ ),
1879
+ parse_mode="html",
1880
  )
1881
  msg = await conv.get_response()
1882
  if msg.media or msg.text.startswith("/"):
1883
  return await conv.send_message(
1884
+ fmtmsg("Terminated ", msgs="The operation was terminated."),
1885
+ buttons=get_back_button(_menu("chatbot")),
1886
+ parse_mode="html",
1887
  )
1888
  udB.set_key("BOT_INFO_START", msg.text)
1889
+ await conv.send_message(
1890
+ fmtmsg("Bot Info Text ", msgs="Text has been saved."),
1891
+ buttons=get_back_button(_menu("chatbot")),
1892
+ parse_mode="html",
1893
+ )
1894
 
1895
 
1896
+ @callback(_handler("bot_fsub"), owner=True)
1897
  async def heheh(event):
1898
  Ll = []
1899
  err = ""
1900
  async with event.client.conversation(event.chat_id) as conv:
1901
  await conv.send_message(
1902
+ fmtmsg(
1903
+ "Force Subscribe ",
1904
+ 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.",
1905
+ ),
1906
+ parse_mode="html",
1907
  )
1908
  await conv.send_message(
1909
+ fmtmsg("Example", msgs="-1001234567\n-100778888\n\nFor multiple chats."),
1910
+ parse_mode="html",
1911
  )
1912
  try:
1913
  msg = await conv.get_response()
1914
  except AsyncTimeOut:
1915
+ return await conv.send_message(
1916
+ fmtmsg("Time Up ", msgs="Start from /start back."),
1917
+ parse_mode="html",
1918
+ )
1919
  if not msg.text or msg.text.startswith("/"):
 
1920
  if msg.text == "/clear":
1921
  udB.del_key("PMBOT_FSUB")
1922
+ return await conv.send_message(
1923
+ fmtmsg(
1924
+ "Force Subscribe ",
1925
+ msgs="Force Subscribe has been stopped and applies to the next incoming message.",
1926
+ ),
1927
+ buttons=get_back_button(_menu("chatbot")),
1928
+ parse_mode="html",
1929
+ )
1930
  return await conv.send_message(
1931
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
1932
+ buttons=get_back_button(_menu("chatbot")),
1933
+ parse_mode="html",
1934
  )
1935
  for chat in msg.message.split("\n"):
1936
  if chat.startswith("-") or chat.isdigit():
 
1941
  except Exception as er:
1942
  err += f"**{chat}** : {er}\n"
1943
  if err:
1944
+ return await conv.send_message(
1945
+ fmtmsg("Error ", msgs=err),
1946
+ parse_mode="html",
1947
+ )
1948
+ # Keep the existing database representation; pmbot now parses this
1949
+ # legacy literal safely and reads it fresh for each incoming message.
1950
  udB.set_key("PMBOT_FSUB", str(Ll))
1951
  await conv.send_message(
1952
+ fmtmsg(
1953
+ "Force Subscribe ",
1954
+ msgs="Done. The setting applies to the next incoming message.",
1955
+ ),
1956
+ buttons=get_back_button(_menu("chatbot")),
1957
+ parse_mode="html",
1958
  )
1959
 
1960
 
1961
+ @callback(_handler("bot_welcome"), owner=True)
1962
  async def name(event):
1963
  await event.delete()
1964
  pru = event.sender_id
 
1966
  name = "Bot Welcome Message:"
1967
  async with event.client.conversation(pru) as conv:
1968
  await conv.send_message(
1969
+ fmtmsg(
1970
+ name,
1971
+ 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.",
1972
+ ),
1973
+ parse_mode="html",
1974
  )
1975
  response = conv.wait_event(events.NewMessage(chats=pru))
1976
  response = await response
1977
  themssg = response.message.message
1978
+ if _is_cancel(response):
1979
  return await conv.send_message(
1980
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
1981
+ buttons=get_back_button(_menu("chatbot")),
1982
+ parse_mode="html",
1983
  )
1984
  await setit(event, var, themssg)
1985
  await conv.send_message(
1986
+ fmtmsg(f"{name} Changed ", msgs=f"New value: {themssg}"),
1987
+ buttons=get_back_button(_menu("chatbot")),
1988
+ parse_mode="html",
1989
  )
1990
 
1991
 
1992
+ @callback(_handler("chatbot_on"), owner=True)
1993
  async def chon(event):
1994
  var = "PMBOT"
1995
  await setit(event, var, "True")
1996
+ await AsyncPluginLoader(path="assistant/pmbot.py", key="PM Bot").load_all(log=False)
1997
  if AST_PLUGINS.get("pmbot"):
1998
  for i, e in AST_PLUGINS["pmbot"]:
1999
  event.client.remove_event_handler(i)
2000
  for i, e in AST_PLUGINS["pmbot"]:
2001
  event.client.add_event_handler(i, events.NewMessage(**e))
2002
  await event.edit(
2003
+ fmtmsg(
2004
+ "Chat Bot ",
2005
+ msgs="Now you can chat with people via this bot.",
2006
+ foot="Currently: On",
2007
+ ),
2008
+ buttons=get_back_button(_menu("chatbot")),
2009
+ parse_mode="html",
2010
  )
2011
 
2012
 
2013
+ @callback(_handler("chatbot_off"), owner=True)
2014
  async def chon(event):
2015
  var = "PMBOT"
2016
  await setit(event, var, "False")
 
2018
  for i, e in AST_PLUGINS["pmbot"]:
2019
  event.client.remove_event_handler(i)
2020
  await event.edit(
2021
+ fmtmsg(
2022
+ "Chat Bot ",
2023
+ msgs="Chat with people via this bot has been stopped.",
2024
+ foot="Currently: Off",
2025
+ ),
2026
+ buttons=get_back_button(_menu("chatbot")),
2027
+ parse_mode="html",
2028
  )
2029
 
2030
 
2031
+ @callback(_handler("inline_pic"), owner=True)
2032
  async def media(event):
2033
  await event.delete()
2034
  pru = event.sender_id
 
2036
  name = "Inline Media"
2037
  async with event.client.conversation(pru) as conv:
2038
  await conv.send_message(
2039
+ fmtmsg(
2040
+ name,
2041
+ msgs="Send me a pic/gif/link to set as inline media.\n\nUse /cancel to terminate the operation.",
2042
+ ),
2043
+ parse_mode="html",
2044
  )
2045
  response = await conv.get_response()
2046
  try:
2047
  themssg = response.message
2048
+ if _is_cancel(response):
2049
  return await conv.send_message(
2050
+ fmtmsg("Cancelled ", msgs="Nothing was changed."),
2051
+ buttons=get_back_button(START_SETTER, " Settings"),
2052
+ parse_mode="html",
2053
  )
2054
  except BaseException as er:
2055
  LOGS.exception(er)
 
2062
  url = text_to_url(response)
2063
  else:
2064
  try:
2065
+ x = upl(media)
2066
+ url = f"https://graph.org/{x[0]}"
2067
  remove(media)
2068
  except BaseException as er:
2069
  LOGS.exception(er)
2070
  return await conv.send_message(
2071
+ fmtmsg("Terminated ", msgs="The operation was terminated."),
2072
+ buttons=get_back_button(START_SETTER, " Settings"),
2073
+ parse_mode="html",
2074
  )
2075
  await setit(event, var, url)
2076
  await conv.send_message(
2077
+ fmtmsg(f"{name} Changed ", msgs=f"New value: {url}"),
2078
+ buttons=get_back_button(START_SETTER, " Settings"),
2079
+ parse_mode="html",
2080
  )
2081
 
2082
 
2083
  FD_MEDIA = {}
2084
 
2085
 
2086
+ @callback(FDROID_PATTERN, owner=True)
2087
  async def fdroid_dler(event):
2088
  uri = event.data_match.group(1).decode("utf-8")
2089
  if FD_MEDIA.get(uri):
2090
  return await event.edit(file=FD_MEDIA[uri])
2091
+ await event.answer(" Starting Download ", alert=True)
2092
+ await event.edit(
2093
+ fmtmsg("Downloading "),
2094
+ parse_mode="html",
2095
+ )
2096
  URL = f"https://f-droid.org/packages/{uri}"
2097
+ conte = await fns.async_searcher(URL, re_content=True)
2098
  BSC = bs(conte, "html.parser", from_encoding="utf-8")
2099
  dl_ = BSC.find("p", "package-version-download").find("a")["href"]
2100
  title = BSC.find("h3", "package-name").text.strip()
2101
  thumb = BSC.find("img", "package-icon")["src"]
2102
  if thumb.startswith("/"):
2103
  thumb = f"https://f-droid.org{thumb}"
2104
+ thumb, _ = await fns.fast_download(thumb, filename=f"{uri}.png")
2105
  s_time = time.time()
2106
+ file, _ = await fns.fast_download(
2107
  dl_,
2108
  filename=f"{title}.apk",
2109
+ progress_callback=lambda d, t: asyncio.get_running_loop().create_task(
2110
+ fns.progress(
2111
  d,
2112
  t,
2113
  event,
 
2121
  n_file = await event.client.fast_uploader(
2122
  file, show_progress=True, event=event, message="Uploading...", to_delete=True
2123
  )
2124
+ buttons = ikm([("Search Again", "switch_inline", "fdroid", True, "green")])
2125
+ caption = fmtmsg(
2126
+ f" {title} ", data={"APK": rawhtml(f'<a href="{URL}">{title}</a>')}
2127
+ )
2128
  try:
2129
  msg = await event.edit(
2130
+ f"** [{title}]({URL}) **", file=n_file, thumb=thumb, buttons=buttons
2131
  )
2132
  except Exception as er:
2133
  LOGS.exception(er)
 
2135
  msg = await event.client.edit_message(
2136
  await event.get_input_chat(),
2137
  event.message_id,
2138
+ f"** [{title}]({URL}) **",
2139
  buttons=buttons,
2140
  thumb=thumb,
2141
  file=n_file,
2142
  )
2143
  except Exception as er:
2144
+ remove(thumb)
2145
  LOGS.exception(er)
2146
+ return await event.edit(
2147
+ fmtmsg("Error ", msgs=str(er)),
2148
+ buttons=buttons,
2149
+ parse_mode="html",
2150
+ )
2151
  if msg and hasattr(msg, "media"):
2152
  FD_MEDIA.update({uri: msg.media})
2153
+ remove(thumb)
2154
+
2155
+
2156
+ @callback("noop")
2157
+ async def _noop(event):
2158
+ await event.answer()
assistant/games.py CHANGED
@@ -1,49 +1,97 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
  """
9
- • `{i}akinator` | `/akinator`
10
- Start akinator game from Userbot/Assistant
11
 
12
- • `/startgame`
13
- Open Portal for Games
14
  """
15
 
16
  import asyncio
17
- import re, uuid, operator
 
 
 
 
18
  from random import choice, shuffle
19
 
20
- from akipy.async_akipy import Akinator
 
 
 
 
 
 
21
  from telethon.errors.rpcerrorlist import BotMethodInvalidError
22
  from telethon.events import Raw
 
23
  from telethon.tl.types import InputMediaPoll, Poll, PollAnswer, UpdateMessagePollVote
24
 
25
  from pyUltroid._misc._decorators import ultroid_cmd
26
- from logging import getLogger
27
- from html import unescape
28
- from telethon.tl.types import TextWithEntities
29
- from pyUltroid.fns.helper import inline_mention
30
- from pyUltroid.fns.tools import async_searcher
31
- from telethon.errors import ChatSendStickersForbiddenError
32
 
33
  from . import * # Ensure this import matches your project structure
 
 
34
 
35
  games = {}
36
  aki_photo = "https://graph.org/file/3cc8825c029fd0cab9edc.jpg"
37
 
38
- akipyLOGS = getLogger("akipy")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  @ultroid_cmd(pattern="akinator")
41
  async def akina(e):
42
  sta = Akinator()
43
  games[e.chat_id] = {e.id: sta}
44
  LOGS.info(f"Game started for chat {e.chat_id} with ID {e.id}.")
 
45
  try:
46
- m = await e.client.inline_query(asst.me.username, f"aki_{e.chat_id}_{e.id}")
47
  await m[0].click(e.chat_id)
48
  akipyLOGS.info(f"Clicked inline result for chat {e.chat_id}")
49
  except BotMethodInvalidError as err:
@@ -51,7 +99,7 @@ async def akina(e):
51
  await asst.send_file(
52
  e.chat_id,
53
  aki_photo,
54
- buttons=Button.inline(get_string("aki_2"), data=f"aki_{e.chat_id}_{e.id}"),
55
  )
56
  except Exception as er:
57
  akipyLOGS.error(f"Unexpected error: {er}")
@@ -65,28 +113,29 @@ async def _akokk(e):
65
  await akina(e)
66
 
67
 
68
- @callback(re.compile("aki_(.*)"), owner=True)
69
  async def doai(e):
70
- adt = e.pattern_match.group(1).strip().decode("utf-8")
71
- dt = adt.split("_")
72
- ch = int(dt[0])
73
- mid = int(dt[1])
74
  await e.edit(get_string("com_1"))
75
  try:
76
  await games[ch][mid].start_game(child_mode=False)
77
- bts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Yes", "No", "Idk"]]
78
- cts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Probably", "Probably Not"]]
79
- bts = [bts, cts]
80
- await e.edit(f"Q. {games[ch][mid].question}", buttons=bts)
 
 
81
  except KeyError:
82
  return await e.answer(get_string("aki_1"), alert=True)
83
 
84
 
85
- @callback(re.compile("aka_(.*)"), owner=True)
86
  async def okah(e):
87
  try:
88
- mk = e.pattern_match.group(1).decode("utf-8").split("_")
89
- #akipyLOGS.info(f"Parsed values: {mk}")
90
 
91
  if len(mk) < 3:
92
  akipyLOGS.error("Pattern match did not return enough parts.")
@@ -102,30 +151,34 @@ async def okah(e):
102
  # Check for the final guess in the API response
103
  if gm.name_proposition and gm.description_proposition:
104
  gm.win = True
105
- text = f"It's {gm.name_proposition}\n{gm.description_proposition}"
106
- await e.edit(text, file=gm.photo)
107
  else:
108
  # Game is not won yet, continue asking questions
109
- buttons = [
110
- [Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Yes", "No", "Idk"]],
111
- [Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Probably", "Probably Not"]],
112
- ]
113
- await e.edit(gm.question, buttons=buttons)
 
114
 
115
  except KeyError:
116
  await e.answer(get_string("aki_3"))
117
  except Exception as ex:
118
- akipyLOGS.error(f"An unexpected error occurred: {ex}")
 
 
 
 
119
 
120
 
121
- @in_pattern(re.compile("aki_?(.*)"), owner=True)
122
  async def eiagx(e):
123
- bts = Button.inline(get_string("aki_2"), data=e.text)
124
  ci = types.InputWebDocument(aki_photo, 0, "image/jpeg", [])
125
  ans = [
126
  await e.builder.article(
127
  "Akinator",
128
- type="photo",
129
  content=ci,
130
  text="Akinator",
131
  thumb=ci,
@@ -138,18 +191,26 @@ async def eiagx(e):
138
 
139
  # ----------------------- Main Command ------------------- #
140
 
141
- GIMAGE = "https://graph.org/file/1c51015bae5205a65fd69.jpg"
 
 
 
 
142
 
143
  @asst_cmd(pattern="startgame", owner=True)
144
  async def magic(event):
145
- buttons = [
146
- [Button.inline("Trivia Quiz", "trzia")],
147
- [Button.inline("Cancel ❌", "delit")],
148
- ]
 
 
 
149
  await event.reply(
150
- get_string("games_1"),
151
- file=GIMAGE,
152
  buttons=buttons,
 
153
  )
154
 
155
 
@@ -169,27 +230,34 @@ CONGO_STICKER = [
169
  "CAADAgADiwMAAsSraAuoe2BwYu1sdQI",
170
  ]
171
 
 
 
172
 
173
- @callback("delit", owner=True)
 
174
  async def delete_it(event):
175
  await event.delete()
176
 
177
 
178
- @callback(re.compile("ctdown(.*)"), owner=True)
179
  async def ct_spam(e):
180
  n = e.data_match.group(1).decode("utf-8")
181
  await e.answer(f"Wait {n} seconds..", alert=True)
182
 
183
 
184
- @callback(re.compile("trzia(.*)"), owner=True)
185
  async def choose_cata(event):
186
- match = event.data_match.group(1).decode("utf-8")
187
- if not match:
 
 
 
 
188
  if TR_BTS.get("category"):
189
  buttons = TR_BTS["category"]
190
  else:
191
  req = (
192
- await async_searcher(
193
  "https://opentdb.com/api_category.php", re_json=True
194
  )
195
  )["trivia_categories"]
@@ -198,39 +266,99 @@ async def choose_cata(event):
198
  name = i["name"]
199
  if ":" in name:
200
  name = name.split(":")[1]
201
- btt.append(Button.inline(name, f"trziad_{i['id']}"))
202
- buttons = list(zip(btt[::2], btt[1::2]))
 
 
 
 
 
 
203
  if len(btt) % 2 == 1:
204
- buttons.append((btt[-1],))
205
- buttons.append([Button.inline("Cancel ❌", "delit")])
 
206
  TR_BTS.update({"category": buttons})
207
- text = get_string("games_2")
208
- elif match[0] == "d":
209
- cat = match[1:]
210
- buttons = [[Button.inline(i, f"trziac{cat}_{i}") for i in DIFI_KEYS]]
211
- buttons.append(get_back_button("trzia"))
212
- text = get_string("games_3")
213
- elif match[0] == "c":
214
- m = match[1:]
215
- buttons = [[Button.inline(str(i), f"trziat{m}_{i}") for i in range(10, 70, 20)]]
216
- text = get_string("games_4")
217
- elif match[0] == "t":
218
- m_ = match[1:]
219
- buttons = [
220
- [Button.inline(str(i), f"trzias{m_}_{i}") for i in [10, 30, 60, 120]]
221
- ]
222
- text = get_string("games_5")
223
- elif match[0] == "s":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  chat = event.chat_id
225
- cat, le, nu, in_ = match[2:].split("_")
226
- msg = await event.edit(get_string("games_6").format(le, nu))
 
 
227
  for i in reversed(range(5)):
228
- msg = await msg.edit(buttons=Button.inline(f"{i} ⏰", f"ctdown{i}"))
 
 
 
 
 
229
  await asyncio.sleep(1)
230
  await msg.edit(
231
- msg.text + "\n\n• Send /cancel to stop the Quiz...", buttons=None
232
  )
233
- qsss = await async_searcher(
234
  f"https://opentdb.com/api.php?amount={nu}&category={cat}&difficulty={le.lower()}",
235
  re_json=True,
236
  )
@@ -244,10 +372,10 @@ async def choose_cata(event):
244
  if TRIVIA_CHATS[chat].get("cancel") is not None:
245
  break
246
  ansi = str(uuid.uuid1()).split("-")[0].encode()
247
- opts = [PollAnswer(TextWithEntities(unescape(q["correct_answer"]), entities=[]), ansi)]
248
  [
249
  opts.append(
250
- PollAnswer(TextWithEntities(unescape(a), entities=[]), str(uuid.uuid1()).split("-")[0].encode())
251
  )
252
  for a in q["incorrect_answers"]
253
  ]
@@ -255,10 +383,7 @@ async def choose_cata(event):
255
  poll = InputMediaPoll(
256
  Poll(
257
  0,
258
- TextWithEntities(
259
- f"[{copper+1}]. " + unescape(q["question"]),
260
- entities=[]
261
- ),
262
  answers=opts,
263
  public_voters=True,
264
  quiz=True,
@@ -273,51 +398,50 @@ async def choose_cata(event):
273
  await asyncio.sleep(int(in_))
274
  if not TRIVIA_CHATS[chat]:
275
  await event.respond(
276
- "No-One Got Any Score in the Quiz!\nBetter Luck Next Time!"
 
 
 
 
277
  )
278
  else:
279
  try:
280
  await event.respond(file=choice(CONGO_STICKER))
281
  except ChatSendStickersForbiddenError:
282
  pass
283
- LBD = "🎯 **Scoreboard of the Quiz.**\n\n"
284
  TRC = TRIVIA_CHATS[chat]
285
  if "cancel" in TRC.keys():
286
  del TRC["cancel"]
287
  for userid, user_score in dict(
288
  sorted(TRC.items(), key=operator.itemgetter(1), reverse=True)
289
  ).items():
290
- user = inline_mention(await event.client.get_entity(userid))
291
- LBD += f"••• {user} - {user_score}\n"
292
- await event.respond(LBD)
 
 
 
 
293
  del TRIVIA_CHATS[chat]
294
  list_ = list(POLLS.copy().keys())
295
  for key in list_:
296
  if POLLS[key]["chat"] == chat:
297
  del POLLS[key]
298
  return
299
- await event.edit(text, buttons=buttons)
300
 
301
 
302
  @asst.on(
303
  Raw(UpdateMessagePollVote, func=lambda x: TRIVIA_CHATS and POLLS.get(x.poll_id))
304
  )
305
- async def pollish(eve: UpdateMessagePollVote):
306
  if POLLS.get(eve.poll_id)["chat"] not in TRIVIA_CHATS.keys():
307
  return
308
- if not eve.options:
309
- # Consider as correct answer if no options selected
310
- chat = POLLS.get(eve.poll_id)["chat"]
311
- user = eve.peer.user_id
312
- if not TRIVIA_CHATS.get(chat, {}).get(user):
313
- TRIVIA_CHATS[chat][user] = 1
314
- else:
315
- TRIVIA_CHATS[chat][user] += 1
316
- return
317
  if POLLS[eve.poll_id]["answer"] != eve.options[0]:
318
  return
319
  chat = POLLS.get(eve.poll_id)["chat"]
320
- user = eve.peer.user_id
321
  if not TRIVIA_CHATS.get(chat, {}).get(user):
322
  TRIVIA_CHATS[chat][user] = 1
323
  else:
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2024 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
  """
9
+ {i}akinator | /akinator
10
+ Start akinator game from Userbot/Assistant
11
 
12
+ /startgame
13
+ Open Portal for Games
14
  """
15
 
16
  import asyncio
17
+ import html
18
+ import re
19
+ import operator
20
+ import uuid
21
+ from html import unescape
22
  from random import choice, shuffle
23
 
24
+ try:
25
+ from akipy.async_akipy import Akinator, akipyLOGS
26
+ except ImportError:
27
+ from akipy.async_akinator import Akinator
28
+ import logging
29
+
30
+ akipyLOGS = logging.getLogger("akipy")
31
  from telethon.errors.rpcerrorlist import BotMethodInvalidError
32
  from telethon.events import Raw
33
+ from telethon.tl import types
34
  from telethon.tl.types import InputMediaPoll, Poll, PollAnswer, UpdateMessagePollVote
35
 
36
  from pyUltroid._misc._decorators import ultroid_cmd
37
+ from custom.tg import ikm
38
+ from custom.fmt import fmtmsg, rawhtml
 
 
 
 
39
 
40
  from . import * # Ensure this import matches your project structure
41
+ from ._cbs import cb, cb_str, cb_exact_pattern, cb_pattern
42
+ from pyUltroid.fns import fns
43
 
44
  games = {}
45
  aki_photo = "https://graph.org/file/3cc8825c029fd0cab9edc.jpg"
46
 
47
+ #: assistant:games:aki:<chat>:<mid> reused verbatim as both the inline
48
+ #: query text (eiagx/akina) and the resulting button/callback data
49
+ #: (doai), so it's built once here rather than three separate times.
50
+ AKI_PREFIX = cb_str("assistant", "games", "aki")
51
+ AKI_CALLBACK_PATTERN = cb_pattern("assistant", "games", "aki")
52
+ AKI_TEXT_PATTERN = re.compile(re.escape(AKI_PREFIX) + r":(.*)")
53
+
54
+ TRIVIA_CAT = cb("assistant", "games", "trivia", "cat")
55
+ DELIT = cb("assistant", "games", "delit")
56
+
57
+
58
+ def _akinator_result(name, description):
59
+ """Build a safe HTML result without interpreting provider text as markup."""
60
+ body = f"It's <b>{html.escape(str(name))}</b>\n{html.escape(str(description))}"
61
+ return fmtmsg("Akinator Result", msgs=rawhtml(body))
62
+
63
+
64
+ def _aka_buttons(ch, mid):
65
+ """Akinator answer keyboard for game (ch, mid) (used by both the
66
+ first question in doai and every follow-up in okah)."""
67
+
68
+ def _a(ans):
69
+ return cb("assistant", "games", "aka", ch, mid, ans)
70
+
71
+ return ikm(
72
+ [
73
+ [
74
+ ("Yes", _a("Yes"), "primary"),
75
+ ("No", _a("No"), "primary"),
76
+ ("Idk", _a("Idk"), "primary"),
77
+ ],
78
+ [
79
+ ("Probably", _a("Probably"), "primary"),
80
+ ("Probably Not", _a("Probably Not"), "primary"),
81
+ ],
82
+ ],
83
+ icon=False,
84
+ )
85
+
86
 
87
  @ultroid_cmd(pattern="akinator")
88
  async def akina(e):
89
  sta = Akinator()
90
  games[e.chat_id] = {e.id: sta}
91
  LOGS.info(f"Game started for chat {e.chat_id} with ID {e.id}.")
92
+ query = f"{AKI_PREFIX}:{e.chat_id}:{e.id}"
93
  try:
94
+ m = await e.client.inline_query(asst.me.username, query)
95
  await m[0].click(e.chat_id)
96
  akipyLOGS.info(f"Clicked inline result for chat {e.chat_id}")
97
  except BotMethodInvalidError as err:
 
99
  await asst.send_file(
100
  e.chat_id,
101
  aki_photo,
102
+ buttons=ikm([[(get_string("aki_2"), query, "primary")]], icon=False),
103
  )
104
  except Exception as er:
105
  akipyLOGS.error(f"Unexpected error: {er}")
 
113
  await akina(e)
114
 
115
 
116
+ @callback(AKI_CALLBACK_PATTERN, owner=True)
117
  async def doai(e):
118
+ adt = e.data_match.group(1).decode("utf-8")
119
+ ch, mid = adt.split(":")
120
+ ch = int(ch)
121
+ mid = int(mid)
122
  await e.edit(get_string("com_1"))
123
  try:
124
  await games[ch][mid].start_game(child_mode=False)
125
+ bts = _aka_buttons(ch, mid)
126
+ await e.edit(
127
+ fmtmsg("Akinator ", msgs=f"Q. {games[ch][mid].question}"),
128
+ buttons=bts,
129
+ parse_mode="html",
130
+ )
131
  except KeyError:
132
  return await e.answer(get_string("aki_1"), alert=True)
133
 
134
 
135
+ @callback(cb_pattern("assistant", "games", "aka"), owner=True)
136
  async def okah(e):
137
  try:
138
+ mk = e.data_match.group(1).decode("utf-8").split(":")
 
139
 
140
  if len(mk) < 3:
141
  akipyLOGS.error("Pattern match did not return enough parts.")
 
151
  # Check for the final guess in the API response
152
  if gm.name_proposition and gm.description_proposition:
153
  gm.win = True
154
+ text = _akinator_result(gm.name_proposition, gm.description_proposition)
155
+ await e.edit(text, file=gm.photo, parse_mode="html")
156
  else:
157
  # Game is not won yet, continue asking questions
158
+ buttons = _aka_buttons(ch, mid)
159
+ await e.edit(
160
+ fmtmsg("Akinator ", msgs=gm.question),
161
+ buttons=buttons,
162
+ parse_mode="html",
163
+ )
164
 
165
  except KeyError:
166
  await e.answer(get_string("aki_3"))
167
  except Exception as ex:
168
+ akipyLOGS.exception(f"An unexpected error occurred: {ex}")
169
+ try:
170
+ await e.answer("The game could not continue. Start a new game.", alert=True)
171
+ except Exception:
172
+ pass
173
 
174
 
175
+ @in_pattern(AKI_TEXT_PATTERN, owner=True)
176
  async def eiagx(e):
177
+ bts = ikm([[(get_string("aki_2"), e.text, "primary")]], icon=False)
178
  ci = types.InputWebDocument(aki_photo, 0, "image/jpeg", [])
179
  ans = [
180
  await e.builder.article(
181
  "Akinator",
 
182
  content=ci,
183
  text="Akinator",
184
  thumb=ci,
 
191
 
192
  # ----------------------- Main Command ------------------- #
193
 
194
+ GIMAGES = [
195
+ "https://graph.org/file/1c51015bae5205a65fd69.jpg",
196
+ "https://imgwhale.xyz/3xyr322l64j9590",
197
+ ]
198
+
199
 
200
  @asst_cmd(pattern="startgame", owner=True)
201
  async def magic(event):
202
+ buttons = ikm(
203
+ [
204
+ [("Trivia Quiz ", TRIVIA_CAT, "primary")],
205
+ [("Cancel ", DELIT, "danger")],
206
+ ],
207
+ icon=False,
208
+ )
209
  await event.reply(
210
+ fmtmsg("SarahUB Games ", msgs=get_string("games_1")),
211
+ file=choice(GIMAGES),
212
  buttons=buttons,
213
+ parse_mode="html",
214
  )
215
 
216
 
 
230
  "CAADAgADiwMAAsSraAuoe2BwYu1sdQI",
231
  ]
232
 
233
+ TRIVIA_PATTERN = cb_pattern("assistant", "games", "trivia")
234
+ CTDOWN_PATTERN = cb_pattern("assistant", "games", "ctdown")
235
 
236
+
237
+ @callback(cb_exact_pattern("assistant", "games", "delit"), owner=True)
238
  async def delete_it(event):
239
  await event.delete()
240
 
241
 
242
+ @callback(CTDOWN_PATTERN, owner=True)
243
  async def ct_spam(e):
244
  n = e.data_match.group(1).decode("utf-8")
245
  await e.answer(f"Wait {n} seconds..", alert=True)
246
 
247
 
248
+ @callback(TRIVIA_PATTERN, owner=True)
249
  async def choose_cata(event):
250
+ tail = event.data_match.group(1).decode("utf-8")
251
+ parts = tail.split(":")
252
+ action = parts[0]
253
+ rest = parts[1:]
254
+
255
+ if action == "cat":
256
  if TR_BTS.get("category"):
257
  buttons = TR_BTS["category"]
258
  else:
259
  req = (
260
+ await fns.async_searcher(
261
  "https://opentdb.com/api_category.php", re_json=True
262
  )
263
  )["trivia_categories"]
 
266
  name = i["name"]
267
  if ":" in name:
268
  name = name.split(":")[1]
269
+ btt.append(
270
+ (
271
+ name,
272
+ cb("assistant", "games", "trivia", "diff", i["id"]),
273
+ "primary",
274
+ )
275
+ )
276
+ buttons_data = list(zip(btt[::2], btt[1::2]))
277
  if len(btt) % 2 == 1:
278
+ buttons_data.append([btt[-1]])
279
+ buttons_data.append([("Cancel ", DELIT, "danger")])
280
+ buttons = ikm(buttons_data, icon=False)
281
  TR_BTS.update({"category": buttons})
282
+ text = fmtmsg("Trivia Setup ", msgs=get_string("games_2"))
283
+ elif action == "diff":
284
+ cat = rest[0]
285
+ buttons = ikm(
286
+ [
287
+ [
288
+ (
289
+ "Easy ",
290
+ cb("assistant", "games", "trivia", "num", cat, "Easy"),
291
+ "primary",
292
+ ),
293
+ (
294
+ "Medium ",
295
+ cb("assistant", "games", "trivia", "num", cat, "Medium"),
296
+ "primary",
297
+ ),
298
+ (
299
+ "Hard ",
300
+ cb("assistant", "games", "trivia", "num", cat, "Hard"),
301
+ "primary",
302
+ ),
303
+ ],
304
+ [("Back", TRIVIA_CAT, None)],
305
+ ],
306
+ icon=False,
307
+ )
308
+ text = fmtmsg("Difficulty Selection ", msgs=get_string("games_3"))
309
+ elif action == "num":
310
+ cat, diff = rest
311
+ buttons = ikm(
312
+ [
313
+ [
314
+ (
315
+ f"{i} Questions",
316
+ cb("assistant", "games", "trivia", "time", cat, diff, i),
317
+ "primary",
318
+ )
319
+ for i in range(10, 70, 20)
320
+ ],
321
+ [("Back", TRIVIA_CAT, None)],
322
+ ],
323
+ icon=False,
324
+ )
325
+ text = fmtmsg("Number of Questions ", msgs=get_string("games_4"))
326
+ elif action == "time":
327
+ cat, diff, num = rest
328
+ buttons = ikm(
329
+ [
330
+ [
331
+ (
332
+ f"{i}s",
333
+ cb("assistant", "games", "trivia", "start", cat, diff, num, i),
334
+ "primary",
335
+ )
336
+ for i in [10, 30, 60, 120]
337
+ ],
338
+ [("Back", TRIVIA_CAT, None)],
339
+ ],
340
+ icon=False,
341
+ )
342
+ text = fmtmsg("Time Limit per Question ", msgs=get_string("games_5"))
343
+ elif action == "start":
344
+ cat, le, nu, in_ = rest
345
  chat = event.chat_id
346
+ msg = await event.edit(
347
+ fmtmsg("Trivia Quiz ", msgs=get_string("games_6").format(le, nu)),
348
+ parse_mode="html",
349
+ )
350
  for i in reversed(range(5)):
351
+ msg = await msg.edit(
352
+ buttons=ikm(
353
+ [[(f"{i}", cb("assistant", "games", "ctdown", i), None)]],
354
+ icon=False,
355
+ )
356
+ )
357
  await asyncio.sleep(1)
358
  await msg.edit(
359
+ msg.text + "\n\n Send /cancel to stop the Quiz...", buttons=None
360
  )
361
+ qsss = await fns.async_searcher(
362
  f"https://opentdb.com/api.php?amount={nu}&category={cat}&difficulty={le.lower()}",
363
  re_json=True,
364
  )
 
372
  if TRIVIA_CHATS[chat].get("cancel") is not None:
373
  break
374
  ansi = str(uuid.uuid1()).split("-")[0].encode()
375
+ opts = [PollAnswer(unescape(q["correct_answer"]), ansi)]
376
  [
377
  opts.append(
378
+ PollAnswer(unescape(a), str(uuid.uuid1()).split("-")[0].encode())
379
  )
380
  for a in q["incorrect_answers"]
381
  ]
 
383
  poll = InputMediaPoll(
384
  Poll(
385
  0,
386
+ f"[{copper + 1}]. " + unescape(q["question"]),
 
 
 
387
  answers=opts,
388
  public_voters=True,
389
  quiz=True,
 
398
  await asyncio.sleep(int(in_))
399
  if not TRIVIA_CHATS[chat]:
400
  await event.respond(
401
+ fmtmsg(
402
+ "Quiz Finished ",
403
+ msgs="No-One Got Any Score in the Quiz!\nBetter Luck Next Time!",
404
+ ),
405
+ parse_mode="html",
406
  )
407
  else:
408
  try:
409
  await event.respond(file=choice(CONGO_STICKER))
410
  except ChatSendStickersForbiddenError:
411
  pass
412
+ LBD = {}
413
  TRC = TRIVIA_CHATS[chat]
414
  if "cancel" in TRC.keys():
415
  del TRC["cancel"]
416
  for userid, user_score in dict(
417
  sorted(TRC.items(), key=operator.itemgetter(1), reverse=True)
418
  ).items():
419
+ user_entity = await event.client.get_entity(userid)
420
+ LBD[get_display_name(user_entity)] = f"{user_score} Points"
421
+
422
+ await event.respond(
423
+ fmtmsg(" Quiz Scoreboard", data=LBD),
424
+ parse_mode="html",
425
+ )
426
  del TRIVIA_CHATS[chat]
427
  list_ = list(POLLS.copy().keys())
428
  for key in list_:
429
  if POLLS[key]["chat"] == chat:
430
  del POLLS[key]
431
  return
432
+ await event.edit(text, buttons=buttons, parse_mode="html")
433
 
434
 
435
  @asst.on(
436
  Raw(UpdateMessagePollVote, func=lambda x: TRIVIA_CHATS and POLLS.get(x.poll_id))
437
  )
438
+ async def pollish(eve):
439
  if POLLS.get(eve.poll_id)["chat"] not in TRIVIA_CHATS.keys():
440
  return
 
 
 
 
 
 
 
 
 
441
  if POLLS[eve.poll_id]["answer"] != eve.options[0]:
442
  return
443
  chat = POLLS.get(eve.poll_id)["chat"]
444
+ user = eve.user_id
445
  if not TRIVIA_CHATS.get(chat, {}).get(user):
446
  TRIVIA_CHATS[chat][user] = 1
447
  else:
assistant/initial.py CHANGED
@@ -1,84 +1,91 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
- import re
9
 
10
  from . import *
 
 
11
 
12
- STRINGS = {
13
- 1: """🎇 **Thanks for Deploying Ultroid Userbot!**
14
-
15
- • Here, are the Some Basic stuff from, where you can Know, about its Usage.""",
16
- 2: """🎉** About Ultroid**
17
-
18
- 🧿 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.
19
-
20
- ❣ Made by **@TeamUltroid**""",
21
- 3: """**💡• FAQs •**
22
 
23
- -> [Username Tracker](https://t.me/UltroidUpdates/24)
24
- -> [Keeping Custom Addons Repo](https://t.me/UltroidUpdates/28)
25
- -> [Disabling Deploy message](https://t.me/UltroidUpdates/27)
26
- -> [Setting up TimeZone](https://t.me/UltroidUpdates/22)
27
- -> [About Inline PmPermit](https://t.me/UltroidUpdates/21)
28
- -> [About Dual Mode](https://t.me/UltroidUpdates/18)
29
- -> [Custom Thumbnail](https://t.me/UltroidUpdates/13)
30
- -> [About FullSudo](https://t.me/UltroidUpdates/11)
31
- -> [Setting Up PmBot](https://t.me/UltroidUpdates/2)
32
- -> [Also Check](https://t.me/UltroidUpdates/14)
33
-
34
- **• To Know About Updates**
35
- - Join @TeamUltroid.""",
36
- 4: f"""• `To Know All Available Commands`
37
-
38
- - `{HNDLR}help`
39
- - `{HNDLR}cmds`""",
40
- 5: """• **For Any Other Query or Suggestion**
41
- - Move to **@UltroidSupportChat**.
42
-
43
- • Thanks for Reaching till END.""",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  }
45
 
 
 
46
 
47
- @callback(re.compile("initft_(\\d+)"))
48
- async def init_depl(e):
49
- CURRENT = int(e.data_match.group(1))
50
- if CURRENT == 5:
51
- return await e.edit(
52
- STRINGS[5],
53
- buttons=Button.inline("<< Back", "initbk_4"),
54
- link_preview=False,
 
 
55
  )
 
 
 
56
 
57
- await e.edit(
58
- STRINGS[CURRENT],
59
- buttons=[
60
- Button.inline("<<", f"initbk_{str(CURRENT - 1)}"),
61
- Button.inline(">>", f"initft_{str(CURRENT + 1)}"),
62
- ],
63
  link_preview=False,
 
64
  )
65
 
66
 
67
- @callback(re.compile("initbk_(\\d+)"))
68
- async def ineiq(e):
69
- CURRENT = int(e.data_match.group(1))
70
- if CURRENT == 1:
71
- return await e.edit(
72
- STRINGS[1],
73
- buttons=Button.inline("Start Back >>", "initft_2"),
74
- link_preview=False,
75
- )
76
-
77
- await e.edit(
78
- STRINGS[CURRENT],
79
- buttons=[
80
- Button.inline("<<", f"initbk_{str(CURRENT - 1)}"),
81
- Button.inline(">>", f"initft_{str(CURRENT + 1)}"),
82
- ],
83
- link_preview=False,
84
- )
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
+ import html
9
 
10
  from . import *
11
+ from ._cbs import cb, cb_pattern
12
+ from custom.tg import ikm
13
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ STRINGS = {
16
+ 1: (
17
+ "<b>Welcome to Ultroid</b>\n\n"
18
+ "Your userbot is online. This short guide covers the first commands, "
19
+ "help, and support."
20
+ ),
21
+ 2: (
22
+ "<b>About Ultroid</b>\n\n"
23
+ "Ultroid is a modular Telegram userbot built with Telethon. Its plugins "
24
+ "add tools for messaging, moderation, media, and automation.\n\n"
25
+ 'Maintained by <a href="https://t.me/TeamUltroid">TeamUltroid</a>.'
26
+ ),
27
+ 3: (
28
+ "<b>Quick links</b>\n\n"
29
+ '<a href="https://t.me/UltroidUpdates/24">Username tracker</a>\n'
30
+ '<a href="https://t.me/UltroidUpdates/28">Custom add-ons</a>\n'
31
+ '<a href="https://t.me/UltroidUpdates/22">Time zone setup</a>\n'
32
+ '<a href="https://t.me/UltroidUpdates/21">Inline PMPermit</a>\n'
33
+ '<a href="https://t.me/UltroidUpdates/18">Dual mode</a>\n'
34
+ '<a href="https://t.me/UltroidUpdates/2">Private-message bot</a>\n'
35
+ '<a href="https://t.me/UltroidUpdates/14">More guides</a>'
36
+ ),
37
+ 4: (
38
+ "<b>Find commands</b>\n\n"
39
+ f"<code>{html.escape(HNDLR)}help</code> opens the help menu.\n"
40
+ f"<code>{html.escape(HNDLR)}help &lt;plugin&gt;</code> shows a plugin's "
41
+ "commands.\n"
42
+ f"<code>{html.escape(HNDLR)}cmds</code> opens the complete command index."
43
+ ),
44
+ 5: (
45
+ "<b>Need a hand?</b>\n\n"
46
+ "For questions, suggestions, and troubleshooting, visit "
47
+ '<a href="https://t.me/UltroidSupportChat">Ultroid Support</a>.\n\n'
48
+ "You're all set."
49
+ ),
50
  }
51
 
52
+ PAGE_COUNT = len(STRINGS)
53
+ PAGE_PATTERN = cb_pattern("assistant", "initial")
54
 
55
+
56
+ def _page_buttons(current):
57
+ rows = []
58
+ if current > 1:
59
+ rows.append(
60
+ ("Previous", cb("assistant", "initial", "prev", current - 1), "primary")
61
+ )
62
+ if current < PAGE_COUNT:
63
+ rows.append(
64
+ ("Next", cb("assistant", "initial", "next", current + 1), "primary")
65
  )
66
+ elif current == PAGE_COUNT:
67
+ rows.append(("Back to start", cb("assistant", "initial", "prev", 1), None))
68
+ return ikm([rows], icon=False) if rows else []
69
 
70
+
71
+ async def _render_page(event, current):
72
+ current = max(1, min(int(current), PAGE_COUNT))
73
+ await event.edit(
74
+ STRINGS[current],
75
+ buttons=_page_buttons(current),
76
  link_preview=False,
77
+ parse_mode="html",
78
  )
79
 
80
 
81
+ @callback(PAGE_PATTERN)
82
+ async def init_depl(event):
83
+ """Render the guide page named by the callback payload."""
84
+ try:
85
+ payload = event.data.decode("utf-8").split(":")
86
+ current = int(payload[-1])
87
+ except (AttributeError, UnicodeDecodeError, ValueError, IndexError):
88
+ return await event.answer("This guide page could not be opened.", alert=True)
89
+ if not 1 <= current <= PAGE_COUNT:
90
+ return await event.answer("This guide page no longer exists.", alert=True)
91
+ await _render_page(event, current)
 
 
 
 
 
 
 
assistant/inlinestuff.py CHANGED
@@ -1,39 +1,134 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
  import base64
 
9
  import inspect
 
10
  from datetime import datetime
11
  from html import unescape
12
  from random import choice
13
- from re import compile as re_compile
14
 
15
  from bs4 import BeautifulSoup as bs
16
  from telethon import Button
17
  from telethon.tl.alltlobjects import LAYER, tlobjects
18
- from telethon.tl.types import DocumentAttributeAudio as Audio
19
  from telethon.tl.types import InputWebDocument as wb
20
 
21
- from pyUltroid.fns.misc import google_search
22
- from pyUltroid.fns.tools import (
23
- _webupload_cache,
24
- async_searcher,
25
- get_ofox,
26
- saavn_search,
27
- webuploader,
 
 
 
28
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- from . import *
31
- from . import _ult_cache
32
 
33
  SUP_BUTTONS = [
34
  [
35
- Button.url("• Repo •", url="https://github.com/TeamUltroid/Ultroid"),
36
- Button.url("• Support •", url="t.me/UltroidSupportChat"),
 
 
37
  ],
38
  ]
39
 
@@ -50,17 +145,24 @@ apis = [
50
 
51
  @in_pattern("ofox", owner=True)
52
  async def _(e):
 
53
  try:
54
  match = e.text.split(" ", maxsplit=1)[1]
55
  except IndexError:
56
- kkkk = e.builder.article(
57
- title="Enter Device Codename",
 
 
 
 
 
58
  thumb=wb(ofox, 0, "image/jpeg", []),
59
- text="**OFᴏx🦊Rᴇᴄᴏᴠᴇʀʏ**\n\nYou didn't search anything",
60
- buttons=Button.switch_inline("Sᴇᴀʀᴄʜ Aɢᴀɪɴ", query="ofox ", same_peer=True),
 
61
  )
62
  return await e.answer([kkkk])
63
- device, releases = await get_ofox(match)
64
  if device.get("detail") is None:
65
  fox = []
66
  fullname = device["full_name"]
@@ -71,27 +173,36 @@ async def _(e):
71
  for data in releases["data"]:
72
  release = data["type"]
73
  version = data["version"]
74
- size = humanbytes(data["size"])
75
  release_date = datetime.utcfromtimestamp(data["date"]).strftime("%Y-%m-%d")
76
- text = f"[­]({ofox})**OrangeFox Recovery For**\n\n"
77
- text += f"` Full Name: {fullname}`\n"
78
- text += f"` Codename: {codename}`\n"
79
- text += f"` Maintainer: {maintainer}`\n"
80
- text += f"` Build Type: {release}`\n"
81
- text += f"` Version: {version}`\n"
82
- text += f"` Size: {size}`\n"
83
- text += f"` Build Date: {release_date}`"
 
 
 
 
 
 
 
 
 
84
  fox.append(
85
- await e.builder.article(
86
- title=f"{fullname}",
 
 
87
  description=f"{version}\n{release_date}",
88
- text=text,
89
  thumb=wb(ofox, 0, "image/jpeg", []),
90
- link_preview=True,
91
  buttons=[
92
- Button.url("Dᴏᴡɴʟᴏᴀᴅ", url=f"{link}"),
93
- Button.switch_inline(
94
- "Sᴇᴀʀᴄʜ Aɢᴀɪɴ", query="ofox ", same_peer=True
95
  ),
96
  ],
97
  )
@@ -105,74 +216,152 @@ async def _(e):
105
  )
106
 
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  @in_pattern("fl2lnk ?(.*)", owner=True)
109
- async def _(e):
110
- match = e.pattern_match.group(1)
 
 
 
 
 
 
111
  chat_id, msg_id = match.split(":")
112
- filename = _webupload_cache[int(chat_id)][int(msg_id)]
 
 
 
 
 
113
  if "/" in filename:
114
  filename = filename.split("/")[-1]
115
- __cache = f"{chat_id}:{msg_id}"
116
- buttons = [
117
- [
118
- Button.inline("anonfiles", data=f"flanonfiles//{__cache}"),
119
- Button.inline("transfer", data=f"fltransfer//{__cache}"),
120
- ],
121
- [
122
- Button.inline("bayfiles", data=f"flbayfiles//{__cache}"),
123
- Button.inline("x0.at", data=f"flx0.at//{__cache}"),
124
- ],
125
- [
126
- Button.inline("file.io", data=f"flfile.io//{__cache}"),
127
- Button.inline("siasky", data=f"flsiasky//{__cache}"),
128
- ],
129
- ]
 
 
 
 
130
  try:
131
- lnk = [
132
- await e.builder.article(
133
- title=f"Upload {filename}",
134
- text=f"**File:**\n{filename}",
 
 
135
  buttons=buttons,
136
  )
137
  ]
138
- except BaseException as er:
139
- LOGS.exception(er)
140
- lnk = [
141
- await e.builder.article(
142
- title="fl2lnk",
143
- text="File not found",
144
- )
145
- ]
146
- await e.answer(lnk, switch_pm="File to Link.", switch_pm_param="start")
147
 
 
148
 
149
- @callback(
150
- re_compile(
151
- "fl(.*)",
152
- ),
153
- owner=True,
154
- )
155
- async def _(e):
156
- t = (e.data).decode("UTF-8")
157
- data = t[2:]
158
- host = data.split("//")[0]
159
- chat_id, msg_id = data.split("//")[1].split(":")
160
- filename = _webupload_cache[int(chat_id)][int(msg_id)]
161
- if "/" in filename:
162
- filename = filename.split("/")[-1]
163
- await e.edit(f"Uploading `{filename}` on {host}")
164
- link = (await webuploader(chat_id, msg_id, host)).strip().replace("\n", "")
165
- await e.edit(f"Uploaded `{filename}` on {host}.", buttons=Button.url("View", link))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
 
168
  @in_pattern("repo", owner=True)
169
  async def repo(e):
 
 
 
 
 
 
 
170
  res = [
171
- await e.builder.article(
172
- title="Ultroid Userbot",
 
 
173
  description="Userbot | Telethon",
174
  thumb=wb(ultpic, 0, "image/jpeg", []),
175
- text="• **ULTROID USERBOT** •",
176
  buttons=SUP_BUTTONS,
177
  ),
178
  ]
@@ -188,18 +377,18 @@ async def gsearch(q_event):
188
  [], switch_pm="Google Search. Enter a query!", switch_pm_param="start"
189
  )
190
  searcher = []
191
- gresults = await google_search(match)
192
  for i in gresults:
193
  try:
194
  title = i["title"]
195
  link = i["link"]
196
  desc = i["description"]
197
  searcher.append(
198
- await q_event.builder.article(
199
  title=title,
200
  description=desc,
201
  thumb=wb(gugirl, 0, "image/jpeg", []),
202
- text=f"**Google Search**\n\n**• Title •**\n`{title}`\n\n**• Description •**\n`{desc}`",
203
  link_preview=False,
204
  buttons=[
205
  [Button.url("Link", url=f"{link}")],
@@ -234,31 +423,31 @@ async def _(e):
234
  start = 0 * 3 + 1
235
  da = base64.b64decode(choice(apis)).decode("ascii")
236
  url = f"https://www.googleapis.com/customsearch/v1?key={da}&cx=25b3b50edb928435b&q={quer}&start={start}"
237
- data = await async_searcher(url, re_json=True)
238
  search_items = data.get("items", [])
239
  modss = []
240
  for a in search_items:
241
  title = a.get("title")
242
  desc = a.get("snippet")
243
  link = a.get("link")
244
- text = f"**••Tɪᴛʟᴇ••** `{title}`\n\n"
245
- text += f"**Dᴇsᴄʀɪᴘᴛɪᴏɴ** `{desc}`"
246
  modss.append(
247
- await e.builder.article(
248
  title=title,
249
  description=desc,
250
  text=text,
251
  link_preview=True,
252
  buttons=[
253
- [Button.url("Dᴏᴡɴʟᴏᴀᴅ", url=f"{link}")],
254
  [
255
  Button.switch_inline(
256
- "Mᴏʀᴇ Mᴏᴅs",
257
  query="mods ",
258
  same_peer=True,
259
  ),
260
  Button.switch_inline(
261
- "Sʜᴀʀᴇ",
262
  query=f"mods {quer}",
263
  same_peer=False,
264
  ),
@@ -296,34 +485,29 @@ async def _(e):
296
  pass
297
  foles = []
298
  url = PLAY_API + f.replace(" ", "+")
299
- aap = await async_searcher(url, re_json=True)
 
300
  for z in aap["results"][:50]:
301
  url = "https://play.google.com/store/apps/details?id=" + z["appId"]
302
  name = z["title"]
303
  desc = unescape(z["summary"])[:300].replace("<br>", "\n") + "..."
304
  dev = z["developer"]["devId"]
305
- text = f"**• App Name •** [{name}]({url})\n"
306
- text += f"**• Developer •** `{dev}`\n"
307
- text += f"**• Description •**\n`{desc}`"
308
  foles.append(
309
- await e.builder.article(
310
- title=name,
 
 
311
  description=dev,
312
  thumb=wb(z["icon"], 0, "image/jpeg", []),
313
- text=text,
314
- link_preview=True,
315
  buttons=[
316
- [Button.url("Link", url=url)],
317
  [
318
- Button.switch_inline(
319
- "More Apps",
320
- query="app ",
321
- same_peer=True,
322
  ),
323
- Button.switch_inline(
324
- "Sʜᴀʀᴇ",
325
- query=f"app {f}",
326
- same_peer=False,
327
  ),
328
  ],
329
  ],
@@ -343,35 +527,52 @@ PISTON_LANGS = {}
343
 
344
  @in_pattern("run", owner=True)
345
  async def piston_run(event):
 
346
  try:
347
  lang = event.text.split()[1]
348
  code = event.text.split(maxsplit=2)[2]
349
  except IndexError:
350
- result = await event.builder.article(
351
- title="Bad Query",
 
 
 
 
 
 
 
 
 
352
  description="Usage: [Language] [code]",
353
  thumb=wb(
354
  "https://graph.org/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", []
355
  ),
356
- 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)',
357
  )
358
  return await event.answer([result])
359
  if not PISTON_LANGS:
360
- se = await async_searcher(f"{PISTON_URI}runtimes", re_json=True)
361
  PISTON_LANGS.update({lang.pop("language"): lang for lang in se})
362
  if lang in PISTON_LANGS.keys():
363
  version = PISTON_LANGS[lang]["version"]
364
  else:
365
- result = await event.builder.article(
366
- title="Unsupported Language",
 
 
 
 
 
 
 
 
 
367
  description="Usage: [Language] [code]",
368
  thumb=wb(
369
  "https://graph.org/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", []
370
  ),
371
- 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)',
372
  )
373
  return await event.answer([result])
374
- output = await async_searcher(
375
  f"{PISTON_URI}execute",
376
  post=True,
377
  json={
@@ -385,16 +586,25 @@ async def piston_run(event):
385
  output = output["run"]["output"] or get_string("instu_4")
386
  if len(output) > 3000:
387
  output = f"{output[:3000]}..."
388
- result = await event.builder.article(
389
- title="Result",
 
 
 
 
 
 
 
 
 
 
390
  description=output,
391
- text=f"• **Language:**\n`{lang}`\n\n• **Code:**\n`{code}`\n\n• **Result:**\n`{output}`",
392
  thumb=wb(
393
  "https://graph.org/file/871ee4a481f58117dccc4.jpg", 0, "image/jpeg", []
394
  ),
395
- buttons=Button.switch_inline("Fork", query=event.text, same_peer=True),
396
  )
397
- await event.answer([result], switch_pm="• Piston •", switch_pm_param="start")
398
 
399
 
400
  FDROID_ = {}
@@ -410,36 +620,43 @@ async def do_magic(event):
410
  )
411
  if FDROID_.get(match):
412
  return await event.answer(
413
- FDROID_[match], switch_pm=f"• Results for {match}", switch_pm_param="start"
414
  )
415
  link = "https://search.f-droid.org/?q=" + match.replace(" ", "+")
416
- content = await async_searcher(link, re_content=True)
417
  BSC = bs(content, "html.parser", from_encoding="utf-8")
418
  ress = []
 
419
  for dat in BSC.find_all("a", "package-header")[:10]:
420
  image = dat.find("img", "package-icon")["src"]
421
  if image.endswith("/"):
422
  image = "https://graph.org/file/a8dd4a92c5a53a89d0eff.jpg"
423
  title = dat.find("h4", "package-name").text.strip()
424
  desc = dat.find("span", "package-summary").text.strip()
425
- text = f"• **Name :** `{title}`\n\n"
426
- text += f"• **Description :** `{desc}`\n"
427
- text += f"• **License :** `{dat.find('span', 'package-license').text.strip()}`"
 
428
  imga = wb(image, 0, "image/jpeg", [])
429
  ress.append(
430
- await event.builder.article(
431
- title=title,
432
- type="photo",
 
433
  description=desc,
434
- text=text,
435
- content=imga,
436
  thumb=imga,
437
- include_media=True,
438
  buttons=[
439
- Button.inline(
440
- "• Download •", "fd" + dat["href"].split("packages/")[-1]
 
 
 
 
 
 
 
441
  ),
442
- Button.switch_inline("• Share •", query=event.text),
443
  ],
444
  )
445
  )
@@ -467,40 +684,46 @@ async def twitter_search(event):
467
  try:
468
  return await event.answer(
469
  _ult_cache["twitter"][match],
470
- switch_pm="• Twitter Search •",
471
  switch_pm_param="start",
472
  )
473
  except KeyError:
474
  pass
475
  headers = {"Authorization": f"bearer {choice(_bearer_collected)}"}
476
- res = await async_searcher(
477
  f"https://api.twitter.com/1.1/users/search.json?q={match}",
478
  headers=headers,
479
  re_json=True,
480
  )
481
  reso = []
 
482
  for user in res:
483
  thumb = wb(user["profile_image_url_https"], 0, "image/jpeg", [])
484
- if user.get("profile_banner_url"):
485
- url = user["profile_banner_url"]
486
- text = f"[\xad]({url})• **Name :** `{user['name']}`\n"
487
- else:
488
- text = f"• **Name :** `{user['name']}`\n"
489
- text += f"• **Description :** `{user['description']}`\n"
490
- text += f"• **Username :** `@{user['screen_name']}`\n"
491
- text += f"• **Followers :** `{user['followers_count']}` • **Following :** `{user['friends_count']}`\n"
492
  pro_ = "https://twitter.com/" + user["screen_name"]
493
- text += f"• **Link :** [Click Here]({pro_})\n_"
 
 
 
 
 
 
 
 
 
 
 
 
494
  reso.append(
495
- await event.builder.article(
496
- title=user["name"],
 
 
497
  description=user["description"],
498
  url=pro_,
499
- text=text,
500
  thumb=thumb,
501
  )
502
  )
503
- swi_ = f"🐦 Showing {len(reso)} Results!" if reso else "No User Found :("
504
  await event.answer(reso, switch_pm=swi_, switch_pm_param="start")
505
  if _ult_cache.get("twitter"):
506
  _ult_cache["twitter"].update({match: reso})
@@ -508,60 +731,24 @@ async def twitter_search(event):
508
  _ult_cache.update({"twitter": {match: reso}})
509
 
510
 
511
- _savn_cache = {}
512
 
513
 
514
  @in_pattern("saavn", owner=True)
515
  async def savn_s(event):
516
- try:
517
- query = event.text.split(maxsplit=1)[1].lower()
518
- except IndexError:
519
- return await event.answer(
520
- [], switch_pm="Enter Query to search 🔍", switch_pm_param="start"
521
- )
522
- if query in _savn_cache:
523
- return await event.answer(
524
- _savn_cache[query],
525
- switch_pm=f"Showing Results for {query}",
526
- switch_pm_param="start",
527
- )
528
- results = await saavn_search(query)
529
- swi = "🎵 Saavn Search" if results else "No Results Found!"
530
- res = []
531
- for song in results:
532
- thumb = wb(song["image"], 0, "image/jpeg", [])
533
- text = f"• **Title :** {song['title']}"
534
- text += f"\n• **Year :** {song['year']}"
535
- text += f"\n• **Lang :** {song['language']}"
536
- text += f"\n• **Artist :** {song['artists']}"
537
- text += f"\n• **Release Date :** {song['release_date']}"
538
- res.append(
539
- await event.builder.article(
540
- title=song["title"],
541
- description=song["artists"],
542
- type="audio",
543
- text=text,
544
- include_media=True,
545
- buttons=Button.switch_inline(
546
- "Search Again 🔍", query="saavn", same_peer=True
547
- ),
548
- thumb=thumb,
549
- content=wb(
550
- song["url"],
551
- 0,
552
- "audio/mp4",
553
- [
554
- Audio(
555
- title=song["title"],
556
- duration=int(song["duration"]),
557
- performer=song["artists"],
558
- )
559
- ],
560
- ),
561
- )
562
- )
563
- await event.answer(res, switch_pm=swi, switch_pm_param="start")
564
- _savn_cache.update({query: res})
565
 
566
 
567
  @in_pattern("tl", owner=True)
@@ -569,33 +756,33 @@ async def inline_tl(ult):
569
  try:
570
  match = ult.text.split(maxsplit=1)[1]
571
  except IndexError:
572
- 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`"
573
  return await ult.answer(
574
  [
575
- await ult.builder.article(
576
  title="How to Use?",
577
  description="Tl Searcher by Ultroid",
578
  url="https://t.me/TeamUltroid",
579
  text=text,
580
  )
581
  ],
582
- switch_pm="Tl Search 🔍",
583
  switch_pm_param="start",
584
  )
585
  res = []
586
  for key in tlobjects.values():
587
  if match.lower() in key.__name__.lower():
588
  tyyp = "Function" if "tl.functions." in str(key) else "Type"
589
- text = f"**Name:** `{key.__name__}`\n"
590
- text += f"**Category:** `{tyyp}`\n"
591
- text += f"\n`from {key.__module__} import {key.__name__}`\n\n"
592
  if args := str(inspect.signature(key))[1:][:-1]:
593
  text += "**Parameter:**\n"
594
  for para in args.split(","):
595
- text += " " * 4 + "`" + para + "`\n"
596
- text += f"\n**Layer:** `{LAYER}`"
597
  res.append(
598
- await ult.builder.article(
599
  title=key.__name__,
600
  description=tyyp,
601
  url="https://t.me/TeamUltroid",
@@ -608,16 +795,16 @@ async def inline_tl(ult):
608
 
609
  InlinePlugin.update(
610
  {
611
- "Pʟᴀʏ Sᴛᴏʀᴇ Aᴘᴘs": "app telegram",
612
- "Mᴏᴅᴅᴇᴅ Aᴘᴘs": "mods minecraft",
613
- "Sᴇᴀʀᴄʜ Oɴ Gᴏᴏɢʟᴇ": "go TeamUltroid",
614
- "WʜɪSᴘᴇʀ": "wspr @username Hello🎉",
615
- "YᴏᴜTᴜʙᴇ Dᴏᴡɴʟᴏᴀᴅᴇʀ": "yt Ed Sheeran Perfect",
616
  "Piston Eval": "run javascript console.log('Hello Ultroid')",
617
- "OʀᴀɴɢᴇFᴏx🦊": "ofox beryllium",
618
- "Tᴡɪᴛᴛᴇʀ Usᴇʀ": "twitter theultroid",
619
- "Fᴅʀᴏɪᴅ Sᴇᴀʀᴄʜ": "fdroid telegram",
620
- "Sᴀᴀᴠɴ sᴇᴀʀᴄʜ": "saavn",
621
- "Tʟ Sᴇᴀʀᴄʜ": "tl",
622
  }
623
  )
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
  import base64
9
+ import hashlib
10
  import inspect
11
+ import os
12
  from datetime import datetime
13
  from html import unescape
14
  from random import choice
 
15
 
16
  from bs4 import BeautifulSoup as bs
17
  from telethon import Button
18
  from telethon.tl.alltlobjects import LAYER, tlobjects
 
19
  from telethon.tl.types import InputWebDocument as wb
20
 
21
+ from custom.rich import resolve_style
22
+ from pyUltroid import LOGS, asst
23
+ from pyUltroid._core.buttonkit import button as rich_button
24
+ from pyUltroid._core.events import InlineResultBuilder
25
+ from pyUltroid._core.inlineresults import InlineResults
26
+ from pyUltroid._core.richmsg import RichBlocks, rich_markup_from_blocks
27
+ from pyUltroid._core.webupload import (
28
+ MENU_SERVICES,
29
+ SERVICE_LABELS,
30
+ UploadResult,
31
  )
32
+ from pyUltroid.fns import fns
33
+ from pyUltroid.fns.tools import _webupload_cache
34
+ from strings import get_string
35
+
36
+ from . import InlinePlugin, _ult_cache, callback, in_pattern
37
+ from ._cbs import cb, cb_pattern
38
+
39
+ #
40
+ # C8 inline result restyle helpers.
41
+ #
42
+ # InlineResults.article_rich() (pyUltroid/_core/inlineresults.py) emits only
43
+ # native RichMessage articles. Missing rich-message constructors or invalid
44
+ # content are hard errors; this path never falls back to a plain article.
45
+ # Block rendering delegates to pyUltroid._core.richmsg, so table() and
46
+ # expandable() blocks use the same native model as other rich-message callers.
47
+ #
48
+ # _rich_article below additionally preserves inline-result thumb=/content=
49
+ # metadata on the native RichMessage result.
50
+ #
51
+
52
+
53
+ async def _rich_article(
54
+ ires,
55
+ title,
56
+ blocks,
57
+ *,
58
+ description=None,
59
+ url=None,
60
+ id=None,
61
+ buttons=None,
62
+ thumb=None,
63
+ content=None,
64
+ rtl=False,
65
+ ):
66
+ """Build one article_rich inline result from a :class:RichBlocks.
67
+
68
+ Converts *blocks* to native RichMarkup while preserving its file vector,
69
+ then passes the complete payload to InlineResults.article_rich. Local
70
+ media that has not already been uploaded to Telegram is rejected by the
71
+ layer-230 engine; it is never silently dropped. thumb/content are assigned
72
+ directly on the pinned InputBotInlineResult schema.
73
+ """
74
+ payload = rich_markup_from_blocks(blocks, format="html")
75
+ result = await ires.article_rich(
76
+ title,
77
+ payload,
78
+ format="html",
79
+ description=description,
80
+ url=url,
81
+ id=id,
82
+ buttons=buttons,
83
+ rtl=rtl,
84
+ )
85
+ changed = False
86
+ if thumb is not None:
87
+ result.thumb = thumb
88
+ changed = True
89
+ if content is not None:
90
+ result.content = content
91
+ changed = True
92
+ if changed and id is None:
93
+ result.id = hashlib.sha256(bytes(result)).hexdigest()
94
+ return result
95
+
96
+
97
+ def _styled(text, *, data=None, url=None, preset=None):
98
+ """Style one button via buttonkit.button (bg-colour presets).
99
+
100
+ Falls back to a plain telethon.Button if styling itself raises for
101
+ any reason custom.rich.button already degrades style/icon
102
+ internally (see its docstring), this is a belt-and-suspenders probe so
103
+ callers below never lose a button entirely over styling.
104
+ """
105
+ try:
106
+ return rich_button(text, data=data, url=url, preset=preset)
107
+ except Exception:
108
+ return (
109
+ Button.url(text, url=url)
110
+ if url is not None
111
+ else Button.inline(text, data=data)
112
+ )
113
+
114
+
115
+ def _styled_switch(text, query, *, same_peer=True, preset=None):
116
+ """Style a switch_inline (search-again / share / fork) button."""
117
+ try:
118
+ style, icon = resolve_style(preset=preset)
119
+ return Button.switch_inline(
120
+ text, query=query, same_peer=same_peer, style=style, icon=icon
121
+ )
122
+ except Exception:
123
+ return Button.switch_inline(text, query=query, same_peer=same_peer)
124
 
 
 
125
 
126
  SUP_BUTTONS = [
127
  [
128
+ _styled(
129
+ " Repo ", url="https://github.com/TeamUltroid/Ultroid", preset="primary"
130
+ ),
131
+ _styled(" Support ", url="t.me/UltroidSupportChat", preset="default"),
132
  ],
133
  ]
134
 
 
145
 
146
  @in_pattern("ofox", owner=True)
147
  async def _(e):
148
+ ires = InlineResults(e)
149
  try:
150
  match = e.text.split(" ", maxsplit=1)[1]
151
  except IndexError:
152
+ blocks = (
153
+ RichBlocks().header("OFoxRecovery").paragraph("You didn't search anything")
154
+ )
155
+ kkkk = await _rich_article(
156
+ ires,
157
+ "Enter Device Codename",
158
+ blocks,
159
  thumb=wb(ofox, 0, "image/jpeg", []),
160
+ buttons=_styled_switch(
161
+ "Search Again", "ofox ", same_peer=True, preset="default"
162
+ ),
163
  )
164
  return await e.answer([kkkk])
165
+ device, releases = await fns.get_ofox(match)
166
  if device.get("detail") is None:
167
  fox = []
168
  fullname = device["full_name"]
 
173
  for data in releases["data"]:
174
  release = data["type"]
175
  version = data["version"]
176
+ size = fns.humanbytes(data["size"])
177
  release_date = datetime.utcfromtimestamp(data["date"]).strftime("%Y-%m-%d")
178
+ blocks = (
179
+ RichBlocks()
180
+ .header(f"OrangeFox Recovery For {fullname}")
181
+ .table(
182
+ [
183
+ ["Field", "Value"],
184
+ ["Full Name", fullname],
185
+ ["Codename", codename],
186
+ ["Maintainer", maintainer],
187
+ ["Build Type", release],
188
+ ["Version", version],
189
+ ["Size", size],
190
+ ["Build Date", release_date],
191
+ ],
192
+ caption="Device Details",
193
+ )
194
+ )
195
  fox.append(
196
+ await _rich_article(
197
+ ires,
198
+ fullname,
199
+ blocks,
200
  description=f"{version}\n{release_date}",
 
201
  thumb=wb(ofox, 0, "image/jpeg", []),
 
202
  buttons=[
203
+ _styled("Download", url=link, preset="primary"),
204
+ _styled_switch(
205
+ "Search Again", "ofox ", same_peer=True, preset="default"
206
  ),
207
  ],
208
  )
 
216
  )
217
 
218
 
219
+ #: emoji icon shown on each fl2lnk service button (presentation-only real
220
+ #: custom-emoji document ids are deployment-specific, see buttonkit.py).
221
+ _FL_SERVICE_ICONS = {
222
+ "catbox": "",
223
+ "litterbox": "",
224
+ "file.io": "",
225
+ "0x0.st": "",
226
+ "transfer": "",
227
+ "uguu": "",
228
+ "filebin": "",
229
+ "siasky": "",
230
+ }
231
+
232
+
233
  @in_pattern("fl2lnk ?(.*)", owner=True)
234
+ async def fl2lnk_command(event):
235
+ match = event.pattern_match.group(1)
236
+ if not match or ":" not in match:
237
+ await event.respond(
238
+ "Invalid format. Please provide chat ID and message ID in the format 'chat_id:message_id'."
239
+ )
240
+ return
241
+
242
  chat_id, msg_id = match.split(":")
243
+ try:
244
+ filename = _webupload_cache[int(chat_id)][int(msg_id)]
245
+ except (KeyError, ValueError):
246
+ await event.respond("File not found or invalid chat ID/message ID.")
247
+ return
248
+
249
  if "/" in filename:
250
  filename = filename.split("/")[-1]
251
+
252
+ ires = InlineResults(event)
253
+ buttons = []
254
+ row_btns = []
255
+ for key in MENU_SERVICES:
256
+ icon = _FL_SERVICE_ICONS.get(key, "")
257
+ row_btns.append(
258
+ _styled(
259
+ f"{icon} {SERVICE_LABELS.get(key, key)}",
260
+ data=cb("assistant", "fl2lnk", key, chat_id, msg_id),
261
+ preset="primary",
262
+ )
263
+ )
264
+ if len(row_btns) == 2:
265
+ buttons.append(row_btns)
266
+ row_btns = []
267
+ if row_btns:
268
+ buttons.append(row_btns)
269
+
270
  try:
271
+ blocks = RichBlocks().header(" Upload File").paragraph(filename)
272
+ articles = [
273
+ await _rich_article(
274
+ ires,
275
+ f"Upload {filename}",
276
+ blocks,
277
  buttons=buttons,
278
  )
279
  ]
280
+ except Exception as e:
281
+ LOGS.exception(e)
282
+ blocks = (
283
+ RichBlocks()
284
+ .header("fl2lnk")
285
+ .paragraph("File not found or error in processing.")
286
+ )
287
+ articles = [await _rich_article(ires, "fl2lnk", blocks)]
 
288
 
289
+ await event.answer(articles, switch_pm="File to Link.", switch_pm_param="start")
290
 
291
+
292
+ @callback(cb_pattern("assistant", "fl2lnk"), owner=True)
293
+ async def fl_callback(event):
294
+ tail = event.data_match.group(1).decode("utf-8")
295
+ parts = tail.split(":")
296
+ if len(parts) != 3:
297
+ await event.respond("Invalid callback data format.")
298
+ return
299
+
300
+ host, chat_id, msg_id = parts
301
+
302
+ try:
303
+ filename = _webupload_cache[int(chat_id)][int(msg_id)]
304
+ except (KeyError, ValueError):
305
+ await event.respond("File not found or invalid chat ID/message ID.")
306
+ return
307
+
308
+ disp = filename.split("/")[-1] if "/" in filename else filename
309
+ label = SERVICE_LABELS.get(host, host)
310
+
311
+ import time as _time
312
+
313
+ state = {"pct": -1, "t": 0.0}
314
+
315
+ async def on_progress(sent, total):
316
+ pct = round(sent / total * 100) if total else 0
317
+ now = _time.time()
318
+ if pct - state["pct"] >= 5 or now - state["t"] >= 1.5 or sent >= total:
319
+ state["pct"] = pct
320
+ state["t"] = now
321
+ try:
322
+ await event.edit(f" Uploading {disp} on {label}... {pct}%")
323
+ except Exception:
324
+ pass
325
+
326
+ await event.edit(f" Uploading {disp} on {label}...")
327
+ result = await fns.webupload_result(
328
+ int(chat_id), int(msg_id), host, on_progress=on_progress
329
+ )
330
+
331
+ if isinstance(result, UploadResult):
332
+ text = f"**Uploaded** {disp} **on** {label}."
333
+ buttons = [[_styled(" View", url=result.url, preset="primary")]]
334
+ if result.delete_url:
335
+ text += f"\n Delete: {result.delete_url}"
336
+ if result.delete_note:
337
+ text += f" ({result.delete_note})"
338
+ if result.expires:
339
+ text += f"\n Expires: {result.expires}"
340
+ await event.edit(text, buttons=buttons, link_preview=False)
341
+ try:
342
+ os.remove(f"resources/downloads/{disp}")
343
+ except FileNotFoundError:
344
+ pass
345
+ else:
346
+ await event.edit(f"Failed to upload {disp} on {label}. Error: {result}")
347
 
348
 
349
  @in_pattern("repo", owner=True)
350
  async def repo(e):
351
+ ires = InlineResults(e)
352
+ blocks = (
353
+ RichBlocks()
354
+ .header("Ultroid Userbot")
355
+ .list(["Userbot", "Telethon"])
356
+ .paragraph(" **ULTROID USERBOT** ")
357
+ )
358
  res = [
359
+ await _rich_article(
360
+ ires,
361
+ "Ultroid Userbot",
362
+ blocks,
363
  description="Userbot | Telethon",
364
  thumb=wb(ultpic, 0, "image/jpeg", []),
 
365
  buttons=SUP_BUTTONS,
366
  ),
367
  ]
 
377
  [], switch_pm="Google Search. Enter a query!", switch_pm_param="start"
378
  )
379
  searcher = []
380
+ gresults = await fns.google_search(match)
381
  for i in gresults:
382
  try:
383
  title = i["title"]
384
  link = i["link"]
385
  desc = i["description"]
386
  searcher.append(
387
+ await InlineResultBuilder(q_event).article(
388
  title=title,
389
  description=desc,
390
  thumb=wb(gugirl, 0, "image/jpeg", []),
391
+ text=f"**Google Search**\n\n** Title **\n{title}\n\n** Description **\n{desc}",
392
  link_preview=False,
393
  buttons=[
394
  [Button.url("Link", url=f"{link}")],
 
423
  start = 0 * 3 + 1
424
  da = base64.b64decode(choice(apis)).decode("ascii")
425
  url = f"https://www.googleapis.com/customsearch/v1?key={da}&cx=25b3b50edb928435b&q={quer}&start={start}"
426
+ data = await fns.async_searcher(url, re_json=True)
427
  search_items = data.get("items", [])
428
  modss = []
429
  for a in search_items:
430
  title = a.get("title")
431
  desc = a.get("snippet")
432
  link = a.get("link")
433
+ text = f"** Title ** {title}\n\n"
434
+ text += f"**Description** {desc}"
435
  modss.append(
436
+ await InlineResultBuilder(e).article(
437
  title=title,
438
  description=desc,
439
  text=text,
440
  link_preview=True,
441
  buttons=[
442
+ [Button.url("Download", url=f"{link}")],
443
  [
444
  Button.switch_inline(
445
+ "More Mods",
446
  query="mods ",
447
  same_peer=True,
448
  ),
449
  Button.switch_inline(
450
+ "Share",
451
  query=f"mods {quer}",
452
  same_peer=False,
453
  ),
 
485
  pass
486
  foles = []
487
  url = PLAY_API + f.replace(" ", "+")
488
+ aap = await fns.async_searcher(url, re_json=True)
489
+ ires = InlineResults(e)
490
  for z in aap["results"][:50]:
491
  url = "https://play.google.com/store/apps/details?id=" + z["appId"]
492
  name = z["title"]
493
  desc = unescape(z["summary"])[:300].replace("<br>", "\n") + "..."
494
  dev = z["developer"]["devId"]
495
+ blocks = RichBlocks().header(name).list([f"Developer: {dev}"]).paragraph(desc)
 
 
496
  foles.append(
497
+ await _rich_article(
498
+ ires,
499
+ name,
500
+ blocks,
501
  description=dev,
502
  thumb=wb(z["icon"], 0, "image/jpeg", []),
 
 
503
  buttons=[
504
+ [_styled("Link", url=url, preset="primary")],
505
  [
506
+ _styled_switch(
507
+ "More Apps", "app ", same_peer=True, preset="default"
 
 
508
  ),
509
+ _styled_switch(
510
+ "Share", f"app {f}", same_peer=False, preset="default"
 
 
511
  ),
512
  ],
513
  ],
 
527
 
528
  @in_pattern("run", owner=True)
529
  async def piston_run(event):
530
+ ires = InlineResults(event)
531
  try:
532
  lang = event.text.split()[1]
533
  code = event.text.split(maxsplit=2)[2]
534
  except IndexError:
535
+ blocks = (
536
+ RichBlocks()
537
+ .header("Bad Query")
538
+ .paragraph("Usage: [Language] [code]")
539
+ .code(f'@{asst.me.username} run python print("hello world")')
540
+ .paragraph("Language List: https://graph.org/Ultroid-09-01-6")
541
+ )
542
+ result = await _rich_article(
543
+ ires,
544
+ "Bad Query",
545
+ blocks,
546
  description="Usage: [Language] [code]",
547
  thumb=wb(
548
  "https://graph.org/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", []
549
  ),
 
550
  )
551
  return await event.answer([result])
552
  if not PISTON_LANGS:
553
+ se = await fns.async_searcher(f"{PISTON_URI}runtimes", re_json=True)
554
  PISTON_LANGS.update({lang.pop("language"): lang for lang in se})
555
  if lang in PISTON_LANGS.keys():
556
  version = PISTON_LANGS[lang]["version"]
557
  else:
558
+ blocks = (
559
+ RichBlocks()
560
+ .header("Unsupported Language")
561
+ .paragraph("Usage: [Language] [code]")
562
+ .code(f'@{asst.me.username} run python print("hello world")')
563
+ .paragraph("Language List: https://graph.org/Ultroid-09-01-6")
564
+ )
565
+ result = await _rich_article(
566
+ ires,
567
+ "Unsupported Language",
568
+ blocks,
569
  description="Usage: [Language] [code]",
570
  thumb=wb(
571
  "https://graph.org/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", []
572
  ),
 
573
  )
574
  return await event.answer([result])
575
+ output = await fns.async_searcher(
576
  f"{PISTON_URI}execute",
577
  post=True,
578
  json={
 
586
  output = output["run"]["output"] or get_string("instu_4")
587
  if len(output) > 3000:
588
  output = f"{output[:3000]}..."
589
+ blocks = (
590
+ RichBlocks()
591
+ .header("Result")
592
+ .table([["Field", "Value"], ["Language", lang]])
593
+ .code(code, lang=lang)
594
+ .header("Output", level=3)
595
+ .code(output)
596
+ )
597
+ result = await _rich_article(
598
+ ires,
599
+ "Result",
600
+ blocks,
601
  description=output,
 
602
  thumb=wb(
603
  "https://graph.org/file/871ee4a481f58117dccc4.jpg", 0, "image/jpeg", []
604
  ),
605
+ buttons=_styled_switch("Fork", event.text, same_peer=True, preset="default"),
606
  )
607
+ await event.answer([result], switch_pm=" Piston ", switch_pm_param="start")
608
 
609
 
610
  FDROID_ = {}
 
620
  )
621
  if FDROID_.get(match):
622
  return await event.answer(
623
+ FDROID_[match], switch_pm=f" Results for {match}", switch_pm_param="start"
624
  )
625
  link = "https://search.f-droid.org/?q=" + match.replace(" ", "+")
626
+ content = await fns.async_searcher(link, re_content=True)
627
  BSC = bs(content, "html.parser", from_encoding="utf-8")
628
  ress = []
629
+ ires = InlineResults(event)
630
  for dat in BSC.find_all("a", "package-header")[:10]:
631
  image = dat.find("img", "package-icon")["src"]
632
  if image.endswith("/"):
633
  image = "https://graph.org/file/a8dd4a92c5a53a89d0eff.jpg"
634
  title = dat.find("h4", "package-name").text.strip()
635
  desc = dat.find("span", "package-summary").text.strip()
636
+ license_ = dat.find("span", "package-license").text.strip()
637
+ blocks = (
638
+ RichBlocks().header(title).list([f"License: {license_}"]).paragraph(desc)
639
+ )
640
  imga = wb(image, 0, "image/jpeg", [])
641
  ress.append(
642
+ await _rich_article(
643
+ ires,
644
+ title,
645
+ blocks,
646
  description=desc,
 
 
647
  thumb=imga,
648
+ content=imga,
649
  buttons=[
650
+ _styled(
651
+ " Download ",
652
+ data=cb(
653
+ "assistant", "fdroid", dat["href"].split("packages/")[-1]
654
+ ),
655
+ preset="primary",
656
+ ),
657
+ _styled_switch(
658
+ " Share ", event.text, same_peer=False, preset="default"
659
  ),
 
660
  ],
661
  )
662
  )
 
684
  try:
685
  return await event.answer(
686
  _ult_cache["twitter"][match],
687
+ switch_pm=" Twitter Search ",
688
  switch_pm_param="start",
689
  )
690
  except KeyError:
691
  pass
692
  headers = {"Authorization": f"bearer {choice(_bearer_collected)}"}
693
+ res = await fns.async_searcher(
694
  f"https://api.twitter.com/1.1/users/search.json?q={match}",
695
  headers=headers,
696
  re_json=True,
697
  )
698
  reso = []
699
+ ires = InlineResults(event)
700
  for user in res:
701
  thumb = wb(user["profile_image_url_https"], 0, "image/jpeg", [])
 
 
 
 
 
 
 
 
702
  pro_ = "https://twitter.com/" + user["screen_name"]
703
+ blocks = (
704
+ RichBlocks()
705
+ .header(user["name"])
706
+ .table(
707
+ [
708
+ ["Field", "Value"],
709
+ ["Username", f"@{user['screen_name']}"],
710
+ ["Followers", str(user["followers_count"])],
711
+ ["Following", str(user["friends_count"])],
712
+ ]
713
+ )
714
+ .paragraph(user["description"] or "")
715
+ )
716
  reso.append(
717
+ await _rich_article(
718
+ ires,
719
+ user["name"],
720
+ blocks,
721
  description=user["description"],
722
  url=pro_,
 
723
  thumb=thumb,
724
  )
725
  )
726
+ swi_ = f" Showing {len(reso)} Results!" if reso else "No User Found :("
727
  await event.answer(reso, switch_pm=swi_, switch_pm_param="start")
728
  if _ult_cache.get("twitter"):
729
  _ult_cache["twitter"].update({match: reso})
 
731
  _ult_cache.update({"twitter": {match: reso}})
732
 
733
 
734
+ # Saavn defunct inline handler removed
735
 
736
 
737
  @in_pattern("saavn", owner=True)
738
  async def savn_s(event):
739
+ """Saavn music service defunct inline search removed."""
740
+ ires = InlineResults(event)
741
+ blocks = (
742
+ RichBlocks()
743
+ .header(" Saavn Search")
744
+ .paragraph("This inline search is no longer available.")
745
+ )
746
+ notice = await _rich_article(ires, "Saavn is no longer available", blocks)
747
+ return await event.answer(
748
+ [notice],
749
+ switch_pm=" Saavn is no longer available",
750
+ switch_pm_param="start",
751
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752
 
753
 
754
  @in_pattern("tl", owner=True)
 
756
  try:
757
  match = ult.text.split(maxsplit=1)[1]
758
  except IndexError:
759
+ 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"
760
  return await ult.answer(
761
  [
762
+ await InlineResultBuilder(ult).article(
763
  title="How to Use?",
764
  description="Tl Searcher by Ultroid",
765
  url="https://t.me/TeamUltroid",
766
  text=text,
767
  )
768
  ],
769
+ switch_pm="Tl Search ",
770
  switch_pm_param="start",
771
  )
772
  res = []
773
  for key in tlobjects.values():
774
  if match.lower() in key.__name__.lower():
775
  tyyp = "Function" if "tl.functions." in str(key) else "Type"
776
+ text = f"**Name:** {key.__name__}\n"
777
+ text += f"**Category:** {tyyp}\n"
778
+ text += f"\nfrom {key.__module__} import {key.__name__}\n\n"
779
  if args := str(inspect.signature(key))[1:][:-1]:
780
  text += "**Parameter:**\n"
781
  for para in args.split(","):
782
+ text += " " * 4 + "" + para + "\n"
783
+ text += f"\n**Layer:** {LAYER}"
784
  res.append(
785
+ await InlineResultBuilder(ult).article(
786
  title=key.__name__,
787
  description=tyyp,
788
  url="https://t.me/TeamUltroid",
 
795
 
796
  InlinePlugin.update(
797
  {
798
+ "Play Store Apps": "app telegram",
799
+ "Modded Apps": "mods minecraft",
800
+ "Search On Google": "go TeamUltroid",
801
+ "WhiSper": "wspr @username Hello",
802
+ "YouTube Downloader": "yt Ed Sheeran Perfect",
803
  "Piston Eval": "run javascript console.log('Hello Ultroid')",
804
+ "OrangeFox": "ofox beryllium",
805
+ "Twitter User": "twitter theultroid",
806
+ "Fdroid Search": "fdroid telegram",
807
+ "Saavn search": "saavn",
808
+ "Tl Search": "tl",
809
  }
810
  )
assistant/localization.py CHANGED
@@ -1,47 +1,117 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
- # PLease read the GNU Affero General Public License in
6
- # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
- import re
 
9
 
10
  from . import (
11
- Button,
12
  ULTConfig,
13
  callback,
14
  get_back_button,
15
  get_languages,
16
- get_string,
17
  udB,
18
  )
 
 
19
 
 
 
 
20
 
21
- @callback("lang", owner=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  async def setlang(event):
23
  languages = get_languages()
24
- tultd = [
25
- Button.inline(
26
- f"{languages[ult]['natively']} [{ult.lower()}]",
27
- data=f"set_{ult}",
 
 
28
  )
29
- for ult in languages
30
  ]
31
- buttons = list(zip(tultd[::2], tultd[1::2]))
32
- if len(tultd) % 2 == 1:
33
- buttons.append((tultd[-1],))
34
- buttons.append([Button.inline("« Back", data="mainmenu")])
35
- await event.edit(get_string("ast_4"), buttons=buttons)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
 
38
- @callback(re.compile(b"set_(.*)"), owner=True)
39
  async def settt(event):
40
- lang = event.data_match.group(1).decode("UTF-8")
 
 
 
 
41
  languages = get_languages()
 
 
 
 
42
  ULTConfig.lang = lang
43
- udB.del_key("language") if lang == "en" else udB.set_key("language", lang)
44
- await event.edit(
45
- f"Your language has been set to {languages[lang]['natively']} [{lang}].",
46
- buttons=get_back_button("lang"),
 
 
 
 
 
 
 
 
 
 
47
  )
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
+ # Please read the GNU Affero General Public License in
6
+ # <https://github.com/TeamUltroid/pyUltroid/blob/main/LICENSE/>.
7
 
8
+ from custom.tg import ikm
9
+ from pyUltroid._core.richmsg import edit_rich
10
 
11
  from . import (
 
12
  ULTConfig,
13
  callback,
14
  get_back_button,
15
  get_languages,
 
16
  udB,
17
  )
18
+ from ._cbs import cb, cb_exact_pattern, cb_pattern
19
+ from .rich_pages import callback_edit_target, rich_page
20
 
21
+ LANG_MENU = cb_exact_pattern("assistant", "lang", "menu")
22
+ LANG_SET_PATTERN = cb_pattern("assistant", "lang", "set")
23
+ MAIN_MENU = cb("assistant", "start", "mainmenu")
24
 
25
+
26
+ def _language_key(raw: str, languages: dict) -> str | None:
27
+ """Resolve a callback token against the currently supported locale keys."""
28
+ key = str(raw or "").strip()
29
+ if key in languages:
30
+ return key
31
+ return next(
32
+ (
33
+ candidate
34
+ for candidate in languages
35
+ if candidate.casefold() == key.casefold()
36
+ ),
37
+ None,
38
+ )
39
+
40
+
41
+ async def _edit_language(event, blocks, buttons):
42
+ """Edit this callback's message through the native RichMessage path."""
43
+ peer, message = callback_edit_target(event)
44
+ return await edit_rich(
45
+ event.client,
46
+ peer,
47
+ message,
48
+ blocks,
49
+ format="html",
50
+ buttons=buttons,
51
+ link_preview=False,
52
+ )
53
+
54
+
55
+ @callback(LANG_MENU, owner=True)
56
  async def setlang(event):
57
  languages = get_languages()
58
+ current = str(getattr(ULTConfig, "lang", "en") or "en").casefold()
59
+ entries = [
60
+ (
61
+ f"{languages[code]['natively']} [{code.casefold()}]",
62
+ cb("assistant", "lang", "set", code),
63
+ "success" if code.casefold() == current else None,
64
  )
65
+ for code in languages
66
  ]
67
+ rows = [list(pair) for pair in zip(entries[::2], entries[1::2])]
68
+ if len(entries) % 2:
69
+ rows.append([entries[-1]])
70
+ rows.append([("Back", MAIN_MENU, None)])
71
+ await _edit_language(
72
+ event,
73
+ rich_page(
74
+ "Language",
75
+ [
76
+ (
77
+ f"{languages[code]['natively']} [{code.casefold()}]",
78
+ "Currently selected" if code.casefold() == current else "Choose this language",
79
+ )
80
+ for code in languages
81
+ ],
82
+ description="Choose the language used by the assistant.",
83
+ columns=("Language", "Status"),
84
+ total=len(languages),
85
+ ),
86
+ ikm(rows, icon=False),
87
+ )
88
 
89
 
90
+ @callback(LANG_SET_PATTERN, owner=True)
91
  async def settt(event):
92
+ try:
93
+ raw = event.data_match.group(1).decode("utf-8")
94
+ except (AttributeError, UnicodeDecodeError, IndexError):
95
+ return await event.answer("That language selection is invalid.", alert=True)
96
+
97
  languages = get_languages()
98
+ lang = _language_key(raw, languages)
99
+ if lang is None:
100
+ return await event.answer("That language is no longer available.", alert=True)
101
+
102
  ULTConfig.lang = lang
103
+ udB.del_key("language") if lang.casefold() == "en" else udB.set_key(
104
+ "language", lang
105
+ )
106
+ name = str(languages[lang].get("natively") or lang)
107
+ await _edit_language(
108
+ event,
109
+ rich_page(
110
+ "Language updated",
111
+ [("Language", f"{name} [{lang}]")],
112
+ description="The assistant language has been updated.",
113
+ columns=("Setting", "Current value"),
114
+ total=1,
115
+ ),
116
+ get_back_button(cb("assistant", "lang", "menu")),
117
  )
assistant/ludo_arcade.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared native group Ludo with locked, revisioned, ephemeral table sessions."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import copy
6
+ import re
7
+ import secrets
8
+ import time
9
+ from dataclasses import dataclass, field
10
+
11
+ from telethon.errors import FloodWaitError, MessageNotModifiedError, RPCError
12
+ from telethon.tl import types as t
13
+
14
+ from pyUltroid._core.ludo_arcade import Ludo
15
+ from pyUltroid._core.ludo_visuals import (
16
+ board_block,
17
+ legend_block,
18
+ player_blocks,
19
+ seat_label,
20
+ status_blocks,
21
+ )
22
+ from pyUltroid._core.matrix_arcade import button, paragraph, row, text, title
23
+ from pyUltroid._core.richdebug import rpc_identifier, trace_rich_rpc
24
+ from pyUltroid._core.richmsg import edit_rich, send_rich
25
+ from pyUltroid._misc._assistant import asst_cmd, callback
26
+
27
+ 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))$")
28
+ TTL = 60 * 60
29
+ CAPACITY = 64
30
+ EDIT_TIMEOUT = 8.0
31
+
32
+
33
+ @dataclass
34
+ class Table:
35
+ """Bind one shared game to its exact group and bot message."""
36
+ token: str
37
+ chat: int
38
+ game: Ludo
39
+ message: int | None = None
40
+ revision: int = 0
41
+ touched: float = field(default_factory=time.monotonic)
42
+ confirmation: tuple[int, str, float] | None = None
43
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)
44
+
45
+ def control(self, label, action):
46
+ """Build an exact-revision native callback control."""
47
+ control = button(label, f"lu:{self.token}:{self.revision}:{action}")
48
+ if action in {"start", "join", "rematch"}:
49
+ control.style = t.RichButtonStyle(bg_success=True)
50
+ elif action in {"cancelok", "resignok"}:
51
+ control.style = t.RichButtonStyle(bg_danger=True)
52
+ elif action == "roll" or action.startswith("move"):
53
+ control.style = t.RichButtonStyle(bg_primary=True)
54
+ return control
55
+
56
+
57
+ TABLES: dict[str, Table] = {}
58
+
59
+
60
+ def prune():
61
+ """Expire idle tables without evicting locked edits or touching persistence."""
62
+ now = time.monotonic()
63
+ for token, table in list(TABLES.items()):
64
+ if now - table.touched >= TTL and not table.lock.locked():
65
+ del TABLES[token]
66
+
67
+
68
+ def render(table):
69
+ """Compose native board cells, readable player cards and nested controls."""
70
+ game, ctl = table.game, table.control
71
+ blocks = [title("🎲 LUDO / THE COLOUR COURT"), *status_blocks(game)]
72
+ if game.status == "lobby":
73
+ blocks += [paragraph("2–4 humans · four tokens each · no AI opponent"),
74
+ row(ctl("+ Join table", "join"), ctl("− Leave seat", "leave")),
75
+ row(ctl("▶ Start · host", "start"))]
76
+ elif game.status == "playing":
77
+ moves = game.legal_moves()
78
+ seat = game.active
79
+ if game.dice is None:
80
+ blocks.append(row(ctl(f"🎲 Roll · {seat_label(seat)}", "roll")))
81
+ elif moves:
82
+ # Two controls per row keeps legal token labels legible on phones.
83
+ for start in range(0, len(moves), 2):
84
+ blocks.append(row(*(ctl(f"{seat_label(seat).split()[0]} {chr(65 + seat)}{i + 1} · Move", f"move{i}")
85
+ for i in moves[start:start + 2])))
86
+ else:
87
+ blocks.append(row(ctl("↺ Rematch lobby · host", "rematch")))
88
+ blocks += [paragraph("Track positions use shared squares 0–51. Your token cards below stay readable even if the full board scrolls sideways."),
89
+ t.PageBlockDetails([board_block(game), legend_block()], text("✦ Open the cross board / 15 × 15 cells"), open=False),
90
+ *player_blocks(game)]
91
+ management = []
92
+ if game.status == "playing":
93
+ management += [row(ctl("◷ Skip AFK turn", "skip")),
94
+ t.PageBlockDetails([paragraph("Resigning removes your tokens. Closing ends the table for everyone. Both require confirmation."),
95
+ row(ctl("⚑ Resign", "resign")),
96
+ row(ctl("■ Close · host", "cancel"))],
97
+ text("⚑ Leave / close table"), open=False)]
98
+ elif game.status == "lobby":
99
+ management.append(row(ctl("■ Close table · host", "cancel")))
100
+ if management:
101
+ blocks.append(t.PageBlockDetails(management, text("Table controls / more"), open=False))
102
+ if table.confirmation:
103
+ actor, action, _deadline = table.confirmation
104
+ blocks += [paragraph(f"Player {actor}: confirm {action}. This confirmation expires in 20 seconds."),
105
+ row(ctl(f"Confirm {action}", action + "ok"), ctl("Keep playing", "back"))]
106
+ if game.events:
107
+ blocks.append(t.PageBlockDetails([paragraph(item) for item in game.events[-6:]],
108
+ text("Arena feed / last six events"), open=False))
109
+ blocks += [t.PageBlockDetails([
110
+ 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)."),
111
+ 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),
112
+ 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."),
113
+ 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),
114
+ ], text("📖 Rules / safety / controls"), open=False),
115
+ t.PageBlockFooter(text(f"Native Layer 230 · table {table.token} · revision {table.revision} · /ludo"))]
116
+ return t.InputRichMessage(blocks)
117
+
118
+
119
+ async def launch(event):
120
+ """Reserve one new table in a group without editing any existing message."""
121
+ if not getattr(event, "is_group", False) or not event.sender_id or event.sender_id <= 0:
122
+ raise ValueError("Ludo is for human players in group chats. Add the assistant to your group and send /ludo there")
123
+ prune()
124
+ if any(table.chat == event.chat_id for table in TABLES.values()):
125
+ raise ValueError("This group already has a Ludo table. Use its current controls, or let it expire after one hour idle")
126
+ if len(TABLES) >= CAPACITY:
127
+ raise ValueError("All Ludo tables are occupied. Try later")
128
+ table = Table(secrets.token_hex(6), event.chat_id, Ludo(event.sender_id, now=time.monotonic()))
129
+ TABLES[table.token] = table
130
+ try:
131
+ async with table.lock:
132
+ result = await asyncio.wait_for(send_rich(event.client, table.chat, render(table)), EDIT_TIMEOUT)
133
+ table.message = result if isinstance(result, int) else getattr(result, "id", None)
134
+ if not isinstance(table.message, int) or not table.message:
135
+ raise ValueError("Telegram returned no table message reference; do not replay the send")
136
+ return result
137
+ except BaseException:
138
+ TABLES.pop(table.token, None)
139
+ raise
140
+
141
+
142
+ @asst_cmd(pattern="ludo")
143
+ async def ludo(event):
144
+ """Open a native shared Ludo lobby for this group's human players."""
145
+ try:
146
+ return await launch(event)
147
+ except ValueError as error:
148
+ return await send_rich(event.client, event.chat_id, t.InputRichMessage([title("Ludo table"), paragraph(str(error))]))
149
+
150
+
151
+ async def commit(event, table, candidate):
152
+ """Publish the candidate before committing state, expiring ambiguous edits."""
153
+ candidate.revision = table.revision + 1
154
+ try:
155
+ await asyncio.wait_for(edit_rich(event.client, table.chat, table.message, render(candidate)), EDIT_TIMEOUT)
156
+ except asyncio.TimeoutError:
157
+ TABLES.pop(table.token, None)
158
+ raise ValueError("Telegram did not confirm the edit. This table expired rather than replaying an uncertain turn") from None
159
+ except MessageNotModifiedError:
160
+ return False
161
+ table.game, table.revision, table.confirmation = candidate.game, candidate.revision, candidate.confirmation
162
+ table.touched = time.monotonic()
163
+ return True
164
+
165
+
166
+ def candidate_for(table):
167
+ """Copy mutable game state while retaining the live table's single lock."""
168
+ return Table(table.token, table.chat, copy.deepcopy(table.game), table.message,
169
+ table.revision, table.touched, table.confirmation, table.lock)
170
+
171
+
172
+ @callback(PATTERN)
173
+ async def ludo_callback(event):
174
+ """Allow group participants while rejecting stale, copied and illegal turns."""
175
+ try:
176
+ data = event.data.decode("ascii", "strict")
177
+ except (AttributeError, UnicodeDecodeError):
178
+ return
179
+ if not PATTERN.fullmatch(data):
180
+ return
181
+ try:
182
+ if not getattr(event, "is_group", False) or not event.sender_id or event.sender_id <= 0:
183
+ raise ValueError("Use Ludo controls as a human player inside the original group")
184
+ if data == "lu:new":
185
+ await launch(event)
186
+ return await event.answer("Ludo lobby opened")
187
+ _, token, revision, action = data.split(":")
188
+ prune()
189
+ table = TABLES.get(token)
190
+ if table is None:
191
+ raise ValueError("Table expired or the bot restarted. Send /ludo for a new lobby")
192
+ if (table.chat, table.message) != (event.chat_id, event.message_id):
193
+ raise ValueError("These controls belong to another group or message")
194
+ if table.lock.locked():
195
+ return await event.answer("A turn is updating; use the newest controls in a moment")
196
+ async with table.lock:
197
+ if int(revision) != table.revision:
198
+ raise ValueError("Old board. Use the newest controls on this table")
199
+ candidate = candidate_for(table)
200
+ now = time.monotonic()
201
+ if action in {"cancel", "resign"}:
202
+ if action == "cancel" and event.sender_id != candidate.game.host:
203
+ raise ValueError("Only the host may close this table")
204
+ 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)):
205
+ raise ValueError("Only a seated player in a running game can resign")
206
+ candidate.confirmation = (event.sender_id, action, now + 20)
207
+ elif action.endswith("ok"):
208
+ expected = (event.sender_id, action[:-2])
209
+ pending = candidate.confirmation
210
+ if not pending or pending[:2] != expected or now > pending[2]:
211
+ raise ValueError("That confirmation expired or belongs to another player")
212
+ candidate.game.apply(action[:-2], event.sender_id, now=now)
213
+ candidate.confirmation = None
214
+ elif action == "back":
215
+ if not candidate.confirmation or candidate.confirmation[0] != event.sender_id:
216
+ raise ValueError("Only the player who requested confirmation may dismiss it")
217
+ candidate.confirmation = None
218
+ else:
219
+ candidate.game.apply(action, event.sender_id, now=now)
220
+ candidate.confirmation = None
221
+ await commit(event, table, candidate)
222
+ return await event.answer()
223
+ except ValueError as error:
224
+ return await event.answer(str(error), alert=True)
225
+ except (RPCError, TypeError, asyncio.TimeoutError) as error:
226
+ trace_rich_rpc("assistant.ludo", error=error, request_kind="edit", target_kind="peer", outcome="rejected")
227
+ 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"
228
+ return await event.answer(detail, alert=True)
assistant/manager/__init__.py CHANGED
@@ -1,11 +1,19 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
 
 
 
 
 
 
 
8
  from pyUltroid._misc._decorators import ultroid_cmd
9
- from pyUltroid.fns.helper import inline_mention
10
 
11
  from .. import *
 
 
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
+ """Group-manager plugin namespace.
9
+
10
+ The manager modules intentionally import this namespace with ``from . import
11
+ *``. Re-export the assistant runtime names exactly as before, and make that
12
+ existing public surface explicit for loader and static-audit tooling.
13
+ """
14
+
15
  from pyUltroid._misc._decorators import ultroid_cmd
 
16
 
17
  from .. import *
18
+
19
+ __all__ = tuple(name for name in globals() if not name.startswith("_"))
assistant/manager/_help.py CHANGED
@@ -1,134 +1,222 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
- from . import *
9
-
10
- START = """
11
- 🪅 **Help Menu** 🪅
12
-
13
- ✘ /start : Check I am Alive or not.
14
- ✘ /help : Get This Message.
15
- ✘ /repo : Get Bot's Repo..
16
-
17
- 🧑‍💻 Join **@TeamUltroid**
18
- """
19
-
20
- ADMINTOOLS = """✘ **AdminTools** ✘
21
-
22
- • /pin : Pins the Replied Message
23
- • /pinned : Get Pinned message in chat.
24
- • /unpin : Unpin the Replied message
25
- • /unpin all : Unpin all Pinned Messages.
26
-
27
- • /ban (username/id/reply) : Ban the User
28
- • /unban (username/id/reply) : UnBan the User.
29
-
30
- • /mute (username/id/reply) : Mute the User.
31
- • /unmute (username/id/reply) : Unmute the User.
32
-
33
- • /tban (username/id/reply) (time) : Temporary ban a user
34
- • /tmute (username/id/reply) (time) : temporary Mutes a User.
35
-
36
- • /purge (purge messages)
37
-
38
- • /setgpic (reply photo) : keep Chat Photo of Group.
39
- • /delgpic : remove current chat Photo."""
40
-
41
- UTILITIES = """
42
- ✘ ** Utilities ** ✘
43
-
44
- • /info (reply/username/id) : get detailed info of user.
45
- • /id : get chat/user id.
46
- • /tr : Translate Languages..
47
- • /q : Create Quotes.
48
-
49
- • /paste (reply file/text) : paste content on Spaceb.in
50
- • /meaning (text) : Get Meaning of that Word.
51
- • /google (query) : Search Something on Google..
52
 
53
- • /suggest (query/reply) : Creates a Yes / No Poll.
54
- """
55
-
56
- LOCKS = """
57
- ✘ ** Locks ** ✘
58
-
59
- • /lock (query) : lock particular content in chat.
60
- • /unlock (query) : Unlock some content.
61
-
62
- • All Queries
63
- - `msgs` : for messages.
64
- - `inlines` : for inline queries.
65
- - `media` : for all medias.
66
- - `games` : for games.
67
- - `sticker` : for stickers.
68
- - `polls` : for polls.
69
- - `gif` : for gifs.
70
- - `pin` : for pins.
71
- - `changeinfo` : for change info right.
72
- """
73
-
74
- MISC = """
75
- ✘ **Misc** ✘
76
-
77
- • /joke : Get Random Jokes.
78
- • /decide : Decide Something..
79
-
80
- **✘ Stickertools ✘**
81
- • /kang : add sticker to your pack.
82
- • /listpack : get all of yours pack..
83
- """
84
-
85
- STRINGS = {"Admintools": ADMINTOOLS, "locks": LOCKS, "Utils": UTILITIES, "Misc": MISC}
86
-
87
- MNGE = udB.get_key("MNGR_EMOJI") or "•"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
 
90
  def get_buttons():
91
- BTTS = []
92
- keys = STRINGS.copy()
93
- while keys:
94
- BT = []
95
- for i in list(keys)[:2]:
96
- text = f"{MNGE} {i} {MNGE}"
97
- BT.append(Button.inline(text, f"hlp_{i}"))
98
- del keys[i]
99
- BTTS.append(BT)
100
- url = f"https://t.me/{asst.me.username}?startgroup=true"
101
- BTTS.append([Button.url("Add me to Group", url)])
102
- return BTTS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
 
105
  @asst_cmd(pattern="help")
106
  async def helpish(event):
107
  if not event.is_private:
108
  url = f"https://t.me/{asst.me.username}?start=start"
109
- return await event.reply(
110
- "Contact me in PM for help!", buttons=Button.url("Click me for Help", url)
 
 
 
 
 
 
 
 
 
 
111
  )
112
  if str(event.sender_id) in owner_and_sudos() and (
113
- udB.get_key("DUAL_MODE") and (udB.get_key("DUAL_HNDLR") == "/")
114
  ):
115
  return
116
- await event.reply(START, buttons=get_buttons())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
 
119
- @callback("mngbtn", owner=True)
120
- async def ehwhshd(e):
121
- buttons = get_buttons()
122
- buttons.append([Button.inline("<< Back", "open")])
123
- await e.edit(buttons=buttons)
124
 
125
 
126
- @callback("mnghome")
127
- async def home_aja(e):
128
- await e.edit(START, buttons=get_buttons())
 
 
 
 
 
 
 
 
 
 
129
 
130
 
131
- @callback(re.compile("hlp_(.*)"))
132
- async def do_something(event):
133
- match = event.pattern_match.group(1).strip().decode("utf-8")
134
- await event.edit(STRINGS[match], buttons=Button.inline("<< Back", "mnghome"))
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
+ """Assistant help menu for group administration and utility commands."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ from . import *
11
+ from .._cbs import cb, cb_exact_pattern, cb_pattern
12
+ from ..rich_pages import edit_callback_page, rich_page
13
+ from pyUltroid._core.richmsg import send_rich
14
+
15
+ HELP_SECTIONS = {
16
+ "Admintools": [
17
+ ("/pin <reply>", "Pin the replied-to message."),
18
+ ("/pinned", "Show the current pinned message."),
19
+ ("/unpin <reply>", "Unpin the replied-to message."),
20
+ ("/unpin all", "Remove all pinned messages."),
21
+ ("/ban <user> [reason]", "Ban a user by reply, ID, or username."),
22
+ ("/unban <user>", "Unban a user."),
23
+ ("/mute <user>", "Mute a user."),
24
+ ("/unmute <user>", "Unmute a user."),
25
+ ("/tban <user> <time>", "Temporarily ban a user."),
26
+ ("/tmute <user> <time>", "Temporarily mute a user."),
27
+ ("/purge <reply>", "Delete messages starting at the replied-to message."),
28
+ ("/setgpic <reply to photo>", "Set the group's profile photo."),
29
+ ("/delgpic", "Remove the current group photo."),
30
+ ],
31
+ "locks": [
32
+ ("/lock <item>", "Restrict a type of content in the current chat."),
33
+ ("/unlock <item>", "Allow a previously restricted type of content."),
34
+ ("msgs", "Messages."),
35
+ ("inlines", "Inline queries."),
36
+ ("media", "Photos, files, and other media."),
37
+ ("games", "Games."),
38
+ ("sticker", "Stickers."),
39
+ ("polls", "Polls."),
40
+ ("gif", "GIFs."),
41
+ ("pin", "Pinning messages."),
42
+ ("changeinfo", "Changing chat information."),
43
+ ],
44
+ "Utils": [
45
+ ("/info <user>", "Show details for a user by reply, ID, or username."),
46
+ ("/id", "Show the current chat and sender IDs."),
47
+ ("/tr <text>", "Translate text."),
48
+ ("/q <reply>", "Create a quote from a message."),
49
+ ("/paste <reply or text>", "Upload text or a file to Spacebin."),
50
+ ("/meaning <word>", "Look up a word's meaning."),
51
+ ("/google <query>", "Search the web."),
52
+ ("/suggest <question>", "Create a yes/no poll."),
53
+ ],
54
+ "Search": [
55
+ ("/search <query>", "Search the web for a query."),
56
+ ("/deepresearch <query>", "Run a deeper, multi-step research search."),
57
+ ],
58
+ "Misc": [
59
+ ("/joke", "Get a random joke."),
60
+ ("/decide <options>", "Choose between options."),
61
+ ("/kang <reply to sticker>", "Add a sticker to your pack."),
62
+ ("/listpack", "List your sticker packs."),
63
+ ],
64
+ "Assistant": [
65
+ ("/agent", "Configure an AI provider."),
66
+ ("/akinator", "Play Akinator in a private chat."),
67
+ ("/startgame", "Start a group game."),
68
+ ("/afk [reason]", "Set or clear your away status."),
69
+ ("/eph <reply>", "Send an ephemeral message."),
70
+ ("/whisper <reply>", "Send a private whisper."),
71
+ ("@botusername <query>", "Open an inline assistant tool."),
72
+ ],
73
+ }
74
+
75
+ CATEGORY_LABELS = {
76
+ "Admintools": "Admin tools",
77
+ "locks": "Chat locks",
78
+ "Utils": "Utilities",
79
+ "Search": "Search",
80
+ "Misc": "More tools",
81
+ "Assistant": "Assistant",
82
+ }
83
+ CATEGORIES = list(HELP_SECTIONS)
84
+ HELP_PAGE_SIZE = 6
85
+
86
+ HELP_HOME = cb_exact_pattern("help", "manager", "home")
87
+ HELP_HOME_DATA = cb("help", "manager", "home")
88
+ CATEGORY_HOME_DATA = {cat: cb("help", cat, 0) for cat in CATEGORIES}
89
+ CATEGORY_PATTERNS = {
90
+ "Admintools": cb_pattern("help", "Admintools"),
91
+ **{cat: cb_pattern("help", cat) for cat in CATEGORIES if cat != "Admintools"},
92
+ }
93
+ assert set(CATEGORY_HOME_DATA) == set(CATEGORY_PATTERNS) == set(CATEGORIES)
94
+
95
+
96
+ def _help_home_page():
97
+ rows = [
98
+ (CATEGORY_LABELS[category], "Browse commands and controls in this section.")
99
+ for category in CATEGORIES
100
+ ]
101
+ return rich_page(
102
+ "Group Help",
103
+ rows,
104
+ description="Choose a section to browse commands and their purpose.",
105
+ columns=("Section", "What it contains"),
106
+ total=len(CATEGORIES),
107
+ )
108
 
109
 
110
  def get_buttons():
111
+ rows = []
112
+ categories = list(CATEGORIES)
113
+ while categories:
114
+ rows.append(
115
+ [
116
+ (CATEGORY_LABELS[cat], CATEGORY_HOME_DATA[cat], "primary")
117
+ for cat in categories[:2]
118
+ ]
119
+ )
120
+ categories = categories[2:]
121
+ buttons = ikm(rows, icon=False)
122
+ if getattr(asst, "me", None) and getattr(asst.me, "username", None):
123
+ buttons.append(
124
+ [
125
+ Button.url(
126
+ "Add assistant to a group",
127
+ f"https://t.me/{asst.me.username}?startgroup=true",
128
+ )
129
+ ]
130
+ )
131
+ return buttons
132
+
133
+
134
+ def _help_page(cat, page):
135
+ """Return a native rich page and navigation buttons for one category."""
136
+ items = HELP_SECTIONS[cat]
137
+ total = max(1, (len(items) + HELP_PAGE_SIZE - 1) // HELP_PAGE_SIZE)
138
+ page = max(0, min(int(page), total - 1))
139
+ start = page * HELP_PAGE_SIZE
140
+ selected = items[start : start + HELP_PAGE_SIZE]
141
+ content = rich_page(
142
+ CATEGORY_LABELS[cat],
143
+ selected,
144
+ description="Commands and what they do.",
145
+ columns=("Command", "Purpose"),
146
+ page=page + 1,
147
+ pages=total,
148
+ total=len(items),
149
+ )
150
+
151
+ nav_row = []
152
+ if page > 0:
153
+ nav_row.append(("Previous", cb("help", cat, page - 1), "primary"))
154
+ if total > 1:
155
+ nav_row.append((f"{page + 1} / {total}", cb("help", cat, page), None))
156
+ if page < total - 1:
157
+ nav_row.append(("Next", cb("help", cat, page + 1), "primary"))
158
+ rows = [nav_row] if nav_row else []
159
+ rows.append([("Back to sections", HELP_HOME_DATA, None)])
160
+ return content, ikm(rows, icon=False)
161
 
162
 
163
  @asst_cmd(pattern="help")
164
  async def helpish(event):
165
  if not event.is_private:
166
  url = f"https://t.me/{asst.me.username}?start=start"
167
+ return await send_rich(
168
+ event.client,
169
+ event.chat_id,
170
+ rich_page(
171
+ "Open Help",
172
+ [("Open the assistant", "Browse help in a private chat.")],
173
+ columns=("Action", "What it does"),
174
+ total=1,
175
+ ),
176
+ reply_to=event,
177
+ buttons=[[Button.url("Open help", url)]],
178
+ link_preview=False,
179
  )
180
  if str(event.sender_id) in owner_and_sudos() and (
181
+ udB.get_key("DUAL_MODE") and udB.get_key("DUAL_HNDLR") == "/"
182
  ):
183
  return
184
+ await send_rich(
185
+ event.client,
186
+ event.chat_id,
187
+ _help_home_page(),
188
+ reply_to=event,
189
+ buttons=get_buttons(),
190
+ link_preview=False,
191
+ )
192
+
193
+
194
+ @callback(cb_exact_pattern("help", "manager", "mngbtn"), owner=True)
195
+ async def manager_help_button(event):
196
+ buttons = get_buttons()
197
+ buttons.append(get_back_button(cb("assistant", "inline", "main"), "Back"))
198
+ await event.edit(buttons=buttons)
199
 
200
 
201
+ @callback(HELP_HOME)
202
+ async def home_aja(event):
203
+ await edit_callback_page(event, _help_home_page(), buttons=get_buttons())
 
 
204
 
205
 
206
+ async def _category_page(event):
207
+ """Shared handler for every ``help:<category>:<page>`` callback."""
208
+ try:
209
+ _, cat, raw_page = event.data.decode("utf-8").split(":", 2)
210
+ if cat not in HELP_SECTIONS:
211
+ return await event.answer(
212
+ "That help section is no longer available.", alert=True
213
+ )
214
+ page = int(raw_page) if raw_page.isdigit() else 0
215
+ content, buttons = _help_page(cat, page)
216
+ except (ValueError, UnicodeDecodeError):
217
+ return await event.answer("This help page could not be opened.", alert=True)
218
+ await edit_callback_page(event, content, buttons=buttons)
219
 
220
 
221
+ for _pattern in CATEGORY_PATTERNS.values():
222
+ callback(_pattern)(_category_page)
 
 
assistant/manager/_on_adds.py CHANGED
@@ -1,5 +1,5 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
@@ -7,17 +7,28 @@
7
 
8
  from telethon import events
9
 
 
 
10
  from . import *
11
 
12
 
13
  @asst.on(events.ChatAction(func=lambda x: x.user_added))
14
  async def dueha(e):
15
  user = await e.get_user()
16
- if not user.is_self:
17
  return
18
  sm = udB.get_key("ON_MNGR_ADD")
19
- if sm == "OFF":
 
 
20
  return
21
  if not sm:
22
- sm = "Thanks for Adding me :)"
23
- await e.reply(sm, link_preview=False)
 
 
 
 
 
 
 
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
 
7
 
8
  from telethon import events
9
 
10
+ from pyUltroid._core.richmsg import RichBlocks, send_rich
11
+
12
  from . import *
13
 
14
 
15
  @asst.on(events.ChatAction(func=lambda x: x.user_added))
16
  async def dueha(e):
17
  user = await e.get_user()
18
+ if user is None or not getattr(user, "is_self", False):
19
  return
20
  sm = udB.get_key("ON_MNGR_ADD")
21
+ if sm is False or (
22
+ isinstance(sm, str) and sm.strip().casefold() in {"off", "false", "0"}
23
+ ):
24
  return
25
  if not sm:
26
+ sm = "Thanks for adding me."
27
+ blocks = RichBlocks().paragraph(str(sm))
28
+ await send_rich(
29
+ e.client,
30
+ e.chat_id,
31
+ blocks,
32
+ reply_to=e,
33
+ link_preview=False,
34
+ )
assistant/manager/admins.py CHANGED
@@ -1,17 +1,20 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
- import re
9
-
10
  from telethon.errors.rpcerrorlist import UserNotParticipantError
11
 
12
  from pyUltroid import _ult_cache
13
 
14
  from . import *
 
 
 
 
 
15
 
16
 
17
  @ultroid_cmd(pattern="d(kick|ban)", manager=True, require="ban_users")
@@ -34,17 +37,24 @@ async def dowj(e):
34
  await e.eor(str(E))
35
 
36
 
37
- @callback(re.compile("cc_(.*)"), func=_ult_cache.get("admin_callback"))
 
 
 
38
  async def callback_(event):
39
- data = event.data_match.group(1).decode("utf-8")
40
- if data not in _ult_cache.get("admin_callback", {}):
41
- return
 
 
 
 
42
  try:
43
  perm = await event.client.get_permissions(event.chat_id, event.sender_id)
44
  except UserNotParticipantError:
45
  return await event.answer("Join the Group First!", alert=True)
46
  if not perm.is_admin:
47
  return await event.answer("You are not an Admin!", alert=True)
48
- _ult_cache["admin_callback"].update({data: (event.sender, perm)})
49
  await event.answer("Verification Done!")
50
  await event.delete()
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
 
 
8
  from telethon.errors.rpcerrorlist import UserNotParticipantError
9
 
10
  from pyUltroid import _ult_cache
11
 
12
  from . import *
13
+ from .._cbs import cb_pattern
14
+
15
+
16
+ def _verification_pending(data, registrations):
17
+ return isinstance(registrations, dict) and data in registrations
18
 
19
 
20
  @ultroid_cmd(pattern="d(kick|ban)", manager=True, require="ban_users")
 
37
  await e.eor(str(E))
38
 
39
 
40
+ @callback(
41
+ cb_pattern("assistant", "admins", "admin_verify"),
42
+ func=_ult_cache.get("admin_callback"),
43
+ )
44
  async def callback_(event):
45
+ try:
46
+ data = event.data_match.group(1).decode("utf-8")
47
+ except (AttributeError, UnicodeDecodeError, IndexError):
48
+ return await event.answer("This verification request is invalid.", alert=True)
49
+ registrations = _ult_cache.get("admin_callback", {})
50
+ if not _verification_pending(data, registrations):
51
+ return await event.answer("This verification request has expired.", alert=True)
52
  try:
53
  perm = await event.client.get_permissions(event.chat_id, event.sender_id)
54
  except UserNotParticipantError:
55
  return await event.answer("Join the Group First!", alert=True)
56
  if not perm.is_admin:
57
  return await event.answer("You are not an Admin!", alert=True)
58
+ registrations[data] = (event.sender, perm)
59
  await event.answer("Verification Done!")
60
  await event.delete()
assistant/manager/afk.py CHANGED
@@ -1,12 +1,13 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
- # PLease read the GNU Affero General Public License in
6
- # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
  from datetime import datetime as dt
9
 
 
10
  from telethon.events import NewMessage
11
  from telethon.tl.types import (
12
  Message,
@@ -16,95 +17,155 @@ from telethon.tl.types import (
16
  )
17
  from telethon.utils import get_display_name
18
 
19
- from pyUltroid.fns.helper import inline_mention, time_formatter
20
-
21
- from . import asst, asst_cmd
22
 
23
  AFK = {}
24
 
25
 
26
- @asst_cmd(pattern="afk", func=lambda x: not x.is_private)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  async def go_afk(event):
28
  sender = await event.get_sender()
29
- if (not isinstance(sender, User)) or sender.bot:
30
  return
31
- try:
32
- reason = event.text.split(" ", maxsplit=1)[1]
33
- except IndexError:
34
- reason = None
35
  if event.is_reply and not reason:
36
  replied = await event.get_reply_message()
37
- if not reason and replied.text and not replied.media:
38
- reason = replied.text
39
- else:
40
- reason = replied
41
- time_ = dt.now()
42
- if AFK.get(event.chat_id):
43
- AFK[event.chat_id].update({event.sender_id: {"reason": reason, "time": time_}})
44
- else:
45
- AFK.update(
46
- {event.chat_id: {event.sender_id: {"reason": reason, "time": time_}}}
 
 
 
 
 
47
  )
48
- mention = inline_mention(sender)
49
- msg = f"**{mention} went AFK Now!**"
50
- if reason and not isinstance(reason, str):
51
- await event.reply(reason)
52
  else:
53
- msg += f"\n\n**Reason : ** `{reason}`"
54
- await event.reply(msg)
55
 
56
 
57
- @asst.on(NewMessage(func=lambda x: AFK.get(x.chat_id) and not x.is_private))
58
  async def make_change(event):
59
- if event.text.startswith("/afk"):
60
  return
61
  sender = await event.get_sender()
62
- if (not isinstance(sender, User)) or sender.bot:
63
  return
64
- chat_ = AFK[event.chat_id]
65
- if event.sender_id in chat_.keys():
66
- name = get_display_name(event.sender)
67
- cha_send = chat_[event.sender_id]
68
- time_ = time_formatter((dt.now() - cha_send["time"]).seconds * 1000)
69
- msg = f"**{name}** is No Longer AFK!\n**Was AFK for** {time_}"
70
- await event.reply(msg)
71
- del chat_[event.sender_id]
72
- if not chat_:
73
- del AFK[event.chat_id]
74
- ST_SPAM = []
 
 
 
75
  replied = await event.get_reply_message()
76
- if replied:
77
- name = get_display_name(replied.sender)
78
- if replied.sender_id in chat_.keys():
79
- s_der = chat_[replied.sender_id]
80
- res_ = s_der["reason"]
81
- time_ = time_formatter((dt.now() - s_der["time"]).seconds * 1000)
82
- msg = f"**{name}** is AFK Currently!\n**From :** {time_}"
83
- if res_ and isinstance(res_, str):
84
- msg += f"\n**Reason :** {res_}"
85
- elif res_ and isinstance(res_, Message):
86
- await event.reply(res_)
87
- await event.reply(msg)
88
- ST_SPAM.append(replied.sender_id)
89
- for ent, text in event.get_entities_text():
90
- dont_send, entity = None, None
91
- if isinstance(ent, MessageEntityMentionName):
92
- c_id = ent.user_id
93
- elif isinstance(ent, MessageEntityMention):
94
- c_id = text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  else:
96
- c_id = None
97
- if c_id:
98
- entity = await event.client.get_entity(c_id)
99
- if entity and entity.id in chat_.keys() and entity.id not in ST_SPAM:
100
- ST_SPAM.append(entity.id)
101
- s_der = chat_[entity.id]
102
- name = get_display_name(entity)
103
- res_ = s_der["reason"]
104
- time_ = time_formatter((dt.now() - s_der["time"]).seconds * 1000)
105
- msg = f"**{name}** is AFK Currently!\n**From :** {time_}"
106
- if res_ and isinstance(res_, str):
107
- msg += f"\n**Reason :** {res_}"
108
- elif res_ and isinstance(res_, Message):
109
- await event.reply(res_)
110
- await event.reply(msg)
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
+ # Please read the GNU Affero General Public License in
6
+ # <https://github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
  from datetime import datetime as dt
9
 
10
+ from telethon.errors import RPCError
11
  from telethon.events import NewMessage
12
  from telethon.tl.types import (
13
  Message,
 
17
  )
18
  from telethon.utils import get_display_name
19
 
20
+ from . import HNDLR, LOGS, asst, asst_cmd
21
+ from pyUltroid._core.richmsg import RichBlocks, send_rich
22
+ from pyUltroid.fns import fns
23
 
24
  AFK = {}
25
 
26
 
27
+ def _afk_duration(started):
28
+ elapsed = max(0, int((dt.now() - started).total_seconds() * 1000))
29
+ return fns.time_formatter(elapsed)
30
+
31
+
32
+ def _is_afk_command(raw_text):
33
+ parts = str(raw_text or "").strip().split(maxsplit=1)
34
+ if not parts:
35
+ return False
36
+ command = parts[0]
37
+ for prefix in {"/", str(HNDLR or "")}:
38
+ if prefix and command.startswith(prefix):
39
+ name = command[len(prefix) :].split("@", 1)[0]
40
+ if name.casefold() == "afk":
41
+ return True
42
+ return False
43
+
44
+
45
+ async def _send_status(event, title, *details):
46
+ blocks = RichBlocks().header(str(title), level=3)
47
+ for detail in details:
48
+ if detail:
49
+ blocks.paragraph(str(detail))
50
+ return await send_rich(
51
+ event.client,
52
+ event.chat_id,
53
+ blocks,
54
+ reply_to=event,
55
+ link_preview=False,
56
+ )
57
+
58
+
59
+ async def _forward_reason_if_needed(event, reason):
60
+ if not isinstance(reason, Message):
61
+ return
62
+ try:
63
+ await event.client.forward_messages(
64
+ event.chat_id,
65
+ reason,
66
+ reply_to=event,
67
+ )
68
+ except RPCError as exc:
69
+ LOGS.warning(
70
+ "assistant AFK reason media could not be forwarded (%s)",
71
+ exc.__class__.__name__,
72
+ )
73
+
74
+
75
+ @asst_cmd(pattern="afk", func=lambda event: not event.is_private)
76
  async def go_afk(event):
77
  sender = await event.get_sender()
78
+ if not isinstance(sender, User) or sender.bot:
79
  return
80
+
81
+ parts = (event.raw_text or event.text or "").split(maxsplit=1)
82
+ reason = parts[1].strip() if len(parts) > 1 else None
 
83
  if event.is_reply and not reason:
84
  replied = await event.get_reply_message()
85
+ if replied is not None:
86
+ if replied.text and not replied.media:
87
+ reason = replied.text
88
+ elif replied.media:
89
+ reason = replied
90
+
91
+ AFK.setdefault(event.chat_id, {})[event.sender_id] = {
92
+ "reason": reason,
93
+ "time": dt.now(),
94
+ }
95
+ if isinstance(reason, str) and reason:
96
+ await _send_status(
97
+ event,
98
+ f"{get_display_name(sender)} went AFK",
99
+ f"Reason: {reason}",
100
  )
 
 
 
 
101
  else:
102
+ await _forward_reason_if_needed(event, reason)
103
+ await _send_status(event, f"{get_display_name(sender)} went AFK")
104
 
105
 
106
+ @asst.on(NewMessage(func=lambda event: AFK.get(event.chat_id) and not event.is_private))
107
  async def make_change(event):
108
+ if _is_afk_command(event.raw_text):
109
  return
110
  sender = await event.get_sender()
111
+ if not isinstance(sender, User) or sender.bot:
112
  return
113
+
114
+ chat_afk = AFK.get(event.chat_id, {})
115
+ if event.sender_id in chat_afk:
116
+ entry = chat_afk.pop(event.sender_id)
117
+ await _send_status(
118
+ event,
119
+ f"{get_display_name(sender)} is no longer AFK",
120
+ f"Away for {_afk_duration(entry['time'])}",
121
+ )
122
+ if not chat_afk:
123
+ AFK.pop(event.chat_id, None)
124
+ return
125
+
126
+ notified = set()
127
  replied = await event.get_reply_message()
128
+ if replied is not None and replied.sender_id in chat_afk:
129
+ user_id = replied.sender_id
130
+ notified.add(user_id)
131
+ entry = chat_afk[user_id]
132
+ display = get_display_name(replied.sender) if replied.sender else str(user_id)
133
+ details = [f"Away for {_afk_duration(entry['time'])}"]
134
+ reason = entry.get("reason")
135
+ if isinstance(reason, str) and reason:
136
+ details.append(f"Reason: {reason}")
137
+ else:
138
+ await _forward_reason_if_needed(event, reason)
139
+ await _send_status(event, f"{display} is currently AFK", *details)
140
+
141
+ for entity, text in event.get_entities_text():
142
+ if isinstance(entity, MessageEntityMentionName):
143
+ user_id = entity.user_id
144
+ elif isinstance(entity, MessageEntityMention):
145
+ user_id = text
146
+ else:
147
+ continue
148
+ if not user_id:
149
+ continue
150
+ try:
151
+ mentioned = await event.client.get_entity(user_id)
152
+ except (RPCError, ValueError) as exc:
153
+ LOGS.debug(
154
+ "assistant AFK mention lookup failed (%s)", exc.__class__.__name__
155
+ )
156
+ continue
157
+ if mentioned.id not in chat_afk or mentioned.id in notified:
158
+ continue
159
+ notified.add(mentioned.id)
160
+ entry = chat_afk[mentioned.id]
161
+ details = [f"Away for {_afk_duration(entry['time'])}"]
162
+ reason = entry.get("reason")
163
+ if isinstance(reason, str) and reason:
164
+ details.append(f"Reason: {reason}")
165
  else:
166
+ await _forward_reason_if_needed(event, reason)
167
+ await _send_status(
168
+ event,
169
+ f"{get_display_name(mentioned)} is currently AFK",
170
+ *details,
171
+ )
 
 
 
 
 
 
 
 
 
assistant/manager/misc.py CHANGED
@@ -1,5 +1,5 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
@@ -11,7 +11,7 @@ import random
11
  import aiohttp
12
 
13
  from pyUltroid.dB import DEVLIST
14
- from pyUltroid.fns.admins import admin_check
15
 
16
  from . import *
17
 
@@ -26,7 +26,7 @@ async def dheh(e):
26
 
27
  @asst_cmd(pattern="echo( (.*)|$)")
28
  async def oqha(e):
29
- if not await admin_check(e):
30
  return
31
  if match := e.pattern_match.group(1).strip():
32
  text = match
@@ -46,7 +46,7 @@ async def oqha(e):
46
  @asst_cmd(pattern="kickme$")
47
  async def doit(e):
48
  if e.sender_id in DEVLIST:
49
- return await eod(e, "`I will Not Kick You, my Developer..`")
50
  try:
51
  await e.client.kick_participant(e.chat_id, e.sender_id)
52
  except Exception as Fe:
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
 
11
  import aiohttp
12
 
13
  from pyUltroid.dB import DEVLIST
14
+ from pyUltroid.fns import fns
15
 
16
  from . import *
17
 
 
26
 
27
  @asst_cmd(pattern="echo( (.*)|$)")
28
  async def oqha(e):
29
+ if not await fns.admin_check(e):
30
  return
31
  if match := e.pattern_match.group(1).strip():
32
  text = match
 
46
  @asst_cmd(pattern="kickme$")
47
  async def doit(e):
48
  if e.sender_id in DEVLIST:
49
+ return await eod(e, "I will Not Kick You, my Developer..")
50
  try:
51
  await e.client.kick_participant(e.chat_id, e.sender_id)
52
  except Exception as Fe:
assistant/manager/stickermanager.py CHANGED
@@ -1,10 +1,11 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
 
8
  import random
9
 
10
  from telethon import errors
@@ -13,15 +14,16 @@ from telethon.tl.functions.messages import GetStickerSetRequest as GetSticker
13
  from telethon.tl.functions.messages import UploadMediaRequest
14
  from telethon.tl.functions.stickers import AddStickerToSetRequest as AddSticker
15
  from telethon.tl.functions.stickers import CreateStickerSetRequest
16
- from telethon.tl.types import InputPeerSelf
17
  from telethon.tl.types import InputStickerSetItem as SetItem
18
- from telethon.tl.types import InputStickerSetShortName, User
19
  from telethon.utils import get_display_name, get_input_document
20
 
 
 
21
  from pyUltroid.fns.misc import Quotly
22
  from pyUltroid.fns.tools import TgConverter
23
 
24
- from . import LOGS, asst, asst_cmd, udB
25
 
26
 
27
  @asst_cmd(
@@ -32,7 +34,7 @@ async def kang_cmd(ult):
32
  if not isinstance(sender, User):
33
  return
34
  if not ult.is_reply:
35
- return await ult.eor("`Reply to a sticker/photo..`", time=5)
36
  reply = await ult.get_reply_message()
37
  if sender.username:
38
  pre = sender.username[:4]
@@ -61,9 +63,9 @@ async def kang_cmd(ult):
61
  elif reply.text:
62
  dl = await Quotly().create_quotly(reply)
63
  else:
64
- return await ult.eor("`Reply to sticker or text to add it in your pack...`")
65
  if not emoji:
66
- emoji = "🏵"
67
  if dl:
68
  upl = await ult.client.upload_file(dl)
69
  file = get_input_document(
@@ -95,8 +97,6 @@ async def kang_cmd(ult):
95
  title=title,
96
  short_name=sn,
97
  stickers=[SetItem(file, emoji=emoji)],
98
- videos=video,
99
- animated=animated,
100
  software="@TeamUltroid",
101
  )
102
  )
@@ -109,7 +109,11 @@ async def kang_cmd(ult):
109
  get_[ult.sender_id].update({type_: [sn]})
110
  udB.set_key("STICKERS", get_)
111
  return await ult.reply(
112
- f"**Kanged Successfully!\nEmoji :** {emoji}\n**Link :** [Click Here](https://t.me/addstickers/{sn})"
 
 
 
 
113
  )
114
  name = get_[ult.sender_id][type_][-1]
115
  try:
@@ -137,7 +141,7 @@ async def kang_cmd(ult):
137
  title=title,
138
  short_name=sn,
139
  stickers=[SetItem(file, emoji=emoji)],
140
- animated=animated,
141
  )
142
  )
143
  except Exception as er:
@@ -145,31 +149,49 @@ async def kang_cmd(ult):
145
  get_[ult.sender_id][type_].append(pack.set.short_name)
146
  udB.set_key("STICKERS", get_)
147
  return await ult.reply(
148
- f"**Created New Kang Pack!\nEmoji :** {emoji}\n**Link :** [Click Here](https://t.me/addstickers/{sn})"
 
 
 
 
149
  )
150
  except Exception as er:
151
  LOGS.exception(er)
152
- return await ult.reply(str(er))
153
  await ult.reply(
154
- f"Sticker Added to Pack Successfully\n**Link :** [Click Here](https://t.me/addstickers/{name})"
 
 
 
 
155
  )
156
 
157
 
 
 
 
 
 
 
 
 
 
 
158
  @asst_cmd(pattern="listpack")
159
  async def do_magic(ult):
160
  ko = udB.get_key("STICKERS") or {}
161
  if not ko.get(ult.sender_id):
162
- return await ult.reply("No Sticker Pack Found!")
163
  al_ = []
164
  ul = ko[ult.sender_id]
165
  for _ in ul.keys():
166
  al_.extend(ul[_])
167
- msg = "• **Stickers Owned by You!**\n\n"
168
  for _ in al_:
169
  try:
170
  pack = await ult.client(GetSticker(InputStickerSetShortName(_), hash=0))
171
- msg += f"• [{pack.set.title}](https://t.me/addstickers/{_})\n"
172
- except StickerSetInvalidError:
173
  if ul.get("anim") and _ in ul["anim"]:
174
  ul["anim"].remove(_)
175
  elif ul.get("vid") and _ in ul["vid"]:
@@ -177,4 +199,33 @@ async def do_magic(ult):
177
  else:
178
  ul["static"].remove(_)
179
  udB.set_key("STICKERS", ko)
180
- await ult.reply(msg)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
+ import html
9
  import random
10
 
11
  from telethon import errors
 
14
  from telethon.tl.functions.messages import UploadMediaRequest
15
  from telethon.tl.functions.stickers import AddStickerToSetRequest as AddSticker
16
  from telethon.tl.functions.stickers import CreateStickerSetRequest
17
+ from telethon.tl.types import InputPeerSelf, InputStickerSetShortName, User
18
  from telethon.tl.types import InputStickerSetItem as SetItem
 
19
  from telethon.utils import get_display_name, get_input_document
20
 
21
+ from custom.fmt import fmtmsg
22
+ from pyUltroid._core.events import InlineResultBuilder
23
  from pyUltroid.fns.misc import Quotly
24
  from pyUltroid.fns.tools import TgConverter
25
 
26
+ from . import LOGS, asst, asst_cmd, in_pattern, udB
27
 
28
 
29
  @asst_cmd(
 
34
  if not isinstance(sender, User):
35
  return
36
  if not ult.is_reply:
37
+ return await ult.eor("Reply to a sticker/photo..", time=5)
38
  reply = await ult.get_reply_message()
39
  if sender.username:
40
  pre = sender.username[:4]
 
63
  elif reply.text:
64
  dl = await Quotly().create_quotly(reply)
65
  else:
66
+ return await ult.eor("Reply to sticker or text to add it in your pack...")
67
  if not emoji:
68
+ emoji = ""
69
  if dl:
70
  upl = await ult.client.upload_file(dl)
71
  file = get_input_document(
 
97
  title=title,
98
  short_name=sn,
99
  stickers=[SetItem(file, emoji=emoji)],
 
 
100
  software="@TeamUltroid",
101
  )
102
  )
 
109
  get_[ult.sender_id].update({type_: [sn]})
110
  udB.set_key("STICKERS", get_)
111
  return await ult.reply(
112
+ fmtmsg(
113
+ "Kanged Successfully! ",
114
+ msgs=f"Emoji: {emoji}\nLink: https://t.me/addstickers/{sn}",
115
+ ),
116
+ parse_mode="html",
117
  )
118
  name = get_[ult.sender_id][type_][-1]
119
  try:
 
141
  title=title,
142
  short_name=sn,
143
  stickers=[SetItem(file, emoji=emoji)],
144
+ software="@TeamUltroid",
145
  )
146
  )
147
  except Exception as er:
 
149
  get_[ult.sender_id][type_].append(pack.set.short_name)
150
  udB.set_key("STICKERS", get_)
151
  return await ult.reply(
152
+ fmtmsg(
153
+ "Created New Kang Pack! ",
154
+ msgs=f"Emoji: {emoji}\nLink: https://t.me/addstickers/{sn}",
155
+ ),
156
+ parse_mode="html",
157
  )
158
  except Exception as er:
159
  LOGS.exception(er)
160
+ return await ult.reply(fmtmsg("Error ", msgs=str(er)), parse_mode="html")
161
  await ult.reply(
162
+ fmtmsg(
163
+ "Sticker Added to Pack Successfully ",
164
+ msgs=f"Link: https://t.me/addstickers/{name}",
165
+ ),
166
+ parse_mode="html",
167
  )
168
 
169
 
170
+ def _owned_pack_names(sender_id):
171
+ """Flat list of every pack short-name this user has kanged so far."""
172
+ ko = udB.get_key("STICKERS") or {}
173
+ owned = ko.get(sender_id) or {}
174
+ names = []
175
+ for kind in owned.values():
176
+ names.extend(kind)
177
+ return names
178
+
179
+
180
  @asst_cmd(pattern="listpack")
181
  async def do_magic(ult):
182
  ko = udB.get_key("STICKERS") or {}
183
  if not ko.get(ult.sender_id):
184
+ return await ult.reply(fmtmsg("No Sticker Pack Found!"), parse_mode="html")
185
  al_ = []
186
  ul = ko[ult.sender_id]
187
  for _ in ul.keys():
188
  al_.extend(ul[_])
189
+ packs = []
190
  for _ in al_:
191
  try:
192
  pack = await ult.client(GetSticker(InputStickerSetShortName(_), hash=0))
193
+ packs.append((pack.set.title, _))
194
+ except StickersetInvalidError:
195
  if ul.get("anim") and _ in ul["anim"]:
196
  ul["anim"].remove(_)
197
  elif ul.get("vid") and _ in ul["vid"]:
 
199
  else:
200
  ul["static"].remove(_)
201
  udB.set_key("STICKERS", ko)
202
+
203
+ links = "\n".join(
204
+ f' <a href="https://t.me/addstickers/{short_name}">{html.escape(title)}</a>'
205
+ for title, short_name in packs
206
+ )
207
+ text = fmtmsg("Stickers Owned by You! ")
208
+ if links:
209
+ text = f"{text}\n\n{links}"
210
+ await ult.reply(text, parse_mode="html")
211
+
212
+
213
+ @in_pattern("packs", owner=True)
214
+ async def packs_inline(e):
215
+ names = _owned_pack_names(e.sender_id)
216
+ if not names:
217
+ return await e.answer(
218
+ [],
219
+ switch_pm="No kanged packs yet reply /kang to a sticker first!",
220
+ switch_pm_param="start",
221
+ )
222
+ results = [
223
+ await InlineResultBuilder(e).article(
224
+ title=name,
225
+ url=f"https://t.me/addstickers/{name}",
226
+ description="Tap to open this pack",
227
+ text=f" [{name}](https://t.me/addstickers/{name})",
228
+ )
229
+ for name in names[:20]
230
+ ]
231
+ await e.answer(results)
assistant/matrix_arcade.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Owner-only native Matrix arcade with bounded, ephemeral callback sessions."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import copy
6
+ import re
7
+ import secrets
8
+ import time
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ from telethon.errors import FloodWaitError, MessageNotModifiedError, RPCError
13
+ from telethon.tl import types
14
+
15
+ from pyUltroid._core.matrix_arcade import Arcade, paragraph, payload, title
16
+ from pyUltroid._core.richdebug import rpc_identifier, trace_rich_rpc
17
+ from pyUltroid._core.richmsg import edit_rich, send_rich
18
+ from pyUltroid._misc._assistant import asst_cmd, callback
19
+
20
+ CALLBACK_PATTERN = re.compile(r"^mx:(?:new|[a-f0-9]{12}:[0-9]{1,9}:(?:menu|rain|ttt|lights|memory|lab|visuals|reset|step|play|stop|download|cell[0-9]{1,2}))$")
21
+ SESSION_TTL = 20 * 60
22
+ MAX_SESSIONS = 64
23
+ FRAME_COUNT = 4
24
+ FRAME_INTERVAL = 2.0
25
+ EDIT_TIMEOUT = 8.0
26
+ COMPANION = Path(__file__).resolve().parents[1] / "resources" / "rich" / "matrix_lab.html"
27
+
28
+
29
+ @dataclass
30
+ class Session:
31
+ """Bind an arcade to one owner, chat and bot-authored message."""
32
+ state: Arcade
33
+ owner: int
34
+ chat: int
35
+ message: int | None = None
36
+ touched: float = field(default_factory=time.monotonic)
37
+ downloaded: float | None = None
38
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)
39
+ stop: bool = False
40
+
41
+
42
+ class SessionStore:
43
+ """Bound idle session memory without timers, database writes or startup work."""
44
+ def __init__(self):
45
+ self.sessions = {}
46
+
47
+ def prune(self):
48
+ """Drop expired idle sessions without interrupting active callbacks."""
49
+ now = time.monotonic()
50
+ for token, session in list(self.sessions.items()):
51
+ if now - session.touched >= SESSION_TTL and not session.lock.locked():
52
+ del self.sessions[token]
53
+
54
+ def create(self, owner, chat):
55
+ """Reserve a session and evict the oldest idle one at capacity."""
56
+ self.prune()
57
+ if len(self.sessions) >= MAX_SESSIONS:
58
+ idle = [(s.touched, token) for token, s in self.sessions.items() if not s.lock.locked()]
59
+ if not idle:
60
+ raise ValueError("All arcade screens are busy; try again shortly")
61
+ del self.sessions[min(idle)[1]]
62
+ token = secrets.token_hex(6)
63
+ session = Session(Arcade(token, seed=secrets.randbits(32)), owner, chat)
64
+ self.sessions[token] = session
65
+ return session
66
+
67
+ def resolve(self, token, owner, chat, message):
68
+ """Reject expired, copied, forwarded or cross-user callback controls."""
69
+ self.prune()
70
+ session = self.sessions.get(token)
71
+ if session is None:
72
+ raise ValueError("This screen expired or the bot restarted. Send /matrix again")
73
+ if (session.owner, session.chat, session.message) != (owner, chat, message):
74
+ raise ValueError("This control belongs to a different owner, chat or message")
75
+ return session
76
+
77
+
78
+ STORE = SessionStore()
79
+
80
+
81
+ async def launch(event):
82
+ """Send a new native arcade without editing the incoming command."""
83
+ session = STORE.create(event.sender_id, event.chat_id)
84
+ try:
85
+ async with session.lock:
86
+ result = await send_rich(event.client, event.chat_id, payload(session.state))
87
+ message = result if isinstance(result, int) else getattr(result, "id", None)
88
+ if not isinstance(message, int) or not message:
89
+ raise ValueError("Native send returned no message reference")
90
+ session.message = message
91
+ return result
92
+ except BaseException:
93
+ STORE.sessions.pop(session.state.token, None)
94
+ raise
95
+
96
+
97
+ @asst_cmd(pattern="(?:matrix|arcade)", owner=True)
98
+ async def matrix(event):
99
+ """Open a fresh owner-only native arcade session."""
100
+ return await launch(event)
101
+
102
+
103
+ async def _commit(event, session, candidate):
104
+ """Commit game state only after Telegram accepts the candidate message edit."""
105
+ candidate.revision = session.state.revision + 1
106
+ try:
107
+ await asyncio.wait_for(
108
+ edit_rich(event.client, session.chat, session.message, payload(candidate)),
109
+ timeout=EDIT_TIMEOUT,
110
+ )
111
+ except asyncio.TimeoutError:
112
+ # A cancelled request may have been accepted: expire, never replay an uncertain move.
113
+ STORE.sessions.pop(session.state.token, None)
114
+ raise ValueError("Telegram did not confirm this update in time. The screen expired; send /matrix again") from None
115
+ except MessageNotModifiedError:
116
+ # Do not commit an unseen revision: its controls would not match Telegram.
117
+ return False
118
+ session.state = candidate
119
+ session.touched = time.monotonic()
120
+ return True
121
+
122
+
123
+ async def _play(event, session):
124
+ """Play at most four native message edits, then restore idle controls."""
125
+ session.stop = False
126
+ for index in range(FRAME_COUNT):
127
+ if session.stop:
128
+ break
129
+ candidate = copy.deepcopy(session.state)
130
+ candidate.frame += 1
131
+ candidate.running = index < FRAME_COUNT - 1
132
+ if not await _commit(event, session, candidate):
133
+ break
134
+ if candidate.running:
135
+ await asyncio.sleep(FRAME_INTERVAL)
136
+ if session.state.running:
137
+ candidate = copy.deepcopy(session.state)
138
+ candidate.running = False
139
+ await _commit(event, session, candidate)
140
+
141
+
142
+ async def _failure(event, message, acknowledged):
143
+ """Report errors natively even when Telethon has already cached the query answer."""
144
+ if not acknowledged:
145
+ return await event.answer(message, alert=True)
146
+ notice = types.InputRichMessage([
147
+ title("Matrix playback stopped"), paragraph(message),
148
+ paragraph("No move was replayed. The last accepted frame may remain visible."),
149
+ ])
150
+ try:
151
+ return await asyncio.wait_for(send_rich(event.client, event.chat_id, notice), timeout=EDIT_TIMEOUT)
152
+ except (RPCError, TypeError, ValueError, asyncio.TimeoutError) as error:
153
+ # One bounded native notice attempt; never retry an uncertain send or downgrade.
154
+ trace_rich_rpc("assistant.matrix.notice", error=error, request_kind="send", target_kind="peer", outcome="rejected")
155
+
156
+
157
+ @callback(CALLBACK_PATTERN, owner=True)
158
+ async def matrix_callback(event):
159
+ """Dispatch native arcade controls with ownership, revision and lock guards."""
160
+ try:
161
+ data = event.data.decode("ascii", "strict")
162
+ except (AttributeError, UnicodeDecodeError):
163
+ return
164
+ if CALLBACK_PATTERN.fullmatch(data) is None:
165
+ return
166
+ if data == "mx:new":
167
+ await event.answer()
168
+ return await launch(event)
169
+ _, token, revision, action = data.split(":")
170
+ acknowledged = False
171
+ try:
172
+ session = STORE.resolve(token, event.sender_id, event.chat_id, event.message_id)
173
+ # Stop remains available across the finite playback's changing frame revisions.
174
+ if action == "stop" and session.lock.locked() and session.state.mode == "rain":
175
+ session.stop = True
176
+ return await event.answer("Stopping after the current frame")
177
+ if session.lock.locked():
178
+ return await event.answer("This screen is updating. Try again in a moment")
179
+ async with session.lock:
180
+ if int(revision) != session.state.revision:
181
+ return await event.answer("That frame is old. Use the newest controls")
182
+ if action == "play":
183
+ if session.state.mode != "rain":
184
+ raise ValueError("Playback belongs to digital rain")
185
+ await event.answer("Requesting up to four native MTProto frames")
186
+ acknowledged = True
187
+ await _play(event, session)
188
+ return
189
+ if action == "download":
190
+ if session.state.mode != "lab":
191
+ raise ValueError("Open Source lab to download the companion")
192
+ now = time.monotonic()
193
+ if session.downloaded is not None and now - session.downloaded < 10:
194
+ raise ValueError("The browser companion was just sent; wait ten seconds")
195
+ if not COMPANION.is_file():
196
+ raise ValueError("The browser companion is unavailable on this deployment")
197
+ await event.client.send_file(
198
+ session.chat, str(COMPANION), force_document=True,
199
+ caption="Matrix browser companion. Download and open in a browser. JavaScript, canvas and SVG run there, not inside Telegram messages.",
200
+ parse_mode=None,
201
+ )
202
+ session.downloaded = time.monotonic()
203
+ session.touched = time.monotonic()
204
+ return await event.answer("Browser companion sent as an HTML document")
205
+ candidate = copy.deepcopy(session.state)
206
+ if action == "stop":
207
+ if candidate.mode != "rain":
208
+ raise ValueError("Stop belongs to digital rain")
209
+ candidate.running = False
210
+ candidate.frame += 1
211
+ else:
212
+ candidate.act(action)
213
+ await _commit(event, session, candidate)
214
+ return await event.answer()
215
+ except ValueError as error:
216
+ # These messages are local fixed validation strings, never remote error bodies.
217
+ return await _failure(event, str(error), acknowledged)
218
+ except (RPCError, TypeError) as error:
219
+ identifier = rpc_identifier(error) if isinstance(error, RPCError) else "LOCAL_VALIDATION_ERROR"
220
+ trace_rich_rpc("assistant.matrix", error=error, request_kind="edit", target_kind="peer", outcome="rejected")
221
+ if isinstance(error, FloodWaitError):
222
+ return await _failure(event, "Telegram rate-limited this screen. Playback stopped; try later", acknowledged)
223
+ return await _failure(event, f"Native update rejected ({identifier}). No fallback was sent", acknowledged)
assistant/pmbot.py CHANGED
@@ -1,5 +1,5 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
@@ -9,9 +9,11 @@
9
 
10
  # --------------------------------------- Imports -------------------------------------------- #
11
 
 
 
12
  import os
13
 
14
- from telethon.errors.rpcerrorlist import UserNotParticipantError
15
  from telethon.tl.custom import Button
16
  from telethon.tl.functions.channels import GetFullChannelRequest
17
  from telethon.tl.functions.messages import GetFullChatRequest
@@ -19,14 +21,34 @@ from telethon.tl.types import Channel, Chat
19
  from telethon.utils import get_display_name
20
 
21
  from pyUltroid.dB.base import KeyManager
22
- from pyUltroid.dB.botchat_db import *
23
- from pyUltroid.fns.helper import inline_mention
24
-
25
  from . import *
 
26
 
27
  botb = KeyManager("BOTBLS", cast=list)
28
- FSUB = udB.get_key("PMBOT_FSUB")
29
  CACHE = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  # --------------------------------------- Incoming -------------------------------------------- #
31
 
32
 
@@ -37,13 +59,17 @@ CACHE = {}
37
  )
38
  async def on_new_mssg(event):
39
  who = event.sender_id
 
 
 
40
  # doesn't reply to that user anymore
41
- if event.text.startswith("/") or who == OWNER_ID:
42
  return
43
- if FSUB:
 
44
  MSG = ""
45
  BTTS = []
46
- for chat in FSUB:
47
  try:
48
  await event.client.get_permissions(chat, event.sender_id)
49
  except UserNotParticipantError:
@@ -53,7 +79,7 @@ async def on_new_mssg(event):
53
  uri = ""
54
  TAHC_ = await event.client.get_entity(chat)
55
  if hasattr(TAHC_, "username") and TAHC_.username:
56
- uri = f"t.me/{TAHC_.username}"
57
  elif CACHE.get(chat):
58
  uri = CACHE[chat]
59
  else:
@@ -66,15 +92,30 @@ async def on_new_mssg(event):
66
  if FUGB.full_chat.exported_invite:
67
  CACHE[chat] = FUGB.full_chat.exported_invite.link
68
  uri = CACHE[chat]
69
- BTTS.append(Button.url(get_display_name(TAHC_), uri))
70
  except Exception as er:
71
  LOGS.exception(f"Error On PmBot Force Sub!\n - {chat} \n{er}")
72
- if MSG and BTTS:
73
- return await event.reply(MSG, buttons=BTTS)
74
- xx = await event.forward_to(OWNER_ID)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  if event.fwd_from:
76
- await xx.reply(f"From {inline_mention(event.sender)} [`{event.sender_id}`]")
77
- add_stuff(xx.id, who)
78
 
79
 
80
  # --------------------------------------- Outgoing -------------------------------------------- #
@@ -88,21 +129,40 @@ async def on_new_mssg(event):
88
  )
89
  async def on_out_mssg(event):
90
  x = event.reply_to_msg_id
91
- to_user = get_who(x)
92
- if event.text.startswith("/who"):
 
 
 
93
  try:
 
 
 
 
94
  k = await asst.get_entity(to_user)
95
  photu = await event.client.download_profile_photo(k.id)
 
 
 
 
 
 
 
 
96
  await event.reply(
97
- f"• **Name :** {get_display_name(k)}\n• **ID :** `{k.id}`\n• **Link :** {inline_mention(k)}",
98
  file=photu,
 
99
  )
100
  if photu:
101
  os.remove(photu)
102
  return
103
- except BaseException as er:
104
- return await event.reply(f"**ERROR : **{str(er)}")
105
- elif event.text.startswith("/"):
 
 
 
106
  return
107
  if to_user:
108
  await asst.send_message(to_user, event.message)
@@ -119,13 +179,27 @@ async def on_out_mssg(event):
119
  )
120
  async def banhammer(event):
121
  if not event.is_reply:
122
- return await event.reply(get_string("pmbot_2"))
123
- target = get_who(event.reply_to_msg_id)
 
 
 
 
 
124
  if botb.contains(target):
125
- return await event.reply(get_string("pmbot_3"))
 
 
 
126
 
127
  botb.add(target)
128
- await event.reply(f"#BAN\nUser : {target}")
 
 
 
 
 
 
129
  await asst.send_message(target, get_string("pmbot_4"))
130
 
131
 
@@ -137,13 +211,27 @@ async def banhammer(event):
137
  )
138
  async def unbanhammer(event):
139
  if not event.is_reply:
140
- return await event.reply(get_string("pmbot_5"))
141
- target = get_who(event.reply_to_msg_id)
 
 
 
 
 
142
  if not botb.contains(target):
143
- return await event.reply(get_string("pmbot_6"))
 
 
 
144
 
145
  botb.remove(target)
146
- await event.reply(f"#UNBAN\nUser : {target}")
 
 
 
 
 
 
147
  await asst.send_message(target, get_string("pmbot_7"))
148
 
149
 
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
 
9
 
10
  # --------------------------------------- Imports -------------------------------------------- #
11
 
12
+ import ast
13
+ import html
14
  import os
15
 
16
+ from telethon.errors.rpcerrorlist import MessageIdInvalidError, UserNotParticipantError
17
  from telethon.tl.custom import Button
18
  from telethon.tl.functions.channels import GetFullChannelRequest
19
  from telethon.tl.functions.messages import GetFullChatRequest
 
21
  from telethon.utils import get_display_name
22
 
23
  from pyUltroid.dB.base import KeyManager
24
+ from pyUltroid.dB import db
25
+ from custom.tg import ikm
26
+ from custom.fmt import fmtmsg, rawhtml
27
  from . import *
28
+ from pyUltroid.fns import fns
29
 
30
  botb = KeyManager("BOTBLS", cast=list)
 
31
  CACHE = {}
32
+
33
+
34
+ def _force_sub_chats(value):
35
+ """Read both native and legacy stringified PMBOT_FSUB values safely."""
36
+ if value is None or value is False or value == "":
37
+ return ()
38
+ if isinstance(value, str):
39
+ try:
40
+ value = ast.literal_eval(value)
41
+ except (SyntaxError, ValueError):
42
+ value = [part.strip() for part in value.split(",") if part.strip()]
43
+ if value is None or value is False:
44
+ return ()
45
+ if isinstance(value, (str, int)):
46
+ value = (value,)
47
+ if not isinstance(value, (list, tuple, set)):
48
+ return ()
49
+ return tuple(value)
50
+
51
+
52
  # --------------------------------------- Incoming -------------------------------------------- #
53
 
54
 
 
59
  )
60
  async def on_new_mssg(event):
61
  who = event.sender_id
62
+ message_text = (
63
+ getattr(event, "raw_text", None) or getattr(event, "text", None) or ""
64
+ )
65
  # doesn't reply to that user anymore
66
+ if message_text.startswith("/") or who == OWNER_ID:
67
  return
68
+ force_sub_chats = _force_sub_chats(udB.get_key("PMBOT_FSUB"))
69
+ if force_sub_chats:
70
  MSG = ""
71
  BTTS = []
72
+ for chat in force_sub_chats:
73
  try:
74
  await event.client.get_permissions(chat, event.sender_id)
75
  except UserNotParticipantError:
 
79
  uri = ""
80
  TAHC_ = await event.client.get_entity(chat)
81
  if hasattr(TAHC_, "username") and TAHC_.username:
82
+ uri = f"https://t.me/{TAHC_.username}"
83
  elif CACHE.get(chat):
84
  uri = CACHE[chat]
85
  else:
 
92
  if FUGB.full_chat.exported_invite:
93
  CACHE[chat] = FUGB.full_chat.exported_invite.link
94
  uri = CACHE[chat]
95
+ BTTS.append((get_display_name(TAHC_), "url", uri))
96
  except Exception as er:
97
  LOGS.exception(f"Error On PmBot Force Sub!\n - {chat} \n{er}")
98
+ if MSG:
99
+ return await event.reply(
100
+ fmtmsg("Subscription Required ", msgs=MSG),
101
+ buttons=ikm(BTTS) if BTTS else None,
102
+ parse_mode="html",
103
+ )
104
+ try:
105
+ xx = await event.forward_to(OWNER_ID)
106
+ except MessageIdInvalidError:
107
+ if not getattr(event, "message", None) and not getattr(event, "media", None):
108
+ return
109
+ try:
110
+ xx = await event.client.send_message(
111
+ OWNER_ID, event.message or "", file=event.media
112
+ )
113
+ except Exception:
114
+ LOGS.exception("PmBot fallback copy failed")
115
+ return
116
  if event.fwd_from:
117
+ await xx.reply(f"From {fns.inline_mention(event.sender)} [{event.sender_id}]")
118
+ db.botchat.add(xx.id, who)
119
 
120
 
121
  # --------------------------------------- Outgoing -------------------------------------------- #
 
129
  )
130
  async def on_out_mssg(event):
131
  x = event.reply_to_msg_id
132
+ to_user = db.botchat.get_who(x)
133
+ message_text = (
134
+ getattr(event, "raw_text", None) or getattr(event, "text", None) or ""
135
+ )
136
+ if message_text.startswith("/who"):
137
  try:
138
+ if not to_user:
139
+ return await event.reply(
140
+ "Could not identify the user for this message."
141
+ )
142
  k = await asst.get_entity(to_user)
143
  photu = await event.client.download_profile_photo(k.id)
144
+ text_out = fmtmsg(
145
+ "User Information ",
146
+ {
147
+ "Name": get_display_name(k),
148
+ "ID": str(k.id),
149
+ "Profile Link": fns.inline_mention(k, html=True),
150
+ },
151
+ )
152
  await event.reply(
153
+ text_out,
154
  file=photu,
155
+ parse_mode="html",
156
  )
157
  if photu:
158
  os.remove(photu)
159
  return
160
+ except Exception as er:
161
+ return await event.reply(
162
+ fmtmsg("Error ", msgs=str(er)),
163
+ parse_mode="html",
164
+ )
165
+ elif message_text.startswith("/"):
166
  return
167
  if to_user:
168
  await asst.send_message(to_user, event.message)
 
179
  )
180
  async def banhammer(event):
181
  if not event.is_reply:
182
+ return await event.reply(
183
+ fmtmsg("Ban target not found", msgs=get_string("pmbot_2")),
184
+ parse_mode="html",
185
+ )
186
+ target = db.botchat.get_who(event.reply_to_msg_id)
187
+ if not target:
188
+ return await event.reply("Could not identify the user for this message.")
189
  if botb.contains(target):
190
+ return await event.reply(
191
+ fmtmsg("Already Banned", msgs=get_string("pmbot_3")),
192
+ parse_mode="html",
193
+ )
194
 
195
  botb.add(target)
196
+ await event.reply(
197
+ fmtmsg(
198
+ "User Banned",
199
+ msgs=rawhtml(f"User ID: <code>{html.escape(str(target))}</code>"),
200
+ ),
201
+ parse_mode="html",
202
+ )
203
  await asst.send_message(target, get_string("pmbot_4"))
204
 
205
 
 
211
  )
212
  async def unbanhammer(event):
213
  if not event.is_reply:
214
+ return await event.reply(
215
+ fmtmsg("Unban target not found", msgs=get_string("pmbot_5")),
216
+ parse_mode="html",
217
+ )
218
+ target = db.botchat.get_who(event.reply_to_msg_id)
219
+ if not target:
220
+ return await event.reply("Could not identify the user for this message.")
221
  if not botb.contains(target):
222
+ return await event.reply(
223
+ fmtmsg("Not Banned", msgs=get_string("pmbot_6")),
224
+ parse_mode="html",
225
+ )
226
 
227
  botb.remove(target)
228
+ await event.reply(
229
+ fmtmsg(
230
+ "User Unbanned",
231
+ msgs=rawhtml(f"User ID: <code>{html.escape(str(target))}</code>"),
232
+ ),
233
+ parse_mode="html",
234
+ )
235
  await asst.send_message(target, get_string("pmbot_7"))
236
 
237
 
assistant/rich_creations.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Board-only assistant command and reusable rich creation exports."""
2
+
3
+ from pyUltroid._core.assistant_creations import (
4
+ CREATIONS,
5
+ chessboard_html,
6
+ creation_payload,
7
+ )
8
+ from pyUltroid._core.richmsg import rich_message, send_rich
9
+ from pyUltroid._misc._assistant import asst_cmd
10
+
11
+ __all__ = ("CREATIONS", "chess", "chessboard_html", "creation_payload")
12
+
13
+
14
+ @asst_cmd(pattern="chess", owner=True)
15
+ async def chess(event):
16
+ """Render only the complete starting chess position."""
17
+ return await send_rich(
18
+ event.client, event.chat_id, rich_message(chessboard_html(), format="html")
19
+ )
assistant/rich_pages.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small native RichMessage helpers for assistant menu pages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ from collections.abc import Sequence
7
+ from typing import Any
8
+
9
+ from pyUltroid._core.richmsg import RichFile, RichMarkup, edit_rich
10
+
11
+
12
+ def page_footer(page: int, pages: int, total: int) -> str:
13
+ """Return the shared lower-case page index and item count."""
14
+ pages = max(1, int(pages))
15
+ page = max(1, min(int(page), pages))
16
+ return f"page {page} of {pages} • total {max(0, int(total))}"
17
+
18
+
19
+ def rich_page(
20
+ title: str,
21
+ rows: Sequence[Sequence[Any]],
22
+ *,
23
+ description: str | None = None,
24
+ columns: Sequence[str] = ("Option", "What it does"),
25
+ page: int = 1,
26
+ pages: int = 1,
27
+ total: int | None = None,
28
+ media: tuple[str, Any, str | None] | None = None,
29
+ ) -> RichMarkup:
30
+ """Build a large-heading, divider, table, divider, indexed RichMessage page."""
31
+ data_rows = [tuple("" if cell is None else str(cell) for cell in row) for row in rows]
32
+ column_names = tuple(str(name) for name in columns)
33
+ total_items = len(data_rows) if total is None else int(total)
34
+ parts = [f"<h1>{html.escape(str(title))}</h1>"]
35
+ if description:
36
+ parts.append(f"<p>{html.escape(str(description))}</p>")
37
+ if media is not None:
38
+ kind, source, caption = media
39
+ if kind not in {"photo", "document"}:
40
+ raise ValueError("media kind must be 'photo' or 'document'")
41
+ file_id = "assistant-page-media"
42
+ if kind == "photo":
43
+ alt = html.escape(caption or "", quote=True)
44
+ parts.append(f'<figure><img src="{file_id}" alt="{alt}"/></figure>')
45
+ else:
46
+ parts.append(f'<figure><tg-document src="{file_id}"></tg-document></figure>')
47
+ if caption:
48
+ parts.append(f"<p>{html.escape(caption)}</p>")
49
+ parts.append("<hr>")
50
+ parts.append('<table class="bordered compact">')
51
+ parts.append("<tr>" + "".join(f"<th>{html.escape(name)}</th>" for name in column_names) + "</tr>")
52
+ for row in data_rows:
53
+ cells = list(row[: len(column_names)])
54
+ cells.extend("" for _ in range(len(column_names) - len(cells)))
55
+ parts.append("<tr>" + "".join(f"<td>{html.escape(cell)}</td>" for cell in cells) + "</tr>")
56
+ parts.append("</table><hr>")
57
+ parts.append(
58
+ f"<p><i>{html.escape(page_footer(page, pages, total_items))}</i></p>"
59
+ )
60
+ files = ()
61
+ if media is not None:
62
+ kind, source, _caption = media
63
+ files = (RichFile("assistant-page-media", source, kind),)
64
+ return RichMarkup("".join(parts), "html", files)
65
+
66
+
67
+ def body_page(
68
+ title: str,
69
+ body_html: str,
70
+ *,
71
+ page: int = 1,
72
+ pages: int = 1,
73
+ total: int = 1,
74
+ media: tuple[str, Any, str | None] | None = None,
75
+ ) -> RichMarkup:
76
+ """Wrap already-sanitized native HTML in a standard indexed page."""
77
+ parts = [f"<h1>{html.escape(str(title))}</h1><hr>{body_html}"]
78
+ files = ()
79
+ if media is not None:
80
+ kind, source, caption = media
81
+ if kind not in {"photo", "document"}:
82
+ raise ValueError("media kind must be 'photo' or 'document'")
83
+ file_id = "assistant-page-media"
84
+ if kind == "photo":
85
+ alt = html.escape(caption or "", quote=True)
86
+ parts.append(f'<figure><img src="{file_id}" alt="{alt}"/></figure>')
87
+ else:
88
+ parts.append(f'<figure><tg-document src="{file_id}"></tg-document></figure>')
89
+ if caption:
90
+ parts.append(f"<p>{html.escape(caption)}</p>")
91
+ files = (RichFile(file_id, source, kind),)
92
+ parts.extend(
93
+ (
94
+ "<hr>",
95
+ f"<p><i>{html.escape(page_footer(page, pages, total))}</i></p>",
96
+ )
97
+ )
98
+ return RichMarkup("".join(parts), "html", files)
99
+
100
+
101
+ def callback_edit_target(event: Any) -> tuple[Any, Any]:
102
+ """Return the actual callback message target, never the query's random ID."""
103
+ query = getattr(event, "query", None)
104
+ inline_id = getattr(query, "msg_id", None)
105
+ inline_types = {"InputBotInlineMessageID", "InputBotInlineMessageID64"}
106
+ if type(inline_id).__name__ in inline_types:
107
+ return inline_id, None
108
+
109
+ message_id = getattr(event, "message_id", None)
110
+ if type(message_id).__name__ in inline_types:
111
+ return message_id, None
112
+ if message_id is None:
113
+ message_id = inline_id
114
+ return getattr(event, "chat_id", None), message_id
115
+
116
+
117
+ async def edit_callback_page(event: Any, content: Any, buttons: Any = None) -> Any:
118
+ """Edit a chat or inline callback message through the Layer 230 API."""
119
+ peer, message = callback_edit_target(event)
120
+ return await edit_rich(
121
+ event.client,
122
+ peer,
123
+ message,
124
+ content,
125
+ format="html",
126
+ buttons=buttons,
127
+ link_preview=False,
128
+ )
assistant/rich_showcase.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Owner-only Layer-230 RichMessage examples: each index pick sends a sample."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from datetime import datetime, timezone
6
+ from typing import Any
7
+
8
+ from telethon import Button
9
+ from telethon.errors import MessageNotModifiedError, RPCError
10
+ from telethon.tl import types
11
+
12
+ from pyUltroid._core.assistant_creations import CREATIONS, creation_payload
13
+ from pyUltroid._core.matrix_arcade import lobby_payload
14
+ from pyUltroid._core.richdebug import rpc_identifier, trace_rich_rpc
15
+ from pyUltroid._core.richmsg import RichBlocks, edit_rich, rich_message, send_rich
16
+ from pyUltroid._misc._assistant import asst_cmd, callback
17
+
18
+ # Native schema examples, NOT a claim of server/account acceptance.
19
+ # No plain-text controls, unsupported title blocks or note-only index entries.
20
+ CATALOG = (
21
+ ("native", "Paragraph", "PageBlockParagraph"),
22
+ *((f"heading-{n}", f"Heading {n}", f"PageBlockHeading{n}") for n in range(1, 7)),
23
+ ("inline", "Inline styles", "TextBold / Italic / Underline / Strike"),
24
+ ("extra-styles", "Mark / sub / superscript", "TextMarked / Subscript / Superscript"),
25
+ ("spoiler", "Spoiler", "TextSpoiler"),
26
+ ("links", "Links / email / phone", "TextUrl / Email / Phone"),
27
+ ("emoji", "Custom emoji", "TextCustomEmoji; account eligibility may restrict it"),
28
+ ("date", "Formatted date", "TextDate"),
29
+ ("divider", "Divider", "PageBlockDivider"),
30
+ ("footer", "Footer", "PageBlockFooter"),
31
+ ("lists", "Unordered list", "PageBlockList"),
32
+ ("ordered", "Ordered list", "PageBlockOrderedList"),
33
+ ("tasks", "Task list", "PageListItemText checkbox / checked"),
34
+ ("code", "Inline / fenced code", "TextFixed / PageBlockPreformatted"),
35
+ ("tables", "Table", "PageBlockTable"),
36
+ ("quotes", "Quotation", "PageBlockBlockquote"),
37
+ ("pullquote", "Pull quote", "PageBlockPullquote"),
38
+ ("rich-expand", "Expandable quotation", "PageBlockBlockquote collapsed flag; not details"),
39
+ ("details", "Details: closed", "PageBlockDetails"),
40
+ ("details-open", "Details: open", "PageBlockDetails open flag"),
41
+ ("details-code", "Details + code", "PageBlockDetails / Preformatted"),
42
+ ("details-steps", "Two-step details", "Two PageBlockDetails blocks"),
43
+ ("native-guide", "Seven-step guide", "Bold paragraph heading + seven details/code sections"),
44
+ ("formula", "Inline / block formula", "TextMath / PageBlockMath"),
45
+ ("anchors", "Named anchor", "TextAnchor / TextUrl"),
46
+ ("map", "Map", "PageBlockMap; static public Rome coordinates"),
47
+ ("rich-buttons", "Rich button row", "PageBlockButtonRow: URL / callback / copy"),
48
+ ("text-buttons", "Inline text button", "TextButton"),
49
+ ("block-quotes", "Multi-block quotation", "PageBlockBlockquoteBlocks"),
50
+ ("nested-details", "Nested details", "PageBlockDetails inside details"),
51
+ ("text-entities", "Native entity text", "TextWithEntities inside a native paragraph"),
52
+ ("details-wrapper", "Native RichBlocks wrapper", "RichBlocks(native=True).expandable"),
53
+ ("rtl", "Right-to-left", "InputRichMessage rtl flag"),
54
+ *((sid, label, description) for sid, label, description, _builder in CREATIONS),
55
+ ("matrix-arcade", "Matrix arcade", "Playable native games, bounded edit rain and a browser source lab"),
56
+ )
57
+ PAGE_SIZE = 8
58
+ CALLBACK_PATTERN = re.compile(r"^rich:(?:index:[0-9]{1,2}|(?:pick|send|edit):[a-z0-9-]{1,32}|ping:ok)$")
59
+
60
+ # Already-delivered keyboards still resolve, but never to their old plain or
61
+ # unsupported payloads. Removed media/footnote entries are not falsely aliased.
62
+ _ALIASES = {
63
+ "plain": "native", "html": "native", "markdown": "native",
64
+ "headings": "heading-1", "native-title": "native",
65
+ "divider-footer": "footer", "details-native": "details",
66
+ "native-open": "details-open", "native-code": "details-code",
67
+ "native-steps": "details-steps", "legacy-styles": "text-entities",
68
+ "legacy-expand": "rich-expand",
69
+ }
70
+
71
+
72
+ def _page(page: int) -> int:
73
+ return max(0, min(page, (len(CATALOG) - 1) // PAGE_SIZE))
74
+
75
+
76
+ def _data(action: str, value: str) -> bytes:
77
+ return f"rich:{action}:{value}".encode("ascii")
78
+
79
+
80
+ def _sample(sid: str):
81
+ sid = _ALIASES.get(sid, sid)
82
+ return next((item for item in CATALOG if item[0] == sid), None)
83
+
84
+
85
+ def _sample_page(sid: str) -> int:
86
+ return next((i // PAGE_SIZE for i, item in enumerate(CATALOG) if item[0] == sid), 0)
87
+
88
+
89
+ def _keyboard(page: int = 0, selected: str = ""):
90
+ page = _page(page)
91
+ if selected:
92
+ return [
93
+ [Button.inline("Send again", _data("send", selected)), Button.inline("Edit this example", _data("edit", selected))],
94
+ [Button.inline("Back to index", _data("index", str(_sample_page(selected))))],
95
+ ]
96
+ items = CATALOG[page * PAGE_SIZE:(page + 1) * PAGE_SIZE]
97
+ rows = [[Button.inline(item[1], _data("pick", item[0])) for item in items[i:i + 2]] for i in range(0, len(items), 2)]
98
+ nav = []
99
+ if page:
100
+ nav.append(Button.inline("Previous", _data("index", str(page - 1))))
101
+ if (page + 1) * PAGE_SIZE < len(CATALOG):
102
+ nav.append(Button.inline("Next", _data("index", str(page + 1))))
103
+ if nav:
104
+ rows.append(nav)
105
+ return rows
106
+
107
+
108
+ def _text(value: str):
109
+ return types.TextPlain(value)
110
+
111
+
112
+ def _paragraph(value: str):
113
+ return types.PageBlockParagraph(_text(value))
114
+
115
+
116
+ def _details(title: str = "Step 1", *, code: bool = False, opened: bool = False):
117
+ children = [_paragraph("Static example instruction.")]
118
+ if code:
119
+ children.append(types.PageBlockPreformatted(_text("echo native_example"), "bash"))
120
+ return types.PageBlockDetails(blocks=children, title=_text(title), open=opened)
121
+
122
+
123
+ def _guide_blocks():
124
+ return [
125
+ types.PageBlockParagraph(types.TextBold(_text("Seven-step guide"))),
126
+ _paragraph("Open each section to inspect its instructions and code."),
127
+ types.PageBlockDivider(),
128
+ *[_details(f"Step {n}", code=True) for n in range(1, 8)],
129
+ types.PageBlockDivider(),
130
+ types.PageBlockParagraph(types.TextItalic(_text("page 1 of 1; seven steps"))),
131
+ ]
132
+
133
+
134
+ def _payload(sample):
135
+ """Every catalog entry resolves to structured InputRichMessage blocks."""
136
+ sid = sample[0]
137
+ if sid.startswith("heading-"):
138
+ level = int(sid.rsplit("-", 1)[1])
139
+ blocks = [getattr(types, f"PageBlockHeading{level}")(_text(f"Heading {level}")), _paragraph("Native heading example.")]
140
+ elif sid == "details-wrapper":
141
+ return rich_message(RichBlocks(native=True).expandable("Native wrapper", "A real details body."))
142
+ elif sid in {entry[0] for entry in CREATIONS}:
143
+ return creation_payload(sid)
144
+ elif sid == "matrix-arcade":
145
+ return lobby_payload()
146
+ else:
147
+ examples = {
148
+ "native": [_paragraph("One native RichMessage paragraph.")],
149
+ "inline": [types.PageBlockParagraph(types.TextConcat([
150
+ types.TextBold(_text("Bold ")), types.TextItalic(_text("italic ")),
151
+ types.TextUnderline(_text("underline ")), types.TextStrike(_text("strike ")),
152
+ types.TextBold(types.TextItalic(_text("nested styles"))),
153
+ ]))],
154
+ "extra-styles": [types.PageBlockParagraph(types.TextConcat([
155
+ types.TextMarked(_text("Highlighted ")), _text("H"), types.TextSubscript(_text("2")),
156
+ _text("O x"), types.TextSuperscript(_text("2")),
157
+ ]))],
158
+ "spoiler": [types.PageBlockParagraph(types.TextSpoiler(_text("Tap to reveal a native spoiler.")))],
159
+ "links": [types.PageBlockParagraph(types.TextConcat([
160
+ types.TextUrl(_text("Telegram "), "https://telegram.org", 0),
161
+ types.TextEmail(_text("Email example "), "example@example.com"),
162
+ types.TextPhone(_text("Fictional phone"), "+12025550123"),
163
+ ]))],
164
+ "emoji": [types.PageBlockParagraph(types.TextCustomEmoji(5368324170671202286, "👍"))],
165
+ "date": [types.PageBlockParagraph(types.TextDate(_text("Sample date"), datetime(2023, 11, 14, tzinfo=timezone.utc), long_date=True))],
166
+ "divider": [_paragraph("Above"), types.PageBlockDivider(), _paragraph("Below")],
167
+ "footer": [_paragraph("Native footer example"), types.PageBlockFooter(_text("Sample footer"))],
168
+ "lists": [types.PageBlockList([types.PageListItemText(_text("First")), types.PageListItemText(_text("Second"))])],
169
+ "ordered": [types.PageBlockOrderedList([types.PageListOrderedItemText(_text("First"), num="1"), types.PageListOrderedItemText(_text("Second"), num="2")])],
170
+ "tasks": [types.PageBlockList([types.PageListItemText(_text("Done"), checkbox=True, checked=True), types.PageListItemText(_text("Next"), checkbox=True, checked=False)])],
171
+ "code": [types.PageBlockParagraph(types.TextFixed(_text("inline_code()"))), types.PageBlockPreformatted(_text('def hello():\n return "rich"'), "python")],
172
+ "tables": [types.PageBlockTable(_text("Sample table"), [
173
+ types.PageTableRow([types.PageTableCell(header=True, text=_text("Format")), types.PageTableCell(header=True, text=_text("Example"))]),
174
+ types.PageTableRow([types.PageTableCell(text=_text("Native")), types.PageTableCell(text=_text("Table"))]),
175
+ ], bordered=True, striped=True)],
176
+ "quotes": [types.PageBlockBlockquote(_text("Native quotation"), _text("Example author"))],
177
+ "pullquote": [types.PageBlockPullquote(_text("Native pull quote"), _text("Example author"))],
178
+ "rich-expand": [types.PageBlockBlockquote(_text("Expandable quotation\nLine two\nLine three\nLine four\nLine five\nLine six"), _text("Example author"), collapsed=True)],
179
+ "details": [_details()],
180
+ "details-open": [_details(opened=True)],
181
+ "details-code": [_details(code=True)],
182
+ "details-steps": [_details(), _details("Step 2", code=True)],
183
+ "native-guide": _guide_blocks(),
184
+ "formula": [types.PageBlockParagraph(types.TextMath("x^2 + y^2")), types.PageBlockMath("E = mc^2")],
185
+ "anchors": [types.PageBlockParagraph(types.TextUrl(_text("Jump to section"), "#section", 0)), types.PageBlockParagraph(types.TextAnchor(_text("Target section"), "section"))],
186
+ "map": [types.PageBlockMap(types.GeoPoint(long=12.5, lat=41.9, access_hash=0), 14, 320, 200, types.PageCaption(_text("Rome"), types.TextEmpty()))],
187
+ "rich-buttons": [types.PageBlockButtonRow([
188
+ types.PageButton(_text("Telegram"), types.InlineButtonTypeUrl("https://telegram.org")),
189
+ types.PageButton(_text("Test callback"), types.InlineButtonTypeCallback(b"rich:ping:ok")),
190
+ types.PageButton(_text("Copy sample"), types.InlineButtonTypeCopy("Sample text")),
191
+ ])],
192
+ "text-buttons": [types.PageBlockParagraph(types.TextButton(_text("Telegram"), types.InlineButtonTypeUrl("https://telegram.org")))],
193
+ "block-quotes": [types.PageBlockBlockquoteBlocks([_paragraph("First quoted paragraph."), types.PageBlockPreformatted(_text("echo quoted"), "bash")], _text("Example author"))],
194
+ "nested-details": [types.PageBlockDetails([_paragraph("Outer body."), _details("Inner section", code=True)], _text("Outer section"), open=False)],
195
+ "text-entities": [types.PageBlockParagraph(types.TextWithEntities("Bold and italic", [types.MessageEntityBold(0, 4), types.MessageEntityItalic(9, 6)]))],
196
+ "rtl": [_paragraph("مرحبا — native right-to-left example")],
197
+ }
198
+ blocks = examples[sid]
199
+ return types.InputRichMessage(blocks=blocks, rtl=True if sid == "rtl" else None)
200
+
201
+
202
+ def _index(page: int = 0, error: str = ""):
203
+ page = _page(page)
204
+ blocks = [
205
+ types.PageBlockParagraph(types.TextBold(_text("RichMessage examples"))),
206
+ _paragraph("Tap an index button to send that native example immediately. Send again creates a new example; Edit this example tests native editing."),
207
+ _paragraph("All examples use structured Layer-230 MTProto. Server/account acceptance varies; a rejection is reported, never downgraded to plain text."),
208
+ _paragraph("Media, collages and slideshows are not indexed: verified uploaded references are required. Raw HTML/Markdown controls and footnote syntax are not demonstrated here."),
209
+ ]
210
+ blocks.extend(_paragraph(f"{label} — {status}") for _sid, label, status in CATALOG[page * PAGE_SIZE:(page + 1) * PAGE_SIZE])
211
+ blocks.append(_paragraph(f"Page {page + 1}/{(len(CATALOG) - 1) // PAGE_SIZE + 1}. {len(CATALOG)} native examples."))
212
+ if error:
213
+ blocks.append(_paragraph(f"Last example rejected: {error}"))
214
+ return types.InputRichMessage(blocks=blocks)
215
+
216
+
217
+ async def _edit_index(event: Any, page: int = 0, error: str = ""):
218
+ try:
219
+ return await edit_rich(event.client, event.chat_id, event.message_id, _index(page, error), buttons=_keyboard(page))
220
+ except MessageNotModifiedError:
221
+ trace_rich_rpc("assistant.rich.index", request_kind="edit", outcome="not_modified")
222
+
223
+
224
+ async def _run_sample(event: Any, sample, operation: str):
225
+ sid, _label, _status = sample
226
+ payload = _payload(sample)
227
+ buttons = _keyboard(selected=sid)
228
+ stage = f"assistant.rich.{sid}"
229
+ trace_rich_rpc(stage, content=payload, request_kind=operation, target_kind="peer", outcome="attempt")
230
+ try:
231
+ if operation == "send":
232
+ result = await send_rich(event.client, event.chat_id, payload, buttons=buttons)
233
+ elif operation == "edit":
234
+ result = await edit_rich(event.client, event.chat_id, event.message_id, payload, buttons=buttons)
235
+ else:
236
+ raise ValueError("unknown rich operation")
237
+ trace_rich_rpc(stage, content=payload, request_kind=operation, target_kind="peer", outcome="success")
238
+ return result
239
+ except (RPCError, ValueError, TypeError) as error:
240
+ identifier = rpc_identifier(error) if isinstance(error, RPCError) else "LOCAL_VALIDATION_ERROR"
241
+ trace_rich_rpc(stage, content=payload, error=error, request_kind=operation, target_kind="peer", outcome="rejected")
242
+ await _edit_index(event, _sample_page(sid), error=f"{sid}/{operation}: {identifier}")
243
+ return None
244
+
245
+
246
+ @asst_cmd(pattern="rich", owner=True)
247
+ async def rich(event: Any):
248
+ # Send our own native index; never edit the user's incoming command.
249
+ return await send_rich(event.client, event.chat_id, _index(), buttons=_keyboard())
250
+
251
+
252
+ @callback(CALLBACK_PATTERN, owner=True)
253
+ async def rich_callback(event: Any):
254
+ try:
255
+ data = event.data.decode("ascii", "strict")
256
+ except (UnicodeDecodeError, AttributeError):
257
+ return
258
+ if CALLBACK_PATTERN.fullmatch(data) is None:
259
+ return
260
+ action, value = data.split(":")[1:]
261
+ await event.answer()
262
+ if action == "ping":
263
+ return
264
+ if action == "index":
265
+ return await _edit_index(event, int(value))
266
+ sample = _sample(value)
267
+ if sample is None:
268
+ return await _edit_index(event, error="unknown or unavailable sample")
269
+ # Selection IS the demonstration, not a label requiring a second click.
270
+ return await _run_sample(event, sample, "send" if action == "pick" else action)
assistant/start.py CHANGED
@@ -1,34 +1,185 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
- from datetime import datetime
 
 
 
9
 
10
- try:
11
- from pytz import timezone as tz
12
- except ImportError:
13
- tz = None
14
- from telethon import Button, events
15
  from telethon.errors.rpcerrorlist import MessageDeleteForbiddenError
16
- from telethon.utils import get_display_name
 
 
17
 
 
 
 
 
18
  from pyUltroid._misc import SUDO_M, owner_and_sudos
 
19
  from pyUltroid.dB.base import KeyManager
20
- from pyUltroid.fns.helper import inline_mention
 
 
21
  from strings import get_string
22
 
23
- from . import *
 
 
24
 
25
- Owner_info_msg = udB.get_key("BOT_INFO_START")
26
- custom_info = True
27
- if Owner_info_msg is None:
28
- custom_info = False
29
- Owner_info_msg = f"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  **Owner** - {OWNER_NAME}
31
- **OwnerID** - `{OWNER_ID}`
32
 
33
  **Message Forwards** - {udB.get_key("PMBOT")}
34
 
@@ -36,46 +187,246 @@ if Owner_info_msg is None:
36
  """
37
 
38
 
39
- _settings = [
40
- [
41
- Button.inline("API Keys", data="cbs_apiset"),
42
- Button.inline("PM Bot", data="cbs_chatbot"),
43
- ],
44
- [
45
- Button.inline("Alive", data="cbs_alvcstm"),
46
- Button.inline("PMPermit", data="cbs_ppmset"),
47
- ],
48
- [
49
- Button.inline("Features", data="cbs_otvars"),
50
- Button.inline("VC Song Bot", data="cbs_vcb"),
51
- ],
52
- [Button.inline("« Back", data="mainmenu")],
53
- ]
54
 
55
- _start = [
56
- [
57
- Button.inline("Language 🌐", data="lang"),
58
- Button.inline("Settings ⚙️", data="setter"),
59
- ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  [
61
- Button.inline("Sᴛᴀᴛs ✨", data="stat"),
62
- Button.inline("Bʀᴏᴀᴅᴄᴀsᴛ 📻", data="bcast"),
 
 
 
 
 
 
 
63
  ],
64
- [Button.inline("TɪᴍᴇZᴏɴᴇ 🌎", data="tz")],
65
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
 
68
  @callback("ownerinfo")
69
  async def own(event):
70
- msg = Owner_info_msg.format(
71
- mention=event.sender.mention, me=inline_mention(ultroid_bot.me)
 
 
 
 
 
72
  )
73
- if custom_info:
74
- msg += "\n\n• Powered by **@TeamUltroid**"
75
- await event.edit(
76
- msg,
77
- buttons=[Button.inline("Close", data="closeit")],
78
- link_preview=False,
79
  )
80
 
81
 
@@ -89,160 +440,275 @@ async def closet(lol):
89
 
90
  @asst_cmd(pattern="start( (.*)|$)", forwards=False, func=lambda x: not x.is_group)
91
  async def ultroid(event):
 
 
92
  args = event.pattern_match.group(1).strip()
93
  keym = KeyManager("BOT_USERS", cast=list)
94
  if not keym.contains(event.sender_id) and event.sender_id not in owner_and_sudos():
95
  keym.add(event.sender_id)
96
  kak_uiw = udB.get_key("OFF_START_LOG")
97
- if not kak_uiw or kak_uiw != True:
98
- msg = f"{inline_mention(event.sender)} `[{event.sender_id}]` started your [Assistant bot](@{asst.me.username})."
99
- buttons = [[Button.inline("Info", "itkkstyo")]]
100
  if event.sender.username:
101
- buttons[0].append(
102
- Button.mention(
103
- "User", await event.client.get_input_entity(event.sender_id)
 
 
 
 
 
 
 
 
104
  )
105
- )
106
- await event.client.send_message(
107
- udB.get_key("LOG_CHANNEL"), msg, buttons=buttons
108
- )
109
  if event.sender_id not in SUDO_M.fullsudos:
110
  ok = ""
111
- me = inline_mention(ultroid_bot.me)
112
- mention = inline_mention(event.sender)
 
 
 
 
113
  if args and args != "set":
114
- await get_stored_file(event, args)
 
 
115
  if not udB.get_key("STARTMSG"):
116
  if udB.get_key("PMBOT"):
117
  ok = "You can contact my master using this bot!!\n\nSend your Message, I will Deliver it To Master."
118
- await event.reply(
 
119
  f"Hey there {mention}, this is Ultroid Assistant of {me}!\n\n{ok}",
120
- file=udB.get_key("STARTMEDIA"),
121
- buttons=[Button.inline("Info.", data="ownerinfo")]
122
- if Owner_info_msg
123
- else None,
 
 
 
 
 
124
  )
125
  else:
126
- await event.reply(
127
- udB.get_key("STARTMSG").format(me=me, mention=mention),
128
- file=udB.get_key("STARTMEDIA"),
129
- buttons=[Button.inline("Info.", data="ownerinfo")]
130
- if Owner_info_msg
131
- else None,
 
 
 
 
 
132
  )
133
  else:
134
  name = get_display_name(event.sender)
135
  if args == "set":
136
- await event.reply(
137
- "Choose from the below options -",
138
- buttons=_settings,
 
 
 
 
139
  )
140
  elif args:
141
- await get_stored_file(event, args)
 
 
 
 
 
 
 
 
 
 
 
 
142
  else:
143
- await event.reply(
144
- get_string("ast_3").format(name),
 
 
 
145
  buttons=_start,
 
146
  )
147
 
148
 
149
- @callback("itkkstyo", owner=True)
150
  async def ekekdhdb(e):
151
  text = f"When New Visitor will visit your Assistant Bot. You will get this log message!\n\nTo Disable : {HNDLR}setdb OFF_START_LOG True"
152
  await e.answer(text, alert=True)
153
 
154
 
155
- @callback("mainmenu", owner=True, func=lambda x: not x.is_group)
156
- async def ultroid(event):
157
- await event.edit(
158
- get_string("ast_3").format(OWNER_NAME),
 
 
 
 
 
159
  buttons=_start,
160
  )
161
 
162
 
163
- @callback("stat", owner=True)
164
  async def botstat(event):
165
  ok = len(udB.get_key("BOT_USERS") or [])
166
- msg = """Ultroid Assistant - Stats
167
- Total Users - {}""".format(
168
- ok,
 
 
 
 
 
 
169
  )
170
- await event.answer(msg, cache_time=0, alert=True)
171
 
172
 
173
  @callback("bcast", owner=True)
174
  async def bdcast(event):
175
  keym = KeyManager("BOT_USERS", cast=list)
176
  total = keym.count()
177
- await event.edit(f"• Broadcast to {total} users.")
 
 
 
178
  async with event.client.conversation(OWNER_ID) as conv:
179
- await conv.send_message(
180
- "Enter your broadcast message.\nUse /cancel to stop the broadcast.",
 
 
 
 
 
 
181
  )
182
- response = await conv.get_response()
183
- if response.message == "/cancel":
184
- return await conv.send_message("Cancelled!!")
 
 
 
 
 
 
 
185
  success = 0
186
  fail = 0
187
- await conv.send_message(f"Starting a broadcast to {total} users...")
188
- start = datetime.now()
 
 
 
 
 
189
  for i in keym.get():
190
  try:
191
  await asst.send_message(int(i), response)
192
  success += 1
193
  except BaseException:
194
  fail += 1
195
- end = datetime.now()
196
  time_taken = (end - start).seconds
197
- await conv.send_message(
198
- f"""
199
- **Broadcast completed in {time_taken} seconds.**
200
- Total Users in Bot - {total}
201
- **Sent to** : `{success} users.`
202
- **Failed for** : `{fail} user(s).`""",
 
 
 
 
 
 
 
 
 
203
  )
204
 
205
 
206
- @callback("setter", owner=True)
207
  async def setting(event):
208
- await event.edit(
209
- "Choose from the below options -",
210
- buttons=_settings,
 
211
  )
212
 
213
 
214
  @callback("tz", owner=True)
215
  async def timezone_(event):
216
  await event.delete()
217
- if tz is None:
218
- return await event.client.send_message(
219
- event.sender_id,
220
- f"`pytz` is not installed, TimeZone feature is unavailable.\n\nInstall it via `{HNDLR}update` or `{HNDLR}bash pip install pytz`.",
221
- )
222
  pru = event.sender_id
223
  var = "TIMEZONE"
224
  name = "Timezone"
225
  async with event.client.conversation(pru) as conv:
226
- await conv.send_message(
227
- "Send Your TimeZone From This List [Check From Here](http://www.timezoneconverter.com/cgi-bin/findzone.tzc)"
228
- )
229
- response = conv.wait_event(events.NewMessage(chats=pru))
230
- response = await response
231
- themssg = response.message.message
232
- if themssg == "/cancel":
233
- return await conv.send_message(
234
- "Cancelled!!",
235
- buttons=get_back_button("mainmenu"),
236
- )
237
- try:
238
- tz(themssg)
239
- await setit(event, var, themssg)
240
- await conv.send_message(
241
- f"{name} changed to {themssg}\n",
242
- buttons=get_back_button("mainmenu"),
243
  )
244
- except BaseException:
245
- await conv.send_message(
246
- "Wrong TimeZone, Try again",
247
- buttons=get_back_button("mainmenu"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  )
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
 
8
+ import html
9
+ import os
10
+ from collections import OrderedDict
11
+ from datetime import datetime as _dt
12
 
13
+ from pytz import UnknownTimeZoneError
14
+ from pytz import timezone as tz
15
+ from telethon import events
 
 
16
  from telethon.errors.rpcerrorlist import MessageDeleteForbiddenError
17
+ from telethon.tl import functions
18
+ from telethon.tl import types as tl_types
19
+ from telethon.utils import get_display_name, resolve_bot_file_id
20
 
21
+ from custom.tg import ikm
22
+ from pyUltroid import HNDLR, asst, udB, ultroid_bot
23
+ from pyUltroid._core.richmsg import coerce_to_rich_markup
24
+ from pyUltroid._core.richmsg import send_rich
25
  from pyUltroid._misc import SUDO_M, owner_and_sudos
26
+ from pyUltroid._misc._assistant import asst_cmd, callback
27
  from pyUltroid.dB.base import KeyManager
28
+ from pyUltroid.fns import fns
29
+ from pyUltroid.startup.logger import LOGS
30
+ from pyUltroid.version import ultroid_version
31
  from strings import get_string
32
 
33
+ from . import OWNER_ID, OWNER_NAME, setit
34
+ from ._cbs import cb, cb_exact_pattern
35
+ from .rich_pages import body_page, edit_callback_page, rich_page
36
 
37
+ SETTER = cb("assistant", "start", "setter")
38
+ MAIN_MENU = cb("assistant", "start", "mainmenu")
39
+ _START_EVENTS = OrderedDict()
40
+ _START_EVENT_LIMIT = 512
41
+
42
+
43
+ def _claim_start_event(event):
44
+ """Suppress a repeated delivery of the same Telegram /start update."""
45
+ message = getattr(event, "message", None)
46
+ message_id = getattr(message, "id", None)
47
+ if message_id is None:
48
+ return True
49
+ key = (
50
+ getattr(event, "chat_id", None),
51
+ getattr(event, "sender_id", None),
52
+ message_id,
53
+ )
54
+ if key in _START_EVENTS:
55
+ return False
56
+ _START_EVENTS[key] = None
57
+ while len(_START_EVENTS) > _START_EVENT_LIMIT:
58
+ _START_EVENTS.popitem(last=False)
59
+ return True
60
+
61
+
62
+ def _valid_timezone(value):
63
+ """Return a trimmed IANA timezone name, or ``None`` for invalid input."""
64
+ name = str(value or "").strip()
65
+ if not name:
66
+ return None
67
+ try:
68
+ tz(name)
69
+ except UnknownTimeZoneError:
70
+ return None
71
+ return name
72
+
73
+
74
+ def _cbstuffs_menu(key):
75
+ return cb("assistant", "callbacks", "menu", key)
76
+
77
+
78
+ def _html_body(body):
79
+ markup = coerce_to_rich_markup(str(body), parse_mode="mdv3")
80
+ return markup.text if markup else html.escape(str(body))
81
+
82
+
83
+ def _rich_menu(head, body, *, media=None):
84
+ return body_page(head, _html_body(body), media=media)
85
+
86
+
87
+ def _settings_configured(key):
88
+ if key == "apiset":
89
+ return any(
90
+ udB.get_key(k) for k in ("RMBG_API", "DEEP_AI", "OCR_API", "SERPAPI")
91
+ )
92
+ if key == "chatbot":
93
+ return bool(udB.get_key("PMBOT"))
94
+ if key == "alive_customisation":
95
+ return bool(udB.get_key("ALIVE_TEXT") or udB.get_key("ALIVE_PIC"))
96
+ if key == "pm_settings":
97
+ return bool(udB.get_key("PMSETTING"))
98
+ if key == "othervars":
99
+ return any(
100
+ udB.get_key(k)
101
+ for k in (
102
+ "TAG_LOG",
103
+ "SUDO",
104
+ "EMOJI_IN_HELP",
105
+ "DUAL_HNDLR",
106
+ "ADDONS",
107
+ "INLINE_PIC",
108
+ "PLUGIN_CHANNEL",
109
+ "SUDO_HNDLR",
110
+ )
111
+ )
112
+ if key == "vc_menu":
113
+ return bool(udB.get_key("VC_SESSION"))
114
+ return False
115
+
116
+
117
+ def _settings_sections():
118
+ return (
119
+ ("API Keys", "Configure image, AI, OCR, and search service credentials."),
120
+ ("Chat Bot", "Toggle the bot and edit its welcome, info, media, and subscription settings."),
121
+ ("Alive", "Customize the assistant's alive message and media."),
122
+ ("PM Permit", "Control the private-message guard and its options."),
123
+ ("Features", "Configure logging, sudo, handlers, plugins, and helper options."),
124
+ ("VC Song Bot", "Set the voice-chat bot session."),
125
+ )
126
+
127
+
128
+ def _settings_page():
129
+ return rich_page(
130
+ "Assistant Settings",
131
+ _settings_sections(),
132
+ description="Choose a section below. Credentials and session values stay hidden.",
133
+ columns=("Section", "What it does"),
134
+ total=6,
135
+ )
136
+
137
+
138
+ def _owner_home_page(name):
139
+ actions = (
140
+ ("Language", "Choose the assistant's display language."),
141
+ ("Settings", "Configure assistant features and services."),
142
+ ("Stats", "View the number of registered assistant users."),
143
+ ("Broadcast", "Send a message to registered assistant users."),
144
+ ("Timezone", "Set the timezone used by the assistant."),
145
+ )
146
+ return rich_page(
147
+ f"Welcome, {name}",
148
+ actions,
149
+ description=_plain_text(get_string("ast_3").format(name)),
150
+ columns=("Action", "What it does"),
151
+ total=len(actions),
152
+ )
153
+
154
+
155
+ def _plain_text(value):
156
+ """Remove simple Markdown markers before inserting a plain table cell."""
157
+ text = str(value)
158
+ for marker in ("**", "__", "~~", "`", "*"):
159
+ text = text.replace(marker, "")
160
+ return text
161
+
162
+
163
+ def _start_media_reference():
164
+ """Resolve the saved Telegram file ID to an already-uploaded RichFile source."""
165
+ file_id = udB.get_key("STARTMEDIA")
166
+ if not file_id:
167
+ return None
168
+ try:
169
+ media = resolve_bot_file_id(file_id)
170
+ except (TypeError, ValueError):
171
+ return None
172
+ if isinstance(media, tl_types.Photo):
173
+ return ("photo", media, None)
174
+ if isinstance(media, tl_types.Document):
175
+ return ("document", media, None)
176
+ return None
177
+
178
+
179
+ def _default_owner_info():
180
+ return f"""
181
  **Owner** - {OWNER_NAME}
182
+ **OwnerID** - {OWNER_ID}
183
 
184
  **Message Forwards** - {udB.get_key("PMBOT")}
185
 
 
187
  """
188
 
189
 
190
+ def _owner_info_state():
191
+ """Return (text, custom, visible), reading the setting at use time."""
192
+ value = udB.get_key("BOT_INFO_START")
193
+ if value is None:
194
+ return _default_owner_info(), False, True
195
+ if value is False or (isinstance(value, str) and value.strip().lower() == "false"):
196
+ return "", True, False
197
+ text = str(value)
198
+ return text, True, bool(text.strip())
 
 
 
 
 
 
199
 
200
+
201
+ class _SafeFormat(dict):
202
+ def __missing__(self, key):
203
+ return "{" + str(key) + "}"
204
+
205
+
206
+ def _safe_format(text, **values):
207
+ try:
208
+ return str(text).format_map(_SafeFormat(values))
209
+ except (TypeError, ValueError):
210
+ return str(text)
211
+
212
+
213
+ # Keep historical module-level names, while callbacks read the current setting.
214
+ Owner_info_msg, custom_info, _owner_info_visible = _owner_info_state()
215
+
216
+
217
+ def _settings_keyboard():
218
+ return ikm(
219
+ [
220
+ [
221
+ (
222
+ "API Keys",
223
+ _cbstuffs_menu("apiset"),
224
+ "success" if _settings_configured("apiset") else None,
225
+ ),
226
+ (
227
+ "Chat Bot",
228
+ _cbstuffs_menu("chatbot"),
229
+ "success" if _settings_configured("chatbot") else None,
230
+ ),
231
+ ],
232
+ [
233
+ (
234
+ "Alive",
235
+ _cbstuffs_menu("alive_customisation"),
236
+ (
237
+ "success"
238
+ if _settings_configured("alive_customisation")
239
+ else None
240
+ ),
241
+ ),
242
+ (
243
+ "PM Permit",
244
+ _cbstuffs_menu("pm_settings"),
245
+ "success" if _settings_configured("pm_settings") else None,
246
+ ),
247
+ ],
248
+ [
249
+ (
250
+ "Features",
251
+ _cbstuffs_menu("othervars"),
252
+ "success" if _settings_configured("othervars") else None,
253
+ ),
254
+ (
255
+ "VC Song Bot",
256
+ _cbstuffs_menu("vc_menu"),
257
+ "success" if _settings_configured("vc_menu") else None,
258
+ ),
259
+ ],
260
+ [("Back", MAIN_MENU, "primary")],
261
+ ],
262
+ icon=False,
263
+ )
264
+
265
+
266
+ _start = ikm(
267
  [
268
+ [
269
+ ("Language", cb("assistant", "lang", "menu"), "primary"),
270
+ ("Settings", SETTER, "primary"),
271
+ ],
272
+ [
273
+ ("Stats", "states", "primary"),
274
+ ("Broadcast", "bcast", "primary"),
275
+ ],
276
+ [("Timezone", "tz", "primary")],
277
  ],
278
+ icon=False,
279
+ )
280
+
281
+
282
+ async def _set_bot_profile():
283
+ if not asst:
284
+ return
285
+ description, _custom, visible = _owner_info_state()
286
+ if not visible:
287
+ description = ""
288
+ description = description or (
289
+ "Manage your Ultroid userbot from chat, or open the Mini App "
290
+ "settings dashboard below."
291
+ )
292
+ stripped = description.strip()
293
+ about = stripped.splitlines()[0][:120] if stripped else "Ultroid Assistant"
294
+ try:
295
+ await asst(
296
+ functions.bots.SetBotInfoRequest(
297
+ lang_code="",
298
+ about=about,
299
+ description=description[:512],
300
+ )
301
+ )
302
+ LOGS.info("assistant.start: bot profile description updated.")
303
+ except Exception as exc:
304
+ LOGS.warning(
305
+ "assistant.start: SetBotInfoRequest failed (%s) -- skipping.",
306
+ exc.__class__.__name__,
307
+ )
308
+
309
+
310
+ async def _configure_miniapp():
311
+ if not asst:
312
+ return
313
+ try:
314
+ from pyUltroid.webserver.miniapp import (
315
+ MINIAPP_URL_KEY,
316
+ SUPERVISOR,
317
+ MiniAppApplication,
318
+ MiniAppStore,
319
+ )
320
+ except Exception:
321
+ LOGS.exception("assistant.start: failed to import the Mini App module.")
322
+ return
323
+
324
+ base_url = (udB.get_key(MINIAPP_URL_KEY) or "").strip()
325
+ if not base_url:
326
+ LOGS.info(
327
+ "assistant.start: %s not set -- Mini App settings dashboard disabled.",
328
+ MINIAPP_URL_KEY,
329
+ )
330
+ return
331
+
332
+ store = MiniAppStore(udB)
333
+ try:
334
+ token = store.ensure_token()
335
+ except Exception:
336
+ LOGS.exception("assistant.start: failed to prepare the Mini App token.")
337
+ return
338
+
339
+ host = os.environ.get("MINIAPP_BIND", "0.0.0.0")
340
+ try:
341
+ port = int(os.environ.get("MINIAPP_PORT", "7861"))
342
+ except ValueError:
343
+ port = 7861
344
+
345
+ try:
346
+ miniapp = MiniAppApplication(token=token, udb=store.db).build()
347
+ server = SUPERVISOR.ensure(miniapp, host=host, port=port)
348
+ except Exception:
349
+ LOGS.exception("assistant.start: failed to start the Mini App server.")
350
+ return
351
+ if server is None:
352
+ LOGS.warning(
353
+ "assistant.start: Mini App port %s:%s unavailable -- dashboard may "
354
+ "already be running elsewhere.",
355
+ host,
356
+ port,
357
+ )
358
+ else:
359
+ LOGS.info(
360
+ "assistant.start: Mini App settings dashboard listening on %s:%s.",
361
+ host,
362
+ port,
363
+ )
364
+
365
+ settings_url = f"{base_url.rstrip('/')}/settings?token={token}"
366
+
367
+ try:
368
+ owner_entity = await asst.get_input_entity(OWNER_ID)
369
+ except Exception as exc:
370
+ LOGS.warning(
371
+ "assistant.start: could not resolve the owner's InputUser (%s) -- "
372
+ "skipping the Mini App menu button. The owner likely needs to "
373
+ "message this assistant bot at least once so it can resolve "
374
+ "the entity.",
375
+ exc.__class__.__name__,
376
+ )
377
+ return
378
+
379
+ try:
380
+ await asst(
381
+ functions.bots.SetBotMenuButtonRequest(
382
+ user_id=owner_entity,
383
+ button=tl_types.BotMenuButton(text="Settings", url=settings_url),
384
+ )
385
+ )
386
+ LOGS.info("assistant.start: Mini App menu button configured for the owner.")
387
+ except Exception as exc:
388
+ LOGS.warning(
389
+ "assistant.start: SetBotMenuButtonRequest failed (%s) -- skipping.",
390
+ exc.__class__.__name__,
391
+ )
392
+
393
+
394
+ async def _configure_assistant_startup():
395
+ try:
396
+ await _set_bot_profile()
397
+ except Exception:
398
+ LOGS.exception("assistant.start: bot profile setup crashed.")
399
+ try:
400
+ await _configure_miniapp()
401
+ except Exception:
402
+ LOGS.exception("assistant.start: Mini App setup crashed.")
403
+
404
+
405
+ if asst:
406
+ try:
407
+ asst.loop.create_task(_configure_assistant_startup())
408
+ except Exception:
409
+ LOGS.exception(
410
+ "assistant.start: could not schedule startup configuration task."
411
+ )
412
 
413
 
414
  @callback("ownerinfo")
415
  async def own(event):
416
+ info_text, is_custom, visible = _owner_info_state()
417
+ if not visible:
418
+ return await event.answer("The bot info message has been disabled.", alert=True)
419
+ msg = _safe_format(
420
+ info_text,
421
+ mention=fns.inline_mention(event.sender),
422
+ me=fns.inline_mention(ultroid_bot.me),
423
  )
424
+ if is_custom:
425
+ msg += "\n\nPowered by [@TeamUltroid](https://t.me/TeamUltroid)"
426
+ await edit_callback_page(
427
+ event,
428
+ _rich_menu("Owner Information", msg),
429
+ buttons=ikm([("Close", "closeit", None)], icon=False),
430
  )
431
 
432
 
 
440
 
441
  @asst_cmd(pattern="start( (.*)|$)", forwards=False, func=lambda x: not x.is_group)
442
  async def ultroid(event):
443
+ if not _claim_start_event(event):
444
+ return
445
  args = event.pattern_match.group(1).strip()
446
  keym = KeyManager("BOT_USERS", cast=list)
447
  if not keym.contains(event.sender_id) and event.sender_id not in owner_and_sudos():
448
  keym.add(event.sender_id)
449
  kak_uiw = udB.get_key("OFF_START_LOG")
450
+ if kak_uiw != True: # noqa: E712 - preserve legacy bool-like config semantics
451
+ msg = f"{fns.inline_mention(event.sender)} [{event.sender_id}] started your [Assistant bot](@{asst.me.username})."
452
+ btn_list = [("Info", "info_stub", "primary")]
453
  if event.sender.username:
454
+ btn_list.append(("User", "url", f"tg://user?id={event.sender_id}"))
455
+ log_channel = udB.get_key("LOG_CHANNEL")
456
+ if log_channel:
457
+ try:
458
+ await event.client.send_message(
459
+ log_channel, msg, buttons=ikm([btn_list], icon=False)
460
+ )
461
+ except Exception as exc:
462
+ LOGS.warning(
463
+ "assistant.start: visitor log could not be sent (%s).",
464
+ exc.__class__.__name__,
465
  )
 
 
 
 
466
  if event.sender_id not in SUDO_M.fullsudos:
467
  ok = ""
468
+ me = fns.inline_mention(ultroid_bot.me)
469
+ mention = fns.inline_mention(event.sender)
470
+ _info, _custom, show_info = _owner_info_state()
471
+ info_button = (
472
+ ikm([("Info", "ownerinfo", "primary")], icon=False) if show_info else None
473
+ )
474
  if args and args != "set":
475
+ stored = await fns.get_stored_file(event, args)
476
+ if stored is not None:
477
+ return stored
478
  if not udB.get_key("STARTMSG"):
479
  if udB.get_key("PMBOT"):
480
  ok = "You can contact my master using this bot!!\n\nSend your Message, I will Deliver it To Master."
481
+ content = _rich_menu(
482
+ "Ultroid Assistant",
483
  f"Hey there {mention}, this is Ultroid Assistant of {me}!\n\n{ok}",
484
+ media=_start_media_reference(),
485
+ )
486
+ await send_rich(
487
+ event.client,
488
+ event.chat_id,
489
+ content,
490
+ reply_to=event,
491
+ buttons=info_button,
492
+ link_preview=False,
493
  )
494
  else:
495
+ custom_msg = _safe_format(udB.get_key("STARTMSG"), me=me, mention=mention)
496
+ content = _rich_menu(
497
+ "Ultroid Assistant", custom_msg, media=_start_media_reference()
498
+ )
499
+ await send_rich(
500
+ event.client,
501
+ event.chat_id,
502
+ content,
503
+ reply_to=event,
504
+ buttons=info_button,
505
+ link_preview=False,
506
  )
507
  else:
508
  name = get_display_name(event.sender)
509
  if args == "set":
510
+ await send_rich(
511
+ event.client,
512
+ event.chat_id,
513
+ _settings_page(),
514
+ reply_to=event,
515
+ buttons=_settings_keyboard(),
516
+ link_preview=False,
517
  )
518
  elif args:
519
+ stored = await fns.get_stored_file(event, args)
520
+ if stored is not None:
521
+ return stored
522
+ # Unrecognized start payloads (including the public ``start``
523
+ # help deep link) should land on the normal owner welcome menu.
524
+ await send_rich(
525
+ event.client,
526
+ event.chat_id,
527
+ _owner_home_page(name),
528
+ reply_to=event,
529
+ buttons=_start,
530
+ link_preview=False,
531
+ )
532
  else:
533
+ await send_rich(
534
+ event.client,
535
+ event.chat_id,
536
+ _owner_home_page(name),
537
+ reply_to=event,
538
  buttons=_start,
539
+ link_preview=False,
540
  )
541
 
542
 
543
+ @callback("info_stub", owner=True)
544
  async def ekekdhdb(e):
545
  text = f"When New Visitor will visit your Assistant Bot. You will get this log message!\n\nTo Disable : {HNDLR}setdb OFF_START_LOG True"
546
  await e.answer(text, alert=True)
547
 
548
 
549
+ @callback(
550
+ cb_exact_pattern("assistant", "start", "mainmenu"),
551
+ owner=True,
552
+ func=lambda x: not x.is_group,
553
+ )
554
+ async def ultroid_menu(event):
555
+ await edit_callback_page(
556
+ event,
557
+ _owner_home_page(OWNER_NAME),
558
  buttons=_start,
559
  )
560
 
561
 
562
+ @callback("states", owner=True)
563
  async def botstat(event):
564
  ok = len(udB.get_key("BOT_USERS") or [])
565
+ await edit_callback_page(
566
+ event,
567
+ rich_page(
568
+ "Assistant Stats",
569
+ [("Registered users", str(ok))],
570
+ columns=("Metric", "Total"),
571
+ total=1,
572
+ ),
573
+ buttons=ikm([("Back", MAIN_MENU, None)], icon=False),
574
  )
 
575
 
576
 
577
  @callback("bcast", owner=True)
578
  async def bdcast(event):
579
  keym = KeyManager("BOT_USERS", cast=list)
580
  total = keym.count()
581
+ await edit_callback_page(
582
+ event,
583
+ body_page("Broadcast", f"<p>Initiating broadcast to {total} users.</p>", total=1),
584
+ )
585
  async with event.client.conversation(OWNER_ID) as conv:
586
+ prompt = await send_rich(
587
+ event.client,
588
+ conv.chat_id,
589
+ body_page(
590
+ "Broadcast",
591
+ "<p>Enter your broadcast message.</p><p>Use /cancel to stop.</p>",
592
+ ),
593
+ link_preview=False,
594
  )
595
+ response = await conv.get_response(prompt)
596
+ cancel_command = str(response.message or "").strip().split(maxsplit=1)[0]
597
+ if cancel_command.split("@", 1)[0].casefold() == "/cancel":
598
+ return await send_rich(
599
+ event.client,
600
+ conv.chat_id,
601
+ body_page("Broadcast cancelled", "<p>Nothing was changed.</p>"),
602
+ buttons=ikm([("Back", MAIN_MENU, "primary")], icon=False),
603
+ link_preview=False,
604
+ )
605
  success = 0
606
  fail = 0
607
+ await send_rich(
608
+ event.client,
609
+ conv.chat_id,
610
+ body_page("Broadcast", f"<p>Starting a broadcast to {total} users.</p>"),
611
+ link_preview=False,
612
+ )
613
+ start = _dt.now()
614
  for i in keym.get():
615
  try:
616
  await asst.send_message(int(i), response)
617
  success += 1
618
  except BaseException:
619
  fail += 1
620
+ end = _dt.now()
621
  time_taken = (end - start).seconds
622
+ await send_rich(
623
+ event.client,
624
+ conv.chat_id,
625
+ rich_page(
626
+ "Broadcast Complete",
627
+ [
628
+ ("Time taken", f"{time_taken} seconds"),
629
+ ("Total users", str(total)),
630
+ ("Successful", f"{success} users"),
631
+ ("Failed", str(fail)),
632
+ ],
633
+ columns=("Result", "Count"),
634
+ total=4,
635
+ ),
636
+ link_preview=False,
637
  )
638
 
639
 
640
+ @callback(cb_exact_pattern("assistant", "start", "setter"), owner=True)
641
  async def setting(event):
642
+ await edit_callback_page(
643
+ event,
644
+ _settings_page(),
645
+ buttons=_settings_keyboard(),
646
  )
647
 
648
 
649
  @callback("tz", owner=True)
650
  async def timezone_(event):
651
  await event.delete()
 
 
 
 
 
652
  pru = event.sender_id
653
  var = "TIMEZONE"
654
  name = "Timezone"
655
  async with event.client.conversation(pru) as conv:
656
+ await send_rich(
657
+ event.client,
658
+ conv.chat_id,
659
+ body_page(
660
+ name,
661
+ '<p>Send an IANA timezone name. Examples: <code>Asia/Kolkata</code>, '
662
+ '<code>Europe/London</code>, <code>America/New_York</code>, or '
663
+ '<code>UTC</code>.</p><p><a href="https://www.timezoneconverter.com/cgi-bin/findzone.tzc">Browse timezone names</a>. Send <code>/cancel</code> to stop.</p>',
664
+ total=4,
665
+ ),
666
+ link_preview=False,
667
+ )
668
+ while True:
669
+ response = await conv.wait_event(events.NewMessage(chats=pru))
670
+ themssg = str(response.message.message or "").strip()
671
+ cancel_command = (
672
+ themssg.split(maxsplit=1)[0].split("@", 1)[0] if themssg else ""
673
  )
674
+ if cancel_command.casefold() == "/cancel":
675
+ return await send_rich(
676
+ event.client,
677
+ conv.chat_id,
678
+ body_page(
679
+ "Timezone update cancelled", "<p>Nothing was changed.</p>"
680
+ ),
681
+ buttons=ikm([("Back", MAIN_MENU, None)], icon=False),
682
+ link_preview=False,
683
+ )
684
+
685
+ timezone_name = _valid_timezone(themssg)
686
+ if timezone_name is None:
687
+ await send_rich(
688
+ event.client,
689
+ conv.chat_id,
690
+ body_page(
691
+ "Timezone not recognized",
692
+ "<p>Use an IANA name such as <code>Asia/Kolkata</code>, "
693
+ "<code>Europe/London</code>, <code>America/New_York</code>, "
694
+ "or <code>UTC</code>.</p><p>Try another value, or send "
695
+ "<code>/cancel</code> to stop.</p>",
696
+ total=4,
697
+ ),
698
+ link_preview=False,
699
+ )
700
+ continue
701
+
702
+ await setit(event, var, timezone_name)
703
+ return await send_rich(
704
+ event.client,
705
+ conv.chat_id,
706
+ body_page(
707
+ "Timezone updated",
708
+ f"<p>{html.escape(name)} changed to "
709
+ f"<code>{html.escape(timezone_name)}</code>.</p>",
710
+ total=1,
711
+ ),
712
+ buttons=ikm([("Back", MAIN_MENU, None)], icon=False),
713
+ link_preview=False,
714
  )
assistant/ytdl.py CHANGED
@@ -1,13 +1,16 @@
1
  # Ultroid - UserBot
2
- # Copyright (C) 2021-2026 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
 
7
 
8
 
 
9
  import os
10
  import re
 
11
 
12
  try:
13
  from PIL import Image
@@ -18,14 +21,11 @@ from telethon.errors.rpcerrorlist import FilePartLengthInvalidError, MediaEmptyE
18
  from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
19
  from telethon.tl.types import InputWebDocument as wb
20
 
21
- from pyUltroid.fns.helper import (
22
- bash,
23
- fast_download,
24
- humanbytes,
25
- numerize,
26
- time_formatter,
27
- )
28
- from pyUltroid.fns.ytdl import dler, get_buttons, get_formats
29
 
30
  from . import LOGS, asst, callback, in_pattern, udB
31
 
@@ -37,23 +37,64 @@ except ImportError:
37
 
38
 
39
  ytt = "https://graph.org/file/afd04510c13914a06dd03.jpg"
40
- _yt_base_url = "https://www.youtube.com/watch?v="
41
  BACK_BUTTON = {}
42
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  @in_pattern("yt", owner=True)
45
- async def _(event):
46
  try:
47
  string = event.text.split(" ", maxsplit=1)[1]
48
  except IndexError:
49
- fuk = event.builder.article(
50
  title="Search Something",
51
  thumb=wb(ytt, 0, "image/jpeg", []),
52
- text="**YᴏᴜTᴜʙᴇ Sᴇᴀʀᴄʜ**\n\nYou didn't search anything",
53
- buttons=Button.switch_inline(
54
- "Sᴇᴀʀᴄʜ Aɢᴀɪɴ",
55
- query="yt ",
56
- same_peer=True,
57
  ),
58
  )
59
  await event.answer([fuk])
@@ -64,7 +105,7 @@ async def _(event):
64
  nibba = nub["result"]
65
  for v in nibba:
66
  ids = v["id"]
67
- link = _yt_base_url + ids
68
  title = v["title"]
69
  duration = v["duration"]
70
  views = v["viewCount"]["short"]
@@ -77,36 +118,39 @@ async def _(event):
77
  else "None"
78
  )
79
  thumb = f"https://i.ytimg.com/vi/{ids}/hqdefault.jpg"
80
- text = f"**Title: [{title}]({link})**\n\n"
81
- text += f"`Description: {description}\n\n"
82
- text += f"「 Duration: {duration} 」\n"
83
- text += f"「 Views: {views} 」\n"
84
- text += f"「 Publisher: {publisher} 」\n"
85
- text += f"「 Published on: {published_on} 」`"
 
 
 
 
 
 
 
86
  desc = f"{title}\n{duration}"
87
  file = wb(thumb, 0, "image/jpeg", [])
88
- buttons = [
89
  [
90
- Button.inline("Audio", data=f"ytdl:audio:{ids}"),
91
- Button.inline("Video", data=f"ytdl:video:{ids}"),
 
 
 
 
 
 
 
 
92
  ],
93
- [
94
- Button.switch_inline(
95
- "Sᴇᴀʀᴄʜ Aɢᴀɪɴ",
96
- query="yt ",
97
- same_peer=True,
98
- ),
99
- Button.switch_inline(
100
- "Sʜᴀʀᴇ",
101
- query=f"yt {string}",
102
- same_peer=False,
103
- ),
104
- ],
105
- ]
106
  BACK_BUTTON.update({ids: {"text": text, "buttons": buttons}})
107
  results.append(
108
  await event.builder.article(
109
- type="photo",
110
  title=title,
111
  description=desc,
112
  thumb=file,
@@ -125,19 +169,22 @@ async def _(event):
125
  ),
126
  owner=True,
127
  )
128
- async def _(e):
129
  _e = e.pattern_match.group(1).strip().decode("UTF-8")
130
  _lets_split = _e.split(":")
131
- _ytdl_data = await dler(e, _yt_base_url + _lets_split[1])
132
  _data = get_formats(_lets_split[0], _lets_split[1], _ytdl_data)
133
- _buttons = get_buttons(_data)
134
- _text = (
135
- "`Select Your Format.`"
136
- if _buttons
137
- else "`Error downloading from YouTube.\nTry Restarting your bot.`"
138
- )
139
 
140
- await e.edit(_text, buttons=_buttons)
 
 
 
 
 
 
 
 
141
 
142
 
143
  @callback(
@@ -146,16 +193,17 @@ async def _(e):
146
  ),
147
  owner=True,
148
  )
149
- async def _(event):
150
  url = event.pattern_match.group(1).strip().decode("UTF-8")
151
  lets_split = url.split(":")
152
  vid_id = lets_split[2]
153
- link = _yt_base_url + vid_id
154
  format = lets_split[1]
155
  try:
156
  ext = lets_split[3]
157
  except IndexError:
158
  ext = "mp3"
 
159
  if lets_split[0] == "audio":
160
  opts = {
161
  "format": "bestaudio",
@@ -173,31 +221,42 @@ async def _(event):
173
  },
174
  {"key": "FFmpegMetadata"},
175
  ],
 
176
  }
177
 
178
  ytdl_data = await dler(event, link, opts, True)
179
  title = ytdl_data["title"]
180
- if ytdl_data.get("artist"):
181
- artist = ytdl_data["artist"]
182
- elif ytdl_data.get("creator"):
183
- artist = ytdl_data["creator"]
184
- elif ytdl_data.get("channel"):
185
- artist = ytdl_data["channel"]
186
- views = numerize(ytdl_data.get("view_count")) or 0
187
- thumb, _ = await fast_download(ytdl_data["thumbnail"], filename=f"{vid_id}.jpg")
188
-
189
- likes = numerize(ytdl_data.get("like_count")) or 0
 
190
  duration = ytdl_data.get("duration") or 0
191
  description = (
192
- ytdl_data["description"]
193
- if len(ytdl_data["description"]) < 100
194
- else ytdl_data["description"][:100]
195
  )
196
- description = description or "None"
197
  filepath = f"{vid_id}.{ext}"
198
  if not os.path.exists(filepath):
199
  filepath = f"{filepath}.{ext}"
200
- size = os.path.getsize(filepath)
 
 
 
 
 
 
 
 
 
201
  file, _ = await event.client.fast_uploader(
202
  filepath,
203
  filename=f"{title}.{ext}",
@@ -213,6 +272,7 @@ async def _(event):
213
  performer=artist,
214
  ),
215
  ]
 
216
  elif lets_split[0] == "video":
217
  opts = {
218
  "format": str(format),
@@ -223,36 +283,60 @@ async def _(event):
223
  "outtmpl": f"%(id)s.{ext}",
224
  "logtostderr": False,
225
  "postprocessors": [{"key": "FFmpegMetadata"}],
 
226
  }
227
 
228
  ytdl_data = await dler(event, link, opts, True)
229
  title = ytdl_data["title"]
230
- if ytdl_data.get("artist"):
231
- artist = ytdl_data["artist"]
232
- elif ytdl_data.get("creator"):
233
- artist = ytdl_data["creator"]
234
- elif ytdl_data.get("channel"):
235
- artist = ytdl_data["channel"]
236
- views = numerize(ytdl_data.get("view_count")) or 0
237
- thumb, _ = await fast_download(ytdl_data["thumbnail"], filename=f"{vid_id}.jpg")
 
 
 
 
 
 
 
 
 
 
238
 
239
  try:
240
  Image.open(thumb).save(thumb, "JPEG")
241
  except Exception as er:
242
  LOGS.exception(er)
243
  thumb = None
244
- description = (
245
- ytdl_data["description"]
246
- if len(ytdl_data["description"]) < 100
247
- else ytdl_data["description"][:100]
248
- )
249
- likes = numerize(ytdl_data.get("like_count")) or 0
250
  hi, wi = ytdl_data.get("height") or 720, ytdl_data.get("width") or 1280
251
  duration = ytdl_data.get("duration") or 0
252
  filepath = f"{vid_id}.mkv"
253
  if not os.path.exists(filepath):
254
  filepath = f"{filepath}.webm"
255
- size = os.path.getsize(filepath)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  file, _ = await event.client.fast_uploader(
257
  filepath,
258
  filename=f"{title}.mkv",
@@ -269,15 +353,27 @@ async def _(event):
269
  supports_streaming=True,
270
  ),
271
  ]
 
272
  description = description if description != "" else "None"
273
- text = f"**Title: [{title}]({_yt_base_url}{vid_id})**\n\n"
274
- text += f"`📝 Description: {description}\n\n"
275
- text += f"「 Duration: {time_formatter(int(duration)*1000)} 」\n"
276
- text += f"「 Artist: {artist} 」\n"
277
- text += f"「 Views: {views} 」\n"
278
- text += f"「 Likes: {likes} 」\n"
279
- text += f"「 Size: {humanbytes(size)} 」`"
280
- button = Button.switch_inline("Search More", query="yt ", same_peer=True)
 
 
 
 
 
 
 
 
 
 
 
281
  try:
282
  await event.edit(
283
  text,
@@ -285,6 +381,7 @@ async def _(event):
285
  buttons=button,
286
  attributes=attributes,
287
  thumb=thumb,
 
288
  )
289
  except (FilePartLengthInvalidError, MediaEmptyError):
290
  file = await asst.send_message(
@@ -294,14 +391,19 @@ async def _(event):
294
  buttons=button,
295
  attributes=attributes,
296
  thumb=thumb,
 
297
  )
298
- await event.edit(text, file=file.media, buttons=button)
299
- await bash(f"rm {vid_id}.jpg")
 
300
 
301
 
302
  @callback(re.compile("ytdl_back:(.*)"), owner=True)
303
- async def ytdl_back(event):
304
  id_ = event.data_match.group(1).decode("utf-8")
305
  if not BACK_BUTTON.get(id_):
306
- return await event.answer("Query Expired! Search again 🔍")
307
- await event.edit(**BACK_BUTTON[id_])
 
 
 
 
1
  # Ultroid - UserBot
2
+ # Copyright (C) 2021-2023 TeamUltroid
3
  #
4
  # This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5
  # PLease read the GNU Affero General Public License in
6
  # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7
+ # Modifed for cookies and fixed by @TrueSaiyan
8
 
9
 
10
+ import html
11
  import os
12
  import re
13
+ from typing import Any
14
 
15
  try:
16
  from PIL import Image
 
21
  from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
22
  from telethon.tl.types import InputWebDocument as wb
23
 
24
+ from custom.fmt import fmtmsg, rawhtml
25
+ from custom.tg import ikm
26
+ from pyUltroid._core.events import InlineResultBuilder
27
+ from pyUltroid.fns import fns
28
+ from pyUltroid.fns.ytdl import FormatInfo, dler, get_formats
 
 
 
29
 
30
  from . import LOGS, asst, callback, in_pattern, udB
31
 
 
37
 
38
 
39
  ytt = "https://graph.org/file/afd04510c13914a06dd03.jpg"
40
+ _yt_base_url = "https://www.youtube.com/watch?"
41
  BACK_BUTTON = {}
42
 
43
 
44
+ def _yt_format_buttons(listt: list[FormatInfo]) -> Any:
45
+ """Build the format-selection keyboard for a ytdl:(.*) result.
46
+
47
+ Local reimplementation of pyUltroid.fns.ytdl.get_buttons() (core,
48
+ out of scope for this rewrite) so the buttons go through :func:ikm
49
+ for consistent styling instead of core's raw, unstyled
50
+ Button.inline calls. Deliberately keeps the same literal
51
+ ytdownload:<type>:<id>:<ytid>[:<ext>] / ytdl_back:<id> token
52
+ format as core (not migrated to the assistant: colon model see
53
+ the ytdl: / ytdl_back: note in the module docstring above).
54
+ listt is the :class:pyUltroid.fns.ytdl.FormatInfo list returned by
55
+ :func:get_formats.
56
+ """
57
+ id_ = listt[0].ytid
58
+
59
+ unique_resolutions: dict[str, FormatInfo] = {}
60
+ for x in listt:
61
+ resolution = x.quality
62
+ size = x.size
63
+ if (
64
+ resolution not in unique_resolutions
65
+ or size > unique_resolutions[resolution].size
66
+ ):
67
+ unique_resolutions[resolution] = x
68
+
69
+ rows = []
70
+ row = []
71
+ for x in unique_resolutions.values():
72
+ text = f"[{x.quality}" + (f" {fns.humanbytes(x.size)}]" if x.size else "]")
73
+ data = f"ytdownload:{x.type}:{x.id}:{x.ytid}" + (f":{x.ext}" if x.ext else "")
74
+ row.append((text, data, "primary"))
75
+ if len(row) == 2:
76
+ rows.append(row)
77
+ row = []
78
+ if row:
79
+ rows.append(row)
80
+
81
+ rows.append([("Back", f"ytdl_back:{id_}", None)])
82
+
83
+ return ikm(rows, icon=False)
84
+
85
+
86
  @in_pattern("yt", owner=True)
87
+ async def _(event: Any) -> None:
88
  try:
89
  string = event.text.split(" ", maxsplit=1)[1]
90
  except IndexError:
91
+ fuk = await InlineResultBuilder(event).article(
92
  title="Search Something",
93
  thumb=wb(ytt, 0, "image/jpeg", []),
94
+ text=fmtmsg("YouTube Search ", msgs="You didn't search anything."),
95
+ buttons=ikm(
96
+ [[Button.switch_inline("Search Again ", query="yt ", same_peer=True)]],
97
+ icon=False,
 
98
  ),
99
  )
100
  await event.answer([fuk])
 
105
  nibba = nub["result"]
106
  for v in nibba:
107
  ids = v["id"]
108
+ link = f"https://www.youtube.com/watch?v={ids}"
109
  title = v["title"]
110
  duration = v["duration"]
111
  views = v["viewCount"]["short"]
 
118
  else "None"
119
  )
120
  thumb = f"https://i.ytimg.com/vi/{ids}/hqdefault.jpg"
121
+
122
+ text = fmtmsg(
123
+ "YouTube Downloader ",
124
+ {
125
+ "Title": rawhtml(f"<a href='{link}'>{html.escape(str(title))}</a>"),
126
+ "Duration": duration,
127
+ "Views": views,
128
+ "Publisher": publisher,
129
+ "Published": published_on,
130
+ },
131
+ msgs=description,
132
+ )
133
+
134
  desc = f"{title}\n{duration}"
135
  file = wb(thumb, 0, "image/jpeg", [])
136
+ buttons = ikm(
137
  [
138
+ [
139
+ ("Audio ", f"ytdl:audio:{ids}", "primary"),
140
+ ("Video ", f"ytdl:video:{ids}", "primary"),
141
+ ],
142
+ [
143
+ Button.switch_inline("Search Again ", query="yt ", same_peer=True),
144
+ Button.switch_inline(
145
+ "Share ", query=f"yt {string}", same_peer=False
146
+ ),
147
+ ],
148
  ],
149
+ icon=False,
150
+ )
 
 
 
 
 
 
 
 
 
 
 
151
  BACK_BUTTON.update({ids: {"text": text, "buttons": buttons}})
152
  results.append(
153
  await event.builder.article(
 
154
  title=title,
155
  description=desc,
156
  thumb=file,
 
169
  ),
170
  owner=True,
171
  )
172
+ async def _(e: Any) -> None:
173
  _e = e.pattern_match.group(1).strip().decode("UTF-8")
174
  _lets_split = _e.split(":")
175
+ _ytdl_data = await dler(e, f"https://www.youtube.com/watch?v={_lets_split[1]}")
176
  _data = get_formats(_lets_split[0], _lets_split[1], _ytdl_data)
177
+ _buttons = _yt_format_buttons(_data) if _data else None
 
 
 
 
 
178
 
179
+ if _buttons:
180
+ _text = fmtmsg("YouTube Downloader ", msgs="Select your preferred format:")
181
+ else:
182
+ _text = fmtmsg(
183
+ "Download Error ",
184
+ msgs="Error downloading from YouTube.\nTry restarting your bot.",
185
+ )
186
+
187
+ await e.edit(_text, buttons=_buttons, parse_mode="html")
188
 
189
 
190
  @callback(
 
193
  ),
194
  owner=True,
195
  )
196
+ async def _(event: Any) -> None:
197
  url = event.pattern_match.group(1).strip().decode("UTF-8")
198
  lets_split = url.split(":")
199
  vid_id = lets_split[2]
200
+ link = f"https://www.youtube.com/watch?v={vid_id}"
201
  format = lets_split[1]
202
  try:
203
  ext = lets_split[3]
204
  except IndexError:
205
  ext = "mp3"
206
+
207
  if lets_split[0] == "audio":
208
  opts = {
209
  "format": "bestaudio",
 
221
  },
222
  {"key": "FFmpegMetadata"},
223
  ],
224
+ "cookiefile": "cookies.txt",
225
  }
226
 
227
  ytdl_data = await dler(event, link, opts, True)
228
  title = ytdl_data["title"]
229
+ artist = (
230
+ ytdl_data.get("artist")
231
+ or ytdl_data.get("creator")
232
+ or ytdl_data.get("channel")
233
+ )
234
+ views = fns.numerize(ytdl_data.get("view_count")) or 0
235
+ thumb, _ = await fns.fast_download(
236
+ ytdl_data["thumbnail"], filename=f"{vid_id}.jpg"
237
+ )
238
+
239
+ likes = fns.numerize(ytdl_data.get("like_count")) or 0
240
  duration = ytdl_data.get("duration") or 0
241
  description = (
242
+ ytdl_data["description"][:100]
243
+ if ytdl_data["description"] and len(ytdl_data["description"]) >= 100
244
+ else ytdl_data.get("description", "None")
245
  )
246
+
247
  filepath = f"{vid_id}.{ext}"
248
  if not os.path.exists(filepath):
249
  filepath = f"{filepath}.{ext}"
250
+ if os.path.exists(filepath):
251
+ size = os.path.getsize(filepath)
252
+ else:
253
+ LOGS.error(f"File not found: {filepath}")
254
+ await event.edit(
255
+ fmtmsg("Download Error ", msgs="Error: File not found after download."),
256
+ parse_mode="html",
257
+ )
258
+ return
259
+
260
  file, _ = await event.client.fast_uploader(
261
  filepath,
262
  filename=f"{title}.{ext}",
 
272
  performer=artist,
273
  ),
274
  ]
275
+
276
  elif lets_split[0] == "video":
277
  opts = {
278
  "format": str(format),
 
283
  "outtmpl": f"%(id)s.{ext}",
284
  "logtostderr": False,
285
  "postprocessors": [{"key": "FFmpegMetadata"}],
286
+ "cookiefile": "cookies.txt",
287
  }
288
 
289
  ytdl_data = await dler(event, link, opts, True)
290
  title = ytdl_data["title"]
291
+ artist = (
292
+ ytdl_data.get("artist")
293
+ or ytdl_data.get("creator")
294
+ or ytdl_data.get("channel")
295
+ )
296
+ views = fns.numerize(ytdl_data.get("view_count")) or 0
297
+ thumb, _ = await fns.fast_download(
298
+ ytdl_data["thumbnail"], filename=f"{vid_id}.jpg"
299
+ )
300
+ description = (
301
+ ytdl_data.get("description", "None")
302
+ if ytdl_data.get("description") and len(ytdl_data["description"]) < 100
303
+ else (
304
+ ytdl_data["description"][:100]
305
+ if ytdl_data.get("description")
306
+ else "None"
307
+ )
308
+ )
309
 
310
  try:
311
  Image.open(thumb).save(thumb, "JPEG")
312
  except Exception as er:
313
  LOGS.exception(er)
314
  thumb = None
315
+
316
+ likes = fns.numerize(ytdl_data.get("like_count")) or 0
 
 
 
 
317
  hi, wi = ytdl_data.get("height") or 720, ytdl_data.get("width") or 1280
318
  duration = ytdl_data.get("duration") or 0
319
  filepath = f"{vid_id}.mkv"
320
  if not os.path.exists(filepath):
321
  filepath = f"{filepath}.webm"
322
+ if os.path.exists(filepath):
323
+ size = os.path.getsize(filepath)
324
+ if not os.path.exists(filepath):
325
+ filepath = f"{vid_id}.mp4.webm"
326
+ if os.path.exists(filepath):
327
+ size = os.path.getsize(filepath)
328
+ if not os.path.exists(filepath):
329
+ filepath = f"{vid_id}.mp4.mkv"
330
+ if os.path.exists(filepath):
331
+ size = os.path.getsize(filepath)
332
+ else:
333
+ LOGS.error(f"File not found: {filepath}")
334
+ await event.edit(
335
+ fmtmsg("Download Error ", msgs="Error: File not found after download."),
336
+ parse_mode="html",
337
+ )
338
+ return
339
+
340
  file, _ = await event.client.fast_uploader(
341
  filepath,
342
  filename=f"{title}.mkv",
 
353
  supports_streaming=True,
354
  ),
355
  ]
356
+
357
  description = description if description != "" else "None"
358
+ text = fmtmsg(
359
+ "YouTube Downloader ",
360
+ {
361
+ "Title": rawhtml(
362
+ f"<a href='https://www.youtube.com/watch?v={vid_id}'>{html.escape(str(title))}</a>"
363
+ ),
364
+ "Artist": artist,
365
+ "Duration": fns.time_formatter(int(duration) * 1000),
366
+ "Views": views,
367
+ "Likes": likes,
368
+ "Size": fns.humanbytes(size),
369
+ },
370
+ msgs=description,
371
+ )
372
+ button = ikm(
373
+ [[Button.switch_inline("Search More ", query="yt ", same_peer=True)]],
374
+ icon=False,
375
+ )
376
+
377
  try:
378
  await event.edit(
379
  text,
 
381
  buttons=button,
382
  attributes=attributes,
383
  thumb=thumb,
384
+ parse_mode="html",
385
  )
386
  except (FilePartLengthInvalidError, MediaEmptyError):
387
  file = await asst.send_message(
 
391
  buttons=button,
392
  attributes=attributes,
393
  thumb=thumb,
394
+ parse_mode="html",
395
  )
396
+ await event.edit(text, file=file.media, buttons=button, parse_mode="html")
397
+
398
+ await fns.bash(f"rm {vid_id}.jpg")
399
 
400
 
401
  @callback(re.compile("ytdl_back:(.*)"), owner=True)
402
+ async def ytdl_back(event: Any) -> None:
403
  id_ = event.data_match.group(1).decode("utf-8")
404
  if not BACK_BUTTON.get(id_):
405
+ return await event.answer("Query Expired! Search again ")
406
+
407
+ text_data = BACK_BUTTON[id_]["text"]
408
+ btns = BACK_BUTTON[id_]["buttons"]
409
+ await event.edit(text_data, buttons=btns, parse_mode="html")
custom/__init__.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .debug import DebugKit, aexec, debug_kit, shell
2
+ from .entities import (
3
+ RICH_MD,
4
+ bankcard,
5
+ blockquote,
6
+ combine,
7
+ custom_emoji,
8
+ emoji_entity,
9
+ expandable,
10
+ formatted_date,
11
+ mdv3_to_entities,
12
+ normalize_parsed,
13
+ parse_rich,
14
+ plain_text,
15
+ premium_emoji,
16
+ spoiler,
17
+ unparse_rich,
18
+ with_emojis,
19
+ )
20
+ from .fmt import FmtKit, fmt_kit, fmtbar, fmtbyte, fmtexc, fmtmsg, fmtsec, prog
21
+ from .rich import (
22
+ STYLE_PRESETS,
23
+ RichKit,
24
+ button,
25
+ resolve_style,
26
+ rich_ikm,
27
+ rich_kit,
28
+ )
29
+ from .tg import (
30
+ DEFAULT_ICON_UNICODE,
31
+ TG_ANDROID_ICON_DOCUMENT_IDS,
32
+ ButtonKit,
33
+ button_kit,
34
+ ids,
35
+ ikm,
36
+ register_button_type,
37
+ request_peer_button,
38
+ rkm,
39
+ )
40
+ from .util import UtilKit, patch, usecs, util_kit
41
+
42
+ try:
43
+ from .icons import IconKit, icon_kit
44
+ except ImportError:
45
+ IconKit = icon_kit = None
46
+
47
+ __all__ = [
48
+ "DEFAULT_ICON_UNICODE",
49
+ "RICH_MD",
50
+ "STYLE_PRESETS",
51
+ "TG_ANDROID_ICON_DOCUMENT_IDS",
52
+ "ButtonKit",
53
+ "DebugKit",
54
+ "FmtKit",
55
+ "IconKit",
56
+ "RichKit",
57
+ "UtilKit",
58
+ "aexec",
59
+ "bankcard",
60
+ "blockquote",
61
+ "button",
62
+ "button_kit",
63
+ "combine",
64
+ "custom_emoji",
65
+ "debug_kit",
66
+ "emoji_entity",
67
+ "expandable",
68
+ "fmt_kit",
69
+ "fmtbar",
70
+ "fmtbyte",
71
+ "fmtexc",
72
+ "fmtmsg",
73
+ "fmtsec",
74
+ "formatted_date",
75
+ "icon_kit",
76
+ "ids",
77
+ "ikm",
78
+ "mdv3_to_entities",
79
+ "normalize_parsed",
80
+ "parse_rich",
81
+ "patch",
82
+ "plain_text",
83
+ "premium_emoji",
84
+ "prog",
85
+ "register_button_type",
86
+ "request_peer_button",
87
+ "resolve_style",
88
+ "rich_ikm",
89
+ "rich_kit",
90
+ "rkm",
91
+ "shell",
92
+ "spoiler",
93
+ "unparse_rich",
94
+ "usecs",
95
+ "util_kit",
96
+ "with_emojis",
97
+ ]
custom/debug.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import asyncio
3
+ import inspect
4
+
5
+
6
+ class DebugKit:
7
+ """Async execution helpers for the eval/debug surfaces.
8
+
9
+ One instance (``debug_kit``); the module-level functions below are
10
+ backward-compatible aliases.
11
+ """
12
+
13
+ async def aexec(self, code: str, kwargs: dict = {}) -> object:
14
+ """Compile *code* as the body of an async function and run it.
15
+
16
+ ``kwargs`` become the function's arguments (by name), so ``code`` can
17
+ reference them directly. A trailing bare expression is returned; if
18
+ that expression itself evaluates to an unawaited coroutine, it is
19
+ awaited too before returning.
20
+ """
21
+ body = ast.parse(code, "exec").body
22
+ if body and isinstance(body[-1], ast.Expr):
23
+ body[-1] = ast.Return(value=body[-1].value)
24
+
25
+ name = "aexec"
26
+ node = ast.Module(
27
+ body=[
28
+ ast.AsyncFunctionDef(
29
+ name=name,
30
+ args=ast.arguments(
31
+ posonlyargs=[],
32
+ args=[ast.arg(arg=key) for key in kwargs],
33
+ vararg=None,
34
+ kwonlyargs=[],
35
+ kw_defaults=[],
36
+ kwarg=None,
37
+ defaults=[],
38
+ ),
39
+ body=body,
40
+ decorator_list=[],
41
+ returns=None,
42
+ type_params=[],
43
+ )
44
+ ],
45
+ type_ignores=[],
46
+ )
47
+ ast.fix_missing_locations(node)
48
+ temp = {}
49
+ exec(compile(node, "<string>", "exec"), temp)
50
+ func = await temp[name](*kwargs.values())
51
+ return await func if inspect.iscoroutine(func) else func
52
+
53
+ async def shell(self, cmd: str) -> str:
54
+ proc = await asyncio.create_subprocess_shell(
55
+ cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
56
+ )
57
+ try:
58
+ stdout, stderr = await proc.communicate()
59
+ return (stdout + stderr).decode()
60
+ finally:
61
+ try:
62
+ if not proc.returncode:
63
+ proc.terminate()
64
+ except ProcessLookupError:
65
+ pass
66
+ else:
67
+ await proc.wait()
68
+
69
+
70
+ debug_kit = DebugKit()
71
+
72
+
73
+ async def aexec(code: str, kwargs: dict = {}) -> object:
74
+ return await debug_kit.aexec(code, kwargs)
75
+
76
+
77
+ async def shell(cmd: str) -> str:
78
+ return await debug_kit.shell(cmd)
79
+
80
+
81
+ async def shell(cmd: str) -> str:
82
+ proc = await asyncio.create_subprocess_shell(
83
+ cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
84
+ )
85
+ try:
86
+ stdout, stderr = await proc.communicate()
87
+ return (stdout + stderr).decode()
88
+ finally:
89
+ try:
90
+ if not proc.returncode:
91
+ proc.terminate()
92
+ except ProcessLookupError:
93
+ pass
94
+ else:
95
+ await proc.wait()
custom/entities.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import datetime
4
+ from collections.abc import Sequence
5
+ from typing import Any
6
+
7
+ from telethon.extensions import html as _html
8
+ from telethon.extensions import markdown as _markdown
9
+ from telethon.extensions import markdownv2 as _markdownv2
10
+ from telethon.extensions.markdownv3 import MarkdownV3
11
+ from telethon.tl import types
12
+ from telethon.tl.custom.message import CustomMarkdown
13
+
14
+ __all__ = (
15
+ "RICH_MD",
16
+ "bankcard",
17
+ "blockquote",
18
+ "combine",
19
+ "custom_emoji",
20
+ "emoji_entity",
21
+ "expandable",
22
+ "formatted_date",
23
+ "mdv3_to_entities",
24
+ "normalize_parsed",
25
+ "parse_rich",
26
+ "plain_text",
27
+ "premium_emoji",
28
+ "spoiler",
29
+ "unparse_rich",
30
+ "with_emojis",
31
+ )
32
+
33
+ RICH_MD = MarkdownV3()
34
+
35
+
36
+ def _utf16_len(text: str) -> int:
37
+ return len(text.encode("utf-16-le", "surrogatepass")) // 2
38
+
39
+
40
+ def spoiler(text: str) -> tuple[str, list[Any]]:
41
+ return text, [types.MessageEntitySpoiler(0, _utf16_len(text))]
42
+
43
+
44
+ def blockquote(text: str, *, collapsed: bool = False) -> tuple[str, list[Any]]:
45
+ return text, [
46
+ types.MessageEntityBlockquote(0, _utf16_len(text), collapsed=bool(collapsed))
47
+ ]
48
+
49
+
50
+ def expandable(text: str) -> tuple[str, list[Any]]:
51
+ return blockquote(text, collapsed=True)
52
+
53
+
54
+ def emoji_entity(offset: int, length: int, document_id: int) -> Any:
55
+ offset, length, document_id = int(offset), int(length), int(document_id)
56
+ if offset < 0 or length <= 0 or document_id <= 0:
57
+ raise ValueError(
58
+ "emoji offset must be non-negative; length and document_id must be positive"
59
+ )
60
+ return types.MessageEntityCustomEmoji(
61
+ offset=offset, length=length, document_id=document_id
62
+ )
63
+
64
+
65
+ def custom_emoji(text: str, doc_id: int) -> tuple[str, list[Any]]:
66
+ return text, [emoji_entity(0, _utf16_len(text), doc_id)]
67
+
68
+
69
+ def premium_emoji(document_id: int, fallback: str = "⭐"):
70
+ return fallback, [emoji_entity(0, _utf16_len(fallback), document_id)]
71
+
72
+
73
+ def with_emojis(text: str, emojis: dict, *, default_fallback: str = "⭐"):
74
+ if not isinstance(text, str):
75
+ raise TypeError("text must be a string")
76
+ if not isinstance(default_fallback, str) or not default_fallback:
77
+ raise ValueError("default_fallback must be a non-empty string")
78
+ entities = []
79
+ for placeholder, spec in (emojis or {}).items():
80
+ if not isinstance(placeholder, str) or not placeholder:
81
+ raise ValueError("emoji placeholders must be non-empty strings")
82
+ if isinstance(spec, (tuple, list)):
83
+ if not spec:
84
+ raise ValueError(f"emoji spec for {placeholder!r} is empty")
85
+ document_id = spec[0]
86
+ fallback = spec[1] if len(spec) > 1 else default_fallback
87
+ else:
88
+ document_id, fallback = spec, default_fallback
89
+ if not isinstance(fallback, str) or not fallback:
90
+ raise ValueError(f"emoji fallback for {placeholder!r} must be non-empty")
91
+ index = text.find(placeholder)
92
+ if index < 0:
93
+ continue
94
+ offset = _utf16_len(text[:index])
95
+ text = text[:index] + fallback + text[index + len(placeholder) :]
96
+ entities.append(emoji_entity(offset, _utf16_len(fallback), document_id))
97
+ entities.sort(key=lambda entity: entity.offset)
98
+ return text, entities
99
+
100
+
101
+ def bankcard(text: str) -> tuple[str, list[Any]]:
102
+ return text, [types.MessageEntityBankCard(0, _utf16_len(text))]
103
+
104
+
105
+ def formatted_date(
106
+ text: str,
107
+ date: datetime.datetime | None,
108
+ *,
109
+ relative: bool | None = None,
110
+ short_time: bool | None = None,
111
+ long_time: bool | None = None,
112
+ short_date: bool | None = None,
113
+ long_date: bool | None = None,
114
+ day_of_week: bool | None = None,
115
+ ) -> tuple[str, list[Any]]:
116
+ return text, [
117
+ types.MessageEntityFormattedDate(
118
+ 0,
119
+ _utf16_len(text),
120
+ date=date,
121
+ relative=relative,
122
+ short_time=short_time,
123
+ long_time=long_time,
124
+ short_date=short_date,
125
+ long_date=long_date,
126
+ day_of_week=day_of_week,
127
+ )
128
+ ]
129
+
130
+
131
+ def combine(*segments: tuple[str, Sequence[Any]]) -> tuple[str, list[Any]]:
132
+ text_parts: list[str] = []
133
+ entities: list[Any] = []
134
+ offset = 0
135
+ for chunk_text, chunk_entities in segments:
136
+ chunk_text = chunk_text or ""
137
+ for entity in chunk_entities or ():
138
+ entity.offset += offset
139
+ entities.append(entity)
140
+ text_parts.append(chunk_text)
141
+ offset += _utf16_len(chunk_text)
142
+ return "".join(text_parts), entities
143
+
144
+
145
+ def normalize_parsed(value: Any, *, fallback: str = "") -> tuple[str, list[Any]]:
146
+ if value is None:
147
+ return fallback, []
148
+ if isinstance(value, str):
149
+ return value, []
150
+ if isinstance(value, (tuple, list)) and len(value) == 2:
151
+ text, entities = value
152
+ if isinstance(text, str) and (
153
+ entities is None or isinstance(entities, (list, tuple))
154
+ ):
155
+ return text, list(entities or ())
156
+ message = getattr(value, "message", None)
157
+ if isinstance(message, str):
158
+ return message, list(getattr(value, "entities", None) or ())
159
+ return str(value), []
160
+
161
+
162
+ def plain_text(value: Any, *, fallback: str = "") -> str:
163
+ return normalize_parsed(value, fallback=fallback)[0]
164
+
165
+
166
+ def mdv3_to_entities(text: str) -> tuple[str, list[Any]]:
167
+ return RICH_MD.parse(text)
168
+
169
+
170
+ def _parser(mode: Any):
171
+ if mode is None:
172
+ return None
173
+ if callable(getattr(mode, "parse", None)) and callable(
174
+ getattr(mode, "unparse", None)
175
+ ):
176
+ return mode
177
+ key = str(mode).strip().lower()
178
+ if key in {"mdv3", "v3", "rich", "markdownv3"}:
179
+ return RICH_MD
180
+ if key in {"custom", "custommarkdown", "custom_markdown"}:
181
+ return CustomMarkdown()
182
+ if key in {"html", "htm"}:
183
+ return _html
184
+ if key in {"md", "markdown"}:
185
+ return _markdown
186
+ if key in {"v2", "mdv2", "markdownv2"}:
187
+ return _markdownv2.Markdown()
188
+ raise ValueError(f"Unknown rich parse mode {mode!r}")
189
+
190
+
191
+ def parse_rich(text: str, mode: Any = "mdv3") -> tuple[str, list[Any]]:
192
+ if not isinstance(text, str):
193
+ raise TypeError("rich text must be a string")
194
+ parser = _parser(mode)
195
+ if parser is None:
196
+ return text, []
197
+ return normalize_parsed(parser.parse(text), fallback=text)
198
+
199
+
200
+ def unparse_rich(text: Any, entities: Sequence[Any] | None = None, mode: Any = "mdv3") -> str:
201
+ text, pair_entities = normalize_parsed(text)
202
+ parser = _parser(mode)
203
+ if parser is None:
204
+ return text
205
+ rendered = parser.unparse(text, list(entities if entities is not None else pair_entities))
206
+ return normalize_parsed(rendered, fallback=text)[0]
custom/fmt.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import html
3
+ import math
4
+ import sys
5
+ import time as _time
6
+ import traceback
7
+
8
+ from telethon.custom import Message
9
+ from telethon.extensions import html as _telethon_html
10
+
11
+ from custom.entities import normalize_parsed
12
+
13
+
14
+ class FmtMessage(str):
15
+ """String-compatible formatter result sent through Layer 230 as HTML."""
16
+
17
+ __slots__ = ()
18
+ __rich_format__ = "html"
19
+
20
+
21
+ class FmtKit:
22
+ """Formatted-message builders (bars, bytes, exception blocks).
23
+
24
+ One instance (``fmt_kit``); the module-level functions below are
25
+ backward-compatible aliases.
26
+ """
27
+
28
+ def fmtbar(
29
+ self,
30
+ current: int,
31
+ total: int,
32
+ bars: int = 10,
33
+ empty: str = "-",
34
+ fill: str = "#",
35
+ ) -> str:
36
+ bars = int(bars)
37
+ if bars < 1:
38
+ raise ValueError("bars must be at least 1")
39
+ current, total = float(current), float(total)
40
+ if not math.isfinite(current) or not math.isfinite(total) or total < 0:
41
+ raise ValueError("current and total must be finite; total cannot be negative")
42
+ ratio = min(1.0, max(0.0, current / total if total else 0.0))
43
+ filled = round(ratio * bars)
44
+ percent = f"{ratio * 100:.2f}".rstrip("0").rstrip(".")
45
+ return f"[ {fill * filled + empty * (bars - filled)} ] {percent}%"
46
+
47
+ def fmtbyte(self, byte: int | float, si: bool = False) -> str:
48
+ byte = float(byte)
49
+ if not math.isfinite(byte):
50
+ raise ValueError("byte count must be finite")
51
+ sign = "-" if byte < 0 else ""
52
+ byte = abs(byte)
53
+ if si:
54
+ units = (
55
+ ("TB", 1000**4),
56
+ ("GB", 1000**3),
57
+ ("MB", 1000**2),
58
+ ("KB", 1000),
59
+ ("B", 1),
60
+ )
61
+ else:
62
+ units = (
63
+ ("TiB", 1024**4),
64
+ ("GiB", 1024**3),
65
+ ("MiB", 1024**2),
66
+ ("KiB", 1024),
67
+ ("B", 1),
68
+ )
69
+
70
+ for unit, factor in units:
71
+ if byte >= factor or factor == 1:
72
+ value = f"{(byte / factor):.2f}".rstrip("0").rstrip(".")
73
+ return f"{sign}{value} {unit}"
74
+
75
+ def fmtexc(self) -> str:
76
+ exc = traceback.TracebackException(*sys.exc_info())
77
+ fmt = exc.exc_type.__name__
78
+ if exc._str:
79
+ fmt += f":\n {exc._str}"
80
+
81
+ ftb = traceback.format_list(
82
+ f for f in exc.stack if "/site-packages/" in f.filename
83
+ )
84
+ if ftb:
85
+ fmt += f"\n\nTraceback:\n{''.join(ftb)}"
86
+
87
+ return fmt
88
+
89
+ def _fmt_value(self, v) -> str:
90
+ if isinstance(v, rawhtml):
91
+ return str(v)
92
+ if isinstance(v, (tuple, list)) and len(v) == 2:
93
+ text, entities = normalize_parsed(v)
94
+ return _telethon_html.unparse(text, entities)
95
+ return f"<code>{html.escape(str(v))}</code>"
96
+
97
+ def _escape_or_raw(self, value) -> str:
98
+ if isinstance(value, rawhtml):
99
+ return str(value)
100
+ if isinstance(value, (tuple, list)) and len(value) == 2:
101
+ text, entities = normalize_parsed(value)
102
+ return _telethon_html.unparse(text, entities)
103
+ return html.escape(str(value))
104
+
105
+ def fmtmsg(
106
+ self, head: str, data: object = None, foot: str = "", msgs: str = ""
107
+ ) -> str:
108
+ body = ""
109
+ if isinstance(data, dict):
110
+ padd = max((len(str(k)) for k in data.keys()), default=0)
111
+ body = "\n".join(
112
+ f" <code>{html.escape(str(k)).ljust(padd)}</code> : {self._fmt_value(v)}"
113
+ for k, v in data.items()
114
+ )
115
+ elif isinstance(data, (list, set, tuple)):
116
+ body = "\n".join(
117
+ f" <code>{n}</code>. {self._fmt_value(item)}"
118
+ for n, item in enumerate(data, start=1)
119
+ )
120
+ elif data:
121
+ body = f" <code>{html.escape(str(data))}</code>"
122
+
123
+ text = [f"<b>{self._escape_or_raw(head)}</b>"]
124
+ if body:
125
+ text.append(body)
126
+
127
+ if msgs:
128
+ text.append(f"<blockquote expandable>{self._escape_or_raw(msgs)}</blockquote>")
129
+
130
+ if foot:
131
+ text.append(f"<b><blockquote>{self._escape_or_raw(foot)}</blockquote></b>")
132
+
133
+ return FmtMessage("\n\n".join(text))
134
+
135
+ def fmtsec(self, sec: object, part: int = 3, human: bool = False) -> str:
136
+ if isinstance(sec, datetime.timedelta):
137
+ total_seconds = sec.total_seconds()
138
+ elif isinstance(sec, datetime.datetime):
139
+ total_seconds = (
140
+ datetime.datetime.now(datetime.UTC) - sec.astimezone(datetime.UTC)
141
+ ).total_seconds()
142
+ elif isinstance(sec, (float, int)):
143
+ total_seconds = float(sec)
144
+ else:
145
+ raise TypeError("sec must be a timedelta, datetime, or number")
146
+
147
+ if not math.isfinite(total_seconds):
148
+ raise ValueError("duration must be finite")
149
+ part = int(part)
150
+ if part < 1:
151
+ raise ValueError("part must be at least 1")
152
+ negative = total_seconds < 0
153
+ total_microseconds = round(abs(total_seconds) * 1_000_000)
154
+ total, micro = divmod(total_microseconds, 1_000_000)
155
+ units = (
156
+ ("week", 60**2 * 24 * 7),
157
+ ("day", 60**2 * 24),
158
+ ("hour", 60**2),
159
+ ("minute", 60),
160
+ ("second", 1),
161
+ )
162
+ parts = []
163
+ for unit, second in units:
164
+ value, total = divmod(total, second)
165
+ if value:
166
+ parts.append(f"{value} {unit}{'' if value == 1 else 's'}")
167
+
168
+ if len(parts) >= part:
169
+ break
170
+
171
+ if len(parts) < part and not human:
172
+ ms, us = divmod(micro, 1000)
173
+ if ms:
174
+ parts.append(f"{ms} ms")
175
+
176
+ if us and len(parts) < part:
177
+ parts.append(f"{us} µs")
178
+
179
+ result = ", ".join(parts) if parts else "0 seconds"
180
+ return f"-{result}" if negative else result
181
+
182
+ async def prog(
183
+ self, current: int, total: int, event: Message, title: str = ""
184
+ ) -> None:
185
+ try:
186
+ now = event._client.loop.time()
187
+ except (AttributeError, Exception):
188
+ now = _time.time()
189
+
190
+ if not hasattr(event, "_start"):
191
+ event._start = now
192
+ event._last = now
193
+ return
194
+
195
+ if now - event._last >= 2.5:
196
+ delta = now - event._start
197
+ speed = current / delta if delta > 0 else 0
198
+ text_to_send = fmtmsg(
199
+ f"{title.title()} Progress".lstrip(),
200
+ {
201
+ "Current": fmtbyte(current),
202
+ "Total": f"{fmtbyte(total)}\n",
203
+ "Speed": f"{fmtbyte(speed)}/s\n",
204
+ "Elapsed": fmtsec(delta, human=True),
205
+ "Estimated": fmtsec(
206
+ (total - current) / speed if speed > 0 else 0, human=True
207
+ ),
208
+ },
209
+ fmtbar(current, total),
210
+ )
211
+
212
+ try:
213
+ await event.edit(text_to_send, parse_mode="html")
214
+ except Exception:
215
+ pass
216
+
217
+ event._last = now
218
+
219
+
220
+ fmt_kit = FmtKit()
221
+
222
+
223
+ def fmtbar(*args, **kwargs):
224
+ return fmt_kit.fmtbar(*args, **kwargs)
225
+
226
+
227
+ def fmtbyte(*args, **kwargs):
228
+ return fmt_kit.fmtbyte(*args, **kwargs)
229
+
230
+
231
+ def fmtexc(*args, **kwargs):
232
+ return fmt_kit.fmtexc(*args, **kwargs)
233
+
234
+
235
+ def _fmt_value(*args, **kwargs):
236
+ return fmt_kit._fmt_value(*args, **kwargs)
237
+
238
+
239
+ def fmtmsg(*args, **kwargs):
240
+ return fmt_kit.fmtmsg(*args, **kwargs)
241
+
242
+
243
+ def fmtsec(*args, **kwargs):
244
+ return fmt_kit.fmtsec(*args, **kwargs)
245
+
246
+
247
+ def prog(*args, **kwargs):
248
+ return fmt_kit.prog(*args, **kwargs)
249
+
250
+
251
+ class rawhtml(str):
252
+ """Marks a string as pre-built, already-safe HTML.
253
+
254
+ ``fmtmsg`` renders ``rawhtml`` values verbatim (no escaping, no
255
+ ``<code>`` wrap), so callers can pass working ``<a href>`` links inside
256
+ ``data`` - plain values keep the escaped ``<code>`` treatment.
257
+ """
custom/icons.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = [
4
+ "ICONS",
5
+ "DEFAULT_ICON_UNICODE",
6
+ "ICON_DOCUMENT_IDS",
7
+ "ICON_CATEGORIES",
8
+ "document_id_for",
9
+ ]
10
+
11
+
12
+ _VS16 = "\ufe0f"
13
+ _ICON_ROWS = [
14
+ # ── navigation
15
+ ("back", "navigation", 0x25C0, True),
16
+ ("next", "navigation", 0x27A1, True),
17
+ ("prev", "navigation", 0x2B05, True),
18
+ ("up", "navigation", 0x2B06, True),
19
+ ("down", "navigation", 0x2B07, True),
20
+ ("home", "navigation", 0x1F3E0, False),
21
+ ("top", "navigation", 0x1F51D, False),
22
+ ("reply", "navigation", 0x21A9, True),
23
+ ("forward", "navigation", 0x21AA, True),
24
+ ("refresh", "navigation", 0x1F504, False),
25
+ ("compass", "navigation", 0x1F9ED, False),
26
+ ("up_left", "navigation", 0x2196, True),
27
+ ("up_right", "navigation", 0x2197, True),
28
+ ("down_right", "navigation", 0x2198, True),
29
+ ("down_left", "navigation", 0x2199, True),
30
+ ("left_right", "navigation", 0x2194, True),
31
+ ("up_down", "navigation", 0x2195, True),
32
+ ("undo", "navigation", 0x21B6, True),
33
+ ("redo", "navigation", 0x21B7, True),
34
+ ("target", "navigation", 0x1F3AF, False),
35
+ ("anchor", "navigation", 0x2693, True),
36
+ ("map", "navigation", 0x1F5FA, True),
37
+ ("airplane", "navigation", 0x2708, True),
38
+ # ── media controls
39
+ ("play", "media", 0x25B6, True),
40
+ ("pause", "media", 0x23F8, True),
41
+ ("stop", "media", 0x23F9, True),
42
+ ("play_pause", "media", 0x23EF, True),
43
+ ("next_track", "media", 0x23ED, True),
44
+ ("prev_track", "media", 0x23EE, True),
45
+ ("fast_forward", "media", 0x23E9, True),
46
+ ("fast_rewind", "media", 0x23EA, True),
47
+ ("shuffle", "media", 0x1F500, False),
48
+ ("repeat", "media", 0x1F501, False),
49
+ ("volume_up", "media", 0x1F50A, False),
50
+ ("volume_down", "media", 0x1F509, False),
51
+ ("mute", "media", 0x1F507, False),
52
+ ("microphone", "media", 0x1F3A4, False),
53
+ ("headphones", "media", 0x1F3A7, False),
54
+ ("music", "media", 0x1F3B5, False),
55
+ ("camera", "media", 0x1F4F7, False),
56
+ ("video", "media", 0x1F3A5, False),
57
+ ("joystick", "media", 0x1F579, True),
58
+ ("record", "media", 0x23FA, True),
59
+ ("eject", "media", 0x23CF, True),
60
+ ("clapper", "media", 0x1F3AC, False),
61
+ ("guitar", "media", 0x1F3B8, False),
62
+ ("speaker", "media", 0x1F508, False),
63
+ ("disc", "media", 0x1F4BF, False),
64
+ # ── files & folders
65
+ ("folder", "files", 0x1F4C1, False),
66
+ ("file", "files", 0x1F4C4, False),
67
+ ("page", "files", 0x1F4C3, False),
68
+ ("archive", "files", 0x1F5C4, True),
69
+ ("trash", "files", 0x1F5D1, True),
70
+ ("paperclip", "files", 0x1F4CE, False),
71
+ ("bookmark", "files", 0x1F516, False),
72
+ ("books", "files", 0x1F4DA, False),
73
+ ("calendar", "files", 0x1F4C5, False),
74
+ ("clock", "files", 0x23F0, True),
75
+ ("hourglass", "files", 0x23F3, True),
76
+ ("save", "files", 0x1F4BE, False),
77
+ ("inbox", "files", 0x1F4E5, False),
78
+ ("outbox", "files", 0x1F4E4, False),
79
+ ("image", "files", 0x1F5BC, True),
80
+ ("printer", "files", 0x1F5A8, True),
81
+ ("notepad", "files", 0x1F5D2, True),
82
+ ("briefcase", "files", 0x1F4BC, False),
83
+ ("package", "files", 0x1F4E6, False),
84
+ ("newspaper", "files", 0x1F4F0, False),
85
+ ("scroll", "files", 0x1F4DC, False),
86
+ ("open_book", "files", 0x1F4D6, False),
87
+ ("closed_book", "files", 0x1F4D5, False),
88
+ ("notebook", "files", 0x1F4D3, False),
89
+ ("label", "files", 0x1F3F7, True),
90
+ ("receipt", "files", 0x1F9FE, False),
91
+ # ── tools & edit
92
+ ("settings", "tools", 0x2699, True),
93
+ ("wrench", "tools", 0x1F527, False),
94
+ ("hammer", "tools", 0x1F528, False),
95
+ ("pencil", "tools", 0x270F, True),
96
+ ("memo", "tools", 0x1F4DD, False),
97
+ ("scissors", "tools", 0x2702, True),
98
+ ("search", "tools", 0x1F50D, False),
99
+ ("redirect", "tools", 0x1F517, False),
100
+ ("key", "tools", 0x1F511, False),
101
+ ("lock", "tools", 0x1F512, False),
102
+ ("unlock", "tools", 0x1F513, False),
103
+ ("keylock", "tools", 0x1F510, False),
104
+ ("pin", "tools", 0x1F4CC, False),
105
+ ("copy", "tools", 0x1F4CB, False),
106
+ ("magnet", "tools", 0x1F9F2, False),
107
+ ("flashlight", "tools", 0x1F526, False),
108
+ ("battery", "tools", 0x1F50B, False),
109
+ ("plug", "tools", 0x1F50C, False),
110
+ ("nut", "tools", 0x1F529, False),
111
+ ("keyboard", "tools", 0x2328, True),
112
+ ("mouse", "tools", 0x1F5B1, True),
113
+ ("scales", "tools", 0x2696, True),
114
+ ("abacus", "tools", 0x1F9EE, False),
115
+ ("fire_extinguisher", "tools", 0x1F9EF, False),
116
+ # ── status & indicators
117
+ ("check", "status", 0x2705, False),
118
+ ("close", "status", 0x2716, True),
119
+ ("cross", "status", 0x274C, False),
120
+ ("cancel", "status", 0x1F6AB, False),
121
+ ("noop", "status", 0x25AB, True),
122
+ ("info", "status", 0x2139, True),
123
+ ("warning", "status", 0x26A0, True),
124
+ ("question", "status", 0x2753, False),
125
+ ("exclaim", "status", 0x2757, False),
126
+ ("no_entry", "status", 0x26D4, False),
127
+ ("new", "status", 0x1F195, False),
128
+ ("free", "status", 0x1F193, False),
129
+ ("ok", "status", 0x1F197, False),
130
+ ("up_button", "status", 0x1F53C, False),
131
+ ("down_button", "status", 0x1F53D, False),
132
+ ("radio", "status", 0x1F518, False),
133
+ ("circle", "status", 0x2B55, False),
134
+ ("green_circle", "status", 0x1F7E2, False),
135
+ ("red_circle", "status", 0x1F534, False),
136
+ ("ballot_check", "status", 0x2611, True),
137
+ ("ballot_x", "status", 0x2612, True),
138
+ ("diamond", "status", 0x1F537, False),
139
+ ("small_diamond", "status", 0x1F539, False),
140
+ ("white_circle", "status", 0x26AA, False),
141
+ ("black_circle", "status", 0x26AB, False),
142
+ ("yellow_circle", "status", 0x1F7E1, False),
143
+ ("blue_circle", "status", 0x1F535, False),
144
+ ("purple_circle", "status", 0x1F7E3, False),
145
+ ("orange_circle", "status", 0x1F7E0, False),
146
+ ("brown_circle", "status", 0x1F7E4, False),
147
+ ("red_square", "status", 0x1F7E5, False),
148
+ ("green_square", "status", 0x1F7E9, False),
149
+ ("blue_square", "status", 0x1F7E6, False),
150
+ ("yellow_square", "status", 0x1F7E8, False),
151
+ ("purple_square", "status", 0x1F7EA, False),
152
+ ("orange_square", "status", 0x1F7E7, False),
153
+ ("white_square", "status", 0x2B1C, False),
154
+ ("black_square", "status", 0x2B1B, False),
155
+ # ── communication & people
156
+ ("person", "communication", 0x1F464, False),
157
+ ("people", "communication", 0x1F465, False),
158
+ ("speech", "communication", 0x1F4AC, False),
159
+ ("phone", "communication", 0x1F4DE, False),
160
+ ("mail", "communication", 0x2709, True),
161
+ ("megaphone", "communication", 0x1F4E2, False),
162
+ ("mobile", "communication", 0x1F4F1, False),
163
+ ("thought", "communication", 0x1F4AD, False),
164
+ ("writing", "communication", 0x270D, True),
165
+ ("broken_heart", "communication", 0x1F494, False),
166
+ ("glasses", "communication", 0x1F453, False),
167
+ ("necktie", "communication", 0x1F454, False),
168
+ ("footprints", "communication", 0x1F463, False),
169
+ # ── misc / objects
170
+ ("star", "misc", 0x2B50, False),
171
+ ("heart", "misc", 0x2764, True),
172
+ ("thumbs_up", "misc", 0x1F44D, False),
173
+ ("thumbs_down", "misc", 0x1F44E, False),
174
+ ("fire", "misc", 0x1F525, False),
175
+ ("rocket", "misc", 0x1F680, False),
176
+ ("gift", "misc", 0x1F381, False),
177
+ ("trophy", "misc", 0x1F3C6, False),
178
+ ("eye", "misc", 0x1F441, True),
179
+ ("bulb", "misc", 0x1F4A1, False),
180
+ ("sparkles", "misc", 0x2728, False),
181
+ ("poll", "misc", 0x1F4CA, False),
182
+ ("chart_up", "misc", 0x1F4C8, False),
183
+ ("chart_down", "misc", 0x1F4C9, False),
184
+ ("money", "misc", 0x1F4B0, False),
185
+ ("buy", "misc", 0x1F4B3, False),
186
+ ("cart", "misc", 0x1F6D2, False),
187
+ ("lang", "misc", 0x1F310, False),
188
+ ("location", "misc", 0x1F4CD, False),
189
+ ("game", "misc", 0x1F3AE, False),
190
+ ("bell", "misc", 0x1F514, False),
191
+ ("flag", "misc", 0x1F6A9, False),
192
+ ("moon", "misc", 0x1F319, False),
193
+ ("sun", "misc", 0x2600, True),
194
+ ("cloud", "misc", 0x2601, True),
195
+ ("zap", "misc", 0x26A1, False),
196
+ ("snowflake", "misc", 0x2744, True),
197
+ ("droplet", "misc", 0x1F4A7, False),
198
+ ("crown", "misc", 0x1F451, False),
199
+ ("gem", "misc", 0x1F48E, False),
200
+ ("bell_muted", "misc", 0x1F515, False),
201
+ ("shield", "misc", 0x1F6E1, True),
202
+ ("ribbon", "misc", 0x1F380, False),
203
+ ("medal", "misc", 0x1F3C5, False),
204
+ ("ticket", "misc", 0x1F3AB, False),
205
+ ("dice", "misc", 0x1F3B2, False),
206
+ ("chess", "misc", 0x265F, True),
207
+ ("timer", "misc", 0x23F2, True),
208
+ ("watch", "misc", 0x231A, False),
209
+ ("robot", "misc", 0x1F916, False),
210
+ ("earth", "misc", 0x1F30D, False),
211
+ ("satellite", "misc", 0x1F6F0, True),
212
+ ("car", "misc", 0x1F697, False),
213
+ ("ship", "misc", 0x1F6A2, False),
214
+ ("bike", "misc", 0x1F6B2, False),
215
+ ("umbrella", "misc", 0x2614, False),
216
+ ("rainbow", "misc", 0x1F308, False),
217
+ ("bomb", "misc", 0x1F4A3, False),
218
+ ("syringe", "misc", 0x1F489, False),
219
+ ("pill", "misc", 0x1F48A, False),
220
+ ("lips", "misc", 0x1F444, False),
221
+ ]
222
+
223
+ ICONS: dict = {}
224
+ DEFAULT_ICON_UNICODE: dict = {}
225
+ ICON_CATEGORIES: dict = {}
226
+
227
+ for _name, _category, _cp, _variant in _ICON_ROWS:
228
+ _glyph = chr(_cp) + (_VS16 if _variant else "")
229
+ ICONS[_name] = {
230
+ "name": _name,
231
+ "category": _category,
232
+ "glyph": _glyph,
233
+ "codepoint": f"U+{_cp:04X}",
234
+ "vector": None,
235
+ "document_id": None,
236
+ }
237
+ DEFAULT_ICON_UNICODE[_name] = _glyph
238
+ ICON_CATEGORIES.setdefault(_category, []).append(_name)
239
+
240
+ del _name, _category, _cp, _variant, _glyph
241
+
242
+
243
+ def document_id_for(name: str):
244
+ real = ICON_DOCUMENT_IDS.get(name)
245
+ if real:
246
+ return real
247
+ entry = ICONS.get(name)
248
+ return entry["document_id"] if entry else None
249
+
250
+
251
+ class IconKit:
252
+ """The icon catalog lookup.
253
+
254
+ One instance (``icon_kit``); the module-level function below is a
255
+ backward-compatible alias.
256
+ """
257
+
258
+ document_id_for = staticmethod(document_id_for)
259
+
260
+
261
+ icon_kit = IconKit()
262
+
263
+
264
+ # .....
265
+ ICON_DOCUMENT_IDS: dict = {
266
+ "back": 5877629862306385808,
267
+ "bell": 5909201569898827582,
268
+ "bookmark": 5843862283964390528,
269
+ "buy": 5927169041595634481,
270
+ "calendar": 5967412305338568701,
271
+ "camera": 5846024087033353251,
272
+ "cancel": 5872829476143894491,
273
+ "chart_up": 5776219138917668486,
274
+ "check": 5776375003280838798,
275
+ "clock": 5985616167740379273,
276
+ "cross": 5778527486270770928,
277
+ "down": 5886451926995833684,
278
+ "down_button": 5875008416132370818,
279
+ "exclaim": 5879813604068298387,
280
+ "eye": 5960714428394507968,
281
+ "fast_forward": 6028482475385164542,
282
+ "file": 5877301185639091664,
283
+ "fire": 6008118472066732010,
284
+ "folder": 5875206779196935950,
285
+ "gift": 6032937473162614352,
286
+ "hammer": 5875450995332353523,
287
+ "headphones": 6007938409857815902,
288
+ "heart": 5899833370052923106,
289
+ "home": 5967822972931542886,
290
+ "image": 5888799736508454231,
291
+ "inbox": 5877307202888273539,
292
+ "info": 5879785854284599288,
293
+ "key": 6005570495603282482,
294
+ "lang": 5879585266426973039,
295
+ "location": 5944940516754853337,
296
+ "lock": 5879895758202735862,
297
+ "mail": 5951665980273858529,
298
+ "megaphone": 5771695636411847302,
299
+ "memo": 5886330010054168711,
300
+ "microphone": 5897554554894946515,
301
+ "mobile": 5985833664884250583,
302
+ "money": 5778318458802409852,
303
+ "music": 5891249688933305846,
304
+ "mute": 5890838600433536921,
305
+ "new": 5886306834410640699,
306
+ "next": 5877468380125990242,
307
+ "outbox": 5877540355187937244,
308
+ "paperclip": 5877495434124988415,
309
+ "pencil": 5879841310902324730,
310
+ "people": 5942877472163892475,
311
+ "person": 5771887475421090729,
312
+ "phone": 5897567714674741148,
313
+ "pin": 5908961403917570106,
314
+ "poll": 5877485980901971030,
315
+ "prev": 5875082500023258804,
316
+ "question": 5873121512445187130,
317
+ "red_circle": 5967333011652350314,
318
+ "redirect": 5877465816030515018,
319
+ "refresh": 5877410604225924969,
320
+ "repeat": 6005843436479975944,
321
+ "save": 5884448719889240368,
322
+ "scissors": 6007895992760799065,
323
+ "settings": 5877260593903177342,
324
+ "speech": 5886666250158870040,
325
+ "star": 5958376256788502078,
326
+ "thumbs_down": 5994368422031397063,
327
+ "thumbs_up": 5992199545151295755,
328
+ "trash": 5879896690210639947,
329
+ "unlock": 5886505193180239900,
330
+ "up": 6005807101056651268,
331
+ "up_button": 5875078273775439450,
332
+ "video": 5882002216323125435,
333
+ "volume_up": 5890997763331591703,
334
+ "warning": 5881702736843511327,
335
+ }
336
+ # <<< EMOJI_ICON_DOC_IDS <<<
custom/rich.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from telethon import Button
4
+
5
+ from .tg import (
6
+ _is_built_button,
7
+ _normalize_icon,
8
+ _normalize_style,
9
+ ikm,
10
+ request_peer_button,
11
+ )
12
+
13
+ __all__ = (
14
+ "STYLE_PRESETS",
15
+ "RichKit",
16
+ "button",
17
+ "request_peer_button",
18
+ "resolve_style",
19
+ "rich_ikm",
20
+ "rich_kit",
21
+ )
22
+
23
+ STYLE_PRESETS = {
24
+ "default": (None, None),
25
+ "neutral": (None, None),
26
+ "unstyled": (None, None),
27
+ "primary": ("primary", None),
28
+ "info": ("primary", None),
29
+ "blue": ("primary", None),
30
+ "success": ("success", None),
31
+ "ok": ("success", None),
32
+ "confirm": ("success", None),
33
+ "green": ("success", None),
34
+ "danger": ("danger", None),
35
+ "error": ("danger", None),
36
+ "warn": ("danger", None),
37
+ "red": ("danger", None),
38
+ "back": ("primary", None),
39
+ "cancel": ("danger", None),
40
+ }
41
+
42
+
43
+ class RichKit:
44
+ """Build Telethon buttons with semantic styles and icons."""
45
+
46
+ def resolve_style(self, style=None, icon=None, preset=None):
47
+ if preset is not None:
48
+ preset_style, preset_icon = STYLE_PRESETS.get(
49
+ str(preset).strip().lower(), (None, None)
50
+ )
51
+ if style is None:
52
+ style = preset_style
53
+ if icon is None:
54
+ icon = preset_icon
55
+ return _normalize_style(style), _normalize_icon(icon)
56
+
57
+ def button(
58
+ self,
59
+ text,
60
+ data=None,
61
+ *,
62
+ url=None,
63
+ style=None,
64
+ icon=None,
65
+ preset=None,
66
+ request=None,
67
+ button_id=1,
68
+ max_quantity=1,
69
+ **peer_kwargs,
70
+ ):
71
+ style, icon = self.resolve_style(style, icon, preset)
72
+ if url is not None:
73
+ return Button.url(text, url=url, style=style, icon=icon)
74
+ if request is not None:
75
+ return request_peer_button(
76
+ text,
77
+ request,
78
+ button_id=button_id,
79
+ max_quantity=max_quantity,
80
+ style=style,
81
+ icon=icon,
82
+ **peer_kwargs,
83
+ )
84
+ return Button.inline(text, data=data, style=style, icon=icon)
85
+
86
+ def rich_ikm(self, data):
87
+ if data is None:
88
+ return None
89
+ if isinstance(data, (tuple, dict)) or _is_built_button(data):
90
+ data = [data]
91
+ rows = []
92
+ for row in data:
93
+ if isinstance(row, (tuple, dict)) or _is_built_button(row):
94
+ row = [row]
95
+ rows.append(
96
+ [self.button(**item) if isinstance(item, dict) else item for item in row]
97
+ )
98
+ return ikm(rows)
99
+
100
+
101
+ rich_kit = RichKit()
102
+
103
+
104
+ def resolve_style(*args, **kwargs):
105
+ return rich_kit.resolve_style(*args, **kwargs)
106
+
107
+
108
+ def button(*args, **kwargs):
109
+ return rich_kit.button(*args, **kwargs)
110
+
111
+
112
+ def rich_ikm(*args, **kwargs):
113
+ return rich_kit.rich_ikm(*args, **kwargs)
custom/tg.py ADDED
@@ -0,0 +1,1089 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class ButtonKit:
2
+ """The Telegram button toolkit: inline builders, styles, and icons.
3
+
4
+ One instance (``button_kit``) owns the custom button-type registry;
5
+ the module-level functions below are backward-compatible aliases.
6
+ """
7
+
8
+ def __init__(self):
9
+ self._registry = {}
10
+
11
+ def _is_built_button(self, obj) -> bool:
12
+ return isinstance(obj, (Button, TLObject))
13
+
14
+ def _normalize_style(self, style):
15
+ """Normalise a button style to a value ``Button.inline`` accepts."""
16
+ if style is None:
17
+ return None
18
+ if isinstance(style, str):
19
+ return _STYLE_MAP.get(style.lower())
20
+ if isinstance(style, int) and not isinstance(style, bool):
21
+ return _STYLE_MAP.get(style)
22
+ return None
23
+
24
+ def _normalize_icon(self, icon):
25
+ """Normalise a button icon to a custom-emoji document id (``int``).
26
+
27
+ The fork's ``KeyboardButtonStyle.icon`` field is a ``long`` holding the
28
+ document id of the custom emoji shown inside the button. Anything that
29
+ is not an int (or a digit string) becomes ``None`` so a bad icon never
30
+ breaks TL serialisation at send time.
31
+ """
32
+ if icon is None or isinstance(icon, bool):
33
+ return None
34
+ if isinstance(icon, int):
35
+ return icon
36
+ if isinstance(icon, str) and icon.isdigit():
37
+ return int(icon)
38
+ if isinstance(icon, str):
39
+ _icon = document_id_for(icon)
40
+ return _icon if _icon else None
41
+ return None
42
+
43
+ def _fold_stylized(self, text: str) -> str:
44
+ """Fold "stylized" small-caps / phonetic-extension Unicode letters (the
45
+ section-header convention this codebase uses, e.g. ``"Aᴅᴅᴏɴs"``,
46
+ ``"« Bᴀᴄᴋ"``) down to plain ASCII, purely so the keyword matcher below
47
+ can still recognise them.
48
+
49
+ These glyphs have no case-folding or decomposition mapping in Unicode -
50
+ they're distinct IPA/phonetic-extension code points, not accented Latin
51
+ letters - so ``str.lower()``/``unicodedata.normalize`` leave them alone.
52
+ Their *character name* does encode the plain letter though
53
+ (``U+1D05 LATIN LETTER SMALL CAPITAL D``), so that's what this walks.
54
+ """
55
+ out = []
56
+ for ch in text:
57
+ if ch.isascii():
58
+ out.append(ch)
59
+ continue
60
+ try:
61
+ name = unicodedata.name(ch)
62
+ except ValueError:
63
+ out.append(ch)
64
+ continue
65
+ if name.startswith("LATIN LETTER SMALL CAPITAL "):
66
+ out.append(name.rsplit(" ", 1)[-1].lower())
67
+ else:
68
+ out.append(ch)
69
+ return "".join(out)
70
+
71
+ def _cbs_words(self, data):
72
+ """Yield lowercase words found in *data*, segment by segment, in order.
73
+
74
+ ``data`` is typically structured colon-model callback data
75
+ (``"assistant:games:aki"`` -> ``"assistant"``, ``"games"``, ``"aki"``),
76
+ but this also degrades gracefully for a plain (non-colon) callback
77
+ string, a URL, or a switch-inline query - ``str.split(":")`` on a
78
+ single-segment string is just ``[string]``, and stray punctuation inside
79
+ a segment is stripped by the word regex.
80
+ """
81
+ if isinstance(data, bytes):
82
+ data = data.decode("utf-8", "ignore")
83
+ if data is None or isinstance(data, (int, float)):
84
+ return
85
+ for segment in str(data).lower().split(":"):
86
+ yield from _WORD_RE.findall(segment)
87
+
88
+ def _default_icon_name(self, text, data=None, type_hint=None, fallback=None):
89
+ """Resolve a default icon *name* (a key of ``DEFAULT_ICON_UNICODE``) or ``None``.
90
+
91
+ Precedence: callback-data (cbs) words first, in segment order - this is
92
+ the primary source, since callback data is structured and stable while
93
+ titles are free-form display text. Title words (folded to ASCII first,
94
+ see :func:`_fold_stylized`) are a secondary source, checked only if no
95
+ cbs word matched. A per-button-kind default (``type_hint``) is checked
96
+ last, only for the handful of structurally-reliable kinds in
97
+ :data:`_TYPE_ICON_NAMES`. If nothing matches at all, ``fallback`` (``None``
98
+ by default) is returned - i.e. no icon, not a generic one.
99
+ """
100
+ for word in self._cbs_words(data):
101
+ name = _WORD_ICON_NAMES.get(word)
102
+ if name:
103
+ return name
104
+ for word in _WORD_RE.findall(self._fold_stylized(str(text or "")).lower()):
105
+ name = _WORD_ICON_NAMES.get(word)
106
+ if name:
107
+ return name
108
+ return _TYPE_ICON_NAMES.get(type_hint, fallback)
109
+
110
+ def _has_icon_glyph(self, text: str) -> bool:
111
+ """True if *text* already starts or ends with an emoji-like glyph
112
+ (crude, avoids double-iconifying a caption such as ``"Close ❌"``).
113
+
114
+ The ``0x2190`` threshold (arrows block onward) deliberately sits above
115
+ the stylized small-caps letters (``U+1D00``-``U+1D7F``) used across the
116
+ codebase's captions, so those never count as icons.
117
+ """
118
+ stripped = text.strip() if text else ""
119
+ if not stripped:
120
+ return False
121
+ return ord(stripped[0]) >= 0x2190 or ord(stripped[-1]) >= 0x2190
122
+
123
+ def _resolve_button_icon(
124
+ self, text, icon_elem, *, auto, data=None, type_hint=None, fallback=None
125
+ ):
126
+ """Resolve the final ``(text, style_icon_document_id)`` for one button.
127
+
128
+ ``icon_elem`` is the button's own icon slot (an explicit id/digit-string
129
+ or an icon-table name like ``"back"`` always wins over auto-selection;
130
+ ``False`` force-disables auto-selection
131
+ for just this button, overriding a truthy ``auto``). ``auto`` is the
132
+ ``ikm(..., icon=True)`` / ``rkm(..., icon=True)`` call-level toggle.
133
+
134
+ Matching precedence: explicit per-button ``icon_elem`` > cbs (callback
135
+ data) keyword > title keyword > per-kind ``type_hint`` icon > no icon.
136
+ See :func:`_default_icon_name`.
137
+ """
138
+ if icon_elem is False:
139
+ return text, None
140
+ # An icon-table *name* ("back", "close", …) is an explicit per-button
141
+ # override too: prefix its emoji and use its document id directly.
142
+ if (
143
+ isinstance(icon_elem, str)
144
+ and not icon_elem.isdigit()
145
+ and icon_elem.lower() in DEFAULT_ICON_UNICODE
146
+ ):
147
+ name = icon_elem.lower()
148
+ else:
149
+ doc_id = self._normalize_icon(icon_elem)
150
+ if doc_id is not None:
151
+ return text, doc_id
152
+ if not auto:
153
+ return text, None
154
+ name = self._default_icon_name(
155
+ text, data=data, type_hint=type_hint, fallback=fallback
156
+ )
157
+ if name is None:
158
+ return text, None
159
+ emoji = DEFAULT_ICON_UNICODE.get(name)
160
+ if emoji and not self._has_icon_glyph(text):
161
+ text = f"{emoji} {text}"
162
+ return text, TG_ANDROID_ICON_DOCUMENT_IDS.get(name)
163
+
164
+ def register_button_type(self, name, factory=None):
165
+ """Register a custom ``ikm``/``rkm`` tuple-form button kind.
166
+
167
+ ``name`` is the string used as a tuple's 2nd element, e.g.
168
+ ``("Text", name, ...)``. ``factory(text, val, btn_tuple)`` is called
169
+ once per matching tuple and must return a built Telethon button (a
170
+ ``Button`` helper instance or a raw TL ``KeyboardButton*`` object).
171
+ ``val`` is the tuple's 3rd element (``None`` if absent); ``btn_tuple``
172
+ is the full tuple, for factories that need later elements.
173
+
174
+ Can be used directly or as a decorator::
175
+
176
+ register_button_type("copy", my_factory)
177
+
178
+ @register_button_type("copy")
179
+ def my_factory(self, text, val, btn_tuple):
180
+ ...
181
+
182
+ Registering an already-used name replaces the previous factory. The
183
+ built-in kinds (``"url"``, ``"user"``, ``"web_app"``, ``"switch_inline"``,
184
+ ``"request_user"``/``"request_chat"``/``"request_broadcast"``, ``"auth"``,
185
+ ``"buy"``, ``"game"``) are handled natively and are never looked up here.
186
+ """
187
+ key = str(name).lower()
188
+ if factory is None:
189
+
190
+ def _decorator(fn):
191
+ self._registry[key] = fn
192
+ return fn
193
+
194
+ return _decorator
195
+ self._registry[key] = factory
196
+ return factory
197
+
198
+ def _build_copy_button(self, text, val, btn_tuple):
199
+ """Built-in ``"copy"`` registration: a copy-to-clipboard button.
200
+
201
+ ``("Text", "copy", copy_text[, style[, icon]])``. Uses the native
202
+ ``KeyboardButtonCopy`` TL type when this Telethon build ships it,
203
+ otherwise degrades to an inline callback carrying the copy text.
204
+ """
205
+ copy_text = str(val) if val is not None else text
206
+ style = btn_tuple[3] if len(btn_tuple) > 3 else None
207
+ icon = btn_tuple[4] if len(btn_tuple) > 4 else None
208
+ style, icon = self._normalize_style(style), self._normalize_icon(icon)
209
+ cls = getattr(_types, "KeyboardButtonCopy", None)
210
+ style_obj = Button._get_style(style, icon)
211
+ if cls is not None:
212
+ return cls(text=text, copy_text=copy_text, style=style_obj)
213
+ inline_cls = getattr(_types, "KeyboardInlineButton", None)
214
+ copy_type_cls = getattr(_types, "InlineButtonTypeCopy", None)
215
+ if inline_cls is not None and copy_type_cls is not None:
216
+ return inline_cls(
217
+ text=text, type=copy_type_cls(copy_text=copy_text), style=style_obj
218
+ )
219
+ return Button.inline(text, data=copy_text.encode()[:64], style=style, icon=icon)
220
+
221
+ def _build_toggle_button(self, text, val, btn_tuple):
222
+ """Built-in ``"toggle"`` registration: an on/off inline callback button.
223
+
224
+ ``("Text", "toggle", callback_data[, is_on[, style]])`` - prefixes the
225
+ title with a checked/unchecked box depending on ``is_on``.
226
+ """
227
+ is_on = bool(btn_tuple[3]) if len(btn_tuple) > 3 else False
228
+ style = self._normalize_style(btn_tuple[4] if len(btn_tuple) > 4 else None)
229
+ box = "☑️" if is_on else "⬜"
230
+ return Button.inline(f"{box} {text}", data=val, style=style)
231
+
232
+ def request_peer_button(
233
+ self,
234
+ text,
235
+ peer="user",
236
+ *,
237
+ button_id=1,
238
+ max_quantity=1,
239
+ style=None,
240
+ icon=None,
241
+ **peer_kwargs,
242
+ ):
243
+ """Build a raw ``KeyboardButtonRequestPeer`` TL button.
244
+
245
+ ``peer`` is one of ``"user"`` / ``"chat"`` / ``"broadcast"`` (the
246
+ ``"request_"``-prefixed ikm type names are also accepted). Extra keyword
247
+ arguments are forwarded to the ``RequestPeerType*`` constructor, e.g.
248
+ ``request_peer_button("Bots", "user", bot=True)`` or
249
+ ``request_peer_button("Forums", "chat", forum=True)``.
250
+
251
+ .. warning::
252
+ Telegram only allows request-peer buttons in *reply keyboards*
253
+ (they are not inline buttons - the fork's ``Button._is_inline`` does
254
+ not list them). Sending one inside an inline markup will be rejected
255
+ by Telegram with ``BUTTON_TYPE_INVALID``.
256
+
257
+ Raises ``ValueError`` for an unknown peer kind and ``NotImplementedError``
258
+ when the installed Telethon build lacks the request-peer TL types.
259
+ """
260
+ kind = str(peer).lower()
261
+ if kind.startswith("request_"):
262
+ kind = kind[len("request_") :]
263
+ try:
264
+ cls_name = _REQUEST_PEER_TYPES[kind]
265
+ except KeyError:
266
+ raise ValueError(
267
+ f"Unknown request-peer type {peer!r}; "
268
+ f"expected one of {sorted(_REQUEST_PEER_TYPES)}"
269
+ ) from None
270
+ peer_cls = getattr(_types, cls_name, None)
271
+ button_cls = getattr(_types, "KeyboardButtonRequestPeer", None)
272
+ if peer_cls is None:
273
+ raise NotImplementedError(
274
+ "This Telethon build does not provide the KeyboardButtonRequestPeer TL types"
275
+ )
276
+ style = self._normalize_style(style)
277
+ icon = self._normalize_icon(icon)
278
+ style_obj = (
279
+ Button._get_style(style, icon)
280
+ if (style is not None or icon is not None)
281
+ else None
282
+ )
283
+ peer_type = peer_cls(**peer_kwargs)
284
+ if button_cls is not None:
285
+ return button_cls(
286
+ text=text,
287
+ button_id=button_id,
288
+ peer_type=peer_type,
289
+ max_quantity=max_quantity,
290
+ style=style_obj,
291
+ )
292
+ keyboard_cls = getattr(_types, "KeyboardButton", None)
293
+ request_type_cls = getattr(_types, "ButtonTypeRequestPeer", None)
294
+ if keyboard_cls is None or request_type_cls is None:
295
+ raise NotImplementedError(
296
+ "This Telethon build does not provide request-peer keyboard types"
297
+ )
298
+ return keyboard_cls(
299
+ text=text,
300
+ type=request_type_cls(
301
+ button_id=button_id,
302
+ peer_type=peer_type,
303
+ max_quantity=max_quantity,
304
+ ),
305
+ style=style_obj,
306
+ )
307
+
308
+ def web_app_button(self, text, url, *, style=None, icon=None, simple=False):
309
+ """Build a web_app keyboard button with graceful degradation.
310
+
311
+ By default builds a ``KeyboardButtonWebView`` (inline-keyboard web_app
312
+ button that can send data back to the bot). Pass ``simple=True`` for a
313
+ reply-keyboard ``KeyboardButtonSimpleWebView`` (opens the web app without
314
+ the data round-trip).
315
+
316
+ On Telethon builds that lack the raw web_app button types, this falls back
317
+ to a ``Button.url`` button (so the link is still usable) or, if ``url`` is
318
+ empty, to an inline callback button carrying the literal ``"web_app"``.
319
+ """
320
+ style = self._normalize_style(style)
321
+ icon = self._normalize_icon(icon)
322
+ style_obj = (
323
+ Button._get_style(style, icon)
324
+ if (style is not None or icon is not None)
325
+ else None
326
+ )
327
+
328
+ cls = _SimpleWebViewButtonCls if simple else _WebViewButtonCls
329
+ if cls is not None:
330
+ if cls is getattr(_types, "KeyboardInlineButton", None):
331
+ view_type = getattr(_types, "InlineButtonTypeWebView", None)
332
+ if view_type is not None:
333
+ return cls(
334
+ text=text, type=view_type(url=url or ""), style=style_obj
335
+ )
336
+ if cls is getattr(_types, "KeyboardButton", None):
337
+ view_type = getattr(_types, "ButtonTypeSimpleWebView", None)
338
+ if view_type is not None:
339
+ return cls(
340
+ text=text, type=view_type(url=url or ""), style=style_obj
341
+ )
342
+ return cls(text=text, url=url or "", style=style_obj)
343
+
344
+ if url:
345
+ return Button.url(text, url=url, style=style, icon=icon)
346
+ return Button.inline(text, data=b"web_app", style=style, icon=icon)
347
+
348
+ def send_web_view_result_message(self, bot_query_id: str, result):
349
+ """Build a ``SendWebViewResultMessageRequest`` TL request when available.
350
+
351
+ ``result`` is an ``InputBotInlineResult`` object. Raises
352
+ ``NotImplementedError`` on Telethon builds that lack this request.
353
+ """
354
+ cls = _SendWebViewResultMsgCls
355
+ if cls is None:
356
+ raise NotImplementedError(
357
+ "This Telethon build does not provide SendWebViewResultMessageRequest"
358
+ )
359
+ return cls(bot_query_id=bot_query_id, result=result)
360
+
361
+ def _web_app_button_from_tuple(self, text, btn_tuple, val, *, icon=None):
362
+ """Shared parser for the ikm/rkm ``('text', 'web_app', url, ...)`` tuple forms.
363
+
364
+ ``btn_tuple`` is the full tuple, ``val`` the URL in its 3rd element,
365
+ ``icon`` the already-resolved style-icon document id (or ``None``).
366
+ """
367
+ simple = btn_tuple[1] in ("simple_web_app", "simple_webapp")
368
+ style = btn_tuple[3] if len(btn_tuple) > 3 else None
369
+ return self.web_app_button(
370
+ text, val or "", style=style, icon=icon, simple=simple
371
+ )
372
+
373
+ def ids(self, inline_message_id: str) -> tuple:
374
+ """
375
+ Resolves an inline_message_id into (chat_id, message_id).
376
+ Handles both normal and bot-API style packed IDs.
377
+ """
378
+ data = resolve_inline_message_id(inline_message_id)
379
+ try:
380
+ cid, mid = data.peer, data.id
381
+ except AttributeError:
382
+ cid, mid = struct.unpack(">ii", data.id.to_bytes(8, signed=True))
383
+
384
+ if cid < 0 or cid >= MAX_CHANNEL_ID:
385
+ cid = get_peer_id(abs(cid))
386
+
387
+ return cid, mid
388
+
389
+ def ikm(self, data: list, *, icon: bool = False):
390
+ """
391
+ Constructs an inline keyboard as a list-of-lists of Button objects.
392
+
393
+ Telethon's send_message / reply / edit_message `buttons=` param accepts
394
+ list-of-lists and serialises them internally. Do NOT return a pre-built
395
+ ReplyInlineMarkup - that causes ReplyMarkupInvalidError.
396
+
397
+ Pre-built Telethon button objects (``Button`` helper instances and raw
398
+ ``KeyboardButton*`` TL objects) pass through untouched - nested inside a
399
+ row, as a bare row, or as the whole input - and are detected positively
400
+ before any tuple-spec len()/indexing happens.
401
+
402
+ Supported tuple formats per button:
403
+ (text, cb) → inline button
404
+ (text, cb, style) → inline button with colour style
405
+ (text, cb, style, icon) → inline button, colour + icon
406
+ (text, "url", url) → URL button
407
+ (text, "url", url, style[, icon]) → URL button with colour style
408
+ (text, "switch_inline", query[, same_peer[, style[, icon]]])
409
+ → inline switch-to-inline-query button
410
+ (text, "user", uid) → request-peer button when the
411
+ Telethon build supports it,
412
+ otherwise an inline fallback
413
+ (text, "request_user"|"request_chat"|"request_broadcast", button_id[, max_quantity[, style[, icon]]])
414
+ → raw KeyboardButtonRequestPeer
415
+ (reply-keyboard contexts only)
416
+ (text, "web_app", url) → inline web_app button
417
+ (KeyboardButtonWebView; falls
418
+ back to a URL button on older
419
+ Telethon builds)
420
+ (text, "simple_webapp", url) → reply-keyboard simple web_app
421
+ button (KeyboardButtonSimpleWebView)
422
+ (text, name, ...) → any kind registered via
423
+ :func:`register_button_type`
424
+
425
+ ``style`` may be one of the strings "default"/"primary"/"success"/"danger"
426
+ or the matching Telegram Bot API integers 0/1/2/3. ``icon`` is a
427
+ custom-emoji document id (int) or an icon-table name (``"back"``,
428
+ ``"close"``, …) - an explicit value here always wins,
429
+ ``False`` disables auto-selection for that one button. Both apply to
430
+ inline AND url buttons (the fork styles both); unknown values degrade to
431
+ the default look instead of raising.
432
+
433
+ ``icon=True`` (default ``False``) turns on automatic icon selection for
434
+ every button in this call that doesn't already have an explicit icon:
435
+ a matching unicode emoji (see :data:`DEFAULT_ICON_UNICODE`) is prefixed
436
+ onto the button title, and the matching :data:`TG_ANDROID_ICON_DOCUMENT_IDS`
437
+ entry (if filled in) is used as the style icon. Matching precedence is
438
+ per-button ``icon=`` element > callback-data keyword > title keyword >
439
+ button-type keyword > no icon - there is no generic fallback icon, so
440
+ turning this on is safe to do call-wide without spamming every unrelated
441
+ button. See :func:`_default_icon_name` for the exact matching rules.
442
+
443
+ The pinned fork has no ``Button.request_peer`` helper, so
444
+ ``("…", "user", uid)`` deliberately produces an inline callback button
445
+ whose data is the user id. The capability is probed once at import time
446
+ (``_HAS_REQUEST_PEER``), so if the fork ever grows the helper the native
447
+ button is used automatically. ``("…", "web_app", url)`` similarly probes
448
+ ``_HAS_WEBVIEW_BUTTONS`` once at import.
449
+
450
+ Usage:
451
+ ikm([("Text", "cb")])
452
+ ikm([[("A", "cb1"), ("B", "cb2")], [("C", "url", "https://...")]])
453
+ ikm([("Confirm", "yes", "success"), ("Cancel", "no", "danger")])
454
+ ikm([("Pick user", "request_user", 1)])
455
+ ikm([("Open app", "web_app", "https://example.com/app")])
456
+ ikm([("Back", "back")], icon=True) # auto-prefixes "◀️ Back"
457
+ """
458
+ auto_icon = icon
459
+
460
+ # a bare top-level tuple or pre-built button is a single one-button row
461
+ if isinstance(data, tuple) or self._is_built_button(data):
462
+ data = [data]
463
+
464
+ rows = []
465
+ for row in data:
466
+ current_row = []
467
+ if isinstance(row, tuple) or self._is_built_button(row):
468
+ row = [row]
469
+
470
+ for btn in row:
471
+ if self._is_built_button(btn):
472
+ current_row.append(btn)
473
+ continue
474
+
475
+ if not isinstance(btn, (list, tuple)):
476
+ current_row.append(btn)
477
+ continue
478
+
479
+ if len(btn) < 2:
480
+ continue
481
+
482
+ text = btn[0]
483
+ bt_type = btn[1]
484
+ val = btn[2] if len(btn) > 2 else None
485
+
486
+ if bt_type == "url":
487
+ # (text, "url", url[, style[, icon]])
488
+ style = btn[3] if len(btn) > 3 else None
489
+ icon_elem = btn[4] if len(btn) > 4 else None
490
+ text, icon_val = self._resolve_button_icon(
491
+ text, icon_elem, auto=auto_icon, data=val, type_hint="url"
492
+ )
493
+ current_row.append(
494
+ Button.url(
495
+ text,
496
+ url=val or "",
497
+ style=self._normalize_style(style),
498
+ icon=icon_val,
499
+ )
500
+ )
501
+ elif bt_type == "switch_inline":
502
+ # (text, "switch_inline", query[, same_peer[, style[, icon]]])
503
+ same_peer = bool(btn[3]) if len(btn) > 3 else False
504
+ style = btn[4] if len(btn) > 4 else None
505
+ icon_elem = btn[5] if len(btn) > 5 else None
506
+ text, icon_val = self._resolve_button_icon(
507
+ text,
508
+ icon_elem,
509
+ auto=auto_icon,
510
+ data=val,
511
+ type_hint="switch_inline",
512
+ )
513
+ current_row.append(
514
+ Button.switch_inline(
515
+ text,
516
+ query=val or "",
517
+ same_peer=same_peer,
518
+ style=self._normalize_style(style),
519
+ icon=icon_val,
520
+ )
521
+ )
522
+ elif bt_type == "user":
523
+ text, _icon_val = self._resolve_button_icon(
524
+ text, None, auto=auto_icon, data=val, type_hint="user"
525
+ )
526
+ if _HAS_REQUEST_PEER:
527
+ current_row.append(
528
+ Button.request_peer(
529
+ text, button_id=val if isinstance(val, int) else 1
530
+ )
531
+ )
532
+ else:
533
+ current_row.append(
534
+ Button.inline(text, data=str(val or "user").encode()[:64])
535
+ )
536
+ elif bt_type in ("request_user", "request_chat", "request_broadcast"):
537
+ # (text, "request_*", button_id[, max_quantity[, style[, icon]]])
538
+ icon_elem = btn[5] if len(btn) > 5 else None
539
+ text, icon_val = self._resolve_button_icon(
540
+ text, icon_elem, auto=auto_icon, type_hint=bt_type
541
+ )
542
+ current_row.append(
543
+ self.request_peer_button(
544
+ text,
545
+ bt_type,
546
+ button_id=val if isinstance(val, int) else 1,
547
+ max_quantity=(
548
+ btn[3]
549
+ if len(btn) > 3 and isinstance(btn[3], int)
550
+ else 1
551
+ ),
552
+ style=btn[4] if len(btn) > 4 else None,
553
+ icon=icon_val,
554
+ )
555
+ )
556
+ elif bt_type in (
557
+ "web_app",
558
+ "webapp",
559
+ "simple_web_app",
560
+ "simple_webapp",
561
+ ):
562
+ icon_elem = btn[4] if len(btn) > 4 else None
563
+ text, icon_val = self._resolve_button_icon(
564
+ text, icon_elem, auto=auto_icon, data=val, type_hint="web_app"
565
+ )
566
+ current_row.append(
567
+ self._web_app_button_from_tuple(text, btn, val, icon=icon_val)
568
+ )
569
+ elif bt_type in ("auth", "buy", "game"):
570
+ icon_elem = btn[3] if len(btn) > 3 else None
571
+ text, icon_val = self._resolve_button_icon(
572
+ text, icon_elem, auto=auto_icon, type_hint=bt_type
573
+ )
574
+ current_row.append(
575
+ Button.inline(
576
+ text,
577
+ data=(
578
+ (val or bt_type).encode()[:64]
579
+ if isinstance(val, str)
580
+ else val or bt_type.encode()
581
+ ),
582
+ icon=icon_val,
583
+ )
584
+ )
585
+ else:
586
+ factory = (
587
+ self._registry.get(str(bt_type).lower())
588
+ if isinstance(bt_type, str)
589
+ else None
590
+ )
591
+ if factory is not None:
592
+ current_row.append(factory(text, val, btn))
593
+ continue
594
+ # (text, callback_data) or (text, callback_data, style[, icon])
595
+ # ``val`` is the 3rd element, i.e. the style for inline buttons.
596
+ icon_elem = btn[3] if len(btn) > 3 else None
597
+ text, icon_val = self._resolve_button_icon(
598
+ text, icon_elem, auto=auto_icon, data=bt_type, type_hint=None
599
+ )
600
+ style = self._normalize_style(val)
601
+ if val is None and str(text).strip().casefold() == "back":
602
+ style = "primary"
603
+ current_row.append(
604
+ Button.inline(
605
+ text,
606
+ data=bt_type,
607
+ style=style,
608
+ icon=icon_val,
609
+ )
610
+ )
611
+
612
+ if current_row:
613
+ rows.append(current_row)
614
+
615
+ return rows or None
616
+
617
+ def rkm(
618
+ self,
619
+ data: list,
620
+ *,
621
+ icon: bool = False,
622
+ resize: bool = None,
623
+ single_use: bool = None,
624
+ selective: bool = None,
625
+ placeholder: str = None,
626
+ ):
627
+ """
628
+ Constructs a reply keyboard (NOT inline) as a list-of-lists of Button objects.
629
+
630
+ Sibling of :func:`ikm` for the button kinds that only exist in *reply*
631
+ keyboards (plain text, request_location/phone/poll/peer, the "simple"
632
+ web_app view). Same passthrough rules for pre-built buttons, same
633
+ style/icon/registry handling, same tolerant defaults.
634
+
635
+ Supported tuple formats per button:
636
+ "Text" → plain text button
637
+ (text,) or (text, "text") → plain text button
638
+ (text, "text", style[, icon]) → plain text button, styled
639
+ (text, "location") → request_location button
640
+ (text, "phone") → request_phone button
641
+ (text, "poll"[, quiz[, style[, icon]]]) → request_poll button
642
+ (text, "user"|"request_user"|"chat"|"request_chat"|"broadcast"|"request_broadcast",
643
+ button_id[, max_quantity[, style[, icon]]])
644
+ → raw KeyboardButtonRequestPeer
645
+ (text, "web_app"|"simple_webapp", url) → KeyboardButtonSimpleWebView
646
+ (the only web_app kind valid
647
+ inside a reply keyboard)
648
+ (text, name, ...) → any kind registered via
649
+ :func:`register_button_type`
650
+ (shared registry with ``ikm``)
651
+
652
+ ``icon=True`` enables the same default-icon auto-selection as ``ikm``
653
+ (see :data:`DEFAULT_ICON_UNICODE`); an unrecognised tuple type falls
654
+ back to a plain text button instead of raising.
655
+
656
+ ``resize``/``single_use``/``selective``/``placeholder`` configure the
657
+ resulting ``ReplyKeyboardMarkup`` the same way ``Button.text(...)``'s
658
+ keyword arguments do - set them here once instead of on every button.
659
+ They are honoured even when every button in the keyboard is a raw TL
660
+ object (``request_peer_button()``, a ``simple_webapp`` button, ...)
661
+ rather than a ``Button`` wrapper - this function wraps whatever it
662
+ built so the options always survive serialisation.
663
+
664
+ Usage:
665
+ rkm(["Yes", "No"])
666
+ rkm([("Share number", "phone")], resize=True)
667
+ rkm([("Pick a user", "request_user", 1)], single_use=True)
668
+ """
669
+ auto_icon = icon
670
+
671
+ if isinstance(data, (str, tuple)) or self._is_built_button(data):
672
+ data = [data]
673
+
674
+ rows = []
675
+ for row in data:
676
+ current_row = []
677
+
678
+ if isinstance(row, (str, tuple)) or self._is_built_button(row):
679
+ row = [row]
680
+
681
+ for btn in row:
682
+ if self._is_built_button(btn):
683
+ current_row.append(btn)
684
+ continue
685
+
686
+ if isinstance(btn, str):
687
+ text, bt_type, val, btn = btn, "text", None, (btn, "text")
688
+ elif isinstance(btn, (list, tuple)):
689
+ if len(btn) < 1:
690
+ continue
691
+ text = btn[0]
692
+ bt_type = btn[1] if len(btn) > 1 else "text"
693
+ val = btn[2] if len(btn) > 2 else None
694
+ else:
695
+ current_row.append(btn)
696
+ continue
697
+
698
+ if bt_type == "text":
699
+ # (text, "text", style[, icon]) - no ``val`` slot of its own.
700
+ style = btn[2] if len(btn) > 2 else None
701
+ icon_elem = btn[3] if len(btn) > 3 else None
702
+ text, icon_val = self._resolve_button_icon(
703
+ text, icon_elem, auto=auto_icon, type_hint="text", fallback=None
704
+ )
705
+ current_row.append(
706
+ Button.text(
707
+ text, style=self._normalize_style(style), icon=icon_val
708
+ )
709
+ )
710
+ elif bt_type in ("location", "request_location"):
711
+ style = btn[3] if len(btn) > 3 else None
712
+ icon_elem = btn[4] if len(btn) > 4 else None
713
+ text, icon_val = self._resolve_button_icon(
714
+ text, icon_elem, auto=auto_icon, type_hint="location"
715
+ )
716
+ current_row.append(
717
+ Button.request_location(
718
+ text, style=self._normalize_style(style), icon=icon_val
719
+ )
720
+ )
721
+ elif bt_type in ("phone", "request_phone"):
722
+ style = btn[3] if len(btn) > 3 else None
723
+ icon_elem = btn[4] if len(btn) > 4 else None
724
+ text, icon_val = self._resolve_button_icon(
725
+ text, icon_elem, auto=auto_icon, type_hint="phone"
726
+ )
727
+ current_row.append(
728
+ Button.request_phone(
729
+ text, style=self._normalize_style(style), icon=icon_val
730
+ )
731
+ )
732
+ elif bt_type in ("poll", "request_poll"):
733
+ quiz = bool(val) if len(btn) > 2 else False
734
+ style = btn[3] if len(btn) > 3 else None
735
+ icon_elem = btn[4] if len(btn) > 4 else None
736
+ text, icon_val = self._resolve_button_icon(
737
+ text, icon_elem, auto=auto_icon, type_hint="poll"
738
+ )
739
+ current_row.append(
740
+ Button.request_poll(
741
+ text,
742
+ style=self._normalize_style(style),
743
+ icon=icon_val,
744
+ force_quiz=quiz,
745
+ )
746
+ )
747
+ elif bt_type in (
748
+ "user",
749
+ "request_user",
750
+ "chat",
751
+ "request_chat",
752
+ "broadcast",
753
+ "request_broadcast",
754
+ ):
755
+ icon_elem = btn[5] if len(btn) > 5 else None
756
+ text, icon_val = self._resolve_button_icon(
757
+ text, icon_elem, auto=auto_icon, type_hint=bt_type
758
+ )
759
+ current_row.append(
760
+ self.request_peer_button(
761
+ text,
762
+ bt_type,
763
+ button_id=val if isinstance(val, int) else 1,
764
+ max_quantity=(
765
+ btn[3]
766
+ if len(btn) > 3 and isinstance(btn[3], int)
767
+ else 1
768
+ ),
769
+ style=btn[4] if len(btn) > 4 else None,
770
+ icon=icon_val,
771
+ )
772
+ )
773
+ elif bt_type in (
774
+ "web_app",
775
+ "webapp",
776
+ "simple_web_app",
777
+ "simple_webapp",
778
+ ):
779
+ # Only KeyboardButtonSimpleWebView is valid in reply keyboards.
780
+ icon_elem = btn[4] if len(btn) > 4 else None
781
+ text, icon_val = self._resolve_button_icon(
782
+ text, icon_elem, auto=auto_icon, data=val, type_hint="web_app"
783
+ )
784
+ current_row.append(
785
+ web_app_button(
786
+ text,
787
+ val or "",
788
+ style=btn[3] if len(btn) > 3 else None,
789
+ icon=icon_val,
790
+ simple=True,
791
+ )
792
+ )
793
+ else:
794
+ factory = (
795
+ self._registry.get(str(bt_type).lower())
796
+ if isinstance(bt_type, str)
797
+ else None
798
+ )
799
+ if factory is not None:
800
+ current_row.append(factory(text, val, btn))
801
+ continue
802
+ # Unrecognised kind: degrade to a plain text button rather
803
+ # than raising, matching ikm's tolerant style.
804
+ icon_elem = btn[3] if len(btn) > 3 else None
805
+ text, icon_val = self._resolve_button_icon(
806
+ text, icon_elem, auto=auto_icon, type_hint="text", fallback=None
807
+ )
808
+ current_row.append(Button.text(text, icon=icon_val))
809
+
810
+ if current_row:
811
+ rows.append(current_row)
812
+
813
+ if rows and any(
814
+ v is not None for v in (resize, single_use, selective, placeholder)
815
+ ):
816
+ for row in rows:
817
+ for i, btn in enumerate(row):
818
+ if isinstance(btn, Button):
819
+ raw = btn.button
820
+ prev_resize, prev_single_use = btn.resize, btn.single_use
821
+ prev_selective, prev_placeholder = (
822
+ btn.selective,
823
+ btn.placeholder,
824
+ )
825
+ persistent = btn.persistent
826
+ elif isinstance(btn, TLObject):
827
+ raw = btn
828
+ prev_resize = prev_single_use = prev_selective = (
829
+ prev_placeholder
830
+ ) = None
831
+ persistent = None
832
+ else:
833
+ continue
834
+ row[i] = Button(
835
+ raw,
836
+ resize=resize if resize is not None else prev_resize,
837
+ single_use=(
838
+ single_use if single_use is not None else prev_single_use
839
+ ),
840
+ selective=(
841
+ selective if selective is not None else prev_selective
842
+ ),
843
+ persistent=persistent,
844
+ placeholder=(
845
+ placeholder if placeholder is not None else prev_placeholder
846
+ ),
847
+ )
848
+
849
+ return rows or None
850
+
851
+
852
+ button_kit = ButtonKit()
853
+
854
+
855
+ def _is_built_button(*args, **kwargs):
856
+ return button_kit._is_built_button(*args, **kwargs)
857
+
858
+
859
+ def _normalize_style(*args, **kwargs):
860
+ return button_kit._normalize_style(*args, **kwargs)
861
+
862
+
863
+ def _normalize_icon(*args, **kwargs):
864
+ return button_kit._normalize_icon(*args, **kwargs)
865
+
866
+
867
+ def _fold_stylized(*args, **kwargs):
868
+ return button_kit._fold_stylized(*args, **kwargs)
869
+
870
+
871
+ def _cbs_words(*args, **kwargs):
872
+ return button_kit._cbs_words(*args, **kwargs)
873
+
874
+
875
+ def _default_icon_name(*args, **kwargs):
876
+ return button_kit._default_icon_name(*args, **kwargs)
877
+
878
+
879
+ def _has_icon_glyph(*args, **kwargs):
880
+ return button_kit._has_icon_glyph(*args, **kwargs)
881
+
882
+
883
+ def _resolve_button_icon(*args, **kwargs):
884
+ return button_kit._resolve_button_icon(*args, **kwargs)
885
+
886
+
887
+ def register_button_type(*args, **kwargs):
888
+ return button_kit.register_button_type(*args, **kwargs)
889
+
890
+
891
+ def _build_copy_button(*args, **kwargs):
892
+ return button_kit._build_copy_button(*args, **kwargs)
893
+
894
+
895
+ def _build_toggle_button(*args, **kwargs):
896
+ return button_kit._build_toggle_button(*args, **kwargs)
897
+
898
+
899
+ def request_peer_button(*args, **kwargs):
900
+ return button_kit.request_peer_button(*args, **kwargs)
901
+
902
+
903
+ def web_app_button(*args, **kwargs):
904
+ return button_kit.web_app_button(*args, **kwargs)
905
+
906
+
907
+ def send_web_view_result_message(*args, **kwargs):
908
+ return button_kit.send_web_view_result_message(*args, **kwargs)
909
+
910
+
911
+ def _web_app_button_from_tuple(*args, **kwargs):
912
+ return button_kit._web_app_button_from_tuple(*args, **kwargs)
913
+
914
+
915
+ def ids(*args, **kwargs):
916
+ return button_kit.ids(*args, **kwargs)
917
+
918
+
919
+ def ikm(*args, **kwargs):
920
+ return button_kit.ikm(*args, **kwargs)
921
+
922
+
923
+ def rkm(*args, **kwargs):
924
+ return button_kit.rkm(*args, **kwargs)
925
+
926
+
927
+ import logging
928
+ import re
929
+ import struct
930
+ import unicodedata
931
+
932
+ from telethon import Button
933
+ from telethon.tl import TLObject
934
+ from telethon.tl import functions as _functions
935
+ from telethon.tl import types as _types
936
+ from telethon.utils import get_peer_id, resolve_inline_message_id
937
+
938
+ from .icons import document_id_for
939
+
940
+ _LOGS = logging.getLogger(__name__)
941
+
942
+ MAX_CHANNEL_ID = -1000000000000
943
+
944
+
945
+ _STYLE_MAP = {
946
+ # normal
947
+ "default": None,
948
+ "primary": "primary",
949
+ "success": "success",
950
+ "danger": "danger",
951
+ # index
952
+ 0: None,
953
+ 1: "primary",
954
+ 2: "success",
955
+ 3: "danger",
956
+ # by name
957
+ "red": "danger",
958
+ "green": "success",
959
+ "blue": "primary",
960
+ }
961
+
962
+
963
+ DEFAULT_ICON_UNICODE = {
964
+ "back": "◀️",
965
+ "close": "✖️",
966
+ "cancel": "🚫",
967
+ "noop": "▫️",
968
+ "copy": "📋",
969
+ "next": "➡️",
970
+ "prev": "⬅️",
971
+ "settings": "⚙️",
972
+ "help": "❓",
973
+ "download": "⬇️",
974
+ "play": "▶️",
975
+ "pause": "⏸️",
976
+ "redirect": "🔗",
977
+ "search": "🔍",
978
+ "person": "👤",
979
+ "game": "🎮",
980
+ "buy": "💳",
981
+ "lock": "🔒",
982
+ "location": "📍",
983
+ "phone": "📞",
984
+ "poll": "📊",
985
+ "lang": "🌐",
986
+ "home": "🏠",
987
+ }
988
+
989
+ TG_ANDROID_ICON_DOCUMENT_IDS = {name: None for name in DEFAULT_ICON_UNICODE}
990
+
991
+ _WORD_ICON_NAMES = {name: name for name in DEFAULT_ICON_UNICODE}
992
+ _WORD_ICON_NAMES.update(
993
+ {
994
+ "previous": "prev",
995
+ "games": "game",
996
+ "language": "lang",
997
+ "languages": "lang",
998
+ "start": "home",
999
+ "mainmenu": "home",
1000
+ "main": "home",
1001
+ }
1002
+ )
1003
+
1004
+ _TYPE_ICON_NAMES = {
1005
+ "url": "redirect",
1006
+ "web_app": "redirect",
1007
+ "webapp": "redirect",
1008
+ "simple_web_app": "redirect",
1009
+ "simple_webapp": "redirect",
1010
+ "switch_inline": "search",
1011
+ "user": "person",
1012
+ "request_user": "person",
1013
+ "chat": "person",
1014
+ "request_chat": "person",
1015
+ "broadcast": "person",
1016
+ "request_broadcast": "person",
1017
+ "game": "game",
1018
+ "buy": "buy",
1019
+ "auth": "lock",
1020
+ "location": "location",
1021
+ "request_location": "location",
1022
+ "phone": "phone",
1023
+ "request_phone": "phone",
1024
+ "poll": "poll",
1025
+ "request_poll": "poll",
1026
+ }
1027
+
1028
+ _WORD_RE = re.compile(r"[a-z]+")
1029
+
1030
+
1031
+ _BUTTON_TYPE_REGISTRY = button_kit._registry
1032
+
1033
+
1034
+ register_button_type("copy", _build_copy_button)
1035
+ register_button_type("toggle", _build_toggle_button)
1036
+
1037
+
1038
+ _HAS_REQUEST_PEER = hasattr(Button, "request_peer")
1039
+ if _HAS_REQUEST_PEER:
1040
+ _LOGS.debug(
1041
+ "custom.tg: Button.request_peer available - 'user' buttons use native request-peer."
1042
+ )
1043
+ else:
1044
+ _LOGS.debug(
1045
+ "custom.tg: Button.request_peer absent on this Telethon build - "
1046
+ "'user' buttons deliberately fall back to inline callback buttons "
1047
+ "carrying the user id as callback data."
1048
+ )
1049
+
1050
+ _REQUEST_PEER_TYPES = {
1051
+ "user": "RequestPeerTypeUser",
1052
+ "chat": "RequestPeerTypeChat",
1053
+ "broadcast": "RequestPeerTypeBroadcast",
1054
+ }
1055
+
1056
+
1057
+ _WebViewButtonCls = getattr(_types, "KeyboardButtonWebView", None) or getattr(
1058
+ _types, "KeyboardInlineButton", None
1059
+ )
1060
+ _SimpleWebViewButtonCls = getattr(_types, "KeyboardButtonSimpleWebView", None) or getattr(
1061
+ _types, "KeyboardButton", None
1062
+ )
1063
+ _WebViewDataSentCls = getattr(_types, "MessageActionWebViewDataSent", None)
1064
+ _WebViewDataSentMeCls = getattr(_types, "MessageActionWebViewDataSentMe", None)
1065
+ _WebViewResultSentCls = getattr(_types, "UpdateWebViewResultSent", None)
1066
+ _WebViewResultUrlCls = getattr(_types, "WebViewResultUrl", None)
1067
+ _SendWebViewResultMsgCls = getattr(
1068
+ _functions.messages, "SendWebViewResultMessageRequest", None
1069
+ )
1070
+
1071
+ _HAS_WEBVIEW_BUTTONS = (
1072
+ _WebViewButtonCls is not None and _SimpleWebViewButtonCls is not None
1073
+ )
1074
+ _HAS_WEBVIEW_DATA_ACTIONS = (
1075
+ _WebViewDataSentCls is not None and _WebViewDataSentMeCls is not None
1076
+ )
1077
+ _HAS_WEBVIEW_RESULT_SENT = _WebViewResultSentCls is not None
1078
+ _HAS_WEBVIEW_RESULT_MSG = _SendWebViewResultMsgCls is not None
1079
+
1080
+ if _HAS_WEBVIEW_BUTTONS:
1081
+ _LOGS.debug(
1082
+ "custom.tg: web_app button TL types available - "
1083
+ "('text', 'web_app', url) builds KeyboardButtonWebView."
1084
+ )
1085
+ else:
1086
+ _LOGS.debug(
1087
+ "custom.tg: web_app button TL types absent on this Telethon build - "
1088
+ "web_app buttons deliberately fall back to URL/inline buttons."
1089
+ )
custom/util.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+
3
+ from .debug import aexec, shell # noqa: F401
4
+
5
+
6
+ class UtilKit:
7
+ """Small patching and time-formatting utilities.
8
+
9
+ One instance (``util_kit``); the module-level functions below are
10
+ backward-compatible aliases.
11
+ """
12
+
13
+ def patch(self, cls: type) -> collections.abc.Callable:
14
+ def wrap(func: collections.abc.Callable) -> collections.abc.Callable:
15
+ if hasattr(func, "_patch"):
16
+ func._patch.append(cls)
17
+ else:
18
+ func._patch = [cls]
19
+
20
+ return func
21
+
22
+ return wrap
23
+
24
+ def usecs(self, s: float) -> str:
25
+ if not s:
26
+ return "0 s"
27
+
28
+ if s >= 1:
29
+ return f"{s:.2f} s"
30
+
31
+ if s >= 0.001:
32
+ return f"{s * 1000:.2f} ms"
33
+
34
+ return f"{s * 1000000:.2f} µs"
35
+
36
+
37
+ util_kit = UtilKit()
38
+
39
+
40
+ def patch(cls: type) -> collections.abc.Callable:
41
+ return util_kit.patch(cls)
42
+
43
+
44
+ def usecs(s: float) -> str:
45
+ return util_kit.usecs(s)
docker-compose.yml DELETED
@@ -1,14 +0,0 @@
1
- services:
2
- worker:
3
- build: .
4
- environment:
5
- REDIS_URI: $REDIS_URI
6
- REDIS_PASSWORD: $REDIS_PASSWORD
7
- SESSION: $SESSION
8
- API_ID: $API_ID # defaults to None
9
- API_HASH: $API_HASH # defaults to None
10
- MONGO_URI: $MONGO_URI # defaults to None
11
- BOT_TOKEN: $BOT_TOKEN # Not mandatory
12
- LOG_CHANNEL: $LOG_CHANNEL # Not mandatory
13
- DATABASE_URL: $DATABASE_URL # defaults to None
14
- OKTETO_TOKEN: $OKTETO_TOKEN