import os from dataclasses import dataclass from pathlib import Path from dotenv import load_dotenv ROOT_DIR = Path(__file__).resolve().parent.parent DEFAULT_COMMENT_FILE = ROOT_DIR / "comment.txt" @dataclass(frozen=True) class Config: bot_token: str discussion_chat_id: int comment_text: str def _load_comment_text() -> str: path_raw = os.getenv("COMMENT_FILE", "").strip() path = Path(path_raw) if path_raw else DEFAULT_COMMENT_FILE if not path.is_absolute(): path = ROOT_DIR / path if not path.is_file(): raise SystemExit( f"Comment file not found: {path}. " "Create comment.txt in the project root or set COMMENT_FILE." ) text = path.read_text(encoding="utf-8").strip() if not text: raise SystemExit(f"Comment file is empty: {path}") return text def load_config() -> Config: load_dotenv() bot_token = os.getenv("BOT_TOKEN", "").strip() chat_id_raw = os.getenv("DISCUSSION_CHAT_ID", "").strip() missing = [ name for name, value in ( ("BOT_TOKEN", bot_token), ("DISCUSSION_CHAT_ID", chat_id_raw), ) if not value ] if missing: raise SystemExit( f"Missing required environment variables: {', '.join(missing)}. " "Copy .env.example to .env and fill in the values." ) try: discussion_chat_id = int(chat_id_raw) except ValueError as exc: raise SystemExit( f"DISCUSSION_CHAT_ID must be an integer, got: {chat_id_raw!r}" ) from exc return Config( bot_token=bot_token, discussion_chat_id=discussion_chat_id, comment_text=_load_comment_text(), )