Fix telegram-archiver: graceful startup without .env + dev tools

This commit is contained in:
2026-02-19 22:22:11 +03:00
parent 5e9815b167
commit 1d23afd8d0
11 changed files with 563 additions and 38 deletions
+35 -11
View File
@@ -4,9 +4,17 @@ Uses pydantic-settings for .env file parsing and validation.
"""
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import Field
from pydantic import Field, ValidationError
from pathlib import Path
from typing import Optional
import logging
logger = logging.getLogger(__name__)
class SettingsError(Exception):
"""Raised when settings cannot be loaded."""
pass
class Settings(BaseSettings):
@@ -19,10 +27,10 @@ class Settings(BaseSettings):
extra="ignore",
)
# Telegram API credentials
api_id: int = Field(..., description="Telegram API ID from my.telegram.org")
api_hash: str = Field(..., description="Telegram API Hash from my.telegram.org")
phone: str = Field(..., description="Phone number for Telegram account")
# Telegram API credentials - required for archiving to work
api_id: Optional[int] = Field(None, description="Telegram API ID from my.telegram.org")
api_hash: Optional[str] = Field(None, description="Telegram API Hash from my.telegram.org")
phone: Optional[str] = Field(None, description="Phone number for Telegram account")
# Session configuration
session_name: str = Field(
@@ -63,8 +71,18 @@ class Settings(BaseSettings):
"""Return full path to session file."""
return Path(__file__).parent / f"{self.session_name}.session"
@property
def is_configured(self) -> bool:
"""Check if credentials are configured."""
return bool(self.api_id and self.api_hash and self.phone)
def validate_credentials(self) -> bool:
"""Validate that required credentials are present."""
"""Validate that required credentials are present and valid."""
if not self.is_configured:
raise SettingsError(
"Missing Telegram credentials. "
"Set API_ID, API_HASH, and PHONE in .env file or environment variables."
)
if self.api_id <= 0:
raise ValueError("API_ID must be a positive integer")
if len(self.api_hash) < 10:
@@ -75,13 +93,19 @@ class Settings(BaseSettings):
# Global settings instance
settings: Optional[Settings] = None
_settings: Optional[Settings] = None
def get_settings() -> Settings:
"""Get or create settings instance."""
global settings
if settings is None:
settings = Settings()
settings.validate_credentials()
global _settings
if _settings is None:
_settings = Settings()
return _settings
def get_required_settings() -> Settings:
"""Get settings and ensure credentials are configured."""
settings = get_settings()
settings.validate_credentials()
return settings