File size: 3,156 Bytes
a571bd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
83
84
from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path

from dotenv import load_dotenv

DEFAULT_SYSTEM_PROMPT = (
    "Ты дружелюбный личный помощник в Telegram. Отвечай по-русски, ясно, кратко "
    "и по делу. В группах учитывай, кто именно пишет, и не путай участников. "
    "Если вопрос требует свежей информации или анализа ссылки, используй доступные "
    "инструменты поиска и URL-контекста."
)

FALLBACK_MODELS = (
    "gemini-3-flash-preview",
    "gemini-2.5-flash",
    "gemini-2.5-flash-lite",
    "gemini-flash-latest",
)


@dataclass(frozen=True)
class Settings:
    telegram_bot_token: str
    gemini_api_key: str
    database_path: Path
    default_model: str
    max_history_messages: int
    default_system_prompt: str
    run_mode: str
    app_base_url: str | None
    webhook_secret: str | None
    port: int

    @classmethod
    def from_env(cls) -> Settings:
        load_dotenv()

        telegram_bot_token = os.environ.get("TELEGRAM_BOT_TOKEN", "").strip()
        gemini_api_key = os.environ.get("GEMINI_API_KEY", "").strip()
        missing = []
        if not telegram_bot_token:
            missing.append("TELEGRAM_BOT_TOKEN")
        if not gemini_api_key:
            missing.append("GEMINI_API_KEY")
        if missing:
            joined = ", ".join(missing)
            raise RuntimeError(f"Missing required environment variables: {joined}")

        max_history_messages = int(os.environ.get("MAX_HISTORY_MESSAGES", "30"))
        if max_history_messages < 1:
            raise RuntimeError("MAX_HISTORY_MESSAGES must be at least 1")

        run_mode = os.environ.get("RUN_MODE", "polling").strip().lower() or "polling"
        if run_mode not in {"polling", "webhook"}:
            raise RuntimeError("RUN_MODE must be either 'polling' or 'webhook'")

        app_base_url = os.environ.get("APP_BASE_URL", "").strip() or None
        webhook_secret = os.environ.get("WEBHOOK_SECRET", "").strip() or None
        port = int(os.environ.get("PORT", "7860"))
        if port < 1:
            raise RuntimeError("PORT must be a positive integer")

        if run_mode == "webhook" and not app_base_url:
            raise RuntimeError("APP_BASE_URL is required when RUN_MODE=webhook")

        return cls(
            telegram_bot_token=telegram_bot_token,
            gemini_api_key=gemini_api_key,
            database_path=Path(os.environ.get("DATABASE_PATH", "data/botik.sqlite3")),
            default_model=os.environ.get("DEFAULT_GEMINI_MODEL", FALLBACK_MODELS[0]).strip(),
            max_history_messages=max_history_messages,
            default_system_prompt=os.environ.get(
                "DEFAULT_SYSTEM_PROMPT",
                DEFAULT_SYSTEM_PROMPT,
            ).strip(),
            run_mode=run_mode,
            app_base_url=app_base_url,
            webhook_secret=webhook_secret,
            port=port,
        )