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

+45
View File
@@ -0,0 +1,45 @@
# Plugin API v1
## Loading
Built-in plugin files are discovered recursively under the compiled `dist/plugins` directory. External directories are listed in `pluginDirectories`. Entry files end in `.plugin.js` and export a default manifest via CommonJS (`exports.default = ...`). TypeScript built-ins use `.plugin.ts` during development and compile to JavaScript. External TypeScript plugins must be compiled first. External dependencies should be packaged alongside the plugin or installed by the server operator.
A manifest declares:
- `apiVersion: 1`, a unique lowercase `id`, a `version`, optional name aliases and bilingual `description`.
- `validate(config)`, returning validated configuration or throwing an error.
- Optional `allowedRooms(config)`, declaring additional target rooms for membership actions and reads.
- `create(context, config)`, returning an instance with a command list and optional `start`, `stop`, `onMember` and `onPowerLevel` hooks.
Duplicate plugin IDs/name aliases and incompatible manifests reject discovery. Command alias collisions reject that plugin's activation before its start hook runs. A failed activation cancels registered jobs and leaves the host's management commands available. Installed plugins with missing required configuration appear as failed until configuration is corrected and activation is retried.
Plugins are trusted code running in the host process. Context room checks and abort signals prevent accidental use outside declared scopes, but are not a security sandbox. Only operators install files; chat commands cannot fetch packages or execute uploaded code.
## Context
The public interfaces live in `src/core/plugin/types.ts`. The context provides:
- `account`, `botUserId`, `roomId`, `locale`, `timeZone`, `adminPowerLevel`, `signal`, `now()`.
- `t({ 'zh-CN': ..., en: ... }, values)` for shared interpolation and language selection.
- `db.get/set/create/remove/entries`, already isolated to the account/room/plugin instance. `create` is atomic and returns false for an existing key.
- `send(text)` and `reply(message, text)` to the current room.
- `members(roomId?)`, `power(userId)`, `isAdmin(userId)`; lookup failures propagate from members/power while administrative checks deny on failure.
- `kick(roomId, userId, reason)` and `invite(roomId, userId)` to declared rooms.
- `schedule(name, cron, callback)` using the room timezone. The host serializes callbacks with commands, lifecycle changes and events.
- `audit(action, actor, details)` for room-scoped administrative history.
Use `context.schedule` instead of unmanaged timers. Disable waits behind already running room work, unregisters scheduled callbacks, aborts the instance signal, calls `stop` and retains data. Async work started outside host callbacks must observe the abort signal and release its resources in `stop`. A stalled plugin can stall its room; plugins should use bounded I/O and cancellation. A process shutdown additionally prevents new transport operations while queues drain.
Use `context.t` and declarative command aliases instead of branching on language in handlers. `context.locale` is a live getter so an enabled plugin sees language changes immediately.
## Commands
Each command declares `id`, `paths`, optional exact `bare` aliases, optional `admin: true`, localized `description` and `usage`, and `run(invocation)`.
The host matches the longest registered command path, normalizes command words and fullwidth prefixes, preserves quoted arguments and recognizes `--raw` / `--原始`. The handler receives `{ message, args, raw }`. Prefix-free aliases must match the entire message, preventing ordinary conversation from accidentally executing a command. The host handles the primary administrator check, help generation and errors. Plugins should also validate arguments and recheck permissions immediately before delayed or confirmed mutations.
## Complete example
Copy `examples/greeting.plugin.js` into an external directory listed in configuration. After restarting to discover the file, use `!plugin enable greeting` or `!插件 启用 问候`. Then `!greet World` and `!问候 世界` invoke the same handler. `!language en` changes the response language without reinstalling the plugin. No changes to the application module, dispatcher or session manager are needed.
A future RSS plugin can use the same API to register subscription commands, persist subscriptions/deduplication keys and schedule polling. Feed retrieval and parsing belong inside that plugin. The host does not currently include an RSS feed parser or subscription implementation.
+36
View File
@@ -0,0 +1,36 @@
# Upgrade from static modules
## Behavior changes
- `rooms` replaces static bot-module registration. The host discovers plugin manifests automatically.
- A room's plugin state and reply language persist. After the first activation, stored choices override configuration defaults.
- Check-in day boundaries are local midnight in the configured timezone. Reports no longer reset daily or monthly data.
- Manual report queries are read-only. Legacy reset, test and manual-level commands no longer execute their previous behavior.
- Other-user, all-user and raw check-in queries require administrator access.
- Cleanup requires `cleanupEnabled`; automatic cleanup additionally requires `autoCleanup`. The legacy `autoKick` field is not carried forward as authorization for the new cleanup workflow.
- Membership management defaults to independent business roles. All automatic membership switches default to false. To retain native power mapping, explicitly choose `mode: matrix` and the required synchronization switches.
- Native administrators are exempt from membership removals. Failed permission lookups do not authorize removals.
- Startup does not announce each plugin. Re-enabling a plugin may deliver due report notifications, and explicitly enabled membership reconciliation can run on enable.
- Old command events preceding the current Matrix session process are ignored to avoid replaying administrative actions. Optional reconciliation works from current membership state.
## Configuration
Use the example `rooms` format for new deployments. The legacy `bots` format is normalized into one plugin instance per account/room, but it should be replaced during upgrade. Do not mix `rooms` and `bots` in one file. Reports are local to each plugin instance; the old `mainRoom` aggregation setting is no longer used.
For a legacy `checkin` bot bound to exactly one account and one room, the migration target is inferred. When shared records previously covered multiple rooms, select exactly one destination explicitly:
```yaml
legacyCheckinTarget:
account: main
roomId: "!control:example.org"
```
The destination must exist in `rooms` and have a configured `checkin` plugin. New room configurations using an old database also need this target. Migration refuses an ambiguous destination, an already populated destination without a migration marker, malformed source records or reassignment after a completed migration.
## Data conversion
The old table used `checkin` as a shared storage scope. Version 2 scopes records by account, room and plugin. Migration copies records and writes its completion marker in one transaction; it leaves the original rows intact.
The legacy schema contains the current monthly count and last check-in timestamp, not a complete daily or lifetime history. Migration preserves the known monthly count as a baseline and the last check-in date as a non-counting daily record. This prevents double counting or a second check-in on that date. Earlier daily dates and earlier monthly totals cannot be reconstructed. The displayed cumulative total is therefore the known baseline plus new records, not an invented lifetime total. Legacy levels are recalculated from that known total. Source data remains available for an explicit future reconciliation if additional history is available.
Take a consistent backup before the first upgraded startup. A code rollback alone does not copy new v2 activity back into legacy records; restore a compatible backup or explicitly reconcile subsequent activity. Migration runs during service initialization, before Matrix sessions start.