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

@@ -0,0 +1,212 @@
import { z } from 'zod';
import { Command, Invocation } from '../../core/command/command-router';
import { MemberEvent, PowerLevelEvent } from '../../core/command/types';
import { choice, common } from '../../core/i18n/i18n';
import { Confirmations } from '../../core/plugin/confirmation';
import { Plugin, PluginContext, PluginDefinition } from '../../core/plugin/types';
import { messages as m } from './messages';
import { matrixRoomId } from '../../config/schema';
export const roomManagerConfig = z.object({
workRoom1: matrixRoomId, workRoom2: matrixRoomId, lostRoom: matrixRoomId,
mode: z.enum(['business', 'matrix']).default('business'),
levelA: z.number().int().default(50), levelB: z.number().int().default(0), levelC: z.number().int().default(-1),
syncPowerChanges: z.boolean().default(false),
syncOnJoin: z.boolean().default(false), syncOnLeave: z.boolean().default(false),
autoReconcile: z.boolean().default(false),
}).refine((c) => c.levelA > c.levelB && c.levelB > c.levelC, 'Require levelA > levelB > levelC')
.refine((c) => new Set([c.workRoom1, c.workRoom2, c.lostRoom]).size === 3, 'Target rooms must be distinct')
.refine((c) => !c.syncPowerChanges || c.mode === 'matrix', 'syncPowerChanges requires matrix mode');
type Config = z.infer<typeof roomManagerConfig>;
type Role = 'core' | 'member' | 'restricted' | 'intermediate';
type Action = { user: string; room: string; type: 'invite' | 'kick' };
type PlanRow = { user: string; role: Role; previous: Role | null; member: boolean; actions: Action[] };
type Plan = { rows: PlanRow[]; assign: boolean };
export class RoomManagerPlugin implements Plugin {
readonly commands: Command[];
private readonly plans: Confirmations<Plan>;
constructor(private readonly ctx: PluginContext, private readonly config: Config) {
if ([config.workRoom1, config.workRoom2, config.lostRoom].includes(ctx.roomId)) throw new Error('Control room must differ from target rooms');
this.plans = new Confirmations(ctx, 'membership');
this.commands = [
{ id: 'access.status', paths: [['access', 'status'], ['成员管理', '状态']], admin: true, description: m.status,
usage: { 'zh-CN': '!成员管理 状态', en: '!access status' }, run: async (inv) => {
await this.reply(inv, ctx.t(m.mode, { mode: ctx.t(m[config.mode]), power: ctx.t(config.syncPowerChanges ? m.on : m.off),
join: ctx.t(config.syncOnJoin ? m.on : m.off), leave: ctx.t(config.syncOnLeave ? m.on : m.off), reconcile: ctx.t(config.autoReconcile ? m.on : m.off) }));
} },
{ id: 'role.set', paths: [['role', 'set'], ['身份', '设置']], admin: true, description: m.role,
usage: { 'zh-CN': '!身份 设置 <用户ID> 核心|普通|受限', en: '!role set <userId> core|member|restricted' }, run: (inv) => this.rolePreview(inv) },
{ id: 'access.preview', paths: [['access', 'preview'], ['access', 'reconcile'], ['成员管理', '预览'], ['成员管理', '核对']], admin: true, description: m.preview,
usage: { 'zh-CN': '!成员管理 预览 [用户ID]', en: '!access preview [userId]' }, run: (inv) => this.preview(inv) },
{ id: 'access.confirm', paths: [['access', 'confirm'], ['成员管理', '确认']], admin: true, description: m.confirm,
usage: { 'zh-CN': '!成员管理 确认 <确认码>', en: '!access confirm <token>' }, run: (inv) => this.confirm(inv) },
];
}
async start(): Promise<void> {
if (this.config.autoReconcile) {
this.ctx.schedule('membership-reconciliation', '0 */15 * * * *', () => this.reconcile());
await this.reconcile();
}
}
private async reply(inv: Invocation, text: string): Promise<void> { await this.ctx.reply(inv.message, text); }
private usage(inv: Invocation, id: string): Promise<void> {
return this.reply(inv, this.ctx.t(common.usage, { usage: this.ctx.t(this.commands.find((command) => command.id === id)!.usage) }));
}
private async admin(inv: Invocation): Promise<boolean> {
if (await this.ctx.isAdmin(inv.message.userId)) return true;
await this.reply(inv, this.ctx.t(common.denied)); return false;
}
private mapPower(power: number): Role {
if (power >= this.config.levelA) return 'core';
if (power >= this.config.levelB) return 'member';
return power > this.config.levelC ? 'intermediate' : 'restricted';
}
private async desired(user: string, isMember: boolean): Promise<Role | undefined> {
if (!isMember) return this.config.syncOnLeave ? 'restricted' : undefined;
return this.config.mode === 'matrix' ? this.mapPower(await this.ctx.power(user)) :
await this.ctx.db.get<Role>(`role:${user}`) ?? 'member';
}
private operations(user: string, role: Role): Action[] {
const { workRoom1: first, workRoom2: second, lostRoom: lost } = this.config;
const table: Record<Role, Array<[string, 'invite' | 'kick']>> = {
core: [[first, 'invite'], [second, 'invite'], [lost, 'kick']],
member: [[first, 'kick'], [second, 'invite'], [lost, 'kick']],
restricted: [[first, 'kick'], [second, 'kick'], [lost, 'invite']],
intermediate: [[lost, 'kick']],
};
return table[role].map(([room, type]) => ({ user, room, type }));
}
private async row(user: string, members: string[], override?: Role): Promise<PlanRow | undefined> {
if (user === this.ctx.botUserId) return undefined;
const member = members.includes(user);
if (override && !member && override !== 'restricted') return undefined;
const role = override ?? await this.desired(user, member);
if (!role) return undefined;
const previous = await this.ctx.db.get<Role>(`role:${user}`);
const power = await this.ctx.power(user);
const admin = power >= this.ctx.adminPowerLevel || await this.ctx.isAdmin(user);
const actions: Action[] = [];
for (const action of this.operations(user, role)) {
if (action.type === 'kick' && admin) continue;
const joined = (await this.ctx.members(action.room)).includes(user);
if (action.type === 'kick' ? joined : !joined) actions.push(action);
}
return { user, role, previous, member, actions };
}
private async collect(user?: string, role?: Role): Promise<{ rows: PlanRow[]; notes: string[] }> {
const members = await this.ctx.members();
const known = (await this.ctx.db.entries()).filter(([key]) => key.startsWith('role:') || key.startsWith('seen:')).map(([key]) => key.slice(5));
const users = user ? [user] : [...new Set([...members, ...known])].filter((id) => id !== this.ctx.botUserId);
const rows: PlanRow[] = [], notes: string[] = [];
for (const id of users) {
try {
const row = await this.row(id, members, role);
if (row) rows.push(row); else if (user) notes.push(this.ctx.t(m.skipped, { user: id }));
} catch { notes.push(this.ctx.t(m.failed, { user: id })); }
}
return { rows, notes };
}
private async showPlan(inv: Invocation, role?: Role): Promise<void> {
const result = await this.collect(inv.args[0], role);
const token = await this.plans.preview(inv.message.userId, { rows: result.rows, assign: !!role });
const lines = result.rows.flatMap((row) => [
...(role ? [this.ctx.t(m.roleChange, { user: row.user, role: this.ctx.t(m[row.role]) })] : []),
...row.actions.map((a) => this.describe(a)),
]);
await this.reply(inv, this.ctx.t(common.preview, { details: [...lines, ...result.notes].join('\n') || this.ctx.t(common.empty),
command: `!access confirm ${token} / !成员管理 确认 ${token}` }));
}
private async rolePreview(inv: Invocation): Promise<void> {
if (!await this.admin(inv)) return;
if (this.config.mode !== 'business') return this.reply(inv, this.ctx.t(m.wrongMode));
const role = choice(inv.args[1], { core: ['核心', '核心成员'], member: ['普通', '普通成员'], restricted: ['受限', '受限成员'] });
if (inv.args.length !== 2 || !/^@.+:.+$/.test(inv.args[0]) || !role) {
return this.usage(inv, 'role.set');
}
await this.showPlan(inv, role);
}
private async preview(inv: Invocation): Promise<void> {
if (!await this.admin(inv)) return;
if (inv.args.length > 1 || (inv.args[0] && !/^@.+:.+$/.test(inv.args[0]))) {
return this.usage(inv, 'access.preview');
}
await this.showPlan(inv);
}
private describe(action: Action): string {
return this.ctx.t(m.action, { user: action.user, action: this.ctx.t(m[action.type]), room: action.room });
}
private async execute(plan: Plan, actor: string): Promise<string[]> {
const result: string[] = [];
for (const row of plan.rows) {
try {
const members = await this.ctx.members();
const previous = await this.ctx.db.get<Role>(`role:${row.user}`);
const desired = plan.assign ? row.role : await this.desired(row.user, members.includes(row.user));
if (previous !== row.previous || members.includes(row.user) !== row.member || desired !== row.role) {
result.push(this.ctx.t(m.skipped, { user: row.user })); continue;
}
if (plan.assign) {
await this.ctx.audit('role.set', actor, { user: row.user, role: row.role });
await this.ctx.db.set(`role:${row.user}`, row.role);
result.push(this.ctx.t(m.roleChange, { user: row.user, role: this.ctx.t(m[row.role]) }));
}
if (row.member) await this.ctx.db.set(`seen:${row.user}`, true);
// Execute only actions shown in the preview, never add new targets at confirmation.
for (const action of row.actions) {
try {
const stillMember = (await this.ctx.members()).includes(row.user);
if (stillMember !== row.member || (!plan.assign && await this.desired(row.user, stillMember) !== row.role)) {
result.push(this.ctx.t(m.skipped, { user: row.user })); break;
}
const joined = (await this.ctx.members(action.room)).includes(action.user);
if (action.type === 'kick' ? !joined : joined) continue;
const power = await this.ctx.power(action.user);
if (action.type === 'kick' && (power >= this.ctx.adminPowerLevel || await this.ctx.isAdmin(action.user))) {
result.push(this.ctx.t(m.skipped, { user: action.user })); continue;
}
await this.ctx.audit(`membership.${action.type}.requested`, actor, { user: action.user, room: action.room });
if (action.type === 'kick') await this.ctx.kick(action.room, action.user, this.ctx.t(m.reason));
else await this.ctx.invite(action.room, action.user);
await this.ctx.audit(`membership.${action.type}.completed`, actor, { user: action.user, room: action.room });
result.push(this.describe(action));
} catch {
await this.ctx.audit(`membership.${action.type}.failed`, actor, { user: action.user, room: action.room });
result.push(this.ctx.t(m.failed, { user: action.user }));
}
}
} catch {
await this.ctx.audit('membership.lookup.failed', actor, { user: row.user });
result.push(this.ctx.t(m.failed, { user: row.user }));
}
}
return result;
}
private async confirm(inv: Invocation): Promise<void> {
if (!await this.admin(inv)) return;
const plan = inv.args.length === 1 ? await this.plans.consume(inv.message.userId, inv.args[0]) : undefined;
if (!plan) return this.reply(inv, this.ctx.t(common.expired));
const result = await this.execute(plan, inv.message.userId);
await this.reply(inv, this.ctx.t(common.done, { details: result.join('\n') || this.ctx.t(common.empty) }));
}
private async reconcile(user?: string): Promise<void> {
const { rows, notes } = await this.collect(user);
const result = await this.execute({ rows, assign: false }, 'scheduler');
if (result.length || notes.length) await this.ctx.send(this.ctx.t(common.done, { details: [...result, ...notes].join('\n') }));
}
async onMember(event: MemberEvent): Promise<void> {
if ((event.membership === 'join' && this.config.syncOnJoin) ||
(event.membership === 'leave' && this.config.syncOnLeave)) await this.reconcile(event.userId);
}
async onPowerLevel(_event: PowerLevelEvent): Promise<void> {
// Reconcile current state, including users_default changes omitted by a users-only diff.
if (this.config.syncPowerChanges) await this.reconcile();
}
}
export default {
apiVersion: 1, id: 'room-manager', aliases: ['成员管理', '权限同步'], version: '2.0.0', description: m.description,
validate: (config) => roomManagerConfig.parse(config),
allowedRooms: (config) => { const c = roomManagerConfig.parse(config); return [c.workRoom1, c.workRoom2, c.lostRoom]; },
create: (ctx, config) => new RoomManagerPlugin(ctx, roomManagerConfig.parse(config)),
} satisfies PluginDefinition;