- package src/signal-cal-bot -> src/signal_cal_bot - distribution and CLI entry point: signal-cal-bot - env vars CALBOT_* -> SIGNAL_CAL_BOT_* - database file, container names, user agents and logs renamed - docs and compose updated
200 lines
6.4 KiB
Python
200 lines
6.4 KiB
Python
"""Entry point: run the bot loop, or dump what would be posted."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import logging
|
|
import os
|
|
import signal
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
from datetime import datetime, timedelta, timezone
|
|
from pathlib import Path
|
|
from zoneinfo import ZoneInfo
|
|
|
|
import httpx
|
|
|
|
from .config import Config, ConfigError, load_config
|
|
from .expand import parse_events
|
|
from .feed import Feed
|
|
from .format import find_postcode, render_post, venue_from_description, venue_from_location
|
|
from .images import ImageService, PageScraper
|
|
from .scheduler import Bot
|
|
from .signal_client import SignalClient
|
|
from .store import Store
|
|
from .watchdog import Watchdog
|
|
|
|
log = logging.getLogger("signal_cal_bot")
|
|
|
|
TICK_SECONDS = 30
|
|
|
|
|
|
def _logging(level: str) -> None:
|
|
logging.basicConfig(
|
|
level=getattr(logging, level.upper(), logging.INFO),
|
|
format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
|
|
)
|
|
|
|
|
|
def _http_client() -> httpx.Client:
|
|
return httpx.Client(
|
|
follow_redirects=True,
|
|
headers={"User-Agent": "signal-cal-bot/0.1 (iCalendar to Signal bridge)"},
|
|
limits=httpx.Limits(max_connections=8, max_keepalive_connections=4),
|
|
)
|
|
|
|
|
|
def dump(config: Config) -> int:
|
|
"""Print rendered posts for the next events, without touching Signal or state."""
|
|
now = datetime.now(timezone.utc)
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
store = Store(Path(tmp) / "dump.sqlite3")
|
|
http = _http_client()
|
|
try:
|
|
feed = Feed(
|
|
config.calendar.url, store, config.calendar.refresh_minutes, http
|
|
)
|
|
try:
|
|
response = feed.fetch(now)
|
|
except httpx.HTTPError as exc:
|
|
print(f"feed fetch failed: {exc}", file=sys.stderr)
|
|
return 1
|
|
if response.content is None:
|
|
print("feed said not-modified (304); nothing to dump")
|
|
return 0
|
|
|
|
events = parse_events(
|
|
response.content,
|
|
now,
|
|
now + timedelta(days=config.calendar.window_days),
|
|
config.calendar.timezone,
|
|
)
|
|
local_tz = ZoneInfo(config.calendar.timezone)
|
|
for event in events:
|
|
venue = venue_from_location(event.location) or venue_from_description(
|
|
event.description
|
|
)
|
|
postcode = find_postcode(event.location, event.description)
|
|
print("=" * 60)
|
|
print(f"{event.start.astimezone(local_tz):%Y-%m-%d %H:%M} [{event.series_id}]")
|
|
print("-" * 60)
|
|
print(
|
|
render_post(
|
|
event,
|
|
config.format,
|
|
local_tz,
|
|
venue=venue,
|
|
postcode=postcode,
|
|
link=event.url,
|
|
)
|
|
)
|
|
print(f"image: {event.image_url or '(none)'}")
|
|
print("=" * 60)
|
|
print(f"{len(events)} event(s)")
|
|
return 0
|
|
finally:
|
|
store.close()
|
|
http.close()
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(prog="signal-cal-bot", description=__doc__)
|
|
parser.add_argument(
|
|
"--config",
|
|
default=os.environ.get("SIGNAL_CAL_BOT_CONFIG", "config.toml"),
|
|
help="path to config.toml (default: $SIGNAL_CAL_BOT_CONFIG or ./config.toml)",
|
|
)
|
|
parser.add_argument("--once", action="store_true", help="run a single tick and exit")
|
|
parser.add_argument("--dump", action="store_true", help="print posts for upcoming events")
|
|
parser.add_argument("--check", action="store_true", help="validate config and connection")
|
|
parser.add_argument("--log-level", default=os.environ.get("LOG_LEVEL", "INFO"))
|
|
args = parser.parse_args(argv)
|
|
|
|
try:
|
|
config = load_config(args.config)
|
|
except ConfigError as exc:
|
|
print(f"config error: {exc}", file=sys.stderr)
|
|
return 2
|
|
|
|
_logging(args.log_level)
|
|
|
|
if args.dump:
|
|
return dump(config)
|
|
|
|
if not config.signal.group_id.startswith("group."):
|
|
log.warning(
|
|
"signal.group_id does not start with 'group.' — "
|
|
"use the internal_id from GET /v1/groups/<number>"
|
|
)
|
|
|
|
store = Store(config.db_path)
|
|
http = _http_client()
|
|
sender = SignalClient(config.signal.api_url, config.signal.number)
|
|
watchdog = Watchdog(config.watchdog, sender, config.signal.number, config.signal.text_mode)
|
|
|
|
if args.check:
|
|
if sender.account_exists():
|
|
log.info("Signal account %s is linked", config.signal.number)
|
|
else:
|
|
log.error(
|
|
"Signal account %s not found at %s. Link it first: "
|
|
"open %s/v1/qrcodelink?device_name=signal-cal-bot and scan the QR code.",
|
|
config.signal.number,
|
|
config.signal.api_url,
|
|
config.signal.api_url,
|
|
)
|
|
return 1
|
|
log.info("config OK: %s", config.config_path)
|
|
return 0
|
|
|
|
bot = Bot(
|
|
config=config,
|
|
store=store,
|
|
feed=Feed(config.calendar.url, store, config.calendar.refresh_minutes, http),
|
|
sender=sender,
|
|
images=ImageService(config.images, config.cache_dir, http),
|
|
scraper=PageScraper(config.images, store, http),
|
|
watchdog=watchdog,
|
|
http=http,
|
|
)
|
|
|
|
if args.once:
|
|
bot.tick()
|
|
return 0
|
|
|
|
stopping = False
|
|
|
|
def stop(_signum, _frame):
|
|
nonlocal stopping
|
|
stopping = True
|
|
|
|
signal.signal(signal.SIGTERM, stop)
|
|
signal.signal(signal.SIGINT, stop)
|
|
|
|
log.info("signal-cal-bot started (feed=%s, group=%s)", config.calendar.url, config.signal.group_id)
|
|
if not sender.account_exists():
|
|
log.warning(
|
|
"Signal account not linked yet. Open %s/v1/qrcodelink?device_name=signal-cal-bot",
|
|
config.signal.api_url,
|
|
)
|
|
|
|
while not stopping:
|
|
try:
|
|
bot.tick()
|
|
except Exception: # noqa: BLE001 - keep the service alive
|
|
log.exception("tick failed")
|
|
deadline = time.monotonic() + TICK_SECONDS
|
|
while not stopping and time.monotonic() < deadline:
|
|
time.sleep(0.5)
|
|
|
|
log.info("signal-cal-bot stopped")
|
|
store.close()
|
|
http.close()
|
|
sender.close()
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|