2026-10-24 20:01:40 +03:00
|
|
|
"""Poll the API for new meetings and announce them on Telegram."""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
import time
|
|
|
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
|
|
|
|
|
|
import telebot
|
|
|
|
|
from telebot import apihelper
|
|
|
|
|
|
|
|
|
|
from .api import ApiError, AuthError, GoChatApi, Meeting
|
|
|
|
|
from .config import HTTP_TIMEOUT_SECONDS, MEETINGS_PAGE_LIMIT, Config
|
|
|
|
|
from .messages import format_new_meeting
|
|
|
|
|
from .state import State, StateStore
|
|
|
|
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
TELEGRAM_MAX_MESSAGE_LENGTH = 4096
|
|
|
|
|
# Meetings scheduled longer ago than this are recorded but not announced.
|
|
|
|
|
STALE_MEETING_GRACE = timedelta(days=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class MeetingsBot:
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
cfg: Config,
|
|
|
|
|
*,
|
|
|
|
|
api: GoChatApi | None = None,
|
|
|
|
|
bot: telebot.TeleBot | None = None,
|
|
|
|
|
store: StateStore | None = None,
|
|
|
|
|
) -> None:
|
|
|
|
|
self.cfg = cfg
|
|
|
|
|
self.api = api or GoChatApi(
|
|
|
|
|
cfg.api_base_url, timeout=HTTP_TIMEOUT_SECONDS, proxy=cfg.socks5_proxy
|
|
|
|
|
)
|
|
|
|
|
if bot is None:
|
|
|
|
|
if cfg.socks5_proxy:
|
|
|
|
|
apihelper.proxy = {"http": cfg.socks5_proxy, "https": cfg.socks5_proxy}
|
|
|
|
|
bot = telebot.TeleBot(cfg.bot_token, threaded=True, num_threads=1)
|
|
|
|
|
self.bot = bot
|
|
|
|
|
self.store = store or StateStore(cfg.state_file)
|
|
|
|
|
self.state: State = State()
|
|
|
|
|
self._stopping = False
|
|
|
|
|
|
|
|
|
|
def start(self) -> None:
|
|
|
|
|
self.state = self.store.load()
|
|
|
|
|
self.api.restore_session(self.state.session_token, self.state.csrf_token)
|
|
|
|
|
|
|
|
|
|
def stop(self) -> None:
|
|
|
|
|
self._stopping = True
|
|
|
|
|
|
|
|
|
|
def ensure_authenticated(self) -> None:
|
|
|
|
|
if self.api.has_session and self.api.still_authenticated():
|
|
|
|
|
return
|
|
|
|
|
self.api.signin(self.cfg.api_login, self.cfg.api_password)
|
|
|
|
|
|
|
|
|
|
def _persist_session(self) -> None:
|
|
|
|
|
self.state.session_token = self.api.session_token
|
|
|
|
|
self.state.csrf_token = self.api.csrf_token
|
|
|
|
|
|
|
|
|
|
def poll_once(self, *, dry_run: bool = False) -> int:
|
|
|
|
|
"""Fetch meetings, announce new ones, update state. Returns the count."""
|
|
|
|
|
self.ensure_authenticated()
|
|
|
|
|
self._persist_session()
|
|
|
|
|
|
|
|
|
|
meetings = self.api.list_meetings(limit=MEETINGS_PAGE_LIMIT)
|
|
|
|
|
|
|
|
|
|
# First run: remember everything without posting, so history is not spammed.
|
|
|
|
|
if not self.state.initialized:
|
|
|
|
|
self.state.seen_meeting_ids.update(m.id for m in meetings)
|
|
|
|
|
self.state.initialized = True
|
|
|
|
|
self._persist_session()
|
|
|
|
|
self.store.save(self.state)
|
|
|
|
|
log.info("first run: seeded %d meetings without announcing", len(meetings))
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
announced = 0
|
|
|
|
|
for meeting in self._new_meetings(meetings):
|
|
|
|
|
if self._is_stale(meeting):
|
|
|
|
|
self.state.seen_meeting_ids.add(meeting.id)
|
|
|
|
|
log.info("skipping stale meeting %s", meeting.id)
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
if dry_run:
|
|
|
|
|
log.info("[dry-run] would announce meeting %s: %s", meeting.id, meeting.title)
|
|
|
|
|
announced += 1
|
|
|
|
|
self.state.seen_meeting_ids.add(meeting.id)
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
# Mark seen only after a successful send so failures retry next tick.
|
|
|
|
|
if self._announce(meeting):
|
|
|
|
|
self.state.seen_meeting_ids.add(meeting.id)
|
|
|
|
|
announced += 1
|
|
|
|
|
|
|
|
|
|
self._persist_session()
|
|
|
|
|
self.store.save(self.state)
|
|
|
|
|
return announced
|
|
|
|
|
|
|
|
|
|
def _new_meetings(self, meetings: list[Meeting]) -> list[Meeting]:
|
|
|
|
|
new = [m for m in meetings if m.id not in self.state.seen_meeting_ids]
|
|
|
|
|
new.sort(key=lambda m: (m.created_at is None, m.created_at))
|
|
|
|
|
return new
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _is_stale(meeting: Meeting) -> bool:
|
|
|
|
|
if meeting.scheduled_at is None:
|
|
|
|
|
return False
|
|
|
|
|
return meeting.scheduled_at < datetime.now(timezone.utc) - STALE_MEETING_GRACE
|
|
|
|
|
|
|
|
|
|
def _announce(self, meeting: Meeting) -> bool:
|
2026-10-24 20:36:47 +03:00
|
|
|
text = format_new_meeting(
|
|
|
|
|
meeting, web_base_url=self.cfg.api_base_url, tz=self.cfg.timezone
|
|
|
|
|
)
|
2026-10-24 20:01:40 +03:00
|
|
|
if len(text) > TELEGRAM_MAX_MESSAGE_LENGTH:
|
|
|
|
|
text = text[: TELEGRAM_MAX_MESSAGE_LENGTH - 3] + "..."
|
|
|
|
|
try:
|
|
|
|
|
self.bot.send_message(
|
|
|
|
|
self.cfg.chat_id,
|
|
|
|
|
text,
|
|
|
|
|
parse_mode="HTML",
|
|
|
|
|
timeout=int(HTTP_TIMEOUT_SECONDS),
|
|
|
|
|
)
|
|
|
|
|
except apihelper.ApiTelegramException as exc:
|
|
|
|
|
log.error("telegram rejected meeting %s: %s", meeting.id, getattr(exc, "description", exc))
|
|
|
|
|
return False
|
|
|
|
|
except apihelper.ApiException as exc:
|
|
|
|
|
log.error("failed to announce meeting %s: %s", meeting.id, exc)
|
|
|
|
|
return False
|
|
|
|
|
except Exception: # noqa: BLE001
|
|
|
|
|
log.exception("unexpected error announcing meeting %s", meeting.id)
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
log.info("announced new meeting %s: %s", meeting.id, meeting.title)
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
def run(self) -> None:
|
|
|
|
|
self.start()
|
|
|
|
|
interval = self.cfg.poll_interval_seconds
|
|
|
|
|
log.info("bot started: api=%s chat=%s interval=%ss", self.cfg.api_base_url, self.cfg.chat_id, interval)
|
|
|
|
|
while not self._stopping:
|
|
|
|
|
started = time.monotonic()
|
|
|
|
|
try:
|
|
|
|
|
self.poll_once()
|
|
|
|
|
except AuthError as exc:
|
|
|
|
|
log.error("authentication failed: %s", exc)
|
|
|
|
|
except ApiError as exc:
|
|
|
|
|
log.error("api error during poll: %s", exc)
|
|
|
|
|
except Exception: # noqa: BLE001
|
|
|
|
|
log.exception("unexpected error during poll")
|
|
|
|
|
self._sleep(max(0.0, interval - (time.monotonic() - started)))
|
|
|
|
|
|
|
|
|
|
def _sleep(self, seconds: float) -> None:
|
|
|
|
|
deadline = time.monotonic() + seconds
|
|
|
|
|
while not self._stopping and time.monotonic() < deadline:
|
|
|
|
|
time.sleep(min(1.0, deadline - time.monotonic()))
|