-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcommands.py
More file actions
847 lines (672 loc) · 26.3 KB
/
commands.py
File metadata and controls
847 lines (672 loc) · 26.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
# -*- coding: utf-8 -*-
# Guillermo Siesto
# github.com/GSiesto
"""Telegram command and callback handlers for MCServerStatBot."""
from __future__ import annotations
import asyncio
import os
import logging
import re
from collections import deque
from collections.abc import Sequence
from typing import Any, cast
from dataclasses import dataclass, replace
from datetime import datetime, timezone
from enum import Enum
from functools import lru_cache
from mcstatus import JavaServer
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.constants import ChatAction
from telegram.error import BadRequest
from telegram.ext import ContextTypes
from telegram.helpers import escape_markdown
import utils
__all__ = [
"cmd_start",
"cmd_status",
"cmd_players",
"cb_status",
"cb_players",
"cb_about",
"CallbackData",
]
logger = logging.getLogger(__name__)
DEFAULT_TIMEOUT = 3.0 # seconds
MAX_PLAYER_NAMES_DISPLAY = 25
AFFILIATE_URL_ENV = "AFFILIATE_URL"
AFFILIATE_LABEL_ENV = "AFFILIATE_LABEL"
AFFILIATE_BLURB_ENV = "AFFILIATE_BLURB"
MESSAGE_CONTEXT_KEY = "message_context"
MESSAGE_CONTEXT_ORDER_KEY = "message_context_order"
MESSAGE_CONTEXT_LIMIT = 20
DEFAULT_AFFILIATE_LABEL = "Create your own MC server"
DEFAULT_AFFILIATE_BLURB = "Sponsored by our hosting partner\nClick to support the bot!"
DEVELOPER_CHANNEL_URL = "https://t.me/GSiesto"
DEVELOPER_HANDLE = "@GSiesto"
class CallbackData(str, Enum):
"""Canonical callback data keys for inline buttons."""
STATUS = "pattern_status"
PLAYERS = "pattern_players"
ABOUT = "pattern_about"
WELCOME_TEXT = (
"👋 *Welcome to MCServerStatBot!*\n"
"I can check Minecraft Java servers for uptime, ping, and connected players.\n\n"
"*Try these commands:*\n"
"• `/status play.example.com`\n"
"• `/players play.example.com`\n\n"
"Run those commands anytime, each result includes inline buttons for quick refreshes."
)
STATUS_HINT_TEXT = (
"ℹ️ *How to check a server*\n"
"Start with `/status host.example.com` to pick a server, then use the buttons to refresh the results."
)
PLAYERS_HINT_TEXT = (
"ℹ️ *How to list players*\n"
"Run `/players host.example.com` first; once the bot has a server, the buttons can refresh the player list."
)
ABOUT_TEXT = (
"🤖 *MCServerStatBot*\n"
"• Built for quick Minecraft Java status checks\n"
"• Shows latency, MOTD, version, and players\n\n"
f"✉️ Chat with the developer: [{DEVELOPER_HANDLE}]({DEVELOPER_CHANNEL_URL})\n"
"📌 Follow updates and share feedback in the channel."
)
@dataclass(slots=True)
class ServerSnapshot:
"""Immutable summary of the current server state."""
address: str
fetched_at: datetime
description: str
version_name: str
latency_ms: int
players_online: int
players_max: int
player_names: tuple[str, ...]
query_available: bool
query_error: str | None
@dataclass(slots=True)
class MessageContextEntry:
"""Per-message context allowing callbacks to recover address and cached data."""
address: str | None
snapshot: ServerSnapshot | None
# ==========================
# Helper utilities
# ==========================
def _clean_description(raw_description: object | None) -> str:
"""Remove colour codes and return a safe server description string."""
if raw_description is None:
return "No description provided."
if isinstance(raw_description, dict):
text = raw_description.get("text") or ""
else:
text = str(raw_description)
text = re.sub(r"§.", "", text)
text = text.strip()
return text or "No description provided."
def _extract_player_names_from_status(status: object) -> tuple[str, ...]:
players = getattr(status, "players", None)
sample = getattr(players, "sample", None)
if not sample:
return tuple()
names: list[str] = []
for entry in sample:
name = getattr(entry, "name", None)
if name is None and isinstance(entry, dict):
name = entry.get("name")
if name:
names.append(str(name))
return tuple(names)
def build_main_keyboard() -> InlineKeyboardMarkup:
"""Create the primary inline keyboard with fresh button instances."""
rows: list[list[InlineKeyboardButton]] = [
[
InlineKeyboardButton("Status", callback_data=CallbackData.STATUS.value),
InlineKeyboardButton("Players", callback_data=CallbackData.PLAYERS.value),
InlineKeyboardButton("About", callback_data=CallbackData.ABOUT.value),
]
]
affiliate_button = _affiliate_button()
if affiliate_button:
rows.append([affiliate_button])
return InlineKeyboardMarkup(rows)
@lru_cache(maxsize=1)
def _get_affiliate_config() -> tuple[str, str, str] | None:
url = (os.getenv(AFFILIATE_URL_ENV) or "").strip()
if not url:
return None
label = (os.getenv(AFFILIATE_LABEL_ENV) or DEFAULT_AFFILIATE_LABEL).strip() or DEFAULT_AFFILIATE_LABEL
blurb = (os.getenv(AFFILIATE_BLURB_ENV) or DEFAULT_AFFILIATE_BLURB).strip() or DEFAULT_AFFILIATE_BLURB
return url, label, blurb
def _affiliate_button() -> InlineKeyboardButton | None:
config = _get_affiliate_config()
if not config:
return None
url, label, _ = config
return InlineKeyboardButton(f"🙌 {label}", url=url)
def _affiliate_hint() -> str | None:
config = _get_affiliate_config()
if not config:
return None
_, _, blurb = config
safe_blurb = escape_markdown(blurb, version=1)
return f"🙌 {safe_blurb}"
def _chat_data(context: ContextTypes.DEFAULT_TYPE) -> dict[str, Any]:
return cast(dict[str, Any], context.chat_data)
def _clear_last_context(chat_data: dict[str, Any]) -> None:
chat_data.pop("last_address", None)
chat_data.pop("last_snapshot", None)
def _store_message_snapshot(
context: ContextTypes.DEFAULT_TYPE,
message_id: int,
snapshot: ServerSnapshot | None,
*,
address: str | None = None,
) -> None:
chat_data = _chat_data(context)
store = cast(dict[int, MessageContextEntry], chat_data.setdefault(MESSAGE_CONTEXT_KEY, {}))
order = cast(deque[int], chat_data.setdefault(MESSAGE_CONTEXT_ORDER_KEY, deque()))
entry = MessageContextEntry(address=address or (snapshot.address if snapshot else None), snapshot=snapshot)
if message_id in store:
store[message_id] = entry
try:
order.remove(message_id)
except ValueError:
pass
else:
store[message_id] = entry
order.append(message_id)
while len(order) > MESSAGE_CONTEXT_LIMIT:
old_id = order.popleft()
store.pop(old_id, None)
def _get_message_context(
context: ContextTypes.DEFAULT_TYPE, message_id: int
) -> MessageContextEntry | None:
chat_data = _chat_data(context)
store = cast(dict[int, MessageContextEntry] | None, chat_data.get(MESSAGE_CONTEXT_KEY))
if not store:
return None
entry = store.get(message_id)
if isinstance(entry, MessageContextEntry):
return entry
if isinstance(entry, ServerSnapshot): # legacy compatibility
converted = MessageContextEntry(address=entry.address, snapshot=entry)
store[message_id] = converted
return converted
return None
async def _run_in_thread(func, *args, timeout: float = DEFAULT_TIMEOUT):
return await asyncio.wait_for(asyncio.to_thread(func, *args), timeout=timeout)
async def _lookup_server(address: str) -> JavaServer:
return await _run_in_thread(JavaServer.lookup, address)
async def _fetch_status(server: JavaServer):
return await _run_in_thread(server.status)
async def _fetch_query(server: JavaServer):
return await _run_in_thread(server.query)
async def _send_typing(context: ContextTypes.DEFAULT_TYPE, chat_id: int) -> None:
await context.bot.send_chat_action(chat_id=chat_id, action=ChatAction.TYPING)
async def _build_snapshot(address: str, *, include_query: bool) -> ServerSnapshot:
server = await _lookup_server(address)
status = await _fetch_status(server)
description = _clean_description(getattr(status, "description", None))
version_name = str(getattr(getattr(status, "version", None), "name", "Unknown"))
latency_ms = int(round(getattr(status, "latency", 0) or 0))
players = getattr(status, "players", None)
online = int(getattr(players, "online", 0) or 0)
maximum = int(getattr(players, "max", 0) or 0)
player_names: tuple[str, ...] = _extract_player_names_from_status(status)
query_available = False
query_error: str | None = None
if include_query:
try:
query = await _fetch_query(server)
names = getattr(getattr(query, "players", None), "names", None)
if names:
player_names = tuple(sorted(str(name) for name in names))
query_available = True
except Exception as exc: # pragma: no cover - network failures
query_error = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__
logger.info("Query failed for %s (%s)", address, query_error)
logger.debug("Query failure details for %s", address, exc_info=exc)
query_available = False
return ServerSnapshot(
address=address,
fetched_at=datetime.now(timezone.utc),
description=description,
version_name=version_name,
latency_ms=latency_ms,
players_online=online,
players_max=maximum,
player_names=player_names,
query_available=query_available,
query_error=query_error,
)
def _format_player_names(names: Sequence[str]) -> str:
if not names:
return "`No players listed`"
trimmed = list(names[:MAX_PLAYER_NAMES_DISPLAY])
escaped = [f"`{escape_markdown(name, version=1)}`" for name in trimmed]
lines: list[str] = []
for idx in range(0, len(escaped), 5):
lines.append(" ".join(escaped[idx : idx + 5]))
remaining = len(names) - len(trimmed)
if remaining > 0:
lines.append(f"`…and {remaining} more`")
return "\n".join(lines)
def _status_message(snapshot: ServerSnapshot) -> str:
safe_address = escape_markdown(snapshot.address, version=1)
description = escape_markdown(snapshot.description, version=1)
version_name = escape_markdown(snapshot.version_name, version=1)
fetched = escape_markdown(snapshot.fetched_at.strftime("%Y-%m-%d %H:%M:%SZ"), version=1)
base = (
"✅ *Server Online*\n"
f"🌐 `{safe_address}`\n"
f"🕒 Checked: {fetched}\n\n"
"📝 *Description*\n"
f"_{description}_\n\n"
f"📦 *Version:* {version_name}\n"
f"📶 *Ping:* {snapshot.latency_ms} ms\n"
f"👥 *Players:* {snapshot.players_online}/{snapshot.players_max}"
)
return _message_with_affiliate_hint(base)
def _players_message(snapshot: ServerSnapshot) -> str:
safe_address = escape_markdown(snapshot.address, version=1)
header = (
"👥 *Players Online*\n"
f"🌐 `{safe_address}`\n"
f"🟢 Currently: {snapshot.players_online} / {snapshot.players_max} players"
)
if snapshot.player_names:
formatted_names = _format_player_names(snapshot.player_names)
parts = [header, "", formatted_names]
if not snapshot.query_available:
parts.extend(
[
"",
"ℹ️ _Showing the limited sample returned by the status ping; the server may not expose its full player list._",
]
)
return _message_with_affiliate_hint("\n".join(parts))
return _players_fallback_message(snapshot)
def _players_fallback_message(snapshot: ServerSnapshot) -> str:
safe_address = escape_markdown(snapshot.address, version=1)
lines = [
"👥 Players Online",
f"🌐 {safe_address}",
f"🟢 Currently: {snapshot.players_online} / {snapshot.players_max} players",
"",
"⚠️ This server has queries disabled, so individual player names aren't available.",
]
if snapshot.query_error:
safe_error = escape_markdown(snapshot.query_error, version=1)
lines.extend(
[
"",
f"ℹ️ Query failed with: {safe_error}",
]
)
return _message_with_affiliate_hint("\n".join(lines))
async def _send_status_message(
context: ContextTypes.DEFAULT_TYPE, chat_id: int, snapshot: ServerSnapshot
) -> None:
message = await context.bot.send_message(
chat_id=chat_id,
text=_status_message(snapshot),
reply_markup=build_main_keyboard(),
disable_web_page_preview=True,
)
_store_message_snapshot(context, message.message_id, snapshot)
async def _send_players_message(
context: ContextTypes.DEFAULT_TYPE, chat_id: int, snapshot: ServerSnapshot
) -> None:
message = await context.bot.send_message(
chat_id=chat_id,
text=_players_message(snapshot),
reply_markup=build_main_keyboard(),
disable_web_page_preview=True,
)
_store_message_snapshot(context, message.message_id, snapshot)
# ==========================
# Commands
# ==========================
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Usage: /start"""
if not update.effective_chat or not update.message:
return
chat_id = update.effective_chat.id
_chat_data(context).clear()
await _send_typing(context, chat_id)
affiliate_button = _affiliate_button()
affiliate_markup = InlineKeyboardMarkup([[affiliate_button]]) if affiliate_button else None
await update.message.reply_text(
_message_with_affiliate_hint(WELCOME_TEXT),
reply_markup=affiliate_markup,
disable_web_page_preview=True,
)
async def cmd_status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Usage: /status <host[:port]>"""
if not update.effective_chat or not update.message:
return
chat_id = update.effective_chat.id
await _send_typing(context, chat_id)
logger.info("/status called")
chat_data = _chat_data(context)
args = context.args or []
if len(args) != 1:
_clear_last_context(chat_data)
await error_incomplete(context, chat_id)
logger.info("/status did not provide an address")
return
address = args[0].strip()
if not utils.is_valid_server_address(address):
_clear_last_context(chat_data)
await error_url(context, chat_id, address)
logger.info("Invalid server address supplied for /status")
return
chat_data["last_address"] = address
chat_data.pop("last_snapshot", None)
try:
snapshot = await _build_snapshot(address, include_query=False)
except (asyncio.TimeoutError, OSError) as exc: # pragma: no cover - network failures
await error_status(context, chat_id, address)
logger.exception(exc)
chat_data.pop("last_address", None)
return
chat_data["last_address"] = snapshot.address
chat_data["last_snapshot"] = snapshot
await _send_status_message(context, chat_id, snapshot)
logger.info("/status %s online", address)
async def cmd_players(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Usage: /players <host[:port]>"""
if not update.effective_chat or not update.message:
return
chat_id = update.effective_chat.id
await _send_typing(context, chat_id)
logger.info("/players called")
chat_data = _chat_data(context)
args = context.args or []
if len(args) != 1:
_clear_last_context(chat_data)
await error_incomplete(context, chat_id)
logger.info("/players did not provide an address")
return
address = args[0].strip()
if not utils.is_valid_server_address(address):
_clear_last_context(chat_data)
await error_url(context, chat_id, address)
logger.info("Invalid server address supplied for /players")
return
chat_data["last_address"] = address
chat_data.pop("last_snapshot", None)
try:
snapshot = await _build_snapshot(address, include_query=True)
except (asyncio.TimeoutError, OSError) as exc: # pragma: no cover - network failures
await error_status(context, chat_id, address)
logger.exception(exc)
chat_data.pop("last_address", None)
return
chat_data["last_address"] = snapshot.address
chat_data["last_snapshot"] = snapshot
await _send_players_message(context, chat_id, snapshot)
logger.info("/players %s online", address)
# ==========================
# Callbacks
# ==========================
async def cb_status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the 'Status' inline button press."""
logger.info("Callback status called")
query = update.callback_query
if not query or not update.effective_chat:
return
message = query.message
if not message:
await query.answer()
return
message_id = message.message_id
chat_data = _chat_data(context)
entry = _get_message_context(context, message_id)
if entry:
address = entry.address
previous_snapshot = entry.snapshot
else:
address = cast(str | None, chat_data.get("last_address"))
previous_snapshot = cast(ServerSnapshot | None, chat_data.get("last_snapshot"))
if not address:
chat_data.pop("last_address", None)
chat_data.pop("last_snapshot", None)
try:
await query.edit_message_text(
_message_with_affiliate_hint(STATUS_HINT_TEXT),
reply_markup=build_main_keyboard(),
disable_web_page_preview=True,
)
except BadRequest as exc:
if "Message is not modified" in str(exc):
await asyncio.sleep(0.5)
else:
raise
_store_message_snapshot(context, message_id, None, address=None)
await query.answer()
return
fallback_notice: str | None = None
try:
snapshot = await _build_snapshot(address, include_query=False)
_store_message_snapshot(context, message_id, snapshot)
chat_data["last_snapshot"] = snapshot
chat_data["last_address"] = snapshot.address
except (asyncio.TimeoutError, OSError) as exc: # pragma: no cover - network failures
logger.exception(exc)
if previous_snapshot:
snapshot = previous_snapshot
_store_message_snapshot(context, message_id, snapshot)
chat_data["last_snapshot"] = snapshot
chat_data["last_address"] = snapshot.address
fallback_notice = "⚠️ _Showing cached data because the server timed out._"
else:
await error_status_edit(update, context, address)
await query.answer()
return
try:
message_text = _status_message(snapshot)
if fallback_notice:
message_text = f"{message_text}\n\n{fallback_notice}"
await query.edit_message_text(
message_text,
reply_markup=build_main_keyboard(),
disable_web_page_preview=True,
)
except BadRequest as exc:
if "Message is not modified" in str(exc):
await asyncio.sleep(0.5)
await query.answer()
return
else:
raise
await query.answer()
async def cb_players(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the 'Players' inline button press."""
logger.info("Callback players called")
query = update.callback_query
if not query or not update.effective_chat:
return
message = query.message
if not message:
await query.answer()
return
message_id = message.message_id
chat_data = _chat_data(context)
entry = _get_message_context(context, message_id)
if entry:
address = entry.address
previous_snapshot = entry.snapshot
else:
address = cast(str | None, chat_data.get("last_address"))
previous_snapshot = cast(ServerSnapshot | None, chat_data.get("last_snapshot"))
if not address:
chat_data.pop("last_address", None)
chat_data.pop("last_snapshot", None)
try:
await query.edit_message_text(
_message_with_affiliate_hint(PLAYERS_HINT_TEXT),
reply_markup=build_main_keyboard(),
disable_web_page_preview=True,
)
except BadRequest as exc:
if "Message is not modified" in str(exc):
await asyncio.sleep(0.5)
else:
raise
_store_message_snapshot(context, message_id, None, address=None)
await query.answer()
return
try:
snapshot = await _build_snapshot(address, include_query=True)
_store_message_snapshot(context, message_id, snapshot)
chat_data["last_snapshot"] = snapshot
chat_data["last_address"] = snapshot.address
message_text = _players_message(snapshot)
except (asyncio.TimeoutError, OSError) as exc: # pragma: no cover - network failures
logger.exception(exc)
if previous_snapshot:
error_detail = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__
snapshot = replace(
previous_snapshot,
fetched_at=datetime.now(timezone.utc),
player_names=tuple(),
query_available=False,
query_error=error_detail,
)
_store_message_snapshot(context, message_id, snapshot)
chat_data["last_snapshot"] = snapshot
chat_data["last_address"] = snapshot.address
message_text = _players_fallback_message(snapshot)
else:
await error_players_edit(update, context, address)
await query.answer()
return
try:
await query.edit_message_text(
message_text,
reply_markup=build_main_keyboard(),
disable_web_page_preview=True,
)
except BadRequest as exc:
if "Message is not modified" in str(exc):
await asyncio.sleep(0.5)
await query.answer()
return
else:
raise
await query.answer()
async def cb_about(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the 'About' inline button press."""
logger.info("Callback about called")
query = update.callback_query
if not query:
return
try:
await query.edit_message_text(
_message_with_affiliate_hint(ABOUT_TEXT),
reply_markup=build_main_keyboard(),
)
except BadRequest as exc:
if "Message is not modified" in str(exc):
await asyncio.sleep(0.5)
await query.answer()
else:
raise
await query.answer()
# ==========================
# Error helpers
# ==========================
async def error_status(context: ContextTypes.DEFAULT_TYPE, chat_id: int, address: str) -> None:
safe_address = escape_markdown(address, version=1)
chat_data = _chat_data(context)
chat_data.pop("last_address", None)
chat_data.pop("last_snapshot", None)
message = await context.bot.send_message(
chat_id=chat_id,
text=(
"❌ *Server Offline*\n"
f"🌐 `{safe_address}`\n"
"⚙️ _Could not connect to the server._"
),
reply_markup=build_main_keyboard(),
)
_store_message_snapshot(context, message.message_id, None, address=None)
async def error_status_edit(
update: Update, context: ContextTypes.DEFAULT_TYPE, address: str
) -> None:
if not update.callback_query:
return
safe_address = escape_markdown(address, version=1)
chat_data = _chat_data(context)
chat_data.pop("last_address", None)
chat_data.pop("last_snapshot", None)
message = update.callback_query.message
await update.callback_query.edit_message_text(
text=(
"❌ *Server Offline*\n"
f"🌐 `{safe_address}`\n"
"⚙️ _Could not connect to the server._"
),
reply_markup=build_main_keyboard(),
)
if message:
_store_message_snapshot(context, message.message_id, None, address=None)
async def error_players_edit(
update: Update, context: ContextTypes.DEFAULT_TYPE, address: str
) -> None:
if not update.callback_query:
return
safe_address = escape_markdown(address, version=1)
chat_data = _chat_data(context)
chat_data.pop("last_address", None)
chat_data.pop("last_snapshot", None)
message = update.callback_query.message
await update.callback_query.edit_message_text(
text=(
"⚠️ *Request Failed*\n"
f"🌐 `{safe_address}`\n"
"⚙️ _Could not connect to the server._\n"
"🔒 _This server might have queries disabled._"
),
reply_markup=build_main_keyboard(),
)
if message:
_store_message_snapshot(context, message.message_id, None, address=None)
async def error_url(context: ContextTypes.DEFAULT_TYPE, chat_id: int, address: str) -> None:
safe_address = escape_markdown(address, version=1)
chat_data = _chat_data(context)
chat_data.pop("last_address", None)
chat_data.pop("last_snapshot", None)
message = await context.bot.send_message(
chat_id=chat_id,
text=(
"⚠️ *Invalid server address*\n"
f"`{safe_address}`\n\n"
"Please provide a hostname like:\n"
"• `play.minecraft.net`\n"
"• `minecraftgame.org`"
),
reply_markup=build_main_keyboard(),
)
_store_message_snapshot(context, message.message_id, None, address=None)
async def error_incomplete(context: ContextTypes.DEFAULT_TYPE, chat_id: int) -> None:
chat_data = _chat_data(context)
chat_data.pop("last_address", None)
chat_data.pop("last_snapshot", None)
message = await context.bot.send_message(
chat_id=chat_id,
text=(
"ℹ️ *Server address required*\n"
"Use the command like this:\n"
"• `/status play.minecraft.net`\n"
"• `/players minecraftgame.org:25565`"
),
reply_markup=build_main_keyboard(),
)
_store_message_snapshot(context, message.message_id, None, address=None)
def _message_with_affiliate_hint(message: str) -> str:
hint = _affiliate_hint()
if not hint:
return message
return f"{message}\n\n{hint}"