tg-mpv 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tg_mpv/__init__.py +3 -0
- tg_mpv/__main__.py +9 -0
- tg_mpv/bot.py +608 -0
- tg_mpv/cli.py +1189 -0
- tg_mpv/config.py +221 -0
- tg_mpv/doctor.py +219 -0
- tg_mpv/installer.py +90 -0
- tg_mpv/media.py +300 -0
- tg_mpv/platform_utils.py +204 -0
- tg_mpv/player.py +244 -0
- tg_mpv/server.py +187 -0
- tg_mpv/state.py +356 -0
- tg_mpv/stream.py +188 -0
- tg_mpv/telegram.py +156 -0
- tg_mpv-0.2.0.dist-info/METADATA +292 -0
- tg_mpv-0.2.0.dist-info/RECORD +20 -0
- tg_mpv-0.2.0.dist-info/WHEEL +5 -0
- tg_mpv-0.2.0.dist-info/entry_points.txt +2 -0
- tg_mpv-0.2.0.dist-info/licenses/LICENSE +678 -0
- tg_mpv-0.2.0.dist-info/top_level.txt +1 -0
tg_mpv/__init__.py
ADDED
tg_mpv/__main__.py
ADDED
tg_mpv/bot.py
ADDED
|
@@ -0,0 +1,608 @@
|
|
|
1
|
+
"""Generic Telegram bot interaction layer, with pluggable bot-specific
|
|
2
|
+
adapters and generic pagination ("Load More") support.
|
|
3
|
+
|
|
4
|
+
This module isolates everything specific to talking to a search/media bot
|
|
5
|
+
(such as @weeceebot) behind a small, generic abstraction:
|
|
6
|
+
|
|
7
|
+
search(query) -> BotResult (text + buttons + media)
|
|
8
|
+
classify_buttons(...) -> (selectable ResultOptions, optional LOAD_MORE option)
|
|
9
|
+
select_result(...) -> BotResult (follow-up after picking a result)
|
|
10
|
+
load_more(...) -> BotResult (follow-up after paginating)
|
|
11
|
+
|
|
12
|
+
It deliberately does NOT hardcode assumptions about the exact current UI of
|
|
13
|
+
any particular bot:
|
|
14
|
+
|
|
15
|
+
1. Sending a message to the bot.
|
|
16
|
+
2. Listening for new incoming messages from that bot for a short,
|
|
17
|
+
debounced window (bots often send multiple messages in a burst:
|
|
18
|
+
a "searching..." notice, then results, etc).
|
|
19
|
+
3. Extracting text, inline keyboard buttons, and playable media from the
|
|
20
|
+
messages collected during that window.
|
|
21
|
+
4. Classifying each button as a normal selectable RESULT or as the
|
|
22
|
+
semantic LOAD_MORE action, using a combination of text patterns,
|
|
23
|
+
callback data hints, and result-count text found in the surrounding
|
|
24
|
+
message -- never a single hardcoded string.
|
|
25
|
+
|
|
26
|
+
Multiple bots are supported via a small adapter registry
|
|
27
|
+
(`get_bot_adapter`). Each bot gets a `BotAdapter` subclass; unknown bots
|
|
28
|
+
fall back to the generic, pattern-based adapter. If the bot's workflow
|
|
29
|
+
changes, only this module should need to change -- the streaming engine
|
|
30
|
+
(server.py / stream.py) operates purely on a Telethon media object once one
|
|
31
|
+
has been selected, independent of which bot found it or how pagination
|
|
32
|
+
worked.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import asyncio
|
|
38
|
+
import logging
|
|
39
|
+
import re
|
|
40
|
+
from contextlib import asynccontextmanager
|
|
41
|
+
from dataclasses import dataclass, field
|
|
42
|
+
from typing import Optional
|
|
43
|
+
|
|
44
|
+
from telethon import TelegramClient, events
|
|
45
|
+
from telethon.tl.types import Message
|
|
46
|
+
|
|
47
|
+
from .media import MediaInfo, SubtitleInfo, extract_media_info, extract_subtitle_info
|
|
48
|
+
|
|
49
|
+
logger = logging.getLogger("tg_mpv.bot")
|
|
50
|
+
|
|
51
|
+
# How long to wait, after the most recent message from the bot, before we
|
|
52
|
+
# consider its "burst" of responses finished.
|
|
53
|
+
QUIET_PERIOD_SECS = 2.5
|
|
54
|
+
# Longer quiet period used while we have NOT yet seen anything useful (a
|
|
55
|
+
# playable video or a clickable button). Many bots first send an ad/notice
|
|
56
|
+
# message, think for a few seconds, and only then send the real results.
|
|
57
|
+
PATIENT_QUIET_PERIOD_SECS = 8.0
|
|
58
|
+
# Hard ceiling so we never hang forever waiting on a bot that never replies.
|
|
59
|
+
MAX_WAIT_SECS = 40.0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class BotError(Exception):
|
|
63
|
+
"""Raised for bot-interaction failures (timeout, no response, etc)."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _button_url(btn) -> Optional[str]:
|
|
67
|
+
"""URL of a Telethon `MessageButton` if it is a link button, else None.
|
|
68
|
+
|
|
69
|
+
Uses the button's own `.url` property rather than isinstance checks on
|
|
70
|
+
Telethon's raw TL classes: those were renamed in newer Telethon releases
|
|
71
|
+
(KeyboardButtonUrl -> KeyboardInlineButton/InlineButtonTypeUrl), while
|
|
72
|
+
`MessageButton.url` / `.data` work across versions."""
|
|
73
|
+
url = getattr(btn, "url", None)
|
|
74
|
+
return url if isinstance(url, str) and url else None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class NoResultsError(BotError):
|
|
78
|
+
"""The bot answered (or stayed silent) but produced nothing playable or
|
|
79
|
+
selectable -- the caller may try a reworded query."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
async def _retry(call, attempts: int = 3):
|
|
83
|
+
"""Await `call()`, retrying transient network errors with backoff."""
|
|
84
|
+
for attempt in range(1, attempts + 1):
|
|
85
|
+
try:
|
|
86
|
+
return await call()
|
|
87
|
+
except (ConnectionError, OSError, asyncio.TimeoutError):
|
|
88
|
+
if attempt == attempts:
|
|
89
|
+
raise
|
|
90
|
+
await asyncio.sleep(2 ** (attempt - 1))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class BotButton:
|
|
95
|
+
"""A single inline keyboard button."""
|
|
96
|
+
|
|
97
|
+
text: str
|
|
98
|
+
row: int
|
|
99
|
+
col: int
|
|
100
|
+
is_url: bool = False
|
|
101
|
+
url: Optional[str] = None
|
|
102
|
+
data: Optional[bytes] = None # callback_data, when present
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def selectable(self) -> bool:
|
|
106
|
+
"""Whether this button can be clicked to get a bot response
|
|
107
|
+
(callback buttons), as opposed to a plain URL link button."""
|
|
108
|
+
return not self.is_url
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass
|
|
112
|
+
class BotResult:
|
|
113
|
+
"""The bot's response state after a query or a button click."""
|
|
114
|
+
|
|
115
|
+
messages: list[Message] = field(default_factory=list)
|
|
116
|
+
text: str = ""
|
|
117
|
+
buttons: list[BotButton] = field(default_factory=list)
|
|
118
|
+
media: list[MediaInfo] = field(default_factory=list)
|
|
119
|
+
subtitles: list[SubtitleInfo] = field(default_factory=list)
|
|
120
|
+
# The message that owns `buttons`, needed to click() them.
|
|
121
|
+
_button_message: Optional[Message] = None
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def has_media(self) -> bool:
|
|
125
|
+
return bool(self.media)
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def has_buttons(self) -> bool:
|
|
129
|
+
return bool(self.buttons)
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def is_empty(self) -> bool:
|
|
133
|
+
return not self.messages
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass(frozen=True)
|
|
137
|
+
class ResultOption:
|
|
138
|
+
"""A selectable (or LOAD_MORE) button, tied to the message that owns it.
|
|
139
|
+
|
|
140
|
+
`identity` is a stable-ish key used for de-duplication when
|
|
141
|
+
accumulating paginated results: (chat_id, message_id, row, col). This
|
|
142
|
+
is stable across a single message's lifetime (including in-place
|
|
143
|
+
edits, since row/col only grow as more buttons are appended) and
|
|
144
|
+
naturally distinct across brand-new messages.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
identity: tuple
|
|
148
|
+
button: BotButton
|
|
149
|
+
source_message: Message
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# --------------------------------------------------------------------------
|
|
153
|
+
# Generic LOAD_MORE detection
|
|
154
|
+
# --------------------------------------------------------------------------
|
|
155
|
+
|
|
156
|
+
# Patterns that, on their own, confidently indicate a pagination control --
|
|
157
|
+
# regardless of which bot sent it. Matched against normalized (lowercased,
|
|
158
|
+
# punctuation/emoji stripped) button text.
|
|
159
|
+
_STRONG_LOAD_MORE_PATTERNS = [
|
|
160
|
+
re.compile(p, re.IGNORECASE)
|
|
161
|
+
for p in (
|
|
162
|
+
r"\bload\s*more\b",
|
|
163
|
+
r"\bmore\s*results?\b",
|
|
164
|
+
r"\bshow\s*more\b",
|
|
165
|
+
r"\bnext\s*results?\b",
|
|
166
|
+
r"\bnext\s*page\b",
|
|
167
|
+
r"^next$",
|
|
168
|
+
r"تحميل\s*المزيد",
|
|
169
|
+
r"عرض\s*المزيد",
|
|
170
|
+
r"المزيد\s*من\s*النتائج",
|
|
171
|
+
)
|
|
172
|
+
]
|
|
173
|
+
|
|
174
|
+
# Patterns that are ambiguous alone (e.g. a bare "More" could be a
|
|
175
|
+
# "Settings" style menu, not pagination) and require a corroborating
|
|
176
|
+
# signal -- a visible result-count/progress indicator in the surrounding
|
|
177
|
+
# message text, or a pagination-flavored callback_data payload.
|
|
178
|
+
_WEAK_LOAD_MORE_PATTERNS = [
|
|
179
|
+
re.compile(p, re.IGNORECASE) for p in (r"^more$", r"^المزيد$")
|
|
180
|
+
]
|
|
181
|
+
|
|
182
|
+
# A bare numeric range used as a button label, e.g. "11-20", commonly used
|
|
183
|
+
# by bots as an implicit "go to the next page of results" control.
|
|
184
|
+
_RANGE_BUTTON_RE = re.compile(r"^\s*\d+\s*-\s*\d+\s*$")
|
|
185
|
+
|
|
186
|
+
# Result-count / progress indicators that can appear in message text, e.g.
|
|
187
|
+
# "10 of 46", "10 من 46", "1-10 of 46", "10/46".
|
|
188
|
+
_PROGRESS_RE = re.compile(r"(\d+)\s*(?:of|من|/)\s*(\d+)")
|
|
189
|
+
|
|
190
|
+
# Hints inside callback_data payloads that suggest a pagination action.
|
|
191
|
+
_CALLBACK_HINT_RE = re.compile(
|
|
192
|
+
r"\b(load_?more|next_?page|page_?\d+|offset_?\d+|more)\b", re.IGNORECASE
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
# Strips emoji/arrows/punctuation for text normalization, keeping Unicode
|
|
196
|
+
# word characters (including Arabic letters) and whitespace.
|
|
197
|
+
_NON_WORD_RE = re.compile(r"[^\w\s]", re.UNICODE)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _normalize_button_text(text: str) -> str:
|
|
201
|
+
cleaned = _NON_WORD_RE.sub(" ", text or "")
|
|
202
|
+
return re.sub(r"\s+", " ", cleaned).strip().lower()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def parse_progress(message_text: str) -> Optional[tuple[int, int]]:
|
|
206
|
+
"""Best-effort extraction of a "loaded of total" indicator from bot
|
|
207
|
+
text, e.g. "عرض 10 من 46 نتيجة" -> (10, 46), or "10 of 46" -> (10, 46).
|
|
208
|
+
|
|
209
|
+
Returns None if no such pattern is found. This is used only as a
|
|
210
|
+
corroborating signal for ambiguous button text -- never as the sole
|
|
211
|
+
trigger for clicking a button.
|
|
212
|
+
"""
|
|
213
|
+
match = _PROGRESS_RE.search(message_text or "")
|
|
214
|
+
if not match:
|
|
215
|
+
return None
|
|
216
|
+
try:
|
|
217
|
+
loaded, total = int(match.group(1)), int(match.group(2))
|
|
218
|
+
except ValueError:
|
|
219
|
+
return None
|
|
220
|
+
return loaded, total
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class BotAdapter:
|
|
224
|
+
"""Generic, pattern-based adapter for a conversation with a Telegram
|
|
225
|
+
bot. Used directly for unknown bots (as `GenericBotAdapter`), and
|
|
226
|
+
subclassed by bot-specific adapters that need extra, exact-match rules
|
|
227
|
+
(see `WeeCeeBotAdapter` below).
|
|
228
|
+
"""
|
|
229
|
+
|
|
230
|
+
# Overridable by subclasses to add bot-specific exact-match rules
|
|
231
|
+
# without needing to touch the generic detection logic.
|
|
232
|
+
STRONG_LOAD_MORE_PATTERNS = _STRONG_LOAD_MORE_PATTERNS
|
|
233
|
+
WEAK_LOAD_MORE_PATTERNS = _WEAK_LOAD_MORE_PATTERNS
|
|
234
|
+
|
|
235
|
+
def __init__(self, client: TelegramClient, bot_username: str) -> None:
|
|
236
|
+
self._client = client
|
|
237
|
+
self._bot_username = bot_username
|
|
238
|
+
self._entity = None
|
|
239
|
+
# Learned per-bot behaviour (filled by the CLI from prefs.json):
|
|
240
|
+
# first_useful_delay: typical seconds until the bot sends something useful
|
|
241
|
+
# load_more_texts: button labels that proved to be "load more"
|
|
242
|
+
self.profile: dict = {}
|
|
243
|
+
# Measured during the last burst (read back by the CLI to learn):
|
|
244
|
+
self.last_first_useful_delay: Optional[float] = None
|
|
245
|
+
|
|
246
|
+
async def _get_entity(self):
|
|
247
|
+
if self._entity is None:
|
|
248
|
+
self._entity = await self._client.get_entity(self._bot_username)
|
|
249
|
+
return self._entity
|
|
250
|
+
|
|
251
|
+
@asynccontextmanager
|
|
252
|
+
async def _listen(self):
|
|
253
|
+
"""Register the message listeners BEFORE we send/click anything, so
|
|
254
|
+
a fast bot reply can never be missed. Yields a queue that receives
|
|
255
|
+
both new messages and in-place edits from the bot."""
|
|
256
|
+
entity = await self._get_entity()
|
|
257
|
+
queue: asyncio.Queue[Message] = asyncio.Queue()
|
|
258
|
+
|
|
259
|
+
async def _handler(event) -> None:
|
|
260
|
+
await queue.put(event.message)
|
|
261
|
+
|
|
262
|
+
new_ev = events.NewMessage(incoming=True, from_users=entity)
|
|
263
|
+
edit_ev = events.MessageEdited(incoming=True, from_users=entity)
|
|
264
|
+
self._client.add_event_handler(_handler, new_ev)
|
|
265
|
+
self._client.add_event_handler(_handler, edit_ev)
|
|
266
|
+
try:
|
|
267
|
+
yield queue
|
|
268
|
+
finally:
|
|
269
|
+
self._client.remove_event_handler(_handler, new_ev)
|
|
270
|
+
self._client.remove_event_handler(_handler, edit_ev)
|
|
271
|
+
|
|
272
|
+
@staticmethod
|
|
273
|
+
def _is_useful(messages: list[Message]) -> bool:
|
|
274
|
+
"""True once the burst contains something we can act on: a
|
|
275
|
+
playable video, or at least one clickable (callback) button."""
|
|
276
|
+
for m in messages:
|
|
277
|
+
if extract_media_info(m) is not None:
|
|
278
|
+
return True
|
|
279
|
+
for row in (m.buttons or []):
|
|
280
|
+
for btn in row:
|
|
281
|
+
if not _button_url(btn):
|
|
282
|
+
return True
|
|
283
|
+
return False
|
|
284
|
+
|
|
285
|
+
async def _drain(self, queue: "asyncio.Queue[Message]") -> list[Message]:
|
|
286
|
+
"""Collect a debounced burst of messages from `queue`.
|
|
287
|
+
|
|
288
|
+
Waits for the first message, then keeps collecting until a quiet
|
|
289
|
+
period passes with no new message. The quiet period is short once
|
|
290
|
+
we already have something useful, and much longer while we only
|
|
291
|
+
have ads/notices -- otherwise we would stop listening before the
|
|
292
|
+
bot sends the actual results. Edited messages replace the earlier
|
|
293
|
+
copy of the same message id.
|
|
294
|
+
"""
|
|
295
|
+
collected: list[Message] = []
|
|
296
|
+
loop = asyncio.get_event_loop()
|
|
297
|
+
started = loop.time()
|
|
298
|
+
deadline = started + MAX_WAIT_SECS
|
|
299
|
+
self.last_first_useful_delay = None
|
|
300
|
+
patient = self._patient_quiet_period()
|
|
301
|
+
|
|
302
|
+
def _add(msg: Message) -> None:
|
|
303
|
+
for i, old in enumerate(collected):
|
|
304
|
+
if old.id == msg.id:
|
|
305
|
+
collected[i] = msg
|
|
306
|
+
return
|
|
307
|
+
collected.append(msg)
|
|
308
|
+
|
|
309
|
+
try:
|
|
310
|
+
_add(await asyncio.wait_for(queue.get(), timeout=MAX_WAIT_SECS))
|
|
311
|
+
except asyncio.TimeoutError:
|
|
312
|
+
return collected
|
|
313
|
+
|
|
314
|
+
while True:
|
|
315
|
+
remaining = deadline - loop.time()
|
|
316
|
+
if remaining <= 0:
|
|
317
|
+
break
|
|
318
|
+
useful = self._is_useful(collected)
|
|
319
|
+
if useful and self.last_first_useful_delay is None:
|
|
320
|
+
self.last_first_useful_delay = loop.time() - started
|
|
321
|
+
quiet = QUIET_PERIOD_SECS if useful else patient
|
|
322
|
+
try:
|
|
323
|
+
_add(await asyncio.wait_for(queue.get(), timeout=min(quiet, remaining)))
|
|
324
|
+
except asyncio.TimeoutError:
|
|
325
|
+
break
|
|
326
|
+
|
|
327
|
+
if self.last_first_useful_delay is None and self._is_useful(collected):
|
|
328
|
+
self.last_first_useful_delay = loop.time() - started
|
|
329
|
+
return collected
|
|
330
|
+
|
|
331
|
+
def _patient_quiet_period(self) -> float:
|
|
332
|
+
"""How long to keep waiting while only ads/notices have arrived.
|
|
333
|
+
|
|
334
|
+
Starts at PATIENT_QUIET_PERIOD_SECS and, once we have learned how
|
|
335
|
+
slow this particular bot usually is, adapts to ~2x that delay
|
|
336
|
+
(never below 4s or above 15s)."""
|
|
337
|
+
learned = self.profile.get("first_useful_delay")
|
|
338
|
+
if isinstance(learned, (int, float)) and learned > 0:
|
|
339
|
+
return max(4.0, min(15.0, learned * 2))
|
|
340
|
+
return PATIENT_QUIET_PERIOD_SECS
|
|
341
|
+
|
|
342
|
+
@staticmethod
|
|
343
|
+
def _extract_buttons(message: Message) -> list[BotButton]:
|
|
344
|
+
buttons: list[BotButton] = []
|
|
345
|
+
if not message.buttons:
|
|
346
|
+
return buttons
|
|
347
|
+
for row_idx, row in enumerate(message.buttons):
|
|
348
|
+
for col_idx, btn in enumerate(row):
|
|
349
|
+
url = _button_url(btn)
|
|
350
|
+
is_url = bool(url)
|
|
351
|
+
data = getattr(btn, "data", None) if not is_url else None
|
|
352
|
+
buttons.append(
|
|
353
|
+
BotButton(
|
|
354
|
+
text=btn.text, row=row_idx, col=col_idx, is_url=is_url, url=url, data=data
|
|
355
|
+
)
|
|
356
|
+
)
|
|
357
|
+
return buttons
|
|
358
|
+
|
|
359
|
+
@staticmethod
|
|
360
|
+
def _build_result(messages: list[Message]) -> BotResult:
|
|
361
|
+
text_parts = [m.message for m in messages if getattr(m, "message", None)]
|
|
362
|
+
media: list[MediaInfo] = []
|
|
363
|
+
buttons: list[BotButton] = []
|
|
364
|
+
button_message: Optional[Message] = None
|
|
365
|
+
|
|
366
|
+
for m in messages:
|
|
367
|
+
info = extract_media_info(m)
|
|
368
|
+
if info is not None:
|
|
369
|
+
media.append(info)
|
|
370
|
+
|
|
371
|
+
# Buttons usually live on the last message that has any; later
|
|
372
|
+
# messages take priority as they represent the current UI state.
|
|
373
|
+
for m in messages:
|
|
374
|
+
btns = BotAdapter._extract_buttons(m)
|
|
375
|
+
if btns:
|
|
376
|
+
buttons = btns
|
|
377
|
+
button_message = m
|
|
378
|
+
|
|
379
|
+
if logger.isEnabledFor(logging.DEBUG):
|
|
380
|
+
# Structural-only diagnostic dump of every message in the burst
|
|
381
|
+
# (media AND non-media), so it's possible to verify whether a
|
|
382
|
+
# pagination control such as "Load More" was actually received
|
|
383
|
+
# from Telegram even when it lives on a message with no media.
|
|
384
|
+
# Never logs session/auth data, callback_data bytes, or content
|
|
385
|
+
# beyond a short text preview.
|
|
386
|
+
for m in messages:
|
|
387
|
+
text_preview = (getattr(m, "message", "") or "").strip()
|
|
388
|
+
if len(text_preview) > 60:
|
|
389
|
+
text_preview = text_preview[:57] + "..."
|
|
390
|
+
has_media = extract_media_info(m) is not None
|
|
391
|
+
has_markup = bool(getattr(m, "reply_markup", None))
|
|
392
|
+
btns = BotAdapter._extract_buttons(m)
|
|
393
|
+
logger.debug(
|
|
394
|
+
"MESSAGE id=%s media=%s text=%r has_reply_markup=%s buttons=%d",
|
|
395
|
+
m.id, has_media, text_preview, has_markup, len(btns),
|
|
396
|
+
)
|
|
397
|
+
for b in btns:
|
|
398
|
+
logger.debug(" [%d,%d] %r", b.row, b.col, b.text)
|
|
399
|
+
|
|
400
|
+
return BotResult(
|
|
401
|
+
messages=messages,
|
|
402
|
+
text="\n".join(text_parts),
|
|
403
|
+
buttons=buttons,
|
|
404
|
+
media=media,
|
|
405
|
+
_button_message=button_message,
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
async def search(self, text: str) -> BotResult:
|
|
409
|
+
"""Send a search query to the bot and collect its response burst."""
|
|
410
|
+
entity = await self._get_entity()
|
|
411
|
+
async with self._listen() as queue:
|
|
412
|
+
await _retry(lambda: self._client.send_message(entity, text))
|
|
413
|
+
messages = await self._drain(queue)
|
|
414
|
+
if not messages:
|
|
415
|
+
raise NoResultsError(
|
|
416
|
+
f"No response from {self._bot_username}. The bot may be offline "
|
|
417
|
+
"or the query produced no results."
|
|
418
|
+
)
|
|
419
|
+
return self._build_result(messages)
|
|
420
|
+
|
|
421
|
+
# Backwards-compatible alias (previous public API name).
|
|
422
|
+
async def query(self, text: str) -> BotResult:
|
|
423
|
+
return await self.search(text)
|
|
424
|
+
|
|
425
|
+
async def click(self, message: Message, button: BotButton) -> BotResult:
|
|
426
|
+
"""Click a specific button on a specific message and collect the
|
|
427
|
+
follow-up burst. This is the low-level primitive both normal
|
|
428
|
+
result-selection and LOAD_MORE pagination are built on."""
|
|
429
|
+
if button.is_url:
|
|
430
|
+
raise BotError("Cannot click a URL button; it is not a callback action.")
|
|
431
|
+
|
|
432
|
+
async with self._listen() as queue:
|
|
433
|
+
await _retry(lambda: message.click(button.row, button.col))
|
|
434
|
+
messages = await self._drain(queue)
|
|
435
|
+
if not messages:
|
|
436
|
+
# Some bots edit the existing message in place instead of
|
|
437
|
+
# sending a new one (e.g. appending more results, or replacing
|
|
438
|
+
# the results list with the video). Re-fetch to pick up edits.
|
|
439
|
+
refreshed = await self._client.get_messages(message.chat_id, ids=message.id)
|
|
440
|
+
messages = [refreshed] if refreshed else []
|
|
441
|
+
if not messages:
|
|
442
|
+
raise BotError("No response after selecting that option.")
|
|
443
|
+
return self._build_result(messages)
|
|
444
|
+
|
|
445
|
+
async def select(self, result: BotResult, button: BotButton) -> BotResult:
|
|
446
|
+
"""Click an inline keyboard button on `result`'s owning message.
|
|
447
|
+
|
|
448
|
+
Kept for backwards compatibility; prefer `select_result` /
|
|
449
|
+
`load_more` with a `ResultOption` where possible, since they carry
|
|
450
|
+
an explicit source message (correct even if a result spans
|
|
451
|
+
multiple messages).
|
|
452
|
+
"""
|
|
453
|
+
if result._button_message is None:
|
|
454
|
+
raise BotError("This result has no clickable buttons.")
|
|
455
|
+
return await self.click(result._button_message, button)
|
|
456
|
+
|
|
457
|
+
async def select_result(self, option: ResultOption) -> BotResult:
|
|
458
|
+
"""Select a normal (non-LOAD_MORE) result option."""
|
|
459
|
+
return await self.click(option.source_message, option.button)
|
|
460
|
+
|
|
461
|
+
async def load_more(self, option: ResultOption) -> BotResult:
|
|
462
|
+
"""Click the LOAD_MORE option to fetch the next page of results."""
|
|
463
|
+
return await self.click(option.source_message, option.button)
|
|
464
|
+
|
|
465
|
+
# ----------------------------------------------------------------
|
|
466
|
+
# Generic button classification
|
|
467
|
+
# ----------------------------------------------------------------
|
|
468
|
+
|
|
469
|
+
def is_load_more_button(self, button: BotButton, message_text: str) -> bool:
|
|
470
|
+
"""Decide whether `button` represents the semantic LOAD_MORE
|
|
471
|
+
action, using text patterns, callback data, and result-count
|
|
472
|
+
context -- never text matching alone as the only mechanism.
|
|
473
|
+
|
|
474
|
+
Conservative by design: ambiguous single-word buttons ("More")
|
|
475
|
+
only count as LOAD_MORE when corroborated by a progress indicator
|
|
476
|
+
in the message text or a pagination-flavored callback payload.
|
|
477
|
+
"""
|
|
478
|
+
if _RANGE_BUTTON_RE.match(button.text or ""):
|
|
479
|
+
return True
|
|
480
|
+
|
|
481
|
+
if (button.text or "").strip() in self.profile.get("load_more_texts", ()):
|
|
482
|
+
return True
|
|
483
|
+
|
|
484
|
+
normalized = _normalize_button_text(button.text)
|
|
485
|
+
|
|
486
|
+
for pattern in self.STRONG_LOAD_MORE_PATTERNS:
|
|
487
|
+
if pattern.search(normalized):
|
|
488
|
+
return True
|
|
489
|
+
|
|
490
|
+
is_weak_match = any(p.search(normalized) for p in self.WEAK_LOAD_MORE_PATTERNS)
|
|
491
|
+
|
|
492
|
+
callback_hint = False
|
|
493
|
+
if button.data:
|
|
494
|
+
try:
|
|
495
|
+
decoded = button.data.decode("utf-8", errors="ignore")
|
|
496
|
+
except Exception:
|
|
497
|
+
decoded = ""
|
|
498
|
+
callback_hint = bool(_CALLBACK_HINT_RE.search(decoded))
|
|
499
|
+
|
|
500
|
+
if is_weak_match:
|
|
501
|
+
if parse_progress(message_text) is not None:
|
|
502
|
+
return True
|
|
503
|
+
if callback_hint:
|
|
504
|
+
return True
|
|
505
|
+
return False
|
|
506
|
+
|
|
507
|
+
# No text match at all, but a strong callback-data hint plus a
|
|
508
|
+
# visible progress indicator is still a reasonably safe signal
|
|
509
|
+
# (some bots use empty/emoji-only labels).
|
|
510
|
+
if callback_hint and parse_progress(message_text) is not None:
|
|
511
|
+
return True
|
|
512
|
+
|
|
513
|
+
return False
|
|
514
|
+
|
|
515
|
+
def classify_buttons(
|
|
516
|
+
self, result: BotResult
|
|
517
|
+
) -> tuple[list[ResultOption], Optional[ResultOption]]:
|
|
518
|
+
"""Split a result's buttons into normal selectable options and, at
|
|
519
|
+
most, one LOAD_MORE option. URL buttons are ignored entirely (they
|
|
520
|
+
are not clickable bot actions).
|
|
521
|
+
"""
|
|
522
|
+
if not result.has_buttons or result._button_message is None:
|
|
523
|
+
return [], None
|
|
524
|
+
|
|
525
|
+
message = result._button_message
|
|
526
|
+
message_text = result.text
|
|
527
|
+
|
|
528
|
+
selectable: list[ResultOption] = []
|
|
529
|
+
load_more: Optional[ResultOption] = None
|
|
530
|
+
|
|
531
|
+
for button in result.buttons:
|
|
532
|
+
if not button.selectable:
|
|
533
|
+
continue
|
|
534
|
+
option = ResultOption(
|
|
535
|
+
identity=(message.chat_id, message.id, button.row, button.col),
|
|
536
|
+
button=button,
|
|
537
|
+
source_message=message,
|
|
538
|
+
)
|
|
539
|
+
if load_more is None and self.is_load_more_button(button, message_text):
|
|
540
|
+
load_more = option
|
|
541
|
+
continue
|
|
542
|
+
selectable.append(option)
|
|
543
|
+
|
|
544
|
+
return selectable, load_more
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
# `GenericBotAdapter` is the explicit, spec-facing name for the fallback
|
|
548
|
+
# adapter used for any bot without a dedicated subclass. It is identical to
|
|
549
|
+
# the base `BotAdapter` -- all of its logic is already bot-agnostic.
|
|
550
|
+
GenericBotAdapter = BotAdapter
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
class WeeCeeBotAdapter(BotAdapter):
|
|
554
|
+
"""Adapter for @weeceebot.
|
|
555
|
+
|
|
556
|
+
Observed workflow:
|
|
557
|
+
|
|
558
|
+
search query
|
|
559
|
+
-> first batch of results (as inline buttons)
|
|
560
|
+
-> "عرض 10 من 46 نتيجة" (progress text)
|
|
561
|
+
-> "⬇️ تحميل المزيد" (LOAD_MORE button)
|
|
562
|
+
-> more results appended
|
|
563
|
+
|
|
564
|
+
The exact button string is recognized here as one bot-specific rule,
|
|
565
|
+
layered on top of (not a replacement for) the generic detection in the
|
|
566
|
+
base class -- so this adapter keeps working even if @weeceebot tweaks
|
|
567
|
+
punctuation/emoji, and the same generic detection logic benefits any
|
|
568
|
+
other bot that happens to use similar phrasing.
|
|
569
|
+
"""
|
|
570
|
+
|
|
571
|
+
KNOWN_LOAD_MORE_TEXTS = {
|
|
572
|
+
"⬇️ تحميل المزيد",
|
|
573
|
+
"تحميل المزيد",
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
def is_load_more_button(self, button: BotButton, message_text: str) -> bool:
|
|
577
|
+
if (button.text or "").strip() in self.KNOWN_LOAD_MORE_TEXTS:
|
|
578
|
+
return True
|
|
579
|
+
return super().is_load_more_button(button, message_text)
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
# --------------------------------------------------------------------------
|
|
583
|
+
# Bot registry / factory
|
|
584
|
+
# --------------------------------------------------------------------------
|
|
585
|
+
|
|
586
|
+
BOT_ADAPTER_REGISTRY: dict[str, type[BotAdapter]] = {
|
|
587
|
+
"@weeceebot": WeeCeeBotAdapter,
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def _normalize_bot_username(name: str) -> str:
|
|
592
|
+
name = (name or "").strip()
|
|
593
|
+
if not name.startswith("@"):
|
|
594
|
+
name = "@" + name
|
|
595
|
+
return name.lower()
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def get_bot_adapter(client: TelegramClient, bot_username: str) -> BotAdapter:
|
|
599
|
+
"""Look up (or fall back to the generic) adapter for `bot_username`.
|
|
600
|
+
|
|
601
|
+
Adding support for a new bot later only requires adding one entry to
|
|
602
|
+
`BOT_ADAPTER_REGISTRY` (and, if it needs special-cased rules, a small
|
|
603
|
+
`BotAdapter` subclass) -- nothing else in the application needs to
|
|
604
|
+
change.
|
|
605
|
+
"""
|
|
606
|
+
key = _normalize_bot_username(bot_username)
|
|
607
|
+
adapter_cls = BOT_ADAPTER_REGISTRY.get(key, GenericBotAdapter)
|
|
608
|
+
return adapter_cls(client, bot_username)
|