Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
628973374e | ||
|
|
041a533457 | ||
|
|
48ae0c2fd8 |
@@ -39,6 +39,7 @@
|
||||
- `/add <имя>` — создать клиента (бот пришлёт команду установки)
|
||||
- `/del <имя>` — удалить клиента
|
||||
- `/list` — список клиентов
|
||||
- **Кнопки** — постоянная клавиатура: ➕ Создать клиента · 📋 Список · 🗑 Удалить (инлайн-выбор) · 📊 Статус · ❓ Помощь.
|
||||
(Работает только для чата из настроек `tg_chat_id`.)
|
||||
|
||||
---
|
||||
@@ -168,7 +169,7 @@ phobos-update --list # список бэкапов
|
||||
|
||||
- 💖 **Boosty:** [boosty.to/andrey27/donate](https://boosty.to/andrey27/donate)
|
||||
- 💳 **Ozon Bank (СБП):** [ссылка](https://finance.ozon.ru/apps/sbp/ozonbankpay/019dc200-2a5d-7931-a619-782d285f6798)
|
||||
- ✉️ **Telegram:** [@Iot_andrey](https://t.me/Iot_andrey) — вопросы, баги, идеи
|
||||
- ✉️ **Telegram:** [@PCAdministration](https://t.me/PCAdministration) — вопросы, баги, идеи
|
||||
|
||||
## На основе и благодарности
|
||||
|
||||
|
||||
187
app.py
187
app.py
@@ -129,10 +129,102 @@ def delete_client_cli(cid):
|
||||
return True, "\U0001F5D1 Клиент <b>%s</b> удалён." % cid
|
||||
|
||||
|
||||
def telegram_bot():
|
||||
"""Poll Telegram getUpdates; allow the admin chat to /add, /del, /list clients."""
|
||||
def tg_api(method, payload, token=None):
|
||||
import urllib.request
|
||||
if token is None:
|
||||
token = load_settings().get("tg_bot_token", "")
|
||||
if not token:
|
||||
return None
|
||||
try:
|
||||
data = json.dumps(payload).encode()
|
||||
req = urllib.request.Request("https://api.telegram.org/bot%s/%s" % (token, method),
|
||||
data=data, headers={"Content-Type": "application/json"})
|
||||
return json.loads(urllib.request.urlopen(req, timeout=15).read())
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
MAIN_KB = {
|
||||
"keyboard": [
|
||||
["➕ Создать клиента", "\U0001F4CB Список"],
|
||||
["\U0001F5D1 Удалить", "\U0001F4CA Статус"],
|
||||
["❓ Помощь"],
|
||||
],
|
||||
"resize_keyboard": True,
|
||||
}
|
||||
|
||||
_bot_state = {}
|
||||
|
||||
|
||||
def _bot_status_text():
|
||||
servers = [{"ip": SERVER_IP, "is_primary": True}] + load_servers()
|
||||
lines = ["\U0001F4CA <b>Серверы</b>:"]
|
||||
for sv in servers:
|
||||
ip = sv.get("ip", "")
|
||||
st = "ok" if ip == SERVER_IP else server_stats_cache.get(ip, {}).get("status", "?")
|
||||
emoji = "\U0001F7E2" if st == "ok" else ("\U0001F534" if st == "down" else "⚪")
|
||||
lines.append("%s %s%s" % (emoji, ip, " (primary)" if sv.get("is_primary") else ""))
|
||||
online = set()
|
||||
try:
|
||||
for p, info in get_wg_peers().items():
|
||||
if is_peer_online(info.get("latest handshake", "")):
|
||||
online.add(p)
|
||||
for _ip, hs in server_handshakes_cache.items():
|
||||
for p, tsv in hs.items():
|
||||
if tsv and (time.time() - tsv) < 180:
|
||||
online.add(p)
|
||||
except Exception:
|
||||
pass
|
||||
lines.append("\n\U0001F4F1 <b>Клиенты</b>:")
|
||||
cl = get_clients()
|
||||
if not cl:
|
||||
lines.append("нет")
|
||||
for c in cl:
|
||||
on = c.get("public_key", "") in online
|
||||
lines.append(("\U0001F7E2 " if on else "⚪ ") + c.get("client_id", ""))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def qr_png_bytes(data):
|
||||
import qrcode, io
|
||||
buf = io.BytesIO(); qrcode.make(data).save(buf, format="PNG"); return buf.getvalue()
|
||||
|
||||
|
||||
def tg_send_photo(chat, png, caption=""):
|
||||
import urllib.request, secrets as _sec
|
||||
token = load_settings().get("tg_bot_token", "")
|
||||
if not token:
|
||||
return None
|
||||
boundary = "----phobos" + _sec.token_hex(8)
|
||||
def fld(name, val):
|
||||
return ("--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n" % (boundary, name, val)).encode()
|
||||
body = fld("chat_id", str(chat)) + fld("caption", caption) + fld("parse_mode", "HTML")
|
||||
body += ("--%s\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"qr.png\"\r\nContent-Type: image/png\r\n\r\n" % boundary).encode()
|
||||
body += png + ("\r\n--%s--\r\n" % boundary).encode()
|
||||
try:
|
||||
req = urllib.request.Request("https://api.telegram.org/bot%s/sendPhoto" % token, data=body,
|
||||
headers={"Content-Type": "multipart/form-data; boundary=%s" % boundary})
|
||||
return urllib.request.urlopen(req, timeout=25).read()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def bot_send_new_client(chat, name):
|
||||
ok, rep = create_client_cli(name)
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": rep, "parse_mode": "HTML", "reply_markup": MAIN_KB})
|
||||
if ok:
|
||||
try:
|
||||
conf, link = build_phone_config(name, "android")
|
||||
if link:
|
||||
tg_send_photo(chat, qr_png_bytes(link), "📱 Android (PhobosWG) — отсканируй QR в приложении")
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": "phobos:// ссылка (Android):\n<code>%s</code>" % link, "parse_mode": "HTML"})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def telegram_bot():
|
||||
offset = 0
|
||||
import urllib.request
|
||||
while True:
|
||||
try:
|
||||
s = load_settings()
|
||||
@@ -144,36 +236,85 @@ def telegram_bot():
|
||||
data = json.loads(urllib.request.urlopen(url, timeout=40).read())
|
||||
for upd in data.get("result", []):
|
||||
offset = upd["update_id"] + 1
|
||||
cq = upd.get("callback_query")
|
||||
if cq:
|
||||
if str(cq.get("message", {}).get("chat", {}).get("id", "")) != chat:
|
||||
continue
|
||||
cdata = cq.get("data", "")
|
||||
if cdata.startswith("del:"):
|
||||
_, rep = delete_client_cli(cdata[4:])
|
||||
tg_api("answerCallbackQuery", {"callback_query_id": cq["id"], "text": "OK"})
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": rep, "parse_mode": "HTML", "reply_markup": MAIN_KB})
|
||||
continue
|
||||
m = upd.get("message") or upd.get("channel_post")
|
||||
if not m:
|
||||
continue
|
||||
if str(m.get("chat", {}).get("id", "")) != chat:
|
||||
continue
|
||||
text = (m.get("text") or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
# detect reply-keyboard button by its emoji prefix (NOT a command/arg)
|
||||
btn = None
|
||||
if not text.startswith("/"):
|
||||
continue
|
||||
parts = text.split()
|
||||
cmd = parts[0].split("@")[0].lower()
|
||||
arg = parts[1] if len(parts) > 1 else ""
|
||||
if cmd in ("/add", "/new", "/create"):
|
||||
reply = "Использование: /add <имя>" if not arg else create_client_cli(arg)[1]
|
||||
elif cmd in ("/del", "/delete", "/remove", "/rm"):
|
||||
reply = "Использование: /del <имя>" if not arg else delete_client_cli(arg)[1]
|
||||
elif cmd in ("/list", "/ls"):
|
||||
cls = [c.get("client_id", "") for c in get_clients()]
|
||||
reply = ("Клиенты (%d):\n" % len(cls)) + "\n".join("\u2022 " + c for c in cls) if cls else "Клиентов нет."
|
||||
elif cmd in ("/help", "/start"):
|
||||
reply = ("Команды PCA Phobos:\n"
|
||||
"/add <имя> — создать клиента\n"
|
||||
"/del <имя> — удалить клиента\n"
|
||||
"/list — список клиентов")
|
||||
else:
|
||||
continue
|
||||
tg_send(reply)
|
||||
if text.startswith("➕"):
|
||||
btn = "add"
|
||||
elif text.startswith("\U0001F5D1"):
|
||||
btn = "del"
|
||||
elif text.startswith("\U0001F4CB"):
|
||||
btn = "list"
|
||||
elif text.startswith("\U0001F4CA"):
|
||||
btn = "status"
|
||||
elif text.startswith("❓"):
|
||||
btn = "help"
|
||||
# conversation: awaiting a client name to create
|
||||
if _bot_state.get(chat) == "add":
|
||||
if btn is None and not text.startswith("/"):
|
||||
_bot_state.pop(chat, None)
|
||||
bot_send_new_client(chat, text)
|
||||
continue
|
||||
_bot_state.pop(chat, None) # a button/command cancels the prompt
|
||||
# parse slash command + arg (buttons carry no arg)
|
||||
cmd = ""
|
||||
arg = ""
|
||||
if text.startswith("/"):
|
||||
toks = text.split()
|
||||
cmd = toks[0].split("@")[0].lower()
|
||||
arg = toks[1] if len(toks) > 1 else ""
|
||||
if btn == "add" or cmd in ("/add", "/new", "/create"):
|
||||
if arg:
|
||||
bot_send_new_client(chat, arg)
|
||||
else:
|
||||
_bot_state[chat] = "add"
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": "Введите имя нового клиента (латиница, цифры, _ и -):"})
|
||||
elif btn == "del" or cmd in ("/del", "/delete", "/remove", "/rm"):
|
||||
if arg:
|
||||
_, rep = delete_client_cli(arg)
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": rep, "parse_mode": "HTML", "reply_markup": MAIN_KB})
|
||||
else:
|
||||
cl = get_clients()
|
||||
if not cl:
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": "Клиентов нет.", "reply_markup": MAIN_KB})
|
||||
else:
|
||||
kb = {"inline_keyboard": [[{"text": "\U0001F5D1 " + c.get("client_id", ""), "callback_data": "del:" + c.get("client_id", "")}] for c in cl]}
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": "Кого удалить? Нажми на клиента:", "reply_markup": kb})
|
||||
elif btn == "list" or cmd in ("/list", "/ls"):
|
||||
cl = [c.get("client_id", "") for c in get_clients()]
|
||||
rep = ("Клиенты (%d):\n" % len(cl)) + "\n".join("• " + c for c in cl) if cl else "Клиентов нет."
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": rep, "reply_markup": MAIN_KB})
|
||||
elif btn == "status" or cmd in ("/status", "/stat"):
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": _bot_status_text(), "parse_mode": "HTML", "reply_markup": MAIN_KB})
|
||||
elif btn == "help" or cmd in ("/help", "/start"):
|
||||
rep = ("<b>PCA Phobos — бот</b>\n\n"
|
||||
"Кнопки внизу или команды:\n"
|
||||
"➕ /add <имя> — создать клиента\n"
|
||||
"\U0001F5D1 /del <имя> — удалить\n"
|
||||
"\U0001F4CB /list — список\n"
|
||||
"\U0001F4CA /status — статус")
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": rep, "parse_mode": "HTML", "reply_markup": MAIN_KB})
|
||||
except Exception:
|
||||
time.sleep(10)
|
||||
|
||||
|
||||
def get_wg_peers():
|
||||
"""Parse `wg show wg0` to get active peers with transfer/handshake info."""
|
||||
try:
|
||||
@@ -767,7 +908,7 @@ input:focus{outline:none;border-color:#4f46e5}
|
||||
CONTENT
|
||||
<div class="footer">
|
||||
<b style="color:#a5b4fc">PCA Phobos Panel</b> — панель управления © <a href="https://github.com/andrey271192/PCA_Phobos" target="_blank" rel="noopener">andrey271192</a><br>
|
||||
Поддержать проект: <a href="https://boosty.to/andrey27/donate" target="_blank" rel="noopener">💖 Boosty</a> · <a href="https://finance.ozon.ru/apps/sbp/ozonbankpay/019dc200-2a5d-7931-a619-782d285f6798" target="_blank" rel="noopener">💳 Ozon Bank</a> · <a href="https://t.me/c/2474115507/78722" target="_blank" rel="noopener">✉️ Telegram</a>
|
||||
Поддержать проект: <a href="https://boosty.to/andrey27/donate" target="_blank" rel="noopener">💖 Boosty</a> · <a href="https://finance.ozon.ru/apps/sbp/ozonbankpay/019dc200-2a5d-7931-a619-782d285f6798" target="_blank" rel="noopener">💳 Ozon Bank</a> · <a href="https://t.me/PCAdministration" target="_blank" rel="noopener">✉️ Telegram</a>
|
||||
<div style="margin-top:8px;font-size:.88em;color:#475569;line-height:1.7;text-align:left;max-width:660px;margin:8px auto 0">
|
||||
<b>Создано на основе открытых проектов:</b><br>
|
||||
• <a href="https://github.com/Ground-Zerro/Phobos" target="_blank" rel="noopener">Phobos</a> — обфусцированный WireGuard VPN, автор <b>Ground_Zerro</b> · <a href="https://boosty.to/ground_zerro" target="_blank" rel="noopener">поддержать</a><br>
|
||||
|
||||
Reference in New Issue
Block a user