File size: 3,178 Bytes
a81d1fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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