-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtelegram_bot.py
More file actions
4395 lines (3625 loc) · 164 KB
/
telegram_bot.py
File metadata and controls
4395 lines (3625 loc) · 164 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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import time, threading
from datetime import datetime, time as dtime
import os, io, json, logging, math, re, asyncio
from functools import wraps
from pathlib import Path
from typing import Dict, Any, Tuple, List, Optional
import requests
from requests import HTTPError, RequestException
from requests.exceptions import HTTPError
from zoneinfo import ZoneInfo
from telegram import (
Update, InlineKeyboardButton, InlineKeyboardMarkup, InputFile, InputMediaPhoto, InputMediaDocument
)
from telegram.constants import ParseMode
from telegram.ext import (
Application, CommandHandler, ContextTypes, CallbackQueryHandler,
MessageHandler, filters
)
from telegram.error import BadRequest
import html as py_html
try:
from telegram.helpers import escape as tg_escape
except Exception:
def tg_escape(s):
return py_html.escape('' if s is None else str(s), quote=False)
try:
from dotenv import load_dotenv
for candidate in (
Path.cwd() / ".env",
Path(__file__).with_name(".env"),
Path(__file__).parent / "instance" / ".env",
):
if candidate.exists():
load_dotenv(candidate, override=False)
except Exception:
pass
BOT_VERSION = "wg-bot-1.1"
HERE = Path(__file__).parent.resolve()
INSTANCE_DIR = Path(os.getenv("PANEL_INSTANCE_PATH", HERE / "instance")).resolve()
INSTANCE_DIR.mkdir(parents=True, exist_ok=True)
TELEGRAM_SETTINGS_FILE = INSTANCE_DIR / "telegram_settings.json"
PANEL_SETTINGS_FILE = INSTANCE_DIR / "panel_settings.json"
RUNTIME_FILE = INSTANCE_DIR / "runtime.json"
_ENV_PANEL = (
os.getenv("PANEL_BASE_URL")
or os.getenv("PANEL")
or ""
).strip().rstrip("/")
def _load_json(path: Path) -> dict:
try:
with path.open("r", encoding="utf-8") as f:
return json.load(f) or {}
except Exception:
return {}
def _safe_int(v, default: int) -> int:
try:
i = int(v)
if 1 <= i <= 65535:
return i
except Exception:
pass
return default
def _detect_panel_base() -> str:
settings = _load_json(PANEL_SETTINGS_FILE)
runtime = _load_json(RUNTIME_FILE)
tls_on = bool(settings.get("tls_enabled"))
runtime_port = _safe_int(os.getenv("PORT") or runtime.get("port") or 8000, 8000)
https_port = _safe_int(settings.get("https_port") or 443, 443)
if _ENV_PANEL:
return _ENV_PANEL
if tls_on:
if runtime_port == https_port:
return f"https://127.0.0.1:{runtime_port}"
return f"http://127.0.0.1:{runtime_port}"
return f"http://127.0.0.1:{runtime_port}"
PANEL = _detect_panel_base().rstrip("/")
API_KEY = (os.getenv("PANEL_API_KEY") or os.getenv("API_KEY") or "").strip()
BOT_TOKEN = (
os.getenv("TG_BOT_TOKEN")
or os.getenv("TELEGRAM_BOT_TOKEN")
or ""
).strip()
def load_bot_token() -> str:
if BOT_TOKEN:
return BOT_TOKEN
try:
with open(TELEGRAM_SETTINGS_FILE, "r", encoding="utf-8") as f:
j = json.load(f)
return (j.get("bot_token") or "").strip()
except Exception:
return ""
api = requests.Session()
if API_KEY:
api.headers.update({
"Authorization": f"Bearer {API_KEY}",
"X-API-KEY": API_KEY,
})
# _________ Optional: session login (OFF by default)
USE_PANEL_SESSION = os.getenv("USE_PANEL_SESSION", "0") == "1"
PANEL_ADMIN_USER = os.getenv("PANEL_ADMIN_USER", "").strip()
PANEL_ADMIN_PASS = os.getenv("PANEL_ADMIN_PASS", "").strip()
sess = requests.Session()
def _login_session() -> None:
if not (PANEL_ADMIN_USER and PANEL_ADMIN_PASS):
raise RuntimeError("Session login requested but PANEL_ADMIN_USER/PASS not set")
g = sess.get(f"{PANEL}/login", timeout=10, allow_redirects=True)
g.raise_for_status()
csrf = sess.cookies.get("csrf_token", "")
if not csrf:
raise RuntimeError("No CSRF cookie from GET /login")
data = {"username": PANEL_ADMIN_USER, "password": PANEL_ADMIN_PASS, "csrf_token": csrf}
headers = {"Referer": f"{PANEL}/login"}
p = sess.post(f"{PANEL}/login", data=data, headers=headers, timeout=10, allow_redirects=False)
if p.status_code in (302, 303):
loc = p.headers.get("Location") or "/"
sess.get(f"{PANEL}{loc}", timeout=10, allow_redirects=True)
return
raise RuntimeError(f"Panel login failed: {p.status_code}")
def _login(func):
if not USE_PANEL_SESSION:
@wraps(func)
def _no_login(*args, **kwargs):
return func(*args, **kwargs)
return _no_login
@wraps(func)
def _wrap(*args, **kwargs):
try:
r = sess.get(f"{PANEL}/", timeout=6)
if r.status_code in (401, 403):
_login_session()
except Exception:
_login_session()
return func(*args, **kwargs)
return _wrap
_admin_cache = {"ids": set(), "ts": 0.0, "full": [], "ttl": 90.0}
def _fetch_admins() -> list[dict]:
try:
r = api.get(f"{PANEL}/api/telegram/admins", timeout=8)
r.raise_for_status()
return r.json().get("admins", []) or []
except Exception:
return []
def _refresh_admin(force: bool = False) -> None:
now = time.time()
if not force and (now - _admin_cache["ts"] < _admin_cache["ttl"]):
return
full = _fetch_admins()
ids = {str(a.get("id")) for a in full if a.get("id")}
_admin_cache.update({"ids": ids, "full": full, "ts": now})
def current_admin_ids() -> set[str]:
_refresh_admin()
return set(_admin_cache["ids"])
def current_admins_full() -> list[dict]:
_refresh_admin()
return list(_admin_cache["full"])
def recipients() -> Set[str]:
return {str(a["id"]) for a in current_admins_full() if not a.get("muted")}
def log_admin(uid: str, uname: str, action: str, details: str = ""):
try:
payload = {
"admin_id": str(uid or ""),
"admin_username": str(uname or ""),
"action": action,
"details": details,
"via": "telegram",
"channel": "telegram",
}
_post_soft(f"{PANEL}/api/admin_logs", session="api", json=payload)
except Exception:
pass
def _log_admin_update(update: "Update", action: str, details: str = ""):
try:
u = getattr(update, "effective_user", None)
uid = str(getattr(u, "id", "") or "")
uname = str(getattr(u, "username", "") or "")
log_admin(uid, uname, action, details)
try:
log_tg(uid, uname, action, details)
except Exception:
pass
except Exception:
pass
def _peer_details(*, pid=None, name=None, iface=None, scope=None, node=None,
created=None, count=None, base=None):
parts = []
if pid is not None: parts.append(f"peer_id={pid}")
if name: parts.append(f"name={name}")
if iface: parts.append(f"iface={iface}")
if scope: parts.append(f"scope={scope}")
if node: parts.append(f"node={node}")
if created is not None and count is not None:
parts.append(f"created={created}/{count}")
if base: parts.append(f"base={base}")
return "; ".join(parts)
def log_tg(uid: str, uname: str, action: str, details: str = ""):
try:
_post_soft(f"{PANEL}/api/telegram/admin_log", session="api", json={
"admin_id": str(uid or ""),
"admin_username": str(uname or ""),
"action": action,
"details": details,
})
except Exception:
pass
class PanelLogHandler(logging.Handler):
"""
Forwards Python logging records to the panel so they show up in Settings > Telegram > Logs.
"""
def __init__(self, admin_id="bot", admin_username="bot", level=logging.INFO):
super().__init__(level)
self.admin_id = str(admin_id)
self.admin_username = str(admin_username)
def emit(self, record: logging.LogRecord) -> None:
try:
msg = self.format(record)
sev = (record.levelname or "INFO").upper()
line = f"{sev}: {msg}"
log_tg(self.admin_id, self.admin_username, "log", line)
except Exception:
pass
def csrf_headers(extra: dict | None = None) -> dict:
tok = (sess.cookies.get("csrf_token") or "").strip()
hdr = {
"X-CSRFToken": tok,
"X-CSRF-Token": tok,
"Referer": PANEL,
}
if extra:
hdr.update(extra)
return hdr
async def _create_single_peer(panel_base, iface_id, payload, session="api"):
body = {**payload, "iface_id": int(iface_id)}
r = _post_soft(f"{panel_base}/api/peers", session=session, json=body)
j = _json_txt(r)
if isinstance(j, dict) and j.get("error"):
err = str(j.get("error"))
msg = str(j.get("message") or "")
summary += f"\n🧾 Server error: <code>{html(err)}</code>"
if msg:
summary += f"\n🧾 Details: <code>{html(msg)}</code>"
if isinstance(j, dict):
return j.get("id") or (j.get("peer") or {}).get("id")
return None
def _post_soft(url: str, session="auto", **kw):
timeout = kw.pop("timeout", 12)
if session == "api":
return api.post(url, timeout=timeout, **kw)
if session == "sess":
return sess.post(url, timeout=timeout, **kw)
if API_KEY:
try:
r = api.post(url, timeout=timeout, **kw)
r.raise_for_status()
return r
except HTTPError as e:
sc = getattr(getattr(e, "response", None), "status_code", None)
if sc not in (401, 403):
return e.response
except RequestException:
pass
return sess.post(url, timeout=timeout, **kw)
def _put_soft(url, **kw):
try:
return _put(url, **kw)
except HTTPError as e:
return e.response
except Exception:
timeout = kw.pop("timeout", 20)
try:
return sess.put(url, timeout=timeout, **kw)
except Exception as ee:
raise ee
def get_shortlink(pid: int) -> str:
try:
j = _get(f"{PANEL}/api/peer/{pid}/shortlink").json()
return j.get("url") or ""
except Exception:
return ""
def _peer_lines(p: Dict[str, Any]) -> str:
ttl = human_ttl(p.get("ttl_seconds"))
used_mib = int(p.get("used_bytes", 0)) / (1024 * 1024)
limit_val = p.get("data_limit") or p.get("data_limit_value") or 0
limit_unit = p.get("limit_unit") or p.get("data_limit_unit") or ""
unlimited = "Yes" if bool(p.get("unlimited")) else "No"
addr = p.get("address") or "—"
endpoint = p.get("endpoint") or "—"
rx = p.get("rx") or 0
tx = p.get("tx") or 0
iface = p.get("iface") or "—"
status = p.get("status") or "—"
return "\n".join([
f"🖧 <b>Interface</b>: {iface} • <b>Status</b>: {status}",
f"📌 <b>Address</b>: {addr}",
f"🌐 <b>Endpoint</b>: {endpoint}",
f"📦 <b>Used</b>: {used_mib:.2f} MiB • <b>TTL</b>: {ttl}",
f"🎚 <b>Limit</b>: {limit_val} {limit_unit} • <b>Unlimited</b>: {unlimited}",
f"⬇️ <b>RX</b>: {rx} MiB • ⬆️ <b>TX</b>: {tx} MiB",
])
def _peer_more_info(p: Dict[str, Any]) -> str:
def g(k, alt=None):
v = p.get(k, p.get(alt) if alt else None)
return "—" if v in (None, "", []) else str(v)
lines = [
f"👤 <b>{html(g('name'))}</b> (id {html(str(p.get('id')))} )",
f"🖧 <b>Interface</b>: {html(g('iface','interface'))} • <b>Status</b>: {html(str(p.get('status') or '—'))}",
f"📌 <b>Address</b>: {html(g('address', 'ip'))} • <b>MTU</b>: {html(g('mtu'))}",
f"🌐 <b>Endpoint</b>: {html(g('endpoint'))}",
f"🧷 <b>Public key</b>: <code>{html(g('public_key'))}</code>",
f"📅 <b>Created</b>: {html(g('created_at'))} • <b>First used</b>: {html(g('first_used'))}",
f"⏳ <b>Expires</b>: {html(g('expires_at'))} • <b>TTL</b>: {html(human_ttl(p.get('ttl_seconds')))}",
f"🎚 <b>Limit</b>: {html(str(p.get('data_limit_value') or p.get('data_limit') or 0))} {html(g('data_limit_unit','limit_unit'))} • <b>Unlimited</b>: { 'Yes' if p.get('unlimited') else 'No' }",
f"⬇️ RX: {html(str(p.get('rx') or 0))} MiB • ⬆️ TX: {html(str(p.get('tx') or 0))} MiB",
f"☎️ <b>Phone</b>: {html(g('phone_number'))} • <b>Telegram</b>: {html(g('telegram_id'))}",
f"🔧 <b>DNS</b>: {html(', '.join(p.get('dns')) if isinstance(p.get('dns'), list) else str(p.get('dns') or '—'))}",
]
return "\n".join(lines)
def scope_keyboard(prefix: str) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([
[InlineKeyboardButton("🖥 Local", callback_data=f"{prefix}:scope:local"),
InlineKeyboardButton("🌐 Node", callback_data=f"{prefix}:scope:node")],
[InlineKeyboardButton("⬅️ Back", callback_data="home")]
])
def _bundle_kb(p: Dict[str, Any]) -> InlineKeyboardMarkup:
"""Keyboard for the bundle card: no enable/disable here."""
pid = int(p.get("id"))
return InlineKeyboardMarkup([
[InlineKeyboardButton("🔁 Refresh", callback_data=f"peer:bundle:{pid}"),
InlineKeyboardButton("✏️ Edit", callback_data=f"peer:edit:{pid}")],
[InlineKeyboardButton("⬅️ Back", callback_data="peers:menu")]
])
def _html_pre(s: str) -> str:
return f"<pre><code>{html(s)}</code></pre>"
def _caption(p: Dict[str, Any], short_url: Optional[str], cfg: str) -> str:
name = p.get("name") or f"peer-{p.get('id')}"
iface = p.get("iface") or p.get("interface") or "—"
status = (p.get("status") or "—").lower()
address = p.get("address") or "—"
endpoint = p.get("endpoint") or "—"
used_mib = (int(p.get("used_bytes", 0)) / (1024 * 1024)) if str(p.get("used_bytes", "0")).isdigit() else 0
ttl = human_ttl(p.get("ttl_seconds")) if "human_ttl" in globals() else (p.get("ttl_seconds") or "—")
rx_mib = p.get("rx") or 0
tx_mib = p.get("tx") or 0
shortlnk = short_url or "—"
return (
f"📦 <b>{html(name)}</b> (id {html(str(p.get('id')))} )\n"
f"🖧 <b>Interface</b>: {html(str(iface))} • <b>Status</b>: {html(status)}\n"
f"📌 <b>Address</b>: {html(str(address))}\n"
f"🌐 <b>Endpoint</b>: {html(str(endpoint))}\n"
f"🔗 <b>Link</b>: {html(shortlnk)}\n"
f"📦 <b>Used</b>: {used_mib:.2f} MiB • <b>TTL</b>: {html(str(ttl))}\n"
f"⬇️ <b>RX</b>: {html(str(rx_mib))} MiB • ⬆️ <b>TX</b>: {html(str(tx_mib))} MiB"
)
MAX_CAPTION = 1024
def _cap_render(cfg_text: str, short: str | None) -> str:
shortline = f"🔗 Link: {tg_escape(short) if short else '—'}"
body = f"<pre><code>{tg_escape(cfg_text)}</code></pre>\n{shortline}"
return body if len(body) <= MAX_CAPTION else ""
async def send_peers(update: Update, pid: int):
p = peer_by_id(pid) if 'peer_by_id' in globals() else get_peer(pid)
if not p:
await edit_send(update, "Peer not found.", KB.peers_index())
return
name = p.get("name") or f"peer-{pid}"
cfg = _peer_config(pid) or ""
short = get_shortlink(pid) if 'get_shortlink' in globals() else None
png = _peer_qr(pid)
cfg_bytes = cfg.encode("utf-8")
if not cfg_bytes:
await edit_send(update, "⚠️ Config is empty.", KB.back(f"peer:open:{pid}"))
return
if not png:
await edit_send(update, "⚠️ QR image not available.", KB.back(f"peer:open:{pid}"))
return
conf_caption = _cap_render(cfg, short)
if conf_caption:
doc_msg = await update.effective_message.reply_document(
document=InputFile(io.BytesIO(cfg_bytes), filename=f"{name}.conf"),
caption=conf_caption,
parse_mode=ParseMode.HTML
)
else:
doc_msg = await update.effective_message.reply_document(
document=InputFile(io.BytesIO(cfg_bytes), filename=f"{name}.conf"),
caption=f"📄 <b>{tg_escape(name)}</b>.conf",
parse_mode=ParseMode.HTML
)
await doc_msg.reply_text(
f"<pre><code>{tg_escape(cfg)}</code></pre>\n🔗 Link: {tg_escape(short) if short else '—'}",
parse_mode=ParseMode.HTML
)
caption = _caption(p, short, cfg)
qr_msg = await doc_msg.reply_photo(
photo=InputFile(io.BytesIO(png), filename=f"{name}.png"),
caption=caption,
parse_mode=ParseMode.HTML
)
await qr_msg.reply_text("Controls:", reply_markup=_bundle_kb(p), parse_mode=ParseMode.HTML)
def _nonempty(val) -> bool:
return val is not None and str(val) != ""
def _for_skip(key: str, val, *, profile_mode: bool) -> bool:
if val is None:
return False
s = str(val).strip()
if s == "":
return False
if profile_mode and key in {"time_limit_days", "time_limit_hours"}:
if s in {"0", "0.0"}:
return False
return True
def _nonempty_bytes(b: bytes) -> bool:
return isinstance(b, (bytes, bytearray)) and len(b) > 0
def admin_only(func):
@wraps(func)
async def wrapper(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat = getattr(update, "effective_chat", None)
if chat and getattr(chat, "type", None) != "private":
try:
await context.bot.send_message(
chat_id=chat.id,
text="⛔️ For security, this bot only works in private chat. Please message me directly."
)
except Exception:
pass
return
uid = str(getattr(getattr(update, "effective_user", None), "id", "") or "")
ids = current_admin_ids()
if not uid or uid not in ids:
try:
await context.bot.send_message(
chat_id=update.effective_chat.id,
parse_mode="HTML",
text=("⛔️ You are not authorized.\n"
f"Your numeric ID is <code>{uid or 'unknown'}</code>.\n"
"Ask an admin to add this ID in Panel → Settings → Telegram.")
)
except Exception:
pass
return
return await func(update, context)
return wrapper
@admin_only
async def cmd_id(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_html(f"🆔 Your Telegram ID: <b>{update.effective_user.id}</b>")
@admin_only
async def cmd_admins(update: Update, context: ContextTypes.DEFAULT_TYPE):
rows = current_admins_full()
if not rows:
await update.message.reply_text("No admins configured in panel.")
return
lines = ["<b>Admins</b>"]
for a in rows:
u = f"@{a['username']}" if a.get("username") else ""
mute = "🔇" if a.get("muted") else "🔔"
note = f" — {a.get('note','')}" if a.get("note") else ""
lines.append(f"• <code>{a['id']}</code> {u} {mute}{note}")
await update.message.reply_html("\n".join(lines))
@admin_only
async def cmd_reload_admins(update: Update, context: ContextTypes.DEFAULT_TYPE):
_refresh_admin(force=True)
await update.message.reply_text("Admin list reloaded from panel.")
def html(s: str) -> str:
return s.replace("&","&").replace("<","<").replace(">",">")
def pre(txt: str) -> str:
return f"<pre>{html(txt.strip())}</pre>"
def _who(update):
u = getattr(update, "effective_user", None)
uid = str(getattr(u, "id", "") or "")
uname = getattr(u, "username", "") or ""
uline = f"@{uname}" if uname else "—"
return uid, uline
def _fmt_pct(v) -> str:
try:
return f"{float(v):.1f}%"
except Exception:
s = str(v).strip()
if not s:
return "—"
return s if s.endswith("%") else f"{s}%"
def _fmt_int(v, default=0) -> int:
try:
return int(v)
except Exception:
return default
def _fmt_uptime_from_stats(st: dict) -> str:
if st.get("uptime_str"):
return str(st["uptime_str"]).strip()
if "uptime_value" in st and "uptime_unit" in st:
return f"{st['uptime_value']}{st['uptime_unit']}"
secs = _fmt_int(st.get("uptime", 0), 0)
if secs <= 0:
return "—"
d = secs // 86400
h = (secs % 86400) // 3600
m = (secs % 3600) // 60
if d > 0:
return f"{d}d {h}h"
if h > 0:
return f"{h}h {m}m"
return f"{m}m"
def render_home(update) -> str:
uid, uline = _who(update)
try:
st = peer_stats() or {}
except Exception:
st = {}
cpu = _fmt_pct(st.get("cpu", "—"))
mem = _fmt_pct(st.get("mem", "—"))
disk = _fmt_pct(st.get("disk", "—"))
upt = _fmt_uptime_from_stats(st)
counts = st.get("counts") or {}
online = _fmt_int(counts.get("online", 0), 0)
offline = _fmt_int(counts.get("offline", 0), 0)
blocked = _fmt_int(counts.get("blocked", 0), 0)
total = online + offline + blocked
panel_url = str(PANEL or "").strip()
panel_line = f'<a href="{html(panel_url)}">{html(panel_url)}</a>' if panel_url else "—"
kpis = [
"📈 <b>System</b>",
f"• <b>CPU</b> <code>{html(cpu)}</code> <b>MEM</b> <code>{html(mem)}</code>",
f"• <b>DISK</b> <code>{html(disk)}</code> <b>UP</b> <code>{html(upt)}</code>",
"",
"👥 <b>Peers</b>",
f"• 🟢 <b>Online</b> <code>{online}</code> ⚪ <b>Offline</b> <code>{offline}</code>",
f"• ⛔ <b>Blocked</b> <code>{blocked}</code> 📌 <b>Total</b> <code>{total}</code>",
]
lines = [
"🏠 <b>Dashboard</b>",
f"👤 <b>{html(uline)}</b> <code>{html(uid)}</code>",
f"🌐 <b>Panel</b> {panel_line}",
"",
"━━━━━━━━━━━━━━━━━━━━",
*kpis,
"━━━━━━━━━━━━━━━━━━━━",
f"🤖 <b>Bot</b> <code>{html(BOT_VERSION)}</code>",
]
return "\n".join(lines)
def file_zip(b: bytes) -> bool:
return isinstance(b, (bytes, bytearray)) and b[:4] == b'PK\x03\x04'
def _safe_zip(r, label="backup"):
ct = (r.headers.get("content-type") or "").lower()
body = r.content
if not file_zip(body):
text = r.text[:400] if hasattr(r, "text") else ""
raise RuntimeError(f"{label} did not return a valid ZIP (content-type={ct}). "
f"Server said: {text or 'no text'}")
return body
def human_ttl(ttl: Optional[int]) -> str:
if not ttl: return "—"
d, r = divmod(ttl, 86400); h, r = divmod(r, 3600); m, _ = divmod(r, 60)
out = []
if d: out.append(f"{d}d")
if h: out.append(f"{h}h")
if m: out.append(f"{m}m")
return " ".join(out) or "0m"
async def edit_send(update: Update, text: str, kb=None):
m = update.callback_query.message if update.callback_query else update.effective_message
try:
await m.edit_text(text, parse_mode=ParseMode.HTML, reply_markup=kb)
except Exception:
await m.reply_text(text, parse_mode=ParseMode.HTML, reply_markup=kb)
async def send_text(update: Update, text: str, kb=None):
await (update.effective_message.reply_text(text, parse_mode=ParseMode.HTML, reply_markup=kb))
def _node_peer(p: dict) -> bool:
s = str(p.get("scope") or "").lower()
if s == "node": return True
if p.get("node_id") is not None: return True
if p.get("node"): return True
return False
def _peer_location(p: dict) -> str:
if not _node_peer(p):
return "🖥 Local"
nid = p.get("node_id")
nlab = p.get("node_name") or p.get("node") or (f"Node {nid}" if nid is not None else "Node")
return f"🌐 {nlab}"
FIELD_MAP = {
"keepalive": "persistent_keepalive",
}
def _payload_api(d: Dict[str, Any]) -> Dict[str, Any]:
out: Dict[str, Any] = {}
for k, v in (d or {}).items():
if v in ("", None):
continue
key = FIELD_MAP.get(k, k)
if key in ("data_limit_value", "persistent_keepalive", "time_limit_days", "time_limit_hours", "mtu"):
try:
out[key] = int(v)
except Exception:
continue
elif key in ("start_on_first_use", "unlimited"):
out[key] = bool(int(v)) if str(v).isdigit() else (str(v).lower() in ("true","yes","on","y"))
else:
out[key] = v
return out
def _edit_label(key: str) -> str:
for k, prompt, _ in EDIT_FIELDS:
if k == key:
clean = re.sub(r"\s*\(enter to skip\)\s*$", "", prompt, flags=re.I).strip()
return clean
return key.replace("_", " ").title()
def _bool01(v) -> str:
s = str(v).strip().lower()
if s in {"1","true","yes","on","y"}: return "1"
if s in {"0","false","no","off","n"}: return "0"
return "0" if s == "" else s
def _float(x):
try: return float(x)
except Exception: return None
def _current_value(peer: Dict[str, Any] | None, key: str) -> str:
def _peer_val(k):
if not peer: return None
if k == "data_limit_value":
return peer.get("data_limit_value", peer.get("data_limit"))
if k == "data_limit_unit":
return peer.get("data_limit_unit", peer.get("limit_unit"))
api_key = FIELD_MAP.get(k, k)
return peer.get(api_key, peer.get(k))
if key in {"start_on_first_use", "unlimited"}:
v = _peer_val(key)
if v is None: v = PANEL_DEFAULTS.get(key, 0)
return _bool01(v)
if key == "time_limit_days":
v_days = _peer_val("time_limit_days")
f = _float(v_days)
if f is not None:
if f < 0: f = 0.0
return str(int(math.floor(f)))
dv = PANEL_DEFAULTS.get("time_limit_days", 0)
return str(int(dv) if isinstance(dv, (int, float)) else 0)
if key == "time_limit_hours":
v_days = _peer_val("time_limit_days")
fd = _float(v_days)
if fd is not None:
if fd < 0: fd = 0.0
hrs = int(round((fd - math.floor(fd)) * 24))
return str(hrs)
v_hours = _peer_val("time_limit_hours")
try:
return str(int(v_hours))
except Exception:
dv = PANEL_DEFAULTS.get("time_limit_hours", 0)
return str(int(dv) if isinstance(dv, (int, float)) else 0)
v = _peer_val(key)
if v in (None, ""):
v = PANEL_DEFAULTS.get(key, "")
return "" if v is None else str(v)
def _get(url: str, session="auto", **kw):
timeout = kw.pop("timeout", 12)
if session == "api":
r = api.get(url, timeout=timeout, **kw)
r.raise_for_status()
return r
if session == "sess":
r = sess.get(url, timeout=timeout, **kw)
r.raise_for_status()
return r
if API_KEY:
try:
r = api.get(url, timeout=timeout, **kw)
r.raise_for_status()
return r
except HTTPError as e:
sc = getattr(getattr(e, "response", None), "status_code", None)
if sc not in (401, 403):
raise
except RequestException:
pass
r = sess.get(url, timeout=timeout, **kw)
r.raise_for_status()
return r
def _post(url: str, session="auto", **kw):
timeout = kw.pop("timeout", 20)
if session == "api":
r = api.post(url, timeout=timeout, **kw)
r.raise_for_status()
return r
if session == "sess":
h = kw.pop("headers", {})
h = {**csrf_headers(), **h}
r = sess.post(url, timeout=timeout, headers=h, **kw)
r.raise_for_status()
return r
if API_KEY:
try:
r = api.post(url, timeout=timeout, **kw)
r.raise_for_status()
return r
except HTTPError as e:
sc = getattr(getattr(e, "response", None), "status_code", None)
if sc not in (401, 403):
raise
except RequestException:
pass
h = kw.pop("headers", {})
h = {**csrf_headers(), **h}
r = sess.post(url, timeout=timeout, headers=h, **kw)
r.raise_for_status()
return r
def _put(url: str, session="auto", **kw):
timeout = kw.pop("timeout", 20)
if session == "api":
r = api.put(url, timeout=timeout, **kw)
r.raise_for_status()
return r
if session == "sess":
h = kw.pop("headers", {})
h = {**csrf_headers(), **h}
r = sess.put(url, timeout=timeout, headers=h, **kw)
r.raise_for_status()
return r
if API_KEY:
try:
r = api.put(url, timeout=timeout, **kw)
r.raise_for_status()
return r
except HTTPError as e:
sc = getattr(getattr(e, "response", None), "status_code", None)
if sc not in (401, 403):
raise
except RequestException:
pass
h = kw.pop("headers", {})
h = {**csrf_headers(), **h}
r = sess.put(url, timeout=timeout, headers=h, **kw)
r.raise_for_status()
return r
def _backup_schedule() -> dict:
try:
r = _get(f"{PANEL}/api/backup/schedule", session="auto", timeout=15)
return _json_txt(r) if r is not None else {}
except Exception as e:
logging.debug("Backup schedule fetch failed: %s", e)
return {}
def _epoch_iso_z(iso: str | None) -> int:
if not iso:
return 0
try:
return int(datetime.fromisoformat(iso.replace("Z", "+00:00")).timestamp())
except Exception:
return 0
def _bot_tz_schedule(sched: dict) -> ZoneInfo:
tzname = (sched.get("timezone") or "UTC").strip() or "UTC"
try:
return ZoneInfo(tzname)
except Exception:
return ZoneInfo("UTC")
def _set_backup_schedule(payload: dict) -> dict:
try:
r = _post(f"{PANEL}/api/backup/schedule", session="auto", json=payload, timeout=12)
return _json_txt(r)
except Exception:
return {"ok": False}
def kb_backup_schedule(s: dict) -> InlineKeyboardMarkup:
enabled = bool(s.get("enabled", False))
freq = str(s.get("freq") or "daily")
hhmm = str(s.get("time") or "03:00")
tz = str(s.get("timezone") or "UTC")
next_run = str(s.get("next_run") or "—")
return InlineKeyboardMarkup([
[InlineKeyboardButton("✅ Disable" if enabled else "✅ Enable", callback_data="backup:schedule:toggle")],
[InlineKeyboardButton("▶️ Run now (store)", callback_data="backup:schedule:run_now")],
[InlineKeyboardButton("🧪 Test in 2 minutes", callback_data="backup:schedule:test_2m")],
[InlineKeyboardButton("🔄 Refresh", callback_data="backup:schedule")],
[InlineKeyboardButton("⬅️ Back", callback_data="backup:menu")],
])
def _delete(url: str, session="auto", **kw):
timeout = kw.pop("timeout", 12)
if session == "api":
r = api.delete(url, timeout=timeout, **kw)
r.raise_for_status()
return r
if session == "sess":
h = kw.pop("headers", {})
h = {**csrf_headers(), **h}
r = sess.delete(url, timeout=timeout, headers=h, **kw)
r.raise_for_status()
return r
if API_KEY:
try:
r = api.delete(url, timeout=timeout, **kw)
r.raise_for_status()
return r
except HTTPError as e:
sc = getattr(getattr(e, "response", None), "status_code", None)
if sc not in (401, 403):
raise
except RequestException:
pass
h = kw.pop("headers", {})
h = {**csrf_headers(), **h}
r = sess.delete(url, timeout=timeout, headers=h, **kw)
r.raise_for_status()
return r
def list_nodes() -> list[dict]:
r = _get(f"{PANEL}/api/nodes", session="api")
j = _json_txt(r)
return j.get("nodes", []) if isinstance(j, dict) else []
def list_node_ifaces(nid: int) -> list[dict]:
r = _get(f"{PANEL}/api/nodes/{nid}/interfaces", session="api")
j = _json_txt(r)
return j.get("interfaces", j if isinstance(j, list) else [])
def _json_txt(r):
try:
return r.json()
except Exception:
return {"text": r.text}
def _json(resp):
ct = (resp.headers.get("content-type") or "").lower()
return ct.startswith("application/json")
def peer_enable(pid: int):
try:
r = _post(f"{PANEL}/api/peer/{pid}/enable", session="api")
return r.json() if _json(r) else {"ok": True}
except HTTPError as e:
sc = getattr(e.response, "status_code", None)
if sc in (400, 409, 503):
try:
p = get_peer(pid) or {}
iid = p.get("iface_id")
if not iid:
for i in (peer_ifaces() or []):
if str(i.get("name")) == str(p.get("iface")):
iid = int(i["id"])
break
if iid:
_post(f"{PANEL}/api/iface/{iid}/enable", session="api")
r2 = _post(f"{PANEL}/api/peer/{pid}/enable", session="api")
return r2.json() if _json(r2) else {"ok": True}
except Exception:
pass
raise
def peer_disable(pid: int):
r = _post(f"{PANEL}/api/peer/{pid}/disable", session="api")
return r.json() if _json(r) else {"ok": True}