mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-11 14:17:31 +01:00
The tally was one integer per person, deleted after each post. Nothing dated survived it, so weeks, months, records, streaks and weekday averages were all unanswerable. This replaces it with an append-only per-message log holding metadata only -- never a message body -- and rebuilds the nightly report on top. What changes for the group: a photo posted without a caption now counts (it was worth zero), stickers count, the bot's own messages no longer do, people who said nothing appear with a 0, and the report covers the previous full calendar day in Europe/Warsaw instead of "since the last post" -- which used to merge two days whenever a group went quiet. Notable decisions, each with the trap it avoids: - Events and people are PERMANENT_TABLES: neither forget_group nor a future SCHEMA_VERSION bump may drop them. Both paths used to cost a day's counter and would now cost the entire history, and forget_group fires on a listing that merely omits members. - is_own comes from which envelope branch carried the payload, not from comparing identities. The account is spelled as a uuid on some frames and a +E.164 number on others, so any comparison misses one of them. - The roster is stashed in refresh(), not _adopt(), which returns early once the watched set stops changing -- i.e. always, in the steady state. - The roster matches on uuid OR number because /v1/groups spells kuhy as +48123456789 while his messages carry an ACI uuid. Joining on uuid alone would have listed him twice every night, once with 0. - Members whose display name we have never seen are counted, not named: their only spellings are a uuid or a phone number. - (group, uuid, sent_at_ms) is the primary key, so a websocket redelivery after a reconnect cannot inflate the counts. - Days come from a stored Warsaw date string, never a timestamp range: 2026-03-29 is 23 hours long and 2026-10-25 is 25. - Polish number agreement is a real rule with a 12-14 exception, so "44 znaki" and "45 znaków" are both spelled correctly. config.py and startup.py were two lines under the 250-line cap and both had to grow, so config_env and startup_retry come out of them first, as pure moves. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
139 lines
4.8 KiB
Python
139 lines
4.8 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
|
"""Reading a :class:`~signal_bot.config.Config` out of the environment.
|
|
|
|
Split out of ``config.py`` so both stay under the 250-line cap. "What the
|
|
settings are" and "how they are parsed and validated" are two things, and only
|
|
the first is imported by the rest of the bot.
|
|
|
|
The dependency runs one way -- this module imports ``config``, never the
|
|
reverse -- so ``load_config`` is imported from here rather than re-exported
|
|
from ``config``. A re-export would need an import at the bottom of ``config``
|
|
and would break depending on which module was imported first.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
from typing import TYPE_CHECKING
|
|
|
|
from dotenv import load_dotenv
|
|
|
|
from signal_bot.config import (
|
|
DEFAULT_API_BASE_URL,
|
|
DEFAULT_BIND_HOST,
|
|
DEFAULT_BIND_PORT,
|
|
DEFAULT_COOLDOWN_SECONDS,
|
|
DEFAULT_DATABASE_PATH,
|
|
DEFAULT_LOG_LEVEL,
|
|
DEFAULT_REPORT_HOUR,
|
|
DEFAULT_REPORT_MINUTE,
|
|
DEFAULT_SILENCE_SECONDS,
|
|
MAX_HOUR,
|
|
MAX_MINUTE,
|
|
MAX_PORT,
|
|
Config,
|
|
)
|
|
from signal_bot.endpoints import (
|
|
DEFAULT_CAT_API_URL,
|
|
DEFAULT_COMMONS_API_URL,
|
|
DEFAULT_DOG_API_URL,
|
|
DEFAULT_GECKO_API_URL,
|
|
)
|
|
from signal_bot.groups import ConfigError, parse_group_ids
|
|
from signal_bot.trust import parse_trusted_inviters
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Mapping
|
|
|
|
__all__ = ["load_config"]
|
|
|
|
|
|
def _require(env: Mapping[str, str], key: str) -> str:
|
|
"""Return a non-empty environment value or raise ConfigError."""
|
|
value = env.get(key, "").strip()
|
|
if not value:
|
|
msg = f"{key} is required and must not be empty."
|
|
raise ConfigError(msg)
|
|
return value
|
|
|
|
|
|
def _positive_int(env: Mapping[str, str], key: str, default: int) -> int:
|
|
"""Return an int environment value, falling back to default when unset."""
|
|
raw = env.get(key, "").strip()
|
|
if not raw:
|
|
return default
|
|
try:
|
|
value = int(raw)
|
|
except ValueError:
|
|
msg = f"{key} must be an integer, got {raw!r}"
|
|
raise ConfigError(msg) from None
|
|
if value < 0:
|
|
msg = f"{key} must not be negative, got {value}"
|
|
raise ConfigError(msg)
|
|
return value
|
|
|
|
|
|
def _report_time(env: Mapping[str, str]) -> tuple[int, int]:
|
|
"""Return the validated (hour, minute) the daily report fires at."""
|
|
hour = _positive_int(env, "REPORT_HOUR", DEFAULT_REPORT_HOUR)
|
|
minute = _positive_int(env, "REPORT_MINUTE", DEFAULT_REPORT_MINUTE)
|
|
if hour > MAX_HOUR or minute > MAX_MINUTE:
|
|
msg = f"REPORT_HOUR/REPORT_MINUTE out of range: {hour:02d}:{minute:02d}"
|
|
raise ConfigError(msg)
|
|
return hour, minute
|
|
|
|
|
|
def _log_level(env: Mapping[str, str]) -> str:
|
|
"""Return the validated logging level name."""
|
|
log_level = env.get("LOG_LEVEL", "").strip().upper() or DEFAULT_LOG_LEVEL
|
|
if log_level not in logging.getLevelNamesMapping():
|
|
msg = f"LOG_LEVEL must be a logging level name, got {log_level!r}"
|
|
raise ConfigError(msg)
|
|
return log_level
|
|
|
|
|
|
def _bind_port(env: Mapping[str, str]) -> int:
|
|
"""Return the validated port the readiness probe binds to."""
|
|
bind_port = _positive_int(env, "BIND_PORT", DEFAULT_BIND_PORT)
|
|
if not 1 <= bind_port <= MAX_PORT:
|
|
msg = f"BIND_PORT must be between 1 and {MAX_PORT}, got {bind_port}"
|
|
raise ConfigError(msg)
|
|
return bind_port
|
|
|
|
|
|
def load_config(env: dict[str, str] | None = None, *, use_dotenv: bool = True) -> Config:
|
|
"""Build a Config from the environment, failing loudly on anything missing.
|
|
|
|
Args:
|
|
env: Mapping to read instead of os.environ. Used by the tests.
|
|
use_dotenv: Load a local .env file first. Disabled in tests.
|
|
|
|
Returns:
|
|
A validated, immutable Config.
|
|
"""
|
|
if env is None:
|
|
if use_dotenv:
|
|
load_dotenv()
|
|
env = dict(os.environ)
|
|
|
|
hour, minute = _report_time(env)
|
|
return Config(
|
|
phone_number=_require(env, "PHONE_NUMBER"),
|
|
group_ids=parse_group_ids(env),
|
|
api_base_url=env.get("API_BASE_URL", "").strip() or DEFAULT_API_BASE_URL,
|
|
database_path=env.get("DATABASE_PATH", "").strip() or DEFAULT_DATABASE_PATH,
|
|
report_hour=hour,
|
|
report_minute=minute,
|
|
cooldown_seconds=_positive_int(env, "COOLDOWN_SECONDS", DEFAULT_COOLDOWN_SECONDS),
|
|
cat_api_url=env.get("CAT_API_URL", "").strip() or DEFAULT_CAT_API_URL,
|
|
dog_api_url=env.get("DOG_API_URL", "").strip() or DEFAULT_DOG_API_URL,
|
|
gecko_api_url=env.get("GECKO_API_URL", "").strip() or DEFAULT_GECKO_API_URL,
|
|
commons_api_url=env.get("COMMONS_API_URL", "").strip() or DEFAULT_COMMONS_API_URL,
|
|
bind_host=env.get("BIND_HOST", "").strip() or DEFAULT_BIND_HOST,
|
|
bind_port=_bind_port(env),
|
|
log_level=_log_level(env),
|
|
trusted_inviters=parse_trusted_inviters(env),
|
|
silence_seconds=_positive_int(env, "SILENCE_SECONDS", DEFAULT_SILENCE_SECONDS),
|
|
)
|