r9k bot for matrix
Files
README.md

r9k-bot #

An encrypted Matrix Robot9000-style moderation bot. Each room gets a permanent set of previously posted text. While R9K mode is enabled, a message whose content is already in that set is redacted.

Behavior #

  • Text, notices, and emotes share one room-local uniqueness set.
  • Repeats by the original sender are duplicates too.
  • Unicode is normalized to NFC, so canonically equivalent text collides.
  • Emoji in message bodies participates in duplicate detection.
  • Reactions, non-image media, state events, and bot commands are ignored.
  • Still-image matching is opt-in per room (see below).
  • Reply fallback quotations are removed before comparison.
  • Edits claim their new content without releasing the original content.
  • Disabling global enforcement does not stop text collection or opted-in image collection.

The uniqueness ledger stores keyed BLAKE3 digests. For duplicates caught while R9K is enabled, a separate persistent catch ledger stores the sender, event ID, timestamps, digest, and the first 160 Unicode characters of the repeated text (plus an ellipsis when truncated). These plaintext snippets power the room stats and leaderboard. Longer bodies are truncated; unique messages remain hash-only.

A one-time forward history pass seeds each room with all decryptable text visible to the bot. Historical duplicates are not retroactively redacted or counted as catches. The bot ignores its own messages, including reports.

Matrix setup #

Use a dedicated Matrix account with password login enabled:

  1. Start the bot and invite its account to a room.
  2. Give the account enough room power to redact other users' events.
  3. As a room moderator, send !r9k on.

The bot accepts invitations from users on its own homeserver by default. R9K_TRUSTED_INVITERS can replace that behavior with an explicit comma-separated user-ID allowlist. Direct-chat invitations are also accepted from users who currently share a channel with the bot.

Room commands:

!r9k on
!r9k off
!r9k status
!r9k stats
!r9k leaderboard
!r9k leaderboard @user:example.org
!r9k images on
!r9k images off
!r9k images status

on, off, status, and all images commands require power level 50 or higher and are acknowledged with reactions. Any room member can use these read-only report commands:

  • !r9k stats: current mode, unique texts indexed, successful catches, number of users caught, pending redactions, and the five most recent catches with their senders and repeated-text snippets or original image-post links. Also shows image mode, unique images indexed, and successful image catches.
  • !r9k leaderboard: the top ten users by successful catches, with each user's most frequently caught content and its catch count. Images link to the first indexed post instead of retaining or reposting a copy. Ties use stable ordering.
  • !r9k leaderboard @user:example.org: that user's total catches and up to 20 distinct caught texts or images in this room, ordered by count, then recency.

In channels, reports cover that channel. In a one-to-one DM, the same commands return global results across channels:

!r9k stats
!r9k leaderboard
!r9k leaderboard @user:example.org

DMs are query-only: private text and images are not indexed or moderated. Global results exclude marked direct rooms. The bot checks current joined and invited members before replying; a direct-room flag alone does not grant access. DM reports are available to trusted inviters and current members of a shared channel.

Reports are plain notices in the requesting room, without mentions. Statistics survive restarts. Only successful redactions count as catches; queued or failed attempts are separate. Replayed events and retries do not count twice. Recognized commands (including unauthorized ones) never enter the uniqueness set.

Recovered catches contribute to the same totals and rankings. Existing databases upgrade automatically. Turning R9K off does not erase statistics or cancel already queued redactions.

Image duplicate detection #

Image matching starts off in every room. A moderator can enable it with !r9k images on; !r9k on must also be enabled to redact matches. Use !r9k images off to stop image downloads and collection, or !r9k images status to check the toggle (🖼️ means on; 🚫 means off). The toggle and hashes survive restarts. Turning either mode off does not cancel redactions already queued.

Supported images are still PNG, JPEG, and WebP sent as m.image, including replacements. Matching is room-local and includes repeats by the original sender. The bot compares both the decrypted file hash and a decoded-pixel hash. It applies EXIF orientation and preserves dimensions, alpha, and 16-bit precision. Pixel matching ignores nonvisual metadata, but preserves color-profile and PNG display metadata differences to avoid false matches. There is no resizing, perceptual matching, or lossy similarity threshold. A recompressed JPEG may therefore not match, while a lossless re-encoding can.

  • No historical image backfill. Images are indexed only when received while image matching is enabled. The first indexed post is the reference for later matches.
  • GIF, animated PNG/WebP, stickers, video, and other formats are skipped. The bot never compares only an animation's first frame.
  • Downloads go through the configured homeserver's authenticated Matrix media API (Matrix 1.11+), with no redirects and a 15-second timeout. Encrypted attachments are decrypted and their ciphertext integrity hash is verified before matching.
  • Hard input limits: 10 MiB downloaded bytes, 4096 pixels per dimension, and 4,194,304 total pixels. These use the actual payload and decoder dimensions, not only sender-supplied metadata. A 64 MiB allocation guard is also passed to codecs that support it; WebP does not honor this guard. It is not a peak process memory cap: input, decoded pixels, and temporary conversion buffers can coexist.
  • A single background worker and a 32-item in-memory queue keep image work bounded and separate from text moderation. Overload, unsupported files, and decoding limits cause an image to be skipped, logged, and marked processed, with no catch or redaction. Fetch/decryption/storage failures leave events retryable on replay. There is no scheduled image retry; waiting image jobs are not persisted across restarts. Redactions already queued use the existing persistent retry worker.
  • Downloaded files and decoded pixels are not persisted or added to the media cache. Attachment keys and filenames are not copied into the image ledger. It stores keyed hashes, event IDs, and sender IDs for catches. Stats link to the first indexed post in the same room; normal Matrix room permissions apply, and links can stop working if that post is removed.

Recover historical catch counts #

scripts/backfill_stats.py is a one-off, opt-in maintenance tool. It uses the bot's Matrix account to find retained Duplicate content! / Duplicate content (R9K) redactions from the two deployed bot versions, fetches each redacted target's sender, and verifies the target's redacted_because evidence. The target must already be in the room's processed-event ledger. Other users' redactions and inaccessible or ambiguous evidence are not imported.

Use Python 3.12 with access to the existing SQLite ledger on its local volume. Supply MATRIX_USERNAME, MATRIX_PASSWORD, and MATRIX_HOMESERVER securely. The tool uses a temporary login/device and logs out afterward. Do not copy secrets into a command line or repository.

python3 scripts/backfill_stats.py --ledger /data/r9k.sqlite3
python3 scripts/backfill_stats.py --ledger /data/r9k.sqlite3 --apply

The default is a read-only dry run. Applying takes a consistent SQLite backup first, then writes only the separate recovered-count and progress tables. It does not change uniqueness claims, moderation mode, processed events, pending redactions, or current catch records. Imports deduplicate by target event and exclude events already in the richer current catch ledger. Page checkpoints and records commit together so interrupted runs can resume. --rescan starts from recent history again without duplicating previously imported catches.

Recovery is best-effort: history visibility, retention, deleted redaction events, and unavailable target metadata can leave gaps. Deleted message text is not reconstructed. A completed import does not mean every past catch was recoverable.

Configuration #

Required environment variables:

Variable Purpose
MATRIX_USERNAME Full bot user ID, such as @r9k:example.org
MATRIX_PASSWORD Bot account password
R9K_STORE_PASSPHRASE Encrypts the Matrix SDK's persistent store
R9K_HASH_KEY Exactly 32 random bytes encoded as 64 hexadecimal characters

Optional variables:

Variable Default Purpose
MATRIX_HOMESERVER http://tuwunel:6167 Client API base URL
MATRIX_DEVICE_ID R9KBOT Stable Matrix device ID
MATRIX_RECOVERY_KEY unset Recovers secret storage and room-key backups
R9K_DATA_DIR /data Persistent SDK and ledger directory
R9K_TRUSTED_INVITERS local users Comma-separated invitation allowlist
RUST_LOG info Standard tracing filter

Generate the independent storage secrets with:

openssl rand -hex 32
openssl rand -hex 32

Do not reuse either value as the Matrix password or recovery key.

Run locally #

The project requires Rust 1.93 or newer:

cargo test
cargo run

The data directory must be persistent. SQLite and the Matrix SDK crypto store should use a local filesystem rather than NFS.

Container #

docker build -t git.dragonfruit.dev/ryphon/r9k-bot:latest .
docker run --rm \
  --env-file .env \
  --volume r9k-data:/data \
  git.dragonfruit.dev/ryphon/r9k-bot:latest

The image runs as UID/GID 10001 and requires write access to /data.