File size: 2,254 Bytes
d79c5f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import re


def validate_bot_token(token: str | None) -> str:
    """Validate Telegram bot token format.

    Expected format: <integer_id>:<alphanumeric_hash>
    Example: 123456789:AAHdqTcvCH1vGWJxfSeofSAsQK6PALsAW

    Args:
        token: The bot token string to validate. May be None if env var unset.

    Returns:
        The validated token string.

    Raises:
        ValueError: If the token is None, empty, or format is invalid.
    """
    if token is None:
        raise ValueError("BOT_TOKEN is None — environment variable not set")

    stripped = token.strip()
    if not stripped:
        raise ValueError("BOT_TOKEN is empty after stripping whitespace")

    pattern = r"^\d+:[A-Za-z0-9_-]{35,}$"
    if not re.match(pattern, stripped):
        raise ValueError(
            f"BOT_TOKEN format is invalid. "
            f"Expected format: '<id>:<hash_35plus>', got: '{stripped[:6]}...'"
        )

    return stripped


def validate_admin_id(admin_id: str | None) -> str:
    """Validate Telegram admin user ID.

    Must be a positive integer that can be used as a Telegram user ID.

    Args:
        admin_id: The admin ID string to validate. May be None if env var unset.

    Returns:
        The validated admin ID string.

    Raises:
        ValueError: If the admin ID is None, empty, or invalid format.
    """
    if admin_id is None:
        raise ValueError("ADMIN_ID is None — environment variable not set")

    stripped = admin_id.strip()
    if not stripped:
        raise ValueError("ADMIN_ID is empty after stripping whitespace")

    if "." in stripped:
        raise ValueError(
            f"ADMIN_ID must be an integer, got float-like value: '{stripped}'"
        )

    try:
        numeric_id = int(stripped)
    except (ValueError, TypeError) as exc:
        raise ValueError(
            f"ADMIN_ID must be a numeric value, got: '{stripped}'"
        ) from exc

    if numeric_id <= 0:
        raise ValueError(
            f"ADMIN_ID must be a positive integer, got: {numeric_id}"
        )

    if numeric_id > 2**63 - 1:
        raise ValueError(
            f"ADMIN_ID exceeds maximum allowed value (2^63-1), got: {numeric_id}"
        )

    return stripped