Files
kawaiipunk add77f6cb8 Rename to sigcal-bot
- package src/sigcal_bot, distribution and CLI sigcal-bot
- environment variables SIGCAL_BOT_*
- database file, container names, user agents, logs and QR device name
- docs and changelog updated
2026-11-18 17:06:40 +00:00

337 lines
14 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# sigcal-bot — iCal → Signal
> **Alpha software.** This project is alpha quality and has never had a stable
> release. Behaviour, configuration keys and defaults may change without
> notice between commits, and it has not run in a real group for long. Watch
> the first weeks of posts closely.
>
> **Disclaimer:** this code was generated by LLMs (several different models)
> and has not been audited by a human security professional. Review it before
> relying on it, especially before exposing the Signal API, and treat it as
> provided without warranty. See [Provenance](#provenance).
>
> In general, we recommend using a fresh Signal identity that is only used for sigcal-bot.
>
> This project is independent of and not associated with Signal, the 501(c)(3) nonprofit.
Polls an iCalendar feed and posts events to a Signal group, with the event's
poster image attached. Built for [Commons Calendar ical feed](https://commonscalendar.uk) (The
Events Calendar), but works with any feed that exposes `UID`, `SUMMARY`,
`DTSTART`, `DTEND` and optionally `ATTACH`, `LOCATION`, `URL`.
```
Folk Night
#November #November14
4.30-6.30pm
Old Print Works B12 9AH
https://commonscalendar.uk/event/folk-night/
```
## Behaviour
Each event produces **at most two posts**; every post carries the poster image
when one exists.
| Post | When |
|---|---|
| Announcement | As soon as the event is first seen in the feed |
| Reminder | 3 days before it starts |
| Reminder (fallback) | 09:00 on the day, if the event was added under 3 days out |
Posts are deferred to the next preferred window — **08:00–10:00** or
**18:00–21:00** local time — unless waiting would mean posting after the event
starts (or within an hour of it), in which case they go out immediately.
Everything due in the same window is **batched into one message**. That is also
what merges the "new event" and "today" posts for an event added on the day.
Other rules:
- **First run seeds silently** (`announce.backfill = false`), so enabling the
bot does not dump the whole calendar into the group. Reminders still work for
everything already in the feed.
- **Recurring events are announced once per series**, not once per occurrence.
The feed pre-expands recurrences; announcements are keyed on the series.
- **Events that disappear from the feed** (cancelled) have their pending posts
dropped. Events beyond the feed's coverage are left alone — The Events
Calendar only exports ~30 upcoming events.
- **The watchdog** messages your own number ("Note to Self") if the feed keeps
failing, parses to nothing, or sending fails repeatedly.
## How it works
```
feed (ICS) ──► parse/expand ──► SQLite ──► dispatch ──► signal-cli-rest-api
│ │
reminder_plans + outbox Signal group
```
One tick every 30 s:
1. **Refresh** — conditional GET (ETag/Last-Modified, every `refresh_minutes`).
The feed is parsed and expanded, then reconciled with the database. New
event rows get reminder plans; a new series gets an announcement.
2. **Dispatch** — every outbox row whose time has come is grouped by event,
rendered, and sent as one message.
3. **Heartbeat** — optional once-a-day "alive" note.
Scheduling decisions are persisted, so restarts and feed edits cannot reorder
or duplicate posts. Delivery is at-least-once: a crash between sending and
committing can duplicate exactly one post.
## Quick start
Requirements: Docker (and Docker Compose). A Signal account to link.
### 1. Start signal-cli-rest-api and give the bot an identity
```bash
mkdir -p signal-data data cache
docker compose up -d signal-api
```
The API listens on `127.0.0.1:8080` only (see `docker-compose.yml`), so it is
reachable from the server itself or through an SSH tunnel — not the network.
Keep it that way: anyone who can reach it can send messages as the account.
There are two ways to give the bot a Signal identity.
#### A. Link to your own account (default, quickest)
The bot becomes a linked device of your phone, like Signal Desktop, and every
post appears **as your number**. There is nothing to register — you scan a QR
code once.
**Linking on a headless server.** `/v1/qrcodelink` returns a QR *image* that
the phone must scan, and the server has no browser. Either:
- **SSH tunnel (easiest).** From your laptop:
```bash
ssh -L 8080:localhost:8080 you@server
```
Then open <http://localhost:8080/v1/qrcodelink?device_name=sigcal-bot>
in your local browser and scan it from
**Signal → Settings → Linked devices → +**.
- **Fetch the QR as a file.** On the server:
```bash
curl -s "http://localhost:8080/v1/qrcodelink?device_name=sigcal-bot" \
-o /tmp/link-qr.png
```
Copy it somewhere with a screen (`scp server:/tmp/link-qr.png .`, or
`ssh server cat /tmp/link-qr.png > link-qr.png`), display it, and scan it
with the phone. The QR rotates on every request and the link session is
short-lived: if the scan fails, request a fresh one. Delete the file
afterwards.
Then read back the number and the group ID:
```bash
curl -s http://localhost:8080/v1/accounts
curl -s http://localhost:8080/v1/groups/+447700900000 | jq -r '.[].internal_id'
```
#### B. Register a dedicated number (separate bot identity)
Linking means every post looks like *you* wrote it. For a community group it is
often better to give the bot its own Signal account — its own name and avatar,
not tied to any member, so people do not mistake reminders for a person
speaking, and the bot can be handed over without touching anyone's phone.
You need a number that can receive an SMS or voice call. A spare SIM or
pay-as-you-go eSIM works; Signal blocks most VoIP providers (Twilio and
similar), so do not plan around one.
1. Signal requires a captcha for registrations made from a server. Open
<https://signalcaptchas.org/registration/generate.html> in a browser, open
the developer console, and find the blocked navigation to
`signalcaptcha://{value}` — copy everything after `signalcaptcha://`.
2. Register the number with that captcha:
```bash
curl -X POST -H "Content-Type: application/json" \
-d '{"captcha":"<captcha value>"}' \
'http://localhost:8080/v1/register/+447700900123'
```
Add `"use_voice": true` to receive the code by voice call instead of SMS.
3. Enter the code you receive:
```bash
curl -X POST 'http://localhost:8080/v1/register/+447700900123/verify/123-456'
```
4. Give the account a recognisable name and avatar through the profile endpoint
(see the [API docs](https://bbernhard.github.io/signal-cli-rest-api/)).
5. Have a group admin **add the bot's number to the group like a normal
contact** (do not try to link it as a device). Then fetch the group ID with
the bot's number:
```bash
curl -s http://localhost:8080/v1/groups/+447700900123 | jq -r '.[].internal_id'
```
Caveats for the dedicated-number route:
- The registration lives in `signal-data/`. Losing it **loses the account**:
there is no phone to re-link from, and re-registering needs a new captcha and
sometimes a cooldown.
- Signal reclaims numbers that go unused for a long time. If the calendar might
be quiet for months, enable `watchdog.daily_heartbeat` so the account keeps
some activity.
- The bot's number is visible to every member of the group.
### 2. Configure
```bash
cp config.example.toml config.toml
chmod 600 config.toml
```
At minimum fill in `signal.number`, `signal.group_id` (including the `group.`
prefix) and `calendar.url`. `webcal://` URLs are accepted and fetched over
https.
### 3. Verify, preview, run
```bash
docker compose run --rm bot python -m sigcal_bot --check # config + account
docker compose run --rm bot python -m sigcal_bot --dump # rendered posts, no sending
docker compose up -d bot
docker compose logs -f bot
```
## CLI
| Command | Purpose |
|---|---|
| `sigcal-bot --config config.toml` | Run the loop |
| `sigcal-bot --once` | Run a single tick and exit |
| `sigcal-bot --dump` | Print rendered posts for the feed; uses a temporary DB, sends nothing |
| `sigcal-bot --check` | Validate config and confirm the Signal account is linked |
All commands accept `--log-level` (or `LOG_LEVEL`).
## Configuration
`config.example.toml` is commented and complete. The essentials:
| Key | Default | Meaning |
|---|---|---|
| `signal.api_url` | — | `http://signal-api:8080` inside Compose |
| `signal.number` | — | The linked account's number, international format |
| `signal.group_id` | — | `internal_id` from `/v1/groups/<number>`, starts with `group.` |
| `signal.text_mode` | `normal` | `styled` enables Signal markup |
| `calendar.url` | — | ICS feed (webcal accepted) |
| `calendar.timezone` | `Europe/London` | Used for windows, hashtags and display |
| `calendar.refresh_minutes` | `15` | Feed poll interval |
| `calendar.window_days` | `60` | How far ahead to keep events |
| `posting.windows` | `08:00-10:00`, `18:00-21:00` | Preferred send times |
| `posting.urgent_guard_minutes` | `60` | Break a window when the event is this close |
| `announce.enabled` | `true` | Post when a new series appears |
| `announce.max_days_ahead` | `30` | Ignore announcements further out |
| `announce.backfill` | `false` | Announce everything on first run |
| `reminders.enabled` | `true` | Post before events |
| `reminders.lead_times` | `["3d"]` | Any number of leads (`"3d"`, `"2h"`, `"90m"`) |
| `reminders.fallback_to_day_of` | `true` | Day-of reminder for late additions |
| `reminders.day_of_time` | `09:00` | When that day-of reminder goes out |
| `images.enabled` | `true` | Attach posters |
| `images.max_pixels` | `1600` | Longest edge after resizing |
| `images.max_bytes` | `400000` | JPEG size target |
| `images.max_images_per_post` | `3` | Cap for batched posts |
| `images.scrape_event_page` | `true` | Fetch pages for venue/`og:image` |
| `format.show_*` | all `true` | Toggle each line of the post |
| `format.shorten_links` | `false` | Shorten links via TinyURL |
| `watchdog.enabled` | `true` | Operator alerts |
| `watchdog.notify_number` | own number | Where alerts go |
| `watchdog.feed_failures` | `3` | Consecutive failures before alerting |
| `watchdog.daily_heartbeat` | `false` | Daily "alive" message |
## Operations
| Task | How |
|---|---|
| Follow logs | `docker compose logs -f bot` |
| Apply config changes | edit `config.toml`, then `docker compose restart bot` |
| Update code | `git pull && docker compose up -d --build` |
| Reset duplicate/seen state | stop bot, delete `data/sigcal-bot.sqlite3`, start (re-seeds silently) |
| Clear image cache | `rm -rf cache/images` |
| Back up | `signal-data/` (linked-device keys) and `config.toml` |
**Back up `signal-data/`.** It contains the linked-device credentials. Losing it
means re-scanning the QR code; if the phone is re-registered, the link breaks
and must be re-paired.
## Troubleshooting
| Symptom | Check |
|---|---|
| `Signal account … not found` | The QR was not scanned, or `signal.number` is wrong (`curl /v1/accounts`). |
| Nothing posts | `--dump` works? Then check windows and whether the first run only seeded. Logs show planned `send_at` only at debug level — check `outbox` in SQLite if needed. |
| Posts appear as you | Expected with a linked device; use a dedicated number for a bot identity. |
| No venue line | The feed has no `LOCATION` and the event page has no JSON-LD venue. |
| No image | Event has no featured image and no `og:image`, or the download exceeded the 20 MB cap. Text still posts. |
| Duplicate post after a crash | At-least-once delivery; expected and bounded to one. |
| Watchdog alert about an empty feed | The site returned an empty calendar; stored events are left untouched. |
| `404` from the feed | The Events Calendar export URL changed; test it in a browser first. |
## Provenance
This project was written by LLM coding agents across several models, with
human direction on requirements, design and review. It is a working tool, not
an audited library:
- No security audit has been performed. The service holds a Signal account's
linked-device credentials and runs an HTTP API on localhost.
- The logic is covered by an offline test suite, but coverage is not exhaustive,
particularly around network failure modes.
- Treat the defaults, comments and claims here as best effort. Verify behaviour
against your own feed and Signal setup before relying on it in production.
- The project is **alpha** and unreleased: expect breaking changes, and do not
treat any config key or default as stable until a version is tagged.
## Limitations
- Signal has no bot API; this relies on `signal-cli` and an unofficial REST
wrapper. Account linking can break when the phone is re-registered.
- Signal message text is not styled by default; hashtags are plain text (Signal
does not linkify them).
- The feed is a snapshot (TEC caps it at ~30 events), not a full history. There
is no reliable cancellation signal beyond "it vanished".
- Rescheduled events keep the same post ID, so they get a fresh reminder but no
new announcement.
- No lockfile yet: `Dockerfile` runs `pip install .`, so builds are not
byte-reproducible.
## Development
```bash
python -m venv .venv && . .venv/bin/activate
pip install -e '.[dev]'
pytest
```
Tests are offline. They inject a fake clock, sender, scraper and image service,
and use `httpx.MockTransport` for the feed. Calendar fixtures live in
`tests/fixtures/*.ics.txt` — `.ics` is gitignored so raw feeds can never be
committed.
See `AGENTS.md` for the invariants and gotchas before making changes.
## License
Copyright (C) 2026 kawaiipunk.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
It is distributed in the hope that it will be useful, but **WITHOUT ANY
WARRANTY**; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See [LICENSE](LICENSE) for the full text.