Release room-scoped Matrix bot plugins and room configuration

This commit is contained in:
Matrix Bot Project committed 2026-11-20 23:23:04 +08:00
commit 86c7e4359c
76 files changed
+13539

No files matched your search

+126
View File
@@ -0,0 +1,126 @@
# Matrix plugin bot
[中文](README.md)
A NestJS / TypeScript host for room-scoped Matrix plugins. The host owns account sessions, encryption, command routing, permissions, localization, scheduling and storage. Installed plugins can be enabled or disabled from a managed room without restarting the host.
Built-in plugins:
- `checkin` / `签到`: calendar-day check-ins, read-only reports and optional inactive-member cleanup.
- `room-manager` / `成员管理` / `权限同步`: independent business roles, optional Matrix power mapping and membership reconciliation.
## Commands
Commands accept `!`, `!` or `/`. Some Matrix clients intercept slash commands; use `!` when a slash command is not sent as a room message. English command words are case-insensitive. Chinese aliases and English aliases invoke the same handlers. Replies use the room's configured language; administrators can change it with `!language en` or `!语言 中文`.
**The ASCII `!` and fullwidth `!` prefixes are interchangeable** for both English and Chinese commands. Send any one command in a row for the same result.
| Action | ASCII + English | Fullwidth + English | ASCII + Chinese | Fullwidth + Chinese |
| --- | --- | --- | --- | --- |
| Check in | `!checkin` | `!checkin` | `!签到` | `!签到` |
| View your record | `!list` | `!list` | `!查询` | `!查询` |
| Show help | `!help` | `!help` | `!帮助` | `!帮助` |
`签到` and `帮助` also work as standalone messages. Queries require a prefix.
### Host commands
| English | 中文 | Permission |
| --- | --- | --- |
| `!help` | `!帮助` or `帮助` | Everyone; help lists commands currently available |
| `!ping` | `!在线` | Everyone |
| `!echo <text>` | `!复述 <文本>` | Everyone |
| `!plugin list` / `!plugin status` | `!插件 列表` / `!插件 状态` | Everyone; error detail is admin-only |
| `!plugin enable <name>` | `!插件 启用 <名称>` | Administrator |
| `!plugin disable <name>` | `!插件 停用 <名称>` / `!插件 禁用 <名称>` | Administrator |
| `!language zh-CN` / `!language en` | `!语言 中文` / `!语言 英文` | Administrator |
| `!audit` | `!操作记录` | Administrator; latest 10 of up to 200 retained entries per room |
An administrator is a user in the room's `admins` list or with a native Matrix power level at least `adminPowerLevel` (default 100). Lookup failures deny access. Business roles do not grant administrator privileges.
Administrators can inspect the current room ID, language, timezone and report settings with `/config` or `!config`. `!config language en` applies immediately. `!config reports off` applies the next time the check-in plugin starts.
If a domainless room ID was configured with an extra server suffix, send `!config` in the actual room, then `!config bind`. Recovery requires a unique candidate, a sender listed in `admins` with sufficient native room power, and bot membership in the actual room but not the configured room. The database stores the correction for the next service start and keeps the original data scope. The command requires a readable message and cannot restore missing encryption keys.
### Check-in commands
| English | 中文 | Effect |
| --- | --- | --- |
| `!checkin` | `!签到` or `签到` | Check in once per local calendar date |
| `!list` | `!查询` | Read own summary |
| `!list <userId>` / `!list all` | `!查询 <用户ID>` / `!查询 全部` | Other users and all records require administrator access |
| `!list [userId\|all] --raw` | `!查询 [用户ID\|全部] --原始` | Administrator; JSON summary |
| `!report daily [YYYY-MM-DD]` | `!日报 [YYYY-MM-DD]` | Administrator; read-only report |
| `!report monthly [YYYY-MM]` | `!月报 [YYYY-MM]` | Administrator; read-only report |
| `!cleanup preview` | `!清理 预览` | Administrator; preview candidates |
| `!cleanup confirm <token>` | `!清理 确认 <确认码>` | Administrator; execute the previewed candidates after revalidation |
Check-ins are unique by account, room, user and calendar date. Day boundaries use the room's explicit `timeZone` (default `Asia/Shanghai`), independently of report scheduling. Reports never clear records. Levels use the total number of known check-ins: Bronze 1–7, Silver 8–14, Gold 15–29, Platinum 30–44, Diamond 45+.
Scheduled daily reports cover the preceding calendar date at 03:00; monthly reports cover the preceding month at 00:05 on the first day. The plugin checks due periods once per minute. Checkpoints survive restarts; after downtime it sends the latest due report with a catch-up notice rather than flooding the room with every missed report. Historical dates remain queryable. Initial activation establishes a checkpoint without sending old reports. Sending and checkpointing are not a distributed transaction: a crash between them can duplicate a notification, but cannot duplicate check-ins or reset counts.
Daily reports compare historical check-ins with **current** membership, not a historical membership snapshot. Legacy migration preserves only the history actually available in the old schema; see [upgrade notes](docs/UPGRADE.md).
`cleanupEnabled` permits explicit preview/confirmation. `autoCleanup` additionally permits automatic daily cleanup after 03:00. Both default to false. Automatic cleanup is not run in the enable hook; the next scheduled check may run it if it is explicitly enabled and due. Members with no known check-in, members who checked in today, listed exemptions and administrators are excluded. Permission read failures skip the member. Cleanup removes members from the current control room and never deletes their check-in history.
### Membership commands
| English | 中文 | Effect |
| --- | --- | --- |
| `!access status` | `!成员管理 状态` | Show mode and automatic action switches |
| `!role set <userId> core\|member\|restricted` | `!身份 设置 <用户ID> 核心\|普通\|受限` | Preview an independent business-role change |
| `!access preview [userId]` / `!access reconcile [userId]` | `!成员管理 预览 [用户ID]` / `!成员管理 核对 [用户ID]` | Preview reconciliation |
| `!access confirm <token>` | `!成员管理 确认 <确认码>` | Apply a preview after rechecking current state |
All membership commands require administrator access. Confirmations are bound to the initiating administrator, room and plugin; expire after five minutes; are single-use; and are invalidated when the plugin is re-enabled. A new preview replaces that administrator's previous preview for the same operation.
| Business role | Intended membership |
| --- | --- |
| `core` / 核心 | Invite to work rooms 1 and 2; remove from lost room |
| `member` / 普通 | Remove from work room 1; invite to work room 2; remove from lost room |
| `restricted` / 受限 | Remove from work rooms 1 and 2; invite to lost room |
Invitations require acceptance by recipients. The bot needs suitable native permissions in each target room. Automatic membership changes are disabled by default. `syncOnJoin`, `syncOnLeave` and `autoReconcile` are independent switches; `autoReconcile` checks current state on enable and every 15 minutes. Previously observed members can be checked after a missed leave when leave synchronization is enabled. Members never observed by this version cannot be inferred from missing history.
The default `business` mode keeps business roles separate from Matrix moderation powers. Optional `matrix` mode maps powers to membership: `>= levelA` is core, `levelB <= power < levelA` is member, `<= levelC` is restricted. Intermediate values between C and B only remove from the lost room. `syncPowerChanges` is available only in matrix mode. Changing power in the control room still changes the user's native Matrix rights; use business mode when only group access should change.
`autoCleanup` does not control this plugin. Turning off inactive-member cleanup does not disable separately enabled leave or power synchronization.
The old `!reset`, `!test ...` and `!level ...` commands return a retirement notice and perform no reset, cleanup or rank mutation.
## Configuration and deployment
Copy `.env.example` to `.env` and `config/bots.example.yaml` to `config/bots.yaml`, then supply the deployment's account credentials and room IDs. The configuration accepts multiple accounts and rooms. A room remains managed even when all of its business plugins are disabled. Configure the bot as a member of each control and target room before enabling the relevant features.
Runtime enable/disable choices and reply language are stored in the database and take precedence over initial configuration defaults after restart. Plugin-specific configuration, room permissions and timezones remain server configuration; changes take effect after restart. Commands do not install packages, accept code or modify server files.
The following starts the real service when `DRY_RUN=false`:
```sh
docker compose up -d --build
```
For a local installation, install dependencies, generate Prisma's client, initialize a dedicated database and build the application before starting it. `.env` is consumed by Docker Compose; direct Node/Nest startup requires exporting the corresponding environment variables. `DRY_RUN=true` suppresses Matrix transport calls but still initializes storage, migrates legacy data and starts scheduled tasks; use the isolated tests below for validation without touching runtime state.
Persistent data:
- `./data`: application SQLite database and plugin states.
- `matrix-crypto` volume: Matrix sessions, device credentials and encryption state.
- `./config`: read-only runtime configuration mount.
- `./plugins`: read-only mount for optional trusted external plugins.
Back up application storage and encryption/session storage together before upgrading. Keep a single active process per account/database deployment: per-room execution queues and single-use confirmations are coordinated within one process. Daily record uniqueness is additionally enforced by the database, but multiple replicas of the same scheduler are not supported.
## Development and verification
```sh
npm ci
npm run prisma:generate
npm run typecheck
npm run build
npm run test:all
```
Tests use fake Matrix transports, blocked network APIs and unique temporary SQLite databases. Runtime configuration files are unavailable to tests. Prisma CLI test subprocesses use `RUST_LOG=info` to avoid the Prisma 5.22 error-parser issue with missing SQLite files under `RUST_LOG=warn`. Test cleanup tolerates initialization failure.
See [plugin development](docs/PLUGINS.md) for the API and a complete external plugin example. New trusted modules require a service restart to be discovered; enabling/disabling already installed plugins does not. Hot replacement of module code and sandboxing untrusted third-party code are not provided.