prtooltest / diagnose_telegram.py
Dink0's picture
Fix Telegram delivery with an authenticated free-tier relay (#1)
a81d1fc
Raw History Blame Contribute Delete
3.18 kB
import getpass
import json
import os
from pathlib import Path
import re
import urllib.error
import urllib.request
from receiver import Clients, Config, network_error_category
def summarize(report):
fields = {"method", "ok", "error", "seconds", "chat_type", "permissions",
"membership", "is_member", "can_send_messages", "can_post_messages"}
return {"status": report.get("status"),
"checks": [{key: value for key, value in check.items() if key in fields}
for check in report.get("checks", [])]}
def compare(token, chat_id, webhook_secret):
config = Config(secret=webhook_secret or "a" * 32,
telegram_token=token, chat_id=chat_id)
report = {"mac": summarize(Clients(config).diagnose_telegram())}
if webhook_secret:
try:
request = urllib.request.Request(
"https://pranalytics-prtooltest.hf.space/diagnostics/" + webhook_secret)
with urllib.request.urlopen(request, timeout=40) as response:
report["space"] = summarize(json.loads(response.read(65536)))
except urllib.error.HTTPError as exc:
report["space"] = {"error": "diagnostics_http_" + str(exc.code)}
exc.close()
except OSError as exc:
report["space"] = {"error": "diagnostics_" + network_error_category(exc)}
except (ValueError, TypeError, AttributeError):
report["space"] = {"error": "diagnostics_invalid_response"}
return report
def main():
print("Проверка только читает настройки. Сообщения не отправляются.")
print("Значения вводятся скрыто и не сохраняются. Используйте значения, заданные при настройке HF.")
token = getpass.getpass("TELEGRAM_BOT_TOKEN: ").strip()
chat_id = getpass.getpass("TELEGRAM_CHAT_ID: ").strip()
webhook_secret = getpass.getpass("WEBHOOK_SECRET (Enter — пропустить проверку Space): ").strip()
if not re.fullmatch(r"\d+:[A-Za-z0-9_-]+", token):
raise SystemExit("Неверный формат TELEGRAM_BOT_TOKEN.")
if not re.fullmatch(r"-?\d+|@[A-Za-z0-9_]+", chat_id):
raise SystemExit("Неверный формат TELEGRAM_CHAT_ID.")
if webhook_secret and not re.fullmatch(r"[A-Za-z0-9_-]{24,}", webhook_secret):
raise SystemExit("Неверный формат WEBHOOK_SECRET.")
result = json.dumps(compare(token, chat_id, webhook_secret), ensure_ascii=False, indent=2)
destination = Path(__file__).with_name(".local-diagnostics.json")
descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
with os.fdopen(descriptor, "w") as report_file:
report_file.write(result + "\n")
print(result)
print("Обезличенный отчёт сохранён. Вернитесь в чат и напишите: готово.")
if __name__ == "__main__":
try:
main()
except (KeyboardInterrupt, EOFError):
raise SystemExit("Проверка отменена.") from None