49 lines
1.4 KiB
Python
49 lines
1.4 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import os
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
|
||
|
|
def resolve_bot_token(config: dict[str, Any], account_id: str = "default") -> str | None:
|
||
|
|
accounts = config.get("accounts", {})
|
||
|
|
account_cfg = accounts.get(account_id, {})
|
||
|
|
|
||
|
|
token = account_cfg.get("bot_token")
|
||
|
|
if token:
|
||
|
|
return token
|
||
|
|
|
||
|
|
token = config.get("bot_token")
|
||
|
|
if token:
|
||
|
|
return token
|
||
|
|
|
||
|
|
token_file = account_cfg.get("token_file") or config.get("token_file")
|
||
|
|
if token_file and os.path.isfile(token_file):
|
||
|
|
with open(token_file) as f:
|
||
|
|
return f.read().strip()
|
||
|
|
|
||
|
|
env_token = os.getenv("TELEGRAM_BOT_TOKEN")
|
||
|
|
if env_token:
|
||
|
|
return env_token
|
||
|
|
|
||
|
|
env_prefix = os.getenv("TELEGRAM_BOT_TOKEN_PREFIX", "")
|
||
|
|
env_suffix = account_id.upper()
|
||
|
|
env_key = f"{env_prefix}_{env_suffix}" if env_prefix else f"TELEGRAM_BOT_TOKEN_{env_suffix}"
|
||
|
|
env_token = os.getenv(env_key)
|
||
|
|
if env_token:
|
||
|
|
return env_token
|
||
|
|
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def resolve_token_source(config: dict[str, Any], account_id: str = "default") -> str:
|
||
|
|
accounts = config.get("accounts", {})
|
||
|
|
account_cfg = accounts.get(account_id, {})
|
||
|
|
|
||
|
|
if account_cfg.get("bot_token"):
|
||
|
|
return f"accounts.{account_id}.bot_token"
|
||
|
|
if config.get("bot_token"):
|
||
|
|
return "config.bot_token"
|
||
|
|
if account_cfg.get("token_file") or config.get("token_file"):
|
||
|
|
return "token_file"
|
||
|
|
return "env.TELEGRAM_BOT_TOKEN"
|