diff --git a/bots/_smoke_test.py b/bots/_smoke_test.py index aea4651..5e642ff 100644 --- a/bots/_smoke_test.py +++ b/bots/_smoke_test.py @@ -64,7 +64,10 @@ class FakeBot: def test_polling(): + from meetings_telegram_bot.config import _resolve_timezone + tmp = tempfile.mkdtemp() + tz = _resolve_timezone(os.getenv("TIMEZONE", "")) cfg = Config( api_base_url="http://x", api_login="u", @@ -72,7 +75,9 @@ def test_polling(): bot_token="t", chat_id="@g", state_file=os.path.join(tmp, "state.json"), + timezone=tz, ) + print("polling timezone:", tz or "local") api = FakeApi([mk(1), mk(2), mk(3)]) tb = FakeBot() @@ -81,11 +86,15 @@ def test_polling(): assert b.poll_once() == 0 and len(tb.sent) == 0 # first run seeds silently print("run1 (seed) announced 0 sent 0") - api._m.append(mk(4, title="Design review")) + # Fixture meetings are scheduled 1 hour in the future (see mk()). + new_meeting = mk(4, title="Design review") + api._m.append(new_meeting) b2 = MeetingsBot(cfg, api=api, bot=tb, store=StateStore(cfg.state_file)) b2.start() assert b2.poll_once() == 1 and len(tb.sent) == 1 # one new meeting posted print("run2 (new) announced 1 sent 1") + print("scheduled (UTC): %s -> shown as: %s" + % (new_meeting.scheduled_at.strftime("%Y-%m-%d %H:%M"), tz or "local")) print("--- message ---") print(tb.sent[0][1]) print("--- end ---") @@ -130,6 +139,26 @@ def test_proxy(): print("proxy wiring OK") +def test_timezone(): + from datetime import timezone as dt_timezone + + from meetings_telegram_bot.config import _resolve_timezone + from meetings_telegram_bot.messages import format_new_meeting + + gmt3 = _resolve_timezone("GMT+3") + assert gmt3.utcoffset(None) == timedelta(hours=3) + assert _resolve_timezone("") is None + assert _resolve_timezone("UTC").utcoffset(None) == timedelta(0) + assert _resolve_timezone("UTC+05:30").utcoffset(None) == timedelta(hours=5, minutes=30) + # A fixed instant to check the rendered hour shifts by +3. + sched = datetime(2026, 1, 1, 12, 0, tzinfo=dt_timezone.utc) + text = format_new_meeting(mk(1, sched=sched), tz=gmt3) + assert "15:00" in text, text # 12:00 UTC rendered as 15:00 at GMT+3 + assert "GMT+3" in text, text + print("timezone OK") + + if __name__ == "__main__": test_polling() test_proxy() + test_timezone() diff --git a/bots/meetings_telegram_bot/.env.example b/bots/meetings_telegram_bot/.env.example index c8318ae..4a7f258 100644 --- a/bots/meetings_telegram_bot/.env.example +++ b/bots/meetings_telegram_bot/.env.example @@ -11,5 +11,8 @@ TELEGRAM_CHAT_ID=@my-group # Optional. BOT_POLL_INTERVAL_SECONDS=900 BOT_STATE_FILE=state.json +# Meeting times displayed in this zone: IANA name or GMT offset. +# Examples: Europe/Moscow, America/New_York, GMT+3, UTC+05:30. Empty = local. +TIMEZONE=GMT+3 # Route API + Telegram traffic through SOCKS5 (needs requests[socks]). SOCKS5_PROXY= diff --git a/bots/meetings_telegram_bot/README.md b/bots/meetings_telegram_bot/README.md index 09617ac..4132213 100644 --- a/bots/meetings_telegram_bot/README.md +++ b/bots/meetings_telegram_bot/README.md @@ -20,8 +20,13 @@ API_LOGIN=bot-user API_PASSWORD=change-me TELEGRAM_BOT_TOKEN=123456:ABC-DEF-your-token TELEGRAM_CHAT_ID=@my-group +TIMEZONE=GMT+3 ``` +`TIMEZONE` sets the zone for the times in posts. Use an IANA name +(`Europe/Moscow`) or a GMT offset (`GMT+3`, `UTC+05:30`). Leave it empty to use +the machine's local time. + Get the bot token from [@BotFather](https://t.me/BotFather). For a public group use `@group_name`; for a private group use the numeric chat id (negative). diff --git a/bots/meetings_telegram_bot/__main__.py b/bots/meetings_telegram_bot/__main__.py index 7588e8c..58d277e 100644 --- a/bots/meetings_telegram_bot/__main__.py +++ b/bots/meetings_telegram_bot/__main__.py @@ -74,6 +74,7 @@ def _check(cfg: Config) -> int: print(f" TELEGRAM_CHAT_ID = {cfg.chat_id}") print(f" BOT_POLL_INTERVAL_SECONDS = {cfg.poll_interval_seconds}") print(f" BOT_STATE_FILE = {cfg.state_file}") + print(f" TIMEZONE = {cfg.timezone or 'local'}") print(f" SOCKS5_PROXY = {_mask_proxy(cfg.socks5_proxy)}") return 0 diff --git a/bots/meetings_telegram_bot/bot.py b/bots/meetings_telegram_bot/bot.py index 7519d94..f0cffcb 100644 --- a/bots/meetings_telegram_bot/bot.py +++ b/bots/meetings_telegram_bot/bot.py @@ -109,7 +109,9 @@ class MeetingsBot: return meeting.scheduled_at < datetime.now(timezone.utc) - STALE_MEETING_GRACE def _announce(self, meeting: Meeting) -> bool: - text = format_new_meeting(meeting, web_base_url=self.cfg.api_base_url) + text = format_new_meeting( + meeting, web_base_url=self.cfg.api_base_url, tz=self.cfg.timezone + ) if len(text) > TELEGRAM_MAX_MESSAGE_LENGTH: text = text[: TELEGRAM_MAX_MESSAGE_LENGTH - 3] + "..." try: diff --git a/bots/meetings_telegram_bot/config.py b/bots/meetings_telegram_bot/config.py index f273216..6ecc15c 100644 --- a/bots/meetings_telegram_bot/config.py +++ b/bots/meetings_telegram_bot/config.py @@ -3,7 +3,9 @@ from __future__ import annotations import os +import re from dataclasses import dataclass +from datetime import timedelta, timezone, tzinfo from pathlib import Path DEFAULT_ENV_FILE = Path(__file__).resolve().parent / ".env" @@ -12,11 +14,44 @@ HTTP_TIMEOUT_SECONDS = 20.0 MEETINGS_PAGE_LIMIT = 200 DEFAULT_STATE_FILE = "state.json" +_OFFSET_RE = re.compile(r"^(?:UTC|GMT)?\s*([+-])(\d{1,2})(?::?(\d{2}))?$", re.IGNORECASE) + class ConfigError(Exception): """Raised when required configuration is missing or invalid.""" +def _resolve_timezone(value: str) -> tzinfo | None: + """Resolve TIMEZONE to a tzinfo. + + Accepts an IANA name (Europe/Moscow) or a GMT/UTC offset (GMT+3, UTC+05:30). + Empty means use the machine's local timezone. + """ + name = (value or "").strip() + if not name: + return None + if name.upper() in ("UTC", "GMT", "Z"): + return timezone.utc + + match = _OFFSET_RE.match(name) + if match: + sign = 1 if match.group(1) == "+" else -1 + hours = int(match.group(2)) + minutes = int(match.group(3) or 0) + if hours > 23 or minutes > 59: + raise ConfigError(f"invalid TIMEZONE offset {value!r}") + return timezone(sign * timedelta(hours=hours, minutes=minutes), name.upper()) + + try: + from zoneinfo import ZoneInfo + + return ZoneInfo(name) + except (ValueError, KeyError) as exc: + raise ConfigError( + f"invalid TIMEZONE {value!r}; use an IANA name (Europe/Moscow) or an offset (GMT+3)" + ) from exc + + def _unquote(value: str) -> str: if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'): return value[1:-1] @@ -83,6 +118,8 @@ class Config: poll_interval_seconds: int = DEFAULT_POLL_INTERVAL_SECONDS state_file: str = DEFAULT_STATE_FILE socks5_proxy: str = "" + # Timezone used to display meeting times; None means local time. + timezone: tzinfo | None = None def load_config(env_file: Path | None = None) -> Config: @@ -105,4 +142,5 @@ def load_config(env_file: Path | None = None) -> Config: poll_interval_seconds=poll_interval, state_file=_env_str("BOT_STATE_FILE", default=DEFAULT_STATE_FILE), socks5_proxy=socks5_proxy, + timezone=_resolve_timezone(_env_str("TIMEZONE")), ) diff --git a/bots/meetings_telegram_bot/messages.py b/bots/meetings_telegram_bot/messages.py index deddbe5..859fb39 100644 --- a/bots/meetings_telegram_bot/messages.py +++ b/bots/meetings_telegram_bot/messages.py @@ -2,21 +2,25 @@ from __future__ import annotations +from datetime import tzinfo from html import escape from urllib.parse import quote from .api import Meeting -def _format_local(moment) -> str: - return moment.astimezone().strftime("%a, %d %b %Y %H:%M %Z") if moment else "unknown" +def _format_time(moment, tz: tzinfo | None) -> str: + # astimezone(None) uses the machine's local timezone. + return moment.astimezone(tz).strftime("%a, %d %b %Y %H:%M %Z") if moment else "unknown" def room_link(web_base_url: str, room: str) -> str: return f"{(web_base_url or '').rstrip('/')}/rooms/{quote(room, safe='')}" -def format_new_meeting(meeting: Meeting, *, web_base_url: str = "") -> str: +def format_new_meeting( + meeting: Meeting, *, web_base_url: str = "", tz: tzinfo | None = None +) -> str: """Render an announcement; the join link appears only when a room exists.""" lines = ["New meeting scheduled", ""] lines.append(f"{escape(meeting.title) or '(untitled meeting)'}") @@ -25,7 +29,7 @@ def format_new_meeting(meeting: Meeting, *, web_base_url: str = "") -> str: lines += ["", escape(meeting.intent)] lines.append("") - lines.append(f"When: {escape(_format_local(meeting.scheduled_at))}") + lines.append(f"When: {escape(_format_time(meeting.scheduled_at, tz))}") lines.append(f"Planned by: {escape(meeting.created_by_name or 'unknown')}") if meeting.room: diff --git a/bots/requirements.txt b/bots/requirements.txt index d54b33c..19e806d 100644 --- a/bots/requirements.txt +++ b/bots/requirements.txt @@ -7,3 +7,5 @@ # The .env parser is built in, so no extra dependency is needed for it. requests[socks]>=2.31,<3 pyTelegramBotAPI>=4.14,<5 +# IANA timezone data (needed for TIMEZONE=Europe/Moscow on Windows). +tzdata>=2023.3