from __future__ import annotations
import html
import io
import json
import mimetypes
import os
import re
import sys
import time
import urllib.error
import urllib.request
import uuid
from typing import Any
import qrcode
from app.core.audit import list_audit_page, write_audit
from app.core.helper import HelperError, run_helper
from app.core.settings import WG_INTERFACE
from app.core.preferences import get_preferences
from app.core.telegram_config import (
get_telegram_settings,
init_telegram_settings,
set_default_endpoint,
set_update_offset,
telegram_api_call,
update_telegram_runtime,
)
PENDING: dict[int, dict[str, Any]] = {}
SELECTED_INTERFACES: dict[int, str] = {}
BOT_TEXT = {"pl": {'audit': 'đź§ľ Audyt',
'audit_title': 'đź§ľ Historia audytu',
'audit_empty': 'Brak wpisĂłw audytu.',
'audit_older': '➡️',
'audit_newer': '⬅️',
'audit_footer': 'Wpisy sÄ… przechowywane przez 30 dni.',
'audit_bad_cursor': 'Ta strona audytu jest niedostępna. Otwórz najnowsze wpisy.',
'interface': 'đź§© Interfejs',
'server': 'âš™ Serwer',
'server_controls': 'Serwer WireGuard · {interface}\nWybierz działanie:',
'choose_interface': 'Wybierz interfejs WireGuard:',
'interface_selected': 'Wybrano interfejs: {name}',
'welcome': 'Sterowanie Telegram jest gotowe. Wybierz działanie:',
'private_only': 'Ze względów bezpieczeństwa bot działa tylko w prywatnej rozmowie.',
'denied': 'Brak dostępu. Twój identyfikator Telegram: {user_id}\nDodaj go w ustawieniach bota Telegram.',
'menu': 'Menu główne',
'status': '📊 Stan serwera',
'clients': '👥 Klienci',
'create': 'âž• Dodaj klienta',
'delete': '➖ Usuń klienta',
'configs': 'đź“„ Konfiguracje',
'choose_config': 'Wybierz klienta. 📄 = konfiguracja dostępna, 🔒 = starszy klient bez zapisanego klucza '
'prywatnego.',
'no_configs': 'Brak skonfigurowanych klientĂłw.',
'legacy_config_unavailable': '🔒 Nie można odtworzyć konfiguracji starszego klienta bez jego klucza '
'prywatnego. Plik .conf i kod QR można wydać ponownie tylko dla klientów '
'utworzonych w panelu.',
'sending_config': 'Przygotowywanie konfiguracji: {name}…',
'config_sent': '✅ Wysłano konfigurację: {name}',
'start': 'Uruchom',
'restart': 'Uruchom ponownie',
'stop': 'Zatrzymaj',
'cancel': 'Anuluj',
'back': '⬅️ Menu',
'running': 'Działa',
'stopped': 'Zatrzymany',
'online': 'online',
'offline': 'offline',
'blocked_schedule': 'zablokowany przez harmonogram',
'blocked_expired': 'wygasł / zablokowany',
'never': 'nigdy',
'status_body': '🛡 WireGuard: {state}\n'
'Interfejs: {interface}\n'
'Adres VPN: {address}\n'
'Port: {port}\n'
'Klienci: {online}/{total} online\n'
'CPU: {cpu}%\n'
'RAM: {memory}%\n'
'Sieć: ↓ {rx}/s · ↑ {tx}/s\n'
'Czas pracy: {uptime}',
'clients_title': '👥 Klienci ({total})',
'no_clients': 'Brak skonfigurowanych klientĂłw.',
'choose_create_group': 'Wybierz grupÄ™ dla nowego klienta lub kontynuuj bez grupy:',
'create_no_group': 'Bez grupy',
'create_name': 'Wyślij nazwę nowego klienta. Aby anulować, wyślij /cancel.',
'create_endpoint': 'Brak publicznego adresu serwera. Wyślij adres lub domenę (np. vpn.example.com), aby '
'zapisać ją jako domyślną. Aby anulować, wyślij /cancel.',
'creating': 'Tworzenie klienta…',
'created': 'âś… Utworzono klienta\n'
'Nazwa: {name}{group_line}\n'
'Adres VPN: {address}\n'
'Trasy: {routes}\n'
'Adres serwera: {endpoint}',
'config_unavailable': 'Utworzono klienta, ale nie udało się wygenerować konfiguracji: {error}',
'choose_delete': 'Wybierz klienta do usunięcia:',
'confirm_delete': 'Usunąć klienta „{name}” ({address})? Najpierw powstanie kopia konfiguracji interfejsu.',
'deleted': '✅ Usunięto klienta: {name}',
'deleting': 'Usuwanie klienta…',
'already_deleted': 'ℹ️ Klient został już usunięty.',
'working': 'Trwa wykonywanie…',
'confirm_stop': 'Zatrzymać WireGuard? Aktywni klienci VPN zostaną rozłączeni.',
'confirm_restart': 'Uruchomić ponownie WireGuard? Aktywni klienci połączą się ponownie.',
'started': 'âś… Uruchomiono WireGuard.',
'stopped_ok': 'âś… Zatrzymano WireGuard.',
'restarted': 'âś… Uruchomiono ponownie WireGuard.',
'yes': 'Tak',
'no': 'Nie',
'cancelled': 'Anulowano.',
'error': '⚠️ {error}',
'unknown': 'UĹĽyj przyciskĂłw lub polecenia /menu.',
'endpoint_saved': 'Zapisano adres serwera: {endpoint}',
'managed_conf': 'Konfiguracja klienta'}}
def lang_for(user: dict[str, Any] | None, settings: dict[str, Any]) -> str:
return "pl"
def tr(lang: str, key: str, **kwargs: Any) -> str:
text = BOT_TEXT["pl"].get(key, key)
try:
return text.format(**kwargs)
except Exception:
return text
def fmt_bytes(value: Any) -> str:
try:
n = float(value or 0)
except (TypeError, ValueError):
n = 0
units = ["B", "KB", "MB", "GB", "TB"]
i = 0
while n >= 1024 and i < len(units) - 1:
n /= 1024.0
i += 1
return f"{n:.1f} {units[i]}" if i else f"{int(n)} B"
def fmt_uptime(value: Any) -> str:
try:
seconds = max(0, int(value or 0))
except (TypeError, ValueError):
seconds = 0
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes = seconds // 60
if days:
return f"{days}d {hours}h"
if hours:
return f"{hours}h {minutes}m"
return f"{minutes}m"
def selected_interface(user_id: int) -> str:
value = str(SELECTED_INTERFACES.get(int(user_id)) or WG_INTERFACE).strip()
return value or WG_INTERFACE
def interface_keyboard(lang: str, user_id: int) -> dict[str, Any]:
current = selected_interface(user_id)
try:
data = run_helper("interfaces_list", interface=current)
items = [item for item in data.get("interfaces") or [] if item.get("configured")]
except Exception:
items = []
rows: list[list[dict[str, str]]] = []
for item in items[:30]:
name = str(item.get("name") or "")
if not name:
continue
alias = str(item.get("display_name") or "").strip()
label = f"{name} · {alias}" if alias and alias != name else name
state = "🟢" if item.get("running") else "🔴"
current_mark = "âś“ " if name == current else ""
rows.append([{"text": f"{current_mark}{state} {label}"[:60], "callback_data": f"iface:{name}"}])
rows.append([{"text": tr(lang, "back"), "callback_data": "menu"}])
return {"inline_keyboard": rows}
def main_keyboard(lang: str, user_id: int = 0) -> dict[str, Any]:
return {
"inline_keyboard": [
[
{"text": f"{tr(lang, 'interface')}: {selected_interface(user_id)}", "callback_data": "interfaces"},
{"text": tr(lang, "server"), "callback_data": "server"},
],
[{"text": tr(lang, "status"), "callback_data": "status"}, {"text": tr(lang, "clients"), "callback_data": "clients"}],
[{"text": tr(lang, "create"), "callback_data": "create"}, {"text": tr(lang, "delete"), "callback_data": "delete"}],
[{"text": tr(lang, "configs"), "callback_data": "configs"}, {"text": tr(lang, "audit"), "callback_data": "audit:latest"}],
]
}
def server_controls_text(lang: str, user_id: int) -> str:
return tr(lang, "server_controls", interface=selected_interface(user_id))
def server_keyboard(lang: str) -> dict[str, Any]:
return {
"inline_keyboard": [
[
{"text": tr(lang, "start"), "callback_data": "start", "style": "success"},
{"text": tr(lang, "restart"), "callback_data": "restart", "style": "primary"},
{"text": tr(lang, "stop"), "callback_data": "stop", "style": "danger"},
],
[{"text": tr(lang, "back"), "callback_data": "menu"}],
]
}
def server_controls_screen(lang: str, user_id: int, prefix: str = "") -> tuple[str, dict[str, Any]]:
return picker_text(prefix, server_controls_text(lang, user_id)), server_keyboard(lang)
def back_keyboard(lang: str) -> dict[str, Any]:
return {"inline_keyboard": [[{"text": tr(lang, "back"), "callback_data": "menu"}]]}
def send_message(token: str, chat_id: int, text: str, reply_markup: dict[str, Any] | None = None, *, parse_mode: str | None = None) -> Any:
payload: dict[str, Any] = {"chat_id": chat_id, "text": text, "disable_web_page_preview": True}
if parse_mode:
payload["parse_mode"] = parse_mode
if reply_markup is not None:
payload["reply_markup"] = reply_markup
return telegram_api_call(token, "sendMessage", payload, timeout=15)
def edit_message(token: str, chat_id: int, message_id: int, text: str, reply_markup: dict[str, Any] | None = None) -> Any:
payload: dict[str, Any] = {"chat_id": chat_id, "message_id": message_id, "text": text, "disable_web_page_preview": True}
if reply_markup is not None:
payload["reply_markup"] = reply_markup
try:
return telegram_api_call(token, "editMessageText", payload, timeout=15)
except Exception as exc:
if "message is not modified" not in str(exc).lower():
raise
return None
def answer_callback(token: str, callback_id: str, text: str = "") -> None:
payload: dict[str, Any] = {"callback_query_id": callback_id}
if text:
payload["text"] = text[:180]
try:
telegram_api_call(token, "answerCallbackQuery", payload, timeout=10)
except Exception:
pass
def clear_inline_keyboard(token: str, chat_id: int, message_id: int) -> None:
"""Best-effort removal of stale inline buttons before a long/destructive action."""
if chat_id <= 0 or message_id <= 0:
return
try:
telegram_api_call(
token,
"editMessageReplyMarkup",
{"chat_id": chat_id, "message_id": message_id, "reply_markup": {"inline_keyboard": []}},
timeout=10,
)
except Exception:
pass
def edit_or_send(
token: str,
chat_id: int,
message_id: int,
text: str,
reply_markup: dict[str, Any] | None = None,
) -> Any:
"""Append bot screens to chat history instead of replacing the previous screen.
Keeps the earlier status, clients and action results readable and reusable.
Only pending confirmation buttons are invalidated after use.
"""
result = send_message(token, chat_id, text, reply_markup)
if isinstance(result, dict):
for state in PENDING.values():
if int(state.get("chat_id") or 0) == chat_id and int(state.get("message_id") or 0) == message_id:
state["message_id"] = int(result.get("message_id") or 0)
break
return result
def pending_prompt(state: dict[str, Any]) -> tuple[int, int]:
return int(state.get("chat_id") or 0), int(state.get("message_id") or 0)
def update_pending_prompt(
token: str,
state: dict[str, Any],
fallback_chat_id: int,
text: str,
reply_markup: dict[str, Any] | None = None,
) -> Any:
prompt_chat, prompt_message = pending_prompt(state)
return edit_or_send(token, prompt_chat or fallback_chat_id, prompt_message, text, reply_markup)
def send_next_pending_prompt(
token: str,
state: dict[str, Any],
chat_id: int,
text: str,
reply_markup: dict[str, Any] | None = None,
) -> Any:
"""After a user text reply, send the next bot prompt below it and retire the previous inline keyboard."""
prompt_chat, prompt_message = pending_prompt(state)
clear_inline_keyboard(token, prompt_chat or chat_id, prompt_message)
result = send_message(token, chat_id, text, reply_markup)
if isinstance(result, dict):
new_message_id = int(result.get("message_id") or 0)
if new_message_id > 0:
state["chat_id"] = chat_id
state["message_id"] = new_message_id
return result
def multipart_call(token: str, method: str, fields: dict[str, Any], file_field: str, filename: str, content: bytes, content_type: str) -> Any:
boundary = f"----WGTools{uuid.uuid4().hex}"
body = io.BytesIO()
for key, value in fields.items():
body.write(f"--{boundary}\r\n".encode())
body.write(f'Content-Disposition: form-data; name="{key}"\r\n\r\n'.encode())
if isinstance(value, (dict, list)):
value = json.dumps(value, ensure_ascii=False)
body.write(str(value).encode("utf-8"))
body.write(b"\r\n")
body.write(f"--{boundary}\r\n".encode())
body.write(f'Content-Disposition: form-data; name="{file_field}"; filename="{filename}"\r\n'.encode("utf-8"))
body.write(f"Content-Type: {content_type}\r\n\r\n".encode())
body.write(content)
body.write(b"\r\n")
body.write(f"--{boundary}--\r\n".encode())
data = body.getvalue()
req = urllib.request.Request(
f"https://api.telegram.org/bot{token}/{method}",
data=data,
headers={"Content-Type": f"multipart/form-data; boundary={boundary}", "Content-Length": str(len(data)), "User-Agent": "WGTools/Telegram"},
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
result = json.loads(resp.read().decode("utf-8", "replace"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace")
raise RuntimeError(f"Telegram HTTP {exc.code}: {detail[:500]}") from exc
except urllib.error.URLError as exc:
raise RuntimeError(f"Telegram connection failed: {exc.reason}") from exc
if not result.get("ok"):
raise RuntimeError(str(result.get("description") or "Telegram upload failed"))
return result.get("result")
def send_client_files(token: str, chat_id: int, config_data: dict[str, Any], lang: str) -> None:
config_text = str(config_data.get("config") or "")
filename = str(config_data.get("filename") or "wireguard-client.conf")
multipart_call(token, "sendDocument", {"chat_id": chat_id, "caption": tr(lang, "managed_conf")}, "document", filename, config_text.encode("utf-8"), "text/plain")
qr = qrcode.make(config_text)
stream = io.BytesIO()
qr.save(stream, format="PNG")
multipart_call(token, "sendPhoto", {"chat_id": chat_id}, "photo", "wireguard-qr.png", stream.getvalue(), "image/png")
def is_private(update: dict[str, Any]) -> bool:
message = update.get("message") or (update.get("callback_query") or {}).get("message") or {}
chat = message.get("chat") or {}
return chat.get("type") == "private"
def actor(update: dict[str, Any]) -> dict[str, Any]:
return (update.get("callback_query") or {}).get("from") or (update.get("message") or {}).get("from") or {}
def chat_id_from(update: dict[str, Any]) -> int:
message = update.get("message") or (update.get("callback_query") or {}).get("message") or {}
return int((message.get("chat") or {}).get("id") or 0)
def allowed(update: dict[str, Any], settings: dict[str, Any]) -> bool:
user_id = int(actor(update).get("id") or 0)
return user_id > 0 and user_id in set(settings.get("allowed_user_ids") or [])
def telegram_audit_actor(user: dict[str, Any] | None) -> str:
data = user or {}
user_id = int(data.get("id") or 0)
username = str(data.get("username") or "").strip().lstrip("@")
if username:
return f"Telegram · @{username} · ID {user_id}"
return f"Telegram · ID {user_id}"
def telegram_audit(
user: dict[str, Any] | None,
action: str,
*,
object: str = "",
result: str = "ok",
details: dict[str, Any] | None = None,
) -> None:
data = user or {}
user_id = int(data.get("id") or 0)
username = str(data.get("username") or "").strip().lstrip("@")
payload: dict[str, Any] = dict(details or {})
payload["source"] = "telegram"
payload["telegram_user_id"] = user_id
if username:
payload["telegram_username"] = username
try:
write_audit(
telegram_audit_actor(data),
action,
object=object,
result=result,
details=payload,
)
except Exception:
# Audit logging must never break an administrative Telegram action.
pass
def telegram_audit_failure(
user: dict[str, Any] | None,
operation: str,
exc: Exception,
*,
interface: str = "",
object: str = "",
) -> None:
target = object or operation
if interface:
target = f"{interface} · {target}"
telegram_audit(
user,
"telegram.action_failed",
object=target,
result=f"error: {exc}",
details={"operation": operation, "interface": interface},
)
def telegram_state_change_attempt(update: dict[str, Any]) -> str:
callback = update.get("callback_query") or {}
data = str(callback.get("data") or "")
if data == "start":
return "WireGuard start"
if data == "stop_yes":
return "WireGuard stop"
if data == "restart_yes":
return "WireGuard restart"
if data.startswith("delyes:"):
return "Delete client"
user_id = int(actor(update).get("id") or 0)
pending = PENDING.get(user_id) or {}
if update.get("message") and str(pending.get("step") or "") in {"name", "endpoint"}:
return "Create client"
return ""
def audit_denied_telegram_action(update: dict[str, Any]) -> None:
operation = telegram_state_change_attempt(update)
if not operation:
return
user = actor(update)
user_id = int(user.get("id") or 0)
iface = selected_interface(user_id) if user_id else WG_INTERFACE
telegram_audit(
user,
"telegram.action_denied",
object=f"{iface} · {operation}",
result="denied",
details={"operation": operation, "interface": iface},
)
def server_status_text(lang: str, user_id: int) -> str:
iface = selected_interface(user_id)
d = run_helper("snapshot", interface=iface)
prefs = get_preferences()
now = time.time()
threshold = int(prefs.get("online_threshold_seconds") or 180)
peers = d.get("peers") or []
online_count = sum(
1
for p in peers
if not bool(p.get("schedule_disabled"))
and not bool(p.get("expired_disabled"))
and int(p.get("latest_handshake") or 0) > 0
and now - int(p.get("latest_handshake") or 0) <= threshold
)
metrics = d.get("metrics") or {}
cpu = metrics.get("cpu") or {}
mem = metrics.get("memory") or {}
net = metrics.get("network") or {}
interface_cfg = (d.get("config") or {}).get("interface") or {}
return tr(
lang,
"status_body",
state=tr(lang, "running" if d.get("running") else "stopped"),
interface=d.get("interface") or "wg0",
address=interface_cfg.get("address") or "—",
port=d.get("listen_port") or interface_cfg.get("listen_port") or "—",
online=online_count,
total=len(peers),
cpu=f"{float(cpu.get('percent') or 0):.1f}",
memory=f"{float(mem.get('percent') or 0):.1f}",
rx=fmt_bytes(net.get("rx_bytes_per_second")),
tx=fmt_bytes(net.get("tx_bytes_per_second")),
uptime=fmt_uptime(metrics.get("uptime_seconds")),
)
def clients_text(lang: str, user_id: int) -> str:
iface = selected_interface(user_id)
d = run_helper("snapshot", interface=iface)
prefs = get_preferences()
now = time.time()
threshold = int(prefs.get("online_threshold_seconds") or 180)
peers = d.get("peers") or []
if not peers:
return tr(lang, "no_clients")
lines = [tr(lang, "clients_title", total=len(peers)), ""]
for p in peers[:50]:
hs = int(p.get("latest_handshake") or 0)
schedule_blocked = bool(p.get("schedule_disabled"))
expired_blocked = bool(p.get("expired_disabled"))
is_on = not schedule_blocked and not expired_blocked and hs > 0 and now - hs <= threshold
icon = "🟢" if is_on else ("⛔" if schedule_blocked or expired_blocked else "🔴")
line = f"{icon} {p.get('name') or 'Peer'} · {p.get('vpn_address') or '—'}"
if p.get("group_name"):
line += f" · [{p.get('group_name')}]"
if schedule_blocked:
line += f" · {tr(lang, 'blocked_schedule')}"
elif expired_blocked:
line += f" · {tr(lang, 'blocked_expired')}"
if is_on and p.get("endpoint"):
line += f"\n ↳ {p.get('endpoint')}"
lines.append(line)
if len(peers) > 50:
lines.append(f"… +{len(peers)-50}")
return "\n".join(lines)
# Human-friendly event labels; unknown event types remain readable as identifiers.
AUDIT_ACTIONS = {'client.created': 'Utworzono klienta',
'client.deleted': 'Usunięto klienta',
'client.updated': 'Zmieniono klienta',
'client.config_viewed': 'Otworzono konfiguracjÄ™ klienta',
'wireguard.client_connected': 'Klient połączył się',
'wireguard.started': 'Uruchomiono WireGuard',
'wireguard.stopped': 'Zatrzymano WireGuard',
'wireguard.restarted': 'Uruchomiono ponownie WireGuard',
'auth.login': 'Logowanie uĹĽytkownika',
'auth.login_failed': 'Nieudane logowanie',
'telegram.action_failed': 'Błąd polecenia Telegram',
'telegram.action_denied': 'Odmowa polecenia Telegram'}
AUDIT_ICONS = {
"client.created": "âž•",
"client.deleted": "🗑️",
"client.updated": "✏️",
"client.config_viewed": "đź“„",
"wireguard.client_connected": "🟢",
"wireguard.started": "🟢",
"wireguard.stopped": "đź”´",
"wireguard.restarted": "🔄",
"auth.login": "🔓",
"auth.login_failed": "⚠️",
"telegram.action_failed": "⚠️",
"telegram.action_denied": "â›”",
}
def _audit_html(value: Any, max_length: int) -> str:
"""Escape untrusted audit values before inserting them into Telegram HTML."""
clean = " ".join(str(value or "").split())[:max_length]
return html.escape(clean, quote=True)
def audit_screen(lang: str, page: dict[str, Any]) -> tuple[str, dict[str, Any]]:
"""Readable, safely escaped Telegram HTML for a read-only audit page."""
items = list(page.get("items") or [])[:20]
title = tr(lang, "audit_title").removeprefix("đź§ľ ").strip()
heading = f"đź§ľ {_audit_html(title, 65)}"
footer = f"{_audit_html(tr(lang, 'audit_footer'), 120)}"
variants = []
for item in items:
date = time.strftime("%d.%m %H:%M", time.localtime(int(item.get("created_at") or 0)))
event = str(item.get("action") or "event")
label = AUDIT_ACTIONS.get(event, event.replace(".", " / "))
actor = _audit_html(item.get("username") or "system", 40)
target = _audit_html(item.get("object"), 56)
outcome_raw = " ".join(str(item.get("result") or "").split())
routine = {"ok", "created", "deleted", "started", "stopped", "restarted", "shown", "success", "connected", "updated"}
outcome = "" if outcome_raw.casefold() in routine else _audit_html(outcome_raw, 36)
icon = AUDIT_ICONS.get(event, "▫️")
stamp = f"{date}"
action = f"{icon} {_audit_html(label, 50)}"
detail = (f" · {target}" if target else "") + (f" · {outcome}" if outcome else "")
full = f"{stamp} · {actor}\n{action}{detail}"
compact = f"{stamp} · {_audit_html(item.get('username') or 'system', 22)}\n{action}"
minimal = f"{stamp}\n{icon} {_audit_html(label, 30)}"
variants.append((full, compact, minimal))
if not items:
body = _audit_html(tr(lang, "audit_empty"), 140)
else:
selected = [variants[i][0] for i in range(len(variants))]
def render() -> str:
return "\n\n".join([heading, *selected, footer])
# Keep all 20 records, reducing optional metadata as needed. Never slice HTML tags.
for level in (1, 2):
for i in range(len(selected) - 1, -1, -1):
if len(render()) <= 3900:
break
selected[i] = variants[i][level]
body = "\n\n".join(selected)
text = "\n\n".join([heading, body, footer])
buttons = []
if items:
if page.get("has_newer"):
buttons.append({"text": tr(lang, "audit_newer"), "callback_data": f"audit:after:{items[0]['id']}"})
if page.get("has_older"):
buttons.append({"text": tr(lang, "audit_older"), "callback_data": f"audit:before:{items[-1]['id']}"})
rows = [buttons] if buttons else []
rows.append([{"text": tr(lang, "back"), "callback_data": "menu"}])
return text, {"inline_keyboard": rows}
def delete_keyboard(lang: str, peers: list[dict[str, Any]]) -> dict[str, Any]:
rows: list[list[dict[str, str]]] = []
for p in peers[:40]:
name = str(p.get("name") or "Peer")[:32]
addr = str(p.get("vpn_address") or "")[:20]
key = str(p.get("public_key") or "")
if key:
rows.append([{"text": f"🗑 {name} · {addr}", "callback_data": f"delpick:{key}"}])
rows.append([{"text": tr(lang, "back"), "callback_data": "menu"}])
return {"inline_keyboard": rows}
def config_keyboard(lang: str, peers: list[dict[str, Any]]) -> dict[str, Any]:
rows: list[list[dict[str, str]]] = []
for p in peers[:40]:
name = str(p.get("name") or "Peer")[:30]
addr = str(p.get("vpn_address") or "")[:20]
key = str(p.get("public_key") or "")
if key:
icon = "đź“„" if p.get("managed") else "đź”’"
rows.append([{"text": f"{icon} {name} · {addr}", "callback_data": f"cfgpick:{key}"}])
rows.append([{"text": tr(lang, "back"), "callback_data": "menu"}])
return {"inline_keyboard": rows}
def picker_text(prefix: str, body: str) -> str:
prefix = str(prefix or "").strip()
return f"{prefix}\n\n{body}" if prefix else body
def config_picker(lang: str, peers: list[dict[str, Any]], prefix: str = "") -> tuple[str, dict[str, Any]]:
if not peers:
return picker_text(prefix, tr(lang, "no_configs")), back_keyboard(lang)
return picker_text(prefix, tr(lang, "choose_config")), config_keyboard(lang, peers)
def delete_picker(lang: str, peers: list[dict[str, Any]], prefix: str = "") -> tuple[str, dict[str, Any]]:
if not peers:
return picker_text(prefix, tr(lang, "no_clients")), back_keyboard(lang)
return picker_text(prefix, tr(lang, "choose_delete")), delete_keyboard(lang, peers)
def current_peers(interface: str) -> list[dict[str, Any]]:
snap = run_helper("snapshot", interface=interface)
return list(snap.get("peers") or [])
def create_group_keyboard(lang: str, groups: list[dict[str, Any]]) -> dict[str, Any]:
rows: list[list[dict[str, str]]] = [[{"text": f"— {tr(lang, 'create_no_group')}", "callback_data": "creategroup:none"}]]
for group in groups[:40]:
group_id = str(group.get("id") or "")
if not group_id:
continue
name = str(group.get("name") or group_id)[:48]
rows.append([{"text": f"👥 {name}", "callback_data": f"creategroup:{group_id}"}])
rows.append([{"text": tr(lang, "back"), "callback_data": "menu"}])
return {"inline_keyboard": rows}
def handle_message(update: dict[str, Any], settings: dict[str, Any], token: str, lang: str) -> None:
message = update.get("message") or {}
chat_id = int((message.get("chat") or {}).get("id") or 0)
user_id = int((message.get("from") or {}).get("id") or 0)
text = str(message.get("text") or "").strip()
if text in {"/start", "/menu"}:
state = PENDING.pop(user_id, None)
if state:
prompt_chat, prompt_message = pending_prompt(state)
clear_inline_keyboard(token, prompt_chat or chat_id, prompt_message)
send_message(token, chat_id, tr(lang, "welcome"), main_keyboard(lang, user_id))
return
if text == "/audit":
state = PENDING.pop(user_id, None)
if state:
prompt_chat, prompt_message = pending_prompt(state)
clear_inline_keyboard(token, prompt_chat or chat_id, prompt_message)
screen, keyboard = audit_screen(lang, list_audit_page(limit=20))
send_message(token, chat_id, screen, keyboard, parse_mode="HTML")
return
if text == "/cancel":
state = PENDING.pop(user_id, None)
if state:
prompt_chat, prompt_message = pending_prompt(state)
clear_inline_keyboard(token, prompt_chat or chat_id, prompt_message)
send_message(token, chat_id, tr(lang, "cancelled"), main_keyboard(lang, user_id))
return
pending = PENDING.get(user_id)
if not pending:
send_message(token, chat_id, tr(lang, "unknown"), main_keyboard(lang, user_id))
return
if pending.get("step") == "name":
name = text.strip()
if not name or len(name) > 64 or any(ord(ch) < 32 for ch in name):
send_next_pending_prompt(
token,
pending,
chat_id,
f"{tr(lang, 'error', error='Peer name must be 1–64 characters.')}\n\n{tr(lang, 'create_name')}",
back_keyboard(lang),
)
return
endpoint = str(settings.get("default_endpoint") or "").strip()
pending["name"] = name
if not endpoint:
pending["step"] = "endpoint"
send_next_pending_prompt(token, pending, chat_id, tr(lang, "create_endpoint"), back_keyboard(lang))
return
finish_create(
user_id,
chat_id,
token,
lang,
settings,
name,
endpoint,
str(pending.get("interface") or selected_interface(user_id)),
str(pending.get("group_id") or ""),
pending,
message.get("from") or {},
)
return
if pending.get("step") == "endpoint":
endpoint = text.strip()
try:
set_default_endpoint(endpoint)
telegram_audit(
message.get("from") or {},
"telegram.settings_updated",
object="Default client endpoint",
result="saved",
details={"setting": "default_endpoint"},
)
except Exception as exc:
telegram_audit_failure(message.get("from") or {}, "Update default client endpoint", exc)
send_next_pending_prompt(
token,
pending,
chat_id,
f"{tr(lang, 'error', error=str(exc))}\n\n{tr(lang, 'create_endpoint')}",
back_keyboard(lang),
)
return
name = str(pending.get("name") or "Peer")
settings = get_telegram_settings(include_token=True)
finish_create(
user_id,
chat_id,
token,
lang,
settings,
name,
endpoint,
str(pending.get("interface") or selected_interface(user_id)),
str(pending.get("group_id") or ""),
pending,
message.get("from") or {},
)
return
PENDING.pop(user_id, None)
update_pending_prompt(token, pending, chat_id, tr(lang, "unknown"), main_keyboard(lang, user_id))
def finish_create(
user_id: int,
chat_id: int,
token: str,
lang: str,
settings: dict[str, Any],
name: str,
endpoint_host: str,
iface: str,
group_id: str = "",
state: dict[str, Any] | None = None,
actor_user: dict[str, Any] | None = None,
) -> None:
state = dict(state or {})
PENDING.pop(user_id, None)
send_next_pending_prompt(token, state, chat_id, tr(lang, "creating"), {"inline_keyboard": []})
try:
snapshot = run_helper("snapshot", interface=iface)
port = int(snapshot.get("listen_port") or ((snapshot.get("config") or {}).get("interface") or {}).get("listen_port") or 51820)
endpoint = f"{endpoint_host}:{port}"
group = next((g for g in snapshot.get("client_groups") or [] if str(g.get("id") or "") == group_id), None) if group_id else None
defaults = (group or {}).get("resolved_defaults") or (group or {}).get("defaults") or {}
routes = list(defaults.get("client_allowed_ips") or ["0.0.0.0/0"])
dns = list(defaults.get("dns") or []) if group else list(settings.get("default_dns") or [])
keepalive = int(defaults.get("persistent_keepalive", 25) or 0)
route_preset = str(defaults.get("route_preset") or "full")
result = run_helper(
"create_client",
{
"name": name,
"type": "client",
"vpn_address": "",
"remote_networks": [],
"persistent_keepalive": keepalive,
"endpoint": endpoint,
"client_allowed_ips": routes,
"route_preset": route_preset,
"dns": dns,
"group_id": str((group or {}).get("id") or ""),
"policy_mode": "inherit" if group else "",
"internet_access": "inherit" if group else "",
"local_access": "inherit" if group else "",
"policy_allow": [],
"policy_deny": [],
# Keep Telegram-created clients aligned with the web UI default.
"use_preshared_key": True,
},
interface=iface,
)
except Exception as exc:
telegram_audit_failure(actor_user, "Create client", exc, interface=iface, object=name)
update_pending_prompt(token, state, chat_id, tr(lang, "error", error=str(exc)), main_keyboard(lang, user_id))
return
telegram_audit(
actor_user,
"client.created",
object=f"{iface} · {name}",
result="created",
details={
"interface": iface,
"client_name": name,
"vpn_address": result.get("vpn_address") or "",
"group_id": str((group or {}).get("id") or ""),
},
)
public_key = str(result.get("public_key") or "")
group_line = f"\nGrupa: {group.get('name')}" if group else ""
created_text = tr(
lang,
"created",
name=name,
group_line=group_line,
address=result.get("vpn_address") or "—",
routes=", ".join(routes),
endpoint=endpoint,
)
update_pending_prompt(token, state, chat_id, created_text, {"inline_keyboard": []})
try:
config = run_helper("client_config", {"public_key": public_key}, interface=iface)
send_client_files(token, chat_id, config, lang)
except Exception as exc:
send_message(token, chat_id, tr(lang, "config_unavailable", error=str(exc)))
# Always end a completed create flow on a fresh main-menu screen below the files.
send_message(token, chat_id, tr(lang, "welcome"), main_keyboard(lang, user_id))
def handle_callback(update: dict[str, Any], settings: dict[str, Any], token: str, lang: str) -> None:
callback = update.get("callback_query") or {}
callback_id = str(callback.get("id") or "")
data = str(callback.get("data") or "")
message = callback.get("message") or {}
chat_id = int((message.get("chat") or {}).get("id") or 0)
message_id = int(message.get("message_id") or 0)
actor_user = callback.get("from") or {}
user_id = int(actor_user.get("id") or 0)
iface = selected_interface(user_id)
answer_callback(token, callback_id)
if data.startswith("audit:"):
PENDING.pop(user_id, None)
parts = data.split(":")
try:
if data == "audit:latest":
page_data = list_audit_page(limit=20)
elif len(parts) == 3 and parts[1] in {"before", "after"} and parts[2].isdigit() and int(parts[2]) > 0:
anchor = int(parts[2])
page_data = list_audit_page(**{("before_id" if parts[1] == "before" else "after_id"): anchor}, limit=20)
else:
raise ValueError("Invalid audit cursor")
except (ValueError, OverflowError):
send_message(token, chat_id, tr(lang, "audit_bad_cursor"), main_keyboard(lang, user_id))
return
text, keyboard = audit_screen(lang, page_data)
send_message(token, chat_id, text, keyboard, parse_mode="HTML")
return
if data == "menu":
PENDING.pop(user_id, None)
edit_or_send(token, chat_id, message_id, tr(lang, "welcome"), main_keyboard(lang, user_id))
return
if data == "interfaces":
PENDING.pop(user_id, None)
edit_or_send(token, chat_id, message_id, tr(lang, "choose_interface"), interface_keyboard(lang, user_id))
return
if data == "server":
PENDING.pop(user_id, None)
text, keyboard = server_controls_screen(lang, user_id)
edit_or_send(token, chat_id, message_id, text, keyboard)
return
if data.startswith("iface:"):
candidate = data.split(":", 1)[1]
listing = run_helper("interfaces_list", interface=iface)
valid = {str(item.get("name") or "") for item in listing.get("interfaces") or [] if item.get("configured")}
if candidate not in valid:
text = picker_text(tr(lang, "error", error="WireGuard interface is no longer available"), tr(lang, "choose_interface"))
edit_or_send(token, chat_id, message_id, text, interface_keyboard(lang, user_id))
return
SELECTED_INTERFACES[user_id] = candidate
PENDING.pop(user_id, None)
edit_or_send(token, chat_id, message_id, tr(lang, "interface_selected", name=candidate), main_keyboard(lang, user_id))
return
if data == "status":
PENDING.pop(user_id, None)
edit_or_send(token, chat_id, message_id, server_status_text(lang, user_id), back_keyboard(lang))
return
if data == "clients":
PENDING.pop(user_id, None)
edit_or_send(token, chat_id, message_id, clients_text(lang, user_id), back_keyboard(lang))
return
if data == "create":
snap = run_helper("snapshot", interface=iface)
groups = snap.get("client_groups") or []
PENDING[user_id] = {
"step": "group" if groups else "name",
"created_at": int(time.time()),
"interface": iface,
"group_id": "",
"chat_id": chat_id,
"message_id": message_id,
}
if groups:
edit_or_send(token, chat_id, message_id, tr(lang, "choose_create_group"), create_group_keyboard(lang, groups))
else:
edit_or_send(token, chat_id, message_id, tr(lang, "create_name"), back_keyboard(lang))
return
if data.startswith("creategroup:"):
state = PENDING.get(user_id) or {}
if state.get("step") != "group" or int(state.get("message_id") or 0) != message_id:
PENDING.pop(user_id, None)
edit_or_send(token, chat_id, message_id, tr(lang, "cancelled"), main_keyboard(lang, user_id))
return
requested = data.split(":", 1)[1]
snap = run_helper("snapshot", interface=str(state.get("interface") or iface))
groups = snap.get("client_groups") or []
valid = {str(g.get("id") or "") for g in groups}
group_id = "" if requested == "none" else requested
if group_id and group_id not in valid:
state["step"] = "group"
text = picker_text(tr(lang, "error", error="Client group is no longer available"), tr(lang, "choose_create_group"))
edit_or_send(token, chat_id, message_id, text, create_group_keyboard(lang, groups))
return
state["group_id"] = group_id
state["step"] = "name"
state["chat_id"] = chat_id
state["message_id"] = message_id
edit_or_send(token, chat_id, message_id, tr(lang, "create_name"), back_keyboard(lang))
return
if data == "configs":
PENDING.pop(user_id, None)
peers = current_peers(iface)
text, keyboard = config_picker(lang, peers)
edit_or_send(token, chat_id, message_id, text, keyboard)
return
if data.startswith("cfgpick:"):
public_key = data.split(":", 1)[1]
peers = current_peers(iface)
peer = next((p for p in peers if p.get("public_key") == public_key), None)
if not peer:
text, keyboard = config_picker(lang, peers, tr(lang, "error", error="Peer not found"))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
if not peer.get("managed"):
text, keyboard = config_picker(lang, peers, tr(lang, "legacy_config_unavailable"))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
name = str(peer.get("name") or "Peer")
clear_inline_keyboard(token, chat_id, message_id)
edit_or_send(token, chat_id, message_id, tr(lang, "sending_config", name=name), {"inline_keyboard": []})
try:
config = run_helper("client_config", {"public_key": public_key}, interface=iface)
send_client_files(token, chat_id, config, lang)
except Exception as exc:
# A document may already have been sent before a QR/upload error. Keep the
# next actionable screen below any emitted files and stay inside Configs.
telegram_audit_failure(actor_user, "Open client config", exc, interface=iface, object=name)
edit_or_send(token, chat_id, message_id, tr(lang, "error", error=str(exc)), {"inline_keyboard": []})
peers = current_peers(iface)
text, keyboard = config_picker(lang, peers)
send_message(token, chat_id, text, keyboard)
return
# Config text and QR are one logical disclosure in WGTools, just like the
# combined web modal. Record one audit event after both Telegram files were sent.
telegram_audit(
actor_user,
"client.config_viewed",
object=str(config.get("filename") or name or "client config"),
result="shown",
details={"interface": iface, "client_name": name},
)
# The selected .conf and QR are separate Telegram messages. Do not leave the
# actionable menu above them: retire the old picker, then send a fresh Configs
# picker below the files so the conversation continues in visual order.
edit_or_send(token, chat_id, message_id, tr(lang, "config_sent", name=name), {"inline_keyboard": []})
peers = current_peers(iface)
text, keyboard = config_picker(lang, peers)
send_message(token, chat_id, text, keyboard)
return
if data == "delete":
PENDING.pop(user_id, None)
peers = current_peers(iface)
text, keyboard = delete_picker(lang, peers)
edit_or_send(token, chat_id, message_id, text, keyboard)
return
if data.startswith("delpick:"):
public_key = data.split(":", 1)[1]
peers = current_peers(iface)
peer = next((p for p in peers if p.get("public_key") == public_key), None)
if not peer:
text, keyboard = delete_picker(lang, peers, tr(lang, "error", error="Peer not found"))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
keyboard = {
"inline_keyboard": [[
{"text": tr(lang, "yes"), "callback_data": f"delyes:{public_key}"},
{"text": tr(lang, "no"), "callback_data": "delete"},
]]
}
PENDING[user_id] = {
"step": "confirm_delete",
"created_at": int(time.time()),
"interface": iface,
"public_key": public_key,
"chat_id": chat_id,
"message_id": message_id,
}
edit_or_send(
token,
chat_id,
message_id,
tr(lang, "confirm_delete", name=peer.get("name") or "Peer", address=peer.get("vpn_address") or "—"),
keyboard,
)
return
if data.startswith("delyes:"):
public_key = data.split(":", 1)[1]
state = PENDING.get(user_id) or {}
peers = current_peers(iface)
peer = next((p for p in peers if p.get("public_key") == public_key), None)
if state.get("step") != "confirm_delete" or str(state.get("public_key") or "") != public_key or int(state.get("message_id") or 0) != message_id:
# A queued second tap after a successful delete is harmless. A stale confirmation
# after navigation is never allowed to delete a still-existing peer. Return to
# the parent delete picker instead of unexpectedly jumping to the main menu.
prefix = tr(lang, "already_deleted") if not peer else tr(lang, "cancelled")
text, keyboard = delete_picker(lang, peers, prefix)
edit_or_send(token, chat_id, message_id, text, keyboard)
return
PENDING.pop(user_id, None)
if not peer:
text, keyboard = delete_picker(lang, peers, tr(lang, "already_deleted"))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
name = str(peer.get("name") or "Peer")
clear_inline_keyboard(token, chat_id, message_id)
edit_or_send(token, chat_id, message_id, tr(lang, "deleting"), {"inline_keyboard": []})
try:
run_helper("delete_client", {"public_key": public_key}, interface=iface)
except Exception as exc:
telegram_audit_failure(actor_user, "Delete client", exc, interface=iface, object=name)
peers = current_peers(iface)
text, keyboard = delete_picker(lang, peers, tr(lang, "error", error=str(exc)))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
telegram_audit(
actor_user,
"client.deleted",
object=f"{iface} · {name}",
result="deleted",
details={"interface": iface, "client_name": name},
)
peers = current_peers(iface)
text, keyboard = delete_picker(lang, peers, tr(lang, "deleted", name=name))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
if data == "start":
PENDING.pop(user_id, None)
clear_inline_keyboard(token, chat_id, message_id)
edit_or_send(token, chat_id, message_id, tr(lang, "working"), {"inline_keyboard": []})
try:
run_helper("wireguard_start", interface=iface)
except Exception as exc:
telegram_audit_failure(actor_user, "Start WireGuard", exc, interface=iface)
text, keyboard = server_controls_screen(lang, user_id, tr(lang, "error", error=str(exc)))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
telegram_audit(actor_user, "wireguard.started", object=iface, result="started", details={"interface": iface})
text, keyboard = server_controls_screen(lang, user_id, tr(lang, "started"))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
if data == "stop":
PENDING[user_id] = {"step": "confirm_stop", "created_at": int(time.time()), "interface": iface, "chat_id": chat_id, "message_id": message_id}
keyboard = {
"inline_keyboard": [[
{"text": tr(lang, "yes"), "callback_data": "stop_yes"},
{"text": tr(lang, "no"), "callback_data": "server"},
]]
}
edit_or_send(token, chat_id, message_id, tr(lang, "confirm_stop"), keyboard)
return
if data == "restart":
PENDING[user_id] = {"step": "confirm_restart", "created_at": int(time.time()), "interface": iface, "chat_id": chat_id, "message_id": message_id}
keyboard = {
"inline_keyboard": [[
{"text": tr(lang, "yes"), "callback_data": "restart_yes"},
{"text": tr(lang, "no"), "callback_data": "server"},
]]
}
edit_or_send(token, chat_id, message_id, tr(lang, "confirm_restart"), keyboard)
return
if data == "stop_yes":
state = PENDING.get(user_id) or {}
if state.get("step") != "confirm_stop" or int(state.get("message_id") or 0) != message_id:
text, keyboard = server_controls_screen(lang, user_id, tr(lang, "cancelled"))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
PENDING.pop(user_id, None)
clear_inline_keyboard(token, chat_id, message_id)
edit_or_send(token, chat_id, message_id, tr(lang, "working"), {"inline_keyboard": []})
target_iface = str(state.get("interface") or iface)
try:
run_helper("wireguard_stop", interface=target_iface)
except Exception as exc:
telegram_audit_failure(actor_user, "Stop WireGuard", exc, interface=target_iface)
text, keyboard = server_controls_screen(lang, user_id, tr(lang, "error", error=str(exc)))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
telegram_audit(actor_user, "wireguard.stopped", object=target_iface, result="stopped", details={"interface": target_iface})
text, keyboard = server_controls_screen(lang, user_id, tr(lang, "stopped_ok"))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
if data == "restart_yes":
state = PENDING.get(user_id) or {}
if state.get("step") != "confirm_restart" or int(state.get("message_id") or 0) != message_id:
text, keyboard = server_controls_screen(lang, user_id, tr(lang, "cancelled"))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
PENDING.pop(user_id, None)
clear_inline_keyboard(token, chat_id, message_id)
edit_or_send(token, chat_id, message_id, tr(lang, "working"), {"inline_keyboard": []})
target_iface = str(state.get("interface") or iface)
try:
run_helper("wireguard_restart", interface=target_iface)
except Exception as exc:
telegram_audit_failure(actor_user, "Restart WireGuard", exc, interface=target_iface)
text, keyboard = server_controls_screen(lang, user_id, tr(lang, "error", error=str(exc)))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
telegram_audit(actor_user, "wireguard.restarted", object=target_iface, result="restarted", details={"interface": target_iface})
text, keyboard = server_controls_screen(lang, user_id, tr(lang, "restarted"))
edit_or_send(token, chat_id, message_id, text, keyboard)
return
PENDING.pop(user_id, None)
edit_or_send(token, chat_id, message_id, tr(lang, "unknown"), main_keyboard(lang, user_id))
def handle_update(update: dict[str, Any], settings: dict[str, Any], token: str) -> None:
user = actor(update)
lang = lang_for(user, settings)
chat_id = chat_id_from(update)
if chat_id <= 0:
return
if not is_private(update):
audit_denied_telegram_action(update)
try:
send_message(token, chat_id, tr(lang, "private_only"))
except Exception:
pass
return
if not allowed(update, settings):
audit_denied_telegram_action(update)
try:
send_message(token, chat_id, tr(lang, "denied", user_id=int(user.get("id") or 0)))
except Exception:
pass
return
try:
if update.get("callback_query"):
handle_callback(update, settings, token, lang)
elif update.get("message"):
handle_message(update, settings, token, lang)
except Exception as exc:
user_id = int(user.get("id") or 0)
callback = update.get("callback_query") or {}
if callback:
message = callback.get("message") or {}
message_id = int(message.get("message_id") or 0)
PENDING.pop(user_id, None)
clear_inline_keyboard(token, chat_id, message_id)
edit_or_send(token, chat_id, message_id, tr(lang, "error", error=str(exc)), main_keyboard(lang, user_id))
else:
send_message(token, chat_id, tr(lang, "error", error=str(exc)), main_keyboard(lang, user_id))
def cleanup_pending() -> None:
cutoff = time.time() - 1800
stale = [uid for uid, state in PENDING.items() if int(state.get("created_at") or 0) < cutoff]
for uid in stale:
PENDING.pop(uid, None)
def main() -> int:
init_telegram_settings()
last_token = ""
while True:
try:
settings = get_telegram_settings(include_token=True)
token = str(settings.get("bot_token") or "")
if not settings.get("enabled") or not token:
last_token = ""
time.sleep(3)
continue
if token != last_token:
try:
me = telegram_api_call(token, "getMe", {}, timeout=12) or {}
username = str(me.get("username") or "")
telegram_api_call(token, "deleteWebhook", {"drop_pending_updates": False}, timeout=12)
update_telegram_runtime(bot_username=username, last_error="")
last_token = token
except Exception as exc:
update_telegram_runtime(last_error=str(exc))
time.sleep(5)
continue
offset = int(settings.get("update_offset") or 0)
updates = telegram_api_call(
token,
"getUpdates",
{"offset": offset, "timeout": 25, "allowed_updates": ["message", "callback_query"]},
timeout=35,
) or []
update_telegram_runtime(last_error="", last_poll_at=int(time.time()))
for update in updates:
update_id = int(update.get("update_id") or 0)
if update_id:
# Persist first so destructive button presses are not replayed after a daemon restart.
set_update_offset(update_id + 1)
settings = get_telegram_settings(include_token=True)
handle_update(update, settings, token)
cleanup_pending()
except KeyboardInterrupt:
return 0
except Exception as exc:
try:
update_telegram_runtime(last_error=str(exc))
except Exception:
pass
time.sleep(3)
return 0
if __name__ == "__main__":
raise SystemExit(main())