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,74 @@
import { testDatabase } from '../../test/database';
import { FakeContext, message } from '../../test/fakes';
import { BotStore } from '../../core/db/bot-store';
import { pluginScope } from '../../core/plugin/room-runtime';
import { CheckinPlugin, checkinConfig } from './checkin.plugin';
import { CommandRouter } from '../../core/command/command-router';
import { migrateCheckin } from '../../core/plugin/migrate-checkin';
import { rootConfigSchema } from '../../config/schema';
let database: Awaited<ReturnType<typeof testDatabase>> | undefined;
beforeAll(async () => { database = await testDatabase(); });
afterAll(async () => { await database?.close(); });
afterEach(async () => { await database?.prisma.botState.deleteMany(); });
const roomId = '!control:example.org';
const user = '@member:example.org';
const config = () => rootConfigSchema.parse({ accounts: { test: { userId: '@bot:example.org', password: 'fixture', homeServer: 'https://example.org' } },
rooms: [{ account: 'test', roomId, plugins: { checkin: { enabled: true } } }], legacyCheckinTarget: { account: 'test', roomId } });
function plugin(room = roomId, account = 'test') {
const ctx = new FakeContext(new BotStore(database!.prisma, pluginScope(account, room, 'checkin')));
const bot = new CheckinPlugin(ctx, checkinConfig.parse({}));
const router = new CommandRouter(bot.commands);
return { ctx, bot, run: async (text: string, actor = user) => {
const match = router.match(message(text, actor))!; await match.command.run(match.invocation);
} };
}
describe('check-in with isolated SQLite', () => {
it('enforces unique user/date records across concurrent plugin instances', async () => {
const a = plugin(), b = plugin();
await Promise.all([a.run('签到'), b.run('!checkin'), a.run('!签到')]);
expect(await a.bot.records()).toHaveLength(1);
expect((await b.bot.stats()).get(user)?.total).toBe(1);
});
it('keeps room and account data separate in the same database', async () => {
const a = plugin(), b = plugin('!second:example.org'), c = plugin(roomId, 'second-account');
await a.run('签到'); await b.run('签到');
expect((await a.bot.stats()).get(user)?.total).toBe(1);
expect((await b.bot.stats()).get(user)?.total).toBe(1);
expect((await c.bot.stats()).size).toBe(0);
});
it('uses native room permissions for administration instead of removed level commands', async () => {
const a = plugin(); await a.run('签到');
await a.run('!查询 全部', '@member:example.org'); expect(a.ctx.transport.sent.at(-1)?.text).toContain('无权限');
await a.run('!查询 全部 --原始', '@admin:example.org'); expect(JSON.parse(a.ctx.transport.sent.at(-1)!.text)[0].total).toBe(1);
});
it('migrates legacy data once, preserves source and avoids counting today twice', async () => {
const legacy = new BotStore(database!.prisma, 'checkin');
await legacy.set(user, { checkinTimesInMonth: 8, checkinUnixMs: Date.parse('2026-01-15T01:00:00Z'), isCheckinToday: true });
await migrateCheckin(database!.prisma, config()); await migrateCheckin(database!.prisma, config());
const a = plugin(); await a.run('签到');
expect((await a.bot.stats()).get(user)).toMatchObject({ total: 8, month: 8, today: true });
expect(await legacy.get(user)).not.toBeNull();
a.ctx.date = new Date('2026-02-01T01:00:00Z'); await a.run('签到');
expect((await a.bot.stats()).get(user)).toMatchObject({ total: 9, month: 1 });
});
it('refuses ambiguous targets, existing destination data and reassignment', async () => {
const legacy = new BotStore(database!.prisma, 'checkin');
await legacy.set(user, { checkinTimesInMonth: 1, checkinUnixMs: Date.parse('2026-01-15T01:00:00Z') });
await expect(migrateCheckin(database!.prisma, { ...config(), legacyCheckinTarget: undefined })).rejects.toThrow('explicit');
const a = plugin(); await a.run('签到');
await expect(migrateCheckin(database!.prisma, config())).rejects.toThrow('already contains');
await database!.prisma.botState.deleteMany({ where: { botName: pluginScope('test', roomId, 'checkin') } });
await migrateCheckin(database!.prisma, config());
const other = config(); other.rooms[0].roomId = '!second:example.org'; other.legacyCheckinTarget!.roomId = '!second:example.org';
await expect(migrateCheckin(database!.prisma, other)).rejects.toThrow('another room');
});
it('rolls back the whole migration when a legacy record is invalid', async () => {
const legacy = new BotStore(database!.prisma, 'checkin');
await legacy.set(user, { checkinTimesInMonth: 1, checkinUnixMs: Date.parse('2026-01-15T01:00:00Z') });
await legacy.set('@invalid:example.org', { checkinTimesInMonth: -1 });
await expect(migrateCheckin(database!.prisma, config())).rejects.toThrow('Invalid');
expect(await database!.prisma.botState.count({ where: { botName: pluginScope('test', roomId, 'checkin') } })).toBe(0);
});
});
+235
View File
@@ -0,0 +1,235 @@
import { z } from 'zod';
import { Command, Invocation } from '../../core/command/command-router';
import { common, choice, Text } from '../../core/i18n/i18n';
import { Plugin, PluginContext, PluginDefinition } from '../../core/plugin/types';
import { Confirmations } from '../../core/plugin/confirmation';
import { localDate, localMinutes, previousMonth, shiftDate, validDate } from '../../core/plugin/calendar';
import { messages as m } from './messages';
export const checkinConfig = z.object({
reportsEnabled: z.boolean().default(true),
cleanupEnabled: z.boolean().default(false),
autoCleanup: z.boolean().default(false),
kickDays: z.number().int().min(1).default(30),
whitelist: z.array(z.string().regex(/^@.+:.+$/)).default([]),
}).refine((c) => !c.autoCleanup || c.cleanupEnabled, 'autoCleanup requires cleanupEnabled');
type Config = z.infer<typeof checkinConfig>;
export interface CheckinRecord { userId: string; date: string; at: number; counted?: boolean; }
export interface LegacyBaseline { userId: string; count: number; month: string; lastAt: number; }
interface Stats { userId: string; total: number; month: number; today: boolean; lastAt: number; }
interface Periods { daily: string; monthly: string; cleanup: string; }
const levels: Array<[number, Text]> = [
[7, { 'zh-CN': '青铜', en: 'Bronze' }], [14, { 'zh-CN': '白银', en: 'Silver' }],
[29, { 'zh-CN': '黄金', en: 'Gold' }], [44, { 'zh-CN': '铂金', en: 'Platinum' }],
[Infinity, { 'zh-CN': '钻石', en: 'Diamond' }],
];
export const recordKey = (userId: string, date: string) => `day:${JSON.stringify([userId, date])}`;
export class CheckinPlugin implements Plugin {
readonly commands: Command[];
private readonly plans: Confirmations<string[]>;
constructor(private readonly ctx: PluginContext, private readonly config: Config) {
this.plans = new Confirmations(ctx, 'cleanup');
this.commands = [
{ id: 'checkin', paths: [['checkin'], ['签到']], bare: ['签到'], description: m.checkin,
usage: { 'zh-CN': '!签到', en: '!checkin' }, run: (inv) => this.checkin(inv) },
{ id: 'checkin.list', paths: [['list'], ['查询'], ['签到', '查询']], description: m.list,
usage: { 'zh-CN': '!查询 [用户ID|全部] [--原始]', en: '!list [userId|all] [--raw]' }, run: (inv) => this.list(inv) },
{ id: 'checkin.daily', paths: [['report', 'daily'], ['日报'], ['统计', '日报']], description: m.daily, admin: true,
usage: { 'zh-CN': '!日报 [YYYY-MM-DD]', en: '!report daily [YYYY-MM-DD]' }, run: (inv) => this.daily(inv) },
{ id: 'checkin.monthly', paths: [['report', 'monthly'], ['月报'], ['统计', '月报']], description: m.monthly, admin: true,
usage: { 'zh-CN': '!月报 [YYYY-MM]', en: '!report monthly [YYYY-MM]' }, run: (inv) => this.monthly(inv) },
{ id: 'checkin.cleanup.preview', paths: [['cleanup', 'preview'], ['清理', '预览']], description: m.cleanupPreview, admin: true,
usage: { 'zh-CN': '!清理 预览', en: '!cleanup preview' }, run: (inv) => this.preview(inv) },
{ id: 'checkin.cleanup.confirm', paths: [['cleanup', 'confirm'], ['清理', '确认']], description: m.cleanupConfirm, admin: true,
usage: { 'zh-CN': '!清理 确认 <确认码>', en: '!cleanup confirm <token>' }, run: (inv) => this.confirm(inv) },
];
}
async start(): Promise<void> {
await this.settle(false);
this.ctx.schedule('period-reports', '0 * * * * *', () => this.settle(true));
}
private today(): string { return localDate(this.ctx.now(), this.ctx.timeZone); }
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;
}
async records(): Promise<CheckinRecord[]> {
return (await this.ctx.db.entries<CheckinRecord>()).filter(([key]) => key.startsWith('day:')).map(([, value]) => value);
}
async stats(month = this.today().slice(0, 7)): Promise<Map<string, Stats>> {
const result = new Map<string, Stats>();
const get = (id: string) => {
if (!result.has(id)) result.set(id, { userId: id, total: 0, month: 0, today: false, lastAt: 0 });
return result.get(id)!;
};
const baselines = (await this.ctx.db.entries<LegacyBaseline>()).filter(([key]) => key.startsWith('legacy:'));
for (const [, base] of baselines) {
const stat = get(base.userId);
stat.total += base.count; stat.month += base.month === month ? base.count : 0;
stat.lastAt = Math.max(stat.lastAt, base.lastAt);
}
for (const record of await this.records()) {
const stat = get(record.userId);
if (record.counted !== false) {
stat.total++; if (record.date.startsWith(month)) stat.month++;
}
stat.today ||= record.date === this.today();
stat.lastAt = Math.max(stat.lastAt, record.at);
}
return result;
}
private level(total: number): string { return this.ctx.t(levels.find(([max]) => total <= max)![1]); }
private async checkin(inv: Invocation): Promise<void> {
if (inv.args.length) return this.usage(inv, 'checkin');
const date = this.today();
const record = { userId: inv.message.userId, date, at: this.ctx.now().getTime() };
const inserted = await this.ctx.db.create(recordKey(record.userId, date), record);
if (!inserted) return this.reply(inv, this.ctx.t(m.duplicate, { date }));
const stat = (await this.stats()).get(record.userId)!;
await this.reply(inv, this.ctx.t(m.checked, { date, month: stat.month, total: stat.total, level: this.level(stat.total) }));
}
private async list(inv: Invocation): Promise<void> {
const target = inv.args[0] ?? inv.message.userId;
const all = choice(target, { all: ['全部', '所有'] }) === 'all';
if ((all || target !== inv.message.userId || inv.raw) && !await this.admin(inv)) return;
if (inv.args.length > 1 || (!all && !/^@.+:.+$/.test(target))) {
return this.usage(inv, 'checkin.list');
}
const stats = await this.stats();
const rows = all ? [...stats.values()] : [stats.get(target)].filter((s): s is Stats => !!s);
await this.reply(inv, !rows.length ? this.ctx.t(common.empty) : inv.raw ? JSON.stringify(rows, null, 2) :
rows.map((stat) => this.ctx.t(m.row, { user: stat.userId, today: this.ctx.t(stat.today ? m.yes : m.no),
month: stat.month, total: stat.total, level: this.level(stat.total) })).join('\n'));
}
async dailyText(date: string): Promise<string> {
const members = await this.ctx.members();
const users = new Set((await this.records()).filter((r) => r.date === date).map((r) => r.userId));
return this.ctx.t(m.reportDay, { date, count: users.size, members: members.length,
missing: members.filter((id) => !users.has(id)).join('\n') || '—' });
}
async monthlyText(month: string): Promise<string> {
const rows = [...(await this.stats(month)).values()].filter((s) => s.month > 0).sort((a, b) => b.month - a.month || a.userId.localeCompare(b.userId));
return this.ctx.t(m.reportMonth, { month, rows: rows.map((s, index) => `${index + 1}. ${s.userId}: ${s.month}`).join('\n') || this.ctx.t(common.empty) });
}
private async daily(inv: Invocation): Promise<void> {
if (!await this.admin(inv)) return;
const date = inv.args[0] ?? this.today();
if (inv.args.length > 1 || !validDate(date)) return this.usage(inv, 'checkin.daily');
await this.reply(inv, await this.dailyText(date));
}
private async monthly(inv: Invocation): Promise<void> {
if (!await this.admin(inv)) return;
const month = inv.args[0] ?? this.today().slice(0, 7);
if (inv.args.length > 1 || !validDate(`${month}-01`)) return this.usage(inv, 'checkin.monthly');
await this.reply(inv, await this.monthlyText(month));
}
async cleanupCandidates(): Promise<{ users: string[]; skipped: string[] }> {
const members = await this.ctx.members();
const stats = await this.stats();
const users: string[] = [], skipped: string[] = [];
for (const user of members) {
if (user === this.ctx.botUserId) continue;
const stat = stats.get(user);
if (!stat?.lastAt || stat.today || this.config.whitelist.includes(user) ||
this.ctx.now().getTime() - stat.lastAt < this.config.kickDays * 86_400_000) continue;
try {
// Read explicitly: a failed lookup must never be interpreted as a low power level.
const power = await this.ctx.power(user);
if (power >= this.ctx.adminPowerLevel || await this.ctx.isAdmin(user)) continue;
users.push(user);
} catch { skipped.push(user); }
}
return { users, skipped };
}
private async preview(inv: Invocation): Promise<void> {
if (!await this.admin(inv)) return;
if (!this.config.cleanupEnabled) return this.reply(inv, this.ctx.t(m.disabled));
if (inv.args.length) return this.usage(inv, 'checkin.cleanup.preview');
const plan = await this.cleanupCandidates();
const token = await this.plans.preview(inv.message.userId, plan.users);
await this.reply(inv, this.ctx.t(common.preview, {
details: [...plan.users, ...plan.skipped.map((user) => this.ctx.t(m.skipped, { user }))].join('\n') || this.ctx.t(common.empty),
command: `!cleanup confirm ${token} / !清理 确认 ${token}`,
}));
}
private async confirm(inv: Invocation): Promise<void> {
if (!await this.admin(inv)) return;
if (!this.config.cleanupEnabled) return this.reply(inv, this.ctx.t(m.disabled));
const users = inv.args.length === 1 ? await this.plans.consume(inv.message.userId, inv.args[0]) : undefined;
if (!users) return this.reply(inv, this.ctx.t(common.expired));
await this.reply(inv, this.ctx.t(common.done, { details: await this.executeCleanup(users, inv.message.userId) }));
}
private async executeCleanup(planned: string[], actor: string): Promise<string> {
const current = await this.cleanupCandidates();
const results: string[] = [];
for (const user of planned) {
if (!current.users.includes(user)) { results.push(this.ctx.t(m.changed, { user })); continue; }
try {
// Recheck privilege immediately before each individual mutation.
if (await this.ctx.power(user) >= this.ctx.adminPowerLevel || await this.ctx.isAdmin(user)) {
results.push(this.ctx.t(m.changed, { user })); continue;
}
await this.ctx.audit('cleanup.kick.requested', actor, { user });
await this.ctx.kick(this.ctx.roomId, user, this.ctx.t(m.kickReason, { days: this.config.kickDays }));
await this.ctx.audit('cleanup.kick.completed', actor, { user });
results.push(this.ctx.t(m.kicked, { user }));
} catch {
await this.ctx.audit('cleanup.kick.failed', actor, { user });
results.push(this.ctx.t(m.kickFailed, { user }));
}
}
return results.join('\n') || this.ctx.t(common.empty);
}
async settle(allowCleanup: boolean): Promise<void> {
const date = this.today(), minutes = localMinutes(this.ctx.now(), this.ctx.timeZone);
const daily = shiftDate(date, minutes >= 180 ? -1 : -2);
const monthly = date.endsWith('-01') && minutes < 5 ? previousMonth(`${previousMonth(date)}-01`) : previousMonth(date);
const saved = await this.ctx.db.get<Periods>('periods');
if (!saved) { await this.ctx.db.set('periods', { daily, monthly, cleanup: date }); return; }
if (saved.daily < daily) {
if (this.config.reportsEnabled) {
const prefix = shiftDate(saved.daily, 1) < daily ? this.ctx.t(m.catchup, { from: shiftDate(saved.daily, 1), to: daily }) + '\n' : '';
await this.ctx.send(prefix + await this.dailyText(daily));
}
saved.daily = daily;
await this.ctx.db.set('periods', saved);
}
if (saved.monthly < monthly) {
if (this.config.reportsEnabled) await this.ctx.send(this.ctx.t(m.catchup, { from: saved.monthly, to: monthly }) + '\n' + await this.monthlyText(monthly));
saved.monthly = monthly;
await this.ctx.db.set('periods', saved);
}
if (allowCleanup && this.config.autoCleanup && saved.cleanup < date && minutes >= 180) {
// Automatic cleanup is separate from reporting and never runs in the enable hook.
const plan = await this.cleanupCandidates();
const results: string[] = [];
if (plan.users.length) results.push(await this.executeCleanup(plan.users, 'scheduler'));
if (plan.skipped.length) {
await this.ctx.audit('cleanup.lookup.failed', 'scheduler', { users: plan.skipped });
results.push(...plan.skipped.map((user) => this.ctx.t(m.skipped, { user })));
}
if (results.length) await this.ctx.send(results.join('\n'));
saved.cleanup = date;
await this.ctx.db.set('periods', saved);
}
}
}
export default {
apiVersion: 1, id: 'checkin', aliases: ['签到'], version: '2.0.0', description: m.description,
validate: (config) => checkinConfig.parse(config),
create: (ctx, config) => new CheckinPlugin(ctx, checkinConfig.parse(config)),
} satisfies PluginDefinition;
+133
View File
@@ -0,0 +1,133 @@
import definition, { CheckinPlugin, checkinConfig, recordKey } from './checkin.plugin';
import { CommandRouter } from '../../core/command/command-router';
import { FakeContext, message } from '../../test/fakes';
function setup(config: Record<string, unknown> = {}) {
const ctx = new FakeContext();
const plugin = new CheckinPlugin(ctx, checkinConfig.parse(config));
const router = new CommandRouter(plugin.commands);
const run = async (text: string, user = '@member:example.org') => {
const match = router.match(message(text, user));
if (!match) throw new Error('Missing command');
await match.command.run(match.invocation);
};
return { ctx, plugin, run };
}
const admin = '@admin:example.org', member = '@member:example.org';
const last = (ctx: FakeContext) => ctx.transport.sent.at(-1)!.text;
describe('date-based check-in plugin', () => {
it('Chinese and English commands share the atomic daily record', async () => {
const { ctx, plugin, run } = setup();
await Promise.all([run('签到'), run('/checkin'), run('!签到')]);
expect((await plugin.records())).toHaveLength(1);
expect((await plugin.stats()).get(member)).toMatchObject({ total: 1, month: 1, today: true });
expect(ctx.transport.sent.filter((s) => s.text.includes('签到成功'))).toHaveLength(1);
});
it('starts a new day at midnight in the configured timezone without a report/reset', async () => {
const { ctx, plugin, run } = setup();
ctx.date = new Date('2026-01-15T15:59:59Z'); await run('!checkin');
ctx.date = new Date('2026-01-15T16:00:00Z'); await run('!checkin');
expect((await plugin.records()).map((r) => r.date)).toEqual(['2026-01-15', '2026-01-16']);
expect((await plugin.stats()).get(member)?.total).toBe(2);
});
it('monthly and daily reports preserve all records and counters', async () => {
const { ctx, run } = setup(); await run('!checkin');
const before = await ctx.db.entries();
await run('!日报', admin); await run('!report monthly', admin); await run('!月报', admin);
expect(await ctx.db.entries()).toEqual(before);
});
it('uses lifetime known records for levels across month boundaries', async () => {
const { ctx, plugin, run } = setup();
for (let day = 0; day < 45; day++) {
ctx.date = new Date(Date.UTC(2026, 0, 1 + day, 2)); await run('!签到');
}
expect((await plugin.stats()).get(member)).toMatchObject({ total: 45, month: 14 });
expect(last(ctx)).toContain('钻石');
});
it('allows own summary but restricts all, other users and raw data', async () => {
const { ctx, run } = setup(); await run('签到'); await run('!查询');
expect(last(ctx)).toContain(member);
for (const query of ['!list all', '!查询 全部', '!list @other:example.org', '!list --raw']) {
await run(query); expect(last(ctx)).toContain('无权限');
}
await run('!查询 全部 --原始', admin); expect(JSON.parse(last(ctx))[0].total).toBe(1);
});
it('supports English replies through the same resources', async () => {
const { ctx, run } = setup(); ctx.locale = 'en'; await run('签到');
expect(last(ctx)).toContain('Checked in'); await run('!签到'); expect(last(ctx)).toContain('Already');
});
it('rejects invalid dates and prevents monthly report access by members', async () => {
const { ctx, run } = setup(); await run('!日报 2026-02-30', admin); expect(last(ctx)).toContain('用法:!日报');
await run('!月报'); expect(last(ctx)).toContain('无权限');
});
it('catches up reports once without deleting history or executing cleanup on enable', async () => {
const { ctx, plugin, run } = setup({ cleanupEnabled: true, autoCleanup: true });
await run('!checkin'); await plugin.start();
ctx.date = new Date('2026-03-03T02:00:00Z');
await plugin.settle(false);
const count = ctx.transport.sent.length;
expect(ctx.transport.kicks).toHaveLength(0);
expect(last(ctx)).toContain('2026-02');
await plugin.settle(false); expect(ctx.transport.sent).toHaveLength(count);
expect((await plugin.stats('2026-01')).get(member)?.month).toBe(1);
});
});
describe('cleanup previews and confirmation', () => {
async function inactive(config: Record<string, unknown> = {}) {
const result = setup({ cleanupEnabled: true, ...config });
await result.run('签到'); result.ctx.date = new Date('2026-03-01T02:00:00Z');
return result;
}
const token = (ctx: FakeContext) => /cleanup confirm ([a-f0-9]+)/.exec(last(ctx))![1];
it('is disabled by default', async () => {
const { ctx, run } = setup(); await run('!清理 预览', admin);
expect(last(ctx)).toContain('未启用'); expect(ctx.transport.kicks).toHaveLength(0);
});
it('previews without kicking; requires the same administrator and consumes the token', async () => {
const { ctx, run } = await inactive();
await run('!清理 预览', admin); const code = token(ctx);
expect(ctx.transport.kicks).toHaveLength(0);
ctx.transport.powers.set('@second:example.org', 100);
await run(`!cleanup confirm ${code}`, '@second:example.org'); expect(ctx.transport.kicks).toHaveLength(0);
await run(`!清理 确认 ${code}`, admin); expect(ctx.transport.kicks).toHaveLength(1);
await run(`!cleanup confirm ${code}`, admin); expect(last(ctx)).toContain('无效');
});
it('rechecks check-in and privileges at confirmation', async () => {
const { ctx, run } = await inactive();
await run('!cleanup preview', admin); const code = token(ctx);
await run('签到'); await run(`!cleanup confirm ${code}`, admin);
expect(ctx.transport.kicks).toHaveLength(0);
});
it('expires previews and refuses a demoted administrator', async () => {
const { ctx, run } = await inactive(); await run('!cleanup preview', admin); const code = token(ctx);
ctx.transport.powers.set(admin, 0); await run(`!cleanup confirm ${code}`, admin);
expect(last(ctx)).toContain('无权限');
ctx.transport.powers.set(admin, 100); ctx.date = new Date(ctx.date.getTime() + 300_001);
await run(`!cleanup confirm ${code}`, admin); expect(last(ctx)).toContain('过期');
expect(ctx.transport.kicks).toHaveLength(0);
});
it('skips permission lookup failures, protected users and never-checked members', async () => {
const { ctx, plugin } = await inactive();
ctx.transport.powerFailures.add(member);
ctx.transport.memberMap.set(ctx.roomId, [member, '@new:example.org']);
expect(await plugin.cleanupCandidates()).toEqual({ users: [], skipped: [member] });
ctx.transport.powerFailures.clear(); ctx.transport.powers.set(member, 100);
expect((await plugin.cleanupCandidates()).users).toEqual([]);
});
it('does not turn a failed member lookup into an empty successful report', async () => {
const { ctx, plugin } = setup(); ctx.transport.memberFailures.add(ctx.roomId);
await expect(plugin.dailyText('2026-01-15')).rejects.toThrow('Unavailable');
});
it('validates automation prerequisites', () => {
expect(() => definition.validate({ autoCleanup: true })).toThrow();
expect(recordKey(member, '2026-01-15')).not.toBe(recordKey('@other:example.org', '2026-01-15'));
});
it('never includes its own account in cleanup candidates', async () => {
const { ctx, plugin, run } = setup({ cleanupEnabled: true });
await run('签到', ctx.botUserId); ctx.date = new Date('2026-03-01T02:00:00Z');
ctx.transport.memberMap.set(ctx.roomId, [ctx.botUserId]);
expect(await plugin.cleanupCandidates()).toEqual({ users: [], skipped: [] });
});
});
+24
View File
@@ -0,0 +1,24 @@
import { Messages } from '../../core/i18n/i18n';
export const messages = {
description: { 'zh-CN': '按日期签到、统计与成员清理', en: 'Daily check-in, reports and membership cleanup' },
checkin: { 'zh-CN': '今日签到', en: 'Check in for today' },
list: { 'zh-CN': '查询签到;他人、全部和原始数据仅管理员可查', en: 'Check-in records; others, all and raw data require admin access' },
daily: { 'zh-CN': '查询日报,不修改数据', en: 'Read daily report without changing data' },
monthly: { 'zh-CN': '查询月报,不修改数据', en: 'Read monthly report without changing data' },
cleanupPreview: { 'zh-CN': '预览长期未签到清理名单', en: 'Preview inactive-member cleanup' },
cleanupConfirm: { 'zh-CN': '执行已预览的清理名单', en: 'Execute a previously previewed cleanup' },
checked: { 'zh-CN': '{date} 签到成功。本月 {month} 次,累计已知记录 {total} 次,等级:{level}。', en: 'Checked in for {date}. This month: {month}; known total: {total}; level: {level}.' },
duplicate: { 'zh-CN': '{date} 已签到,无需重复。', en: 'Already checked in for {date}.' },
row: { 'zh-CN': '{user}:今日 {today},本月 {month} 次,累计已知记录 {total} 次,等级 {level}', en: '{user}: today {today}, month {month}, known total {total}, level {level}' },
yes: { 'zh-CN': '已签到', en: 'checked in' },
no: { 'zh-CN': '未签到', en: 'not checked in' },
reportDay: { 'zh-CN': '{date} 日报\n已签到 {count} 人;当前群成员 {members} 人。\n按当前成员核对,未找到当日记录:\n{missing}', en: 'Daily report {date}\nChecked in: {count}; current members: {members}.\nCurrent members without a record for this date:\n{missing}' },
reportMonth: { 'zh-CN': '{month} 月报\n{rows}', en: 'Monthly report {month}\n{rows}' },
skipped: { 'zh-CN': '{user}:权限读取失败,已跳过', en: '{user}: permission lookup failed; skipped' },
kickReason: { 'zh-CN': '连续至少 {days} 天未签到', en: 'No check-in for at least {days} days' },
kicked: { 'zh-CN': '{user}:已移出', en: '{user}: removed' },
kickFailed: { 'zh-CN': '{user}:移出失败,待人工复核', en: '{user}: removal failed; review required' },
changed: { 'zh-CN': '{user}:状态已变化,已跳过', en: '{user}: eligibility changed; skipped' },
disabled: { 'zh-CN': '成员清理未启用。请由维护人员配置 cleanupEnabled。', en: 'Membership cleanup is disabled. Configure cleanupEnabled first.' },
catchup: { 'zh-CN': '补发统计:{from} 至 {to} 期间的最新一期;完整历史仍可按日期查询。', en: 'Catch-up: latest report for the interval {from} through {to}. Full history remains available by date.' },
} satisfies Messages;