Files
Vincent BourdonandClaude Opus 5.5 b54aab1534 fix: panic stack without sender, log service error frames, refresh account on reconnect
- handler panic log includes the stack trace and no longer the sender number
- error and exception frames from the service are logged at Warn level
- Listen looks the account up again after a connection loss (re-link)
- document that received but unhandled messages are lost at shutdown

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:46:12 +01:00

159 lines
6.7 KiB
Markdown

# signalbot
Send and receive Signal text messages from Go, in a few lines.
signalbot is a small, pure-Go library (no CGO) plus a CLI. It talks HTTP and
websocket to a [signal-cli-rest-api](https://github.com/bbernhard/signal-cli-rest-api)
container, which runs [signal-cli](https://github.com/AsamK/signal-cli) and
handles the Signal protocol.
> Unofficial client, not affiliated with or endorsed by Signal.
## How it works
```
┌──────────────── docker compose ────────────────┐
│ your app │
│ └─ signalbot (Go library) ──HTTP/ws──┐ │
│ ▼ │
│ signal-api (bbernhard/signal-cli-rest-api) │
│ └─ volume: account keys, sessions, groups │
└─────────────────────────────────────────────────┘
```
Signal has no bot API and no broadcast channels. A bot is a regular Signal
account (use a dedicated number) linked as a **secondary device** of a phone,
and a "channel" is an **announcement group**: a group where only admins can
send messages, with the bot as an admin.
## Install
```sh
go get git.siteop.biz/vincentb99/signalbot
go install git.siteop.biz/vincentb99/signalbot/cmd/signalbot@latest # CLI
```
Requires Go 1.23+.
## Quick start
```go
client, err := signalbot.New("http://signal-api:8080")
if err != nil {
log.Fatal(err)
}
// Send to a group ("group.<base64>", see `signalbot groups`),
// a phone number (E.164) or an ACI UUID. Plain text only.
err = client.Send(ctx, "group.SGVsbG8...", "New release available")
// Receive incoming text messages until ctx is cancelled.
err = client.Listen(ctx, func(ctx context.Context, m signalbot.Message) {
// m.From, m.GroupID ("" for direct messages), m.Text, m.Timestamp
_ = m.Reply(ctx, "got it") // answers in the same conversation
})
```
`Listen` reconnects automatically (backoff 1s → 30s) and calls the handler
for one message at a time, in arrival order. It ignores everything that is
not a text message (receipts, typing, reactions, attachments, messages sent
from the bot's own phone). A panic in the handler is recovered and logged
with its stack trace; errors reported by the service (e.g. a message that
could not be decrypted) are logged at Warn level.
Messages are acknowledged to Signal as soon as the service receives them:
those already received but not yet handled when the context is cancelled
are lost. Keep handlers short, or hand work off to your own queue.
The linked account is looked up once and cached. `Listen` looks it up again
after each connection loss; for `Send` and `Groups`, create a new `Client`
after linking a different account.
Options: `WithNumber` (choose an account when several are linked),
`WithHTTPClient`, `WithLogger` (`*slog.Logger`, default `slog.Default()`).
Errors can be checked with `errors.Is`: `ErrNotLinked`,
`ErrMultipleAccounts`, `ErrUnavailable` (unreachable or 5xx),
`ErrRateLimited` (429), `ErrEmptyText`, `ErrNotJSONRPC` (the service is not in
`MODE=json-rpc`/`json-rpc-native`; `Listen` stops instead of silently
consuming messages). Other API errors are `*APIError`
(`StatusCode`, `Message`). `Send` never retries. Observed: an unknown
group gives `400 Invalid identifier group.…`, an invalid number
`400 Failed to send message`. Long texts work: a 3,000-character message
arrives whole, shown truncated with a "Read more" link in the Signal app.
See [`examples/`](examples/) for a complete app and a docker-compose file.
## Setup
1. **Bot account.** Get a dedicated number with Signal installed on a phone.
On that phone, create the group, make it an announcement group (group
settings → *Send messages* → *Only admins*) and add members.
2. **Start the service** with port 8080 published on localhost (see
[`examples/docker-compose.yml`](examples/docker-compose.yml), uncomment
`ports`).
3. **Link** the bot: `signalbot link`, then on the bot's phone: Signal →
Settings → Linked devices → **+**, and scan the QR code. Without the CLI,
you can also open
`http://localhost:8080/v1/qrcodelink?device_name=signalbot` in a browser
and scan the PNG.
4. **Sync once, then find the group id.** With `JSON_RPC_RECEIVE_MODE=manual`,
signal-cli fetches nothing (not even the group list) until something
listens: run `signalbot listen` for a few seconds first. Then
`signalbot groups` (it warns if the bot is not an
admin or the group is not admins-only). Test with
`signalbot send -to group.… "hello"` and `signalbot listen`.
5. **Unpublish the port** and configure your app with the service URL and
the group id.
## Important
- **Keep `Listen` running, even if you only publish.** Receiving also
processes retry receipts (e.g. a member who reinstalled Signal); without
it, some members may stop being able to decrypt the bot's group messages.
- **Use `JSON_RPC_RECEIVE_MODE=manual`.** With the default (`on-start`),
messages that arrive while your app is down are silently lost. With
`manual`, they stay queued by Signal and are delivered when `Listen`
reconnects (verified). This setting is newer than the 0.101 release
(2026-09-25): use a later build. signalbot was verified with
`bbernhard/signal-cli-rest-api:1794354199-ci` (master build of
2026-11-10); switch to the next stable tag when it is out.
- **Open Signal on the bot's phone at least once every 30 days**, or
Signal unlinks its linked devices, including the bot
([Signal support](https://support.signal.org/hc/en-us/articles/360007320551)).
A linked device is also unlinked after 45 days of inactivity, which a
permanently running `Listen` avoids.
- **Never expose the service publicly**: signal-cli-rest-api has no
authentication. Keep it on the compose network.
- **Keep the volume.** It holds the account keys; losing it means linking
again.
- `MODE=json-rpc-native` is fast and light; if it proves unstable, use
`MODE=json-rpc` (JVM, more memory).
## CLI
```
signalbot link [-device-name signalbot] [-timeout 5m]
signalbot groups [-number N]
signalbot send [-number N] -to <group id | number | uuid> <text...>
signalbot listen [-number N]
```
All commands accept `-url` (default `$SIGNALBOT_URL`, else
`http://localhost:8080`).
## Tests
```sh
go test ./...
# against a real, linked service:
SIGNALBOT_IT_URL=http://localhost:8080 SIGNALBOT_IT_GROUP=group.… go test -run Integration -v
```
## Licence
signalbot is MIT licensed. The signal-cli-rest-api image it talks to ships
components under GPL-3.0 (signal-cli) and AGPL-3.0 (libsignal); signalbot
contains none of them and only communicates with the service over the
network.