init
This commit is contained in:
commit
440f572834
53 files changed
+12776
No files matched your search
@@ -0,0 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from './config/config.module';
|
||||
import { DbModule } from './core/db/db.module';
|
||||
import { MatrixModule } from './core/matrix/matrix.module';
|
||||
import { BotModule } from './core/bot/bot.module';
|
||||
import { CheckinModule } from './bots/checkin/checkin.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule,
|
||||
DbModule,
|
||||
MatrixModule,
|
||||
BotModule,
|
||||
// —— 在此注册各房间机器人 feature module ——
|
||||
CheckinModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,415 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '../../config/config.service';
|
||||
import { RegisterBot } from '../../core/bot/register-bot.decorator';
|
||||
import { BotContext, RoomBot } from '../../core/bot/room-bot.interface';
|
||||
import {
|
||||
CronSpec,
|
||||
InboundMessage,
|
||||
ParsedCommand,
|
||||
} from '../../core/command/types';
|
||||
import {
|
||||
analyzeUnchecked,
|
||||
buildDailyReport,
|
||||
computeKickTargets,
|
||||
} from './report';
|
||||
import {
|
||||
applyCheckin,
|
||||
clearLevel,
|
||||
levelChoices,
|
||||
levelLabel,
|
||||
newUserState,
|
||||
parseLevel,
|
||||
raiseLevel,
|
||||
resetDaily,
|
||||
resetMonthly,
|
||||
setLevel,
|
||||
UserState,
|
||||
} from './user-state';
|
||||
|
||||
interface CheckinConfig {
|
||||
mainRoom?: string;
|
||||
kickDays: number;
|
||||
autoKick: boolean;
|
||||
whitelist: string[];
|
||||
admins: string[];
|
||||
adminPowerLevel: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 签到机器人:完整移植 Rust daily_bot 的签到/等级/日报/踢人/月统计。
|
||||
*
|
||||
* 命令(! 前缀):
|
||||
* !ping
|
||||
* !checkin
|
||||
* !list <用户ID|all>
|
||||
* !reset 重置所有用户当日签到
|
||||
* !level set <用户ID> <等级>
|
||||
* !level raise <用户ID>
|
||||
* !level super <用户ID>
|
||||
* !level clear <用户ID>
|
||||
* 定时:
|
||||
* 每日 03:00 日报 + 可选自动踢人 + 重置当日
|
||||
* 每月 1 日 00:05 月度统计 + 重置月度计数
|
||||
*/
|
||||
@RegisterBot()
|
||||
@Injectable()
|
||||
export class CheckinBot implements RoomBot {
|
||||
readonly name = 'checkin';
|
||||
readonly account: string;
|
||||
readonly rooms: string[];
|
||||
private readonly logger = new Logger('CheckinBot');
|
||||
private readonly cfg: CheckinConfig;
|
||||
|
||||
constructor(config: ConfigService) {
|
||||
const entry = config.bots.find((b) => b.name === 'checkin');
|
||||
if (!entry) {
|
||||
throw new Error('config 中缺少 name=checkin 的 bot 配置');
|
||||
}
|
||||
this.account = entry.account;
|
||||
this.rooms = entry.rooms;
|
||||
const c = entry.config;
|
||||
this.cfg = {
|
||||
mainRoom: (c.mainRoom as string) ?? entry.rooms[0],
|
||||
kickDays: (c.kickDays as number) ?? 30,
|
||||
autoKick: (c.autoKick as boolean) ?? false,
|
||||
whitelist: (c.whitelist as string[]) ?? [],
|
||||
admins: (c.admins as string[]) ?? [],
|
||||
adminPowerLevel: (c.adminPowerLevel as number) ?? 100,
|
||||
};
|
||||
this.logger.log(
|
||||
`管理员判定:房间 power level ≥ ${this.cfg.adminPowerLevel}` +
|
||||
(this.cfg.admins.length > 0
|
||||
? ` 或 config.admins 白名单(${this.cfg.admins.length} 人)`
|
||||
: ''),
|
||||
);
|
||||
}
|
||||
|
||||
/** 管理员鉴权:房间内 power level ≥ 阈值,或在 config.admins 白名单中。 */
|
||||
private async isAdmin(
|
||||
roomId: string,
|
||||
userId: string,
|
||||
ctx: BotContext,
|
||||
): Promise<boolean> {
|
||||
if (this.cfg.admins.includes(userId)) return true;
|
||||
const power = await ctx.getPowerLevel(roomId, userId);
|
||||
return power >= this.cfg.adminPowerLevel;
|
||||
}
|
||||
|
||||
/** 校验调用者是否管理员,非管理员回拒绝并返回 false。 */
|
||||
private async requireAdmin(
|
||||
cmd: ParsedCommand,
|
||||
ctx: BotContext,
|
||||
): Promise<boolean> {
|
||||
if (await this.isAdmin(cmd.raw.roomId, cmd.raw.userId, ctx)) return true;
|
||||
await ctx.reply(cmd.raw, '⛔ 无权限:该命令仅管理员可用');
|
||||
this.logger.warn(
|
||||
`拒绝越权命令 !${cmd.command} 来自 ${cmd.raw.userId}`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 平台登录完成后,向主房间发送一条上线通知,便于确认收发正常。 */
|
||||
async onReady(ctx: BotContext): Promise<void> {
|
||||
const room = this.cfg.mainRoom ?? this.rooms[0];
|
||||
if (!room) return;
|
||||
const time = new Date().toLocaleString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
});
|
||||
await ctx.send(room, `✅ 签到机器人已启动(${time})。发送 !help 查看命令。`);
|
||||
this.logger.log(`已发送上线通知到 ${room}`);
|
||||
}
|
||||
|
||||
/** 中文「签到」无需前缀也可触发(对应 Rust support_chinese_command)。 */
|
||||
async onMessage(msg: InboundMessage, ctx: BotContext): Promise<void> {
|
||||
const text = msg.text.trim();
|
||||
if (text === '签到') {
|
||||
await this.handleCheckin(msg, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
async onCommand(cmd: ParsedCommand, ctx: BotContext): Promise<void> {
|
||||
switch (cmd.command) {
|
||||
case 'ping':
|
||||
await ctx.reply(cmd.raw, 'pong');
|
||||
break;
|
||||
case 'help':
|
||||
await ctx.reply(cmd.raw, this.helpText());
|
||||
break;
|
||||
case 'echo':
|
||||
await ctx.reply(cmd.raw, cmd.args.join(' ') || '(空)');
|
||||
break;
|
||||
case 'checkin':
|
||||
case '签到':
|
||||
await this.handleCheckin(cmd.raw, ctx);
|
||||
break;
|
||||
case 'list':
|
||||
await this.handleList(cmd, ctx);
|
||||
break;
|
||||
case 'reset':
|
||||
if (!(await this.requireAdmin(cmd, ctx))) break;
|
||||
await this.handleReset(cmd.raw, ctx);
|
||||
break;
|
||||
case 'level':
|
||||
if (!(await this.requireAdmin(cmd, ctx))) break;
|
||||
await this.handleLevel(cmd, ctx);
|
||||
break;
|
||||
case 'test':
|
||||
if (!(await this.requireAdmin(cmd, ctx))) break;
|
||||
await this.handleTest(cmd, ctx);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
registerCrons(ctx: BotContext): CronSpec[] {
|
||||
return [
|
||||
{
|
||||
name: 'daily-report',
|
||||
cron: '0 0 3 * * *',
|
||||
run: () => this.dailyReport(ctx),
|
||||
},
|
||||
{
|
||||
name: 'monthly-report',
|
||||
cron: '0 5 0 1 * *',
|
||||
run: () => this.monthlyReport(ctx),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// ——— 命令处理 ———
|
||||
|
||||
private async handleCheckin(
|
||||
raw: InboundMessage,
|
||||
ctx: BotContext,
|
||||
): Promise<void> {
|
||||
const existing = await ctx.db.get<UserState>(raw.userId);
|
||||
if (existing?.isCheckinToday) {
|
||||
await ctx.reply(raw, '您今天已签到过了,请勿重复签到');
|
||||
return;
|
||||
}
|
||||
const state = applyCheckin(existing ?? newUserState());
|
||||
await ctx.db.set(raw.userId, state);
|
||||
await ctx.reply(
|
||||
raw,
|
||||
`${raw.userId} 签到成功 ✅ 本月第 ${state.checkinTimesInMonth} 次,当前等级 ${levelLabel(state.level)}`,
|
||||
);
|
||||
}
|
||||
|
||||
private async handleList(cmd: ParsedCommand, ctx: BotContext): Promise<void> {
|
||||
const target = cmd.args[0];
|
||||
const raw = cmd.options.raw !== undefined;
|
||||
if (!target) {
|
||||
await ctx.reply(cmd.raw, '用法: !list <用户ID|all> [--raw]');
|
||||
return;
|
||||
}
|
||||
if (target === 'all') {
|
||||
const entries = await ctx.db.entries<UserState>();
|
||||
if (raw) {
|
||||
await ctx.reply(
|
||||
cmd.raw,
|
||||
entries.length ? JSON.stringify(entries, null, 2) : '暂无签到记录',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const text = entries.length
|
||||
? entries
|
||||
.map(
|
||||
([uid, s]) =>
|
||||
`${uid}: ${s.isCheckinToday ? '已签到' : '未签到'} 等级=${levelLabel(s.level)} 本月=${s.checkinTimesInMonth}次`,
|
||||
)
|
||||
.join('\n')
|
||||
: '暂无签到记录';
|
||||
await ctx.reply(cmd.raw, text);
|
||||
return;
|
||||
}
|
||||
const state = await ctx.db.get<UserState>(target);
|
||||
if (raw) {
|
||||
await ctx.reply(
|
||||
cmd.raw,
|
||||
state ? JSON.stringify(state, null, 2) : `${target} 尚未签到过`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await ctx.reply(
|
||||
cmd.raw,
|
||||
state
|
||||
? `${target}: ${state.isCheckinToday ? '已签到' : '未签到'} 等级=${levelLabel(state.level)} 本月=${state.checkinTimesInMonth}次`
|
||||
: `${target} 尚未签到过`,
|
||||
);
|
||||
}
|
||||
|
||||
private helpText(): string {
|
||||
return [
|
||||
'签到机器人命令列表:',
|
||||
'!checkin / 签到 — 今日签到',
|
||||
'!list <用户ID|all> [--raw] — 查询签到状态',
|
||||
'!level set <用户ID> <等级> — 设置等级(管理员)',
|
||||
'!level raise <用户ID> — 提升一级(管理员)',
|
||||
'!level super <用户ID> — 赋予超级管理(管理员)',
|
||||
'!level clear <用户ID> — 清除等级(管理员)',
|
||||
'!reset — 重置所有人当日签到(管理员)',
|
||||
'!test daily|monthly — 手动触发日报/月报(管理员)',
|
||||
'!echo <文本> / !ping / !help',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** 手动触发定时任务,便于运维测试(对应 Rust `!test daily_report`)。 */
|
||||
private async handleTest(cmd: ParsedCommand, ctx: BotContext): Promise<void> {
|
||||
const project = cmd.args[0];
|
||||
if (!project) {
|
||||
await ctx.reply(cmd.raw, '用法: !test <daily|monthly>');
|
||||
return;
|
||||
}
|
||||
switch (project) {
|
||||
case 'daily':
|
||||
case 'daily_report':
|
||||
await ctx.reply(cmd.raw, '开始执行日报测试…');
|
||||
await this.dailyReport(ctx);
|
||||
await ctx.reply(cmd.raw, '日报测试完成 ✅');
|
||||
break;
|
||||
case 'monthly':
|
||||
case 'monthly_report':
|
||||
await ctx.reply(cmd.raw, '开始执行月报测试…');
|
||||
await this.monthlyReport(ctx);
|
||||
await ctx.reply(cmd.raw, '月报测试完成 ✅');
|
||||
break;
|
||||
default:
|
||||
await ctx.reply(cmd.raw, `未知测试项目: ${project}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleReset(
|
||||
raw: InboundMessage,
|
||||
ctx: BotContext,
|
||||
): Promise<void> {
|
||||
const entries = await ctx.db.entries<UserState>();
|
||||
for (const [uid, s] of entries) {
|
||||
if (s.isCheckinToday) {
|
||||
await ctx.db.set(uid, resetDaily(s));
|
||||
}
|
||||
}
|
||||
await ctx.reply(raw, '已重置所有用户的当日签到状态');
|
||||
}
|
||||
|
||||
private async handleLevel(cmd: ParsedCommand, ctx: BotContext): Promise<void> {
|
||||
const [action, userId, levelArg] = cmd.args;
|
||||
if (!action) {
|
||||
await ctx.reply(
|
||||
cmd.raw,
|
||||
'用法: !level set|raise|super|clear <用户ID> [等级]',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!userId) {
|
||||
await ctx.reply(cmd.raw, '请提供用户ID,例如: !level super @user:hs');
|
||||
return;
|
||||
}
|
||||
|
||||
const current = (await ctx.db.get<UserState>(userId)) ?? newUserState();
|
||||
switch (action) {
|
||||
case 'set': {
|
||||
const level = levelArg ? parseLevel(levelArg) : null;
|
||||
if (!level) {
|
||||
await ctx.reply(
|
||||
cmd.raw,
|
||||
`无效的等级。可选: ${levelChoices()}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await ctx.db.set(userId, setLevel(current, level));
|
||||
await ctx.reply(cmd.raw, `已设置用户 ${userId} 的等级为 ${levelLabel(level)}`);
|
||||
break;
|
||||
}
|
||||
case 'raise': {
|
||||
const next = raiseLevel(current);
|
||||
await ctx.db.set(userId, next);
|
||||
await ctx.reply(cmd.raw, `已提升用户 ${userId} 的等级为 ${levelLabel(next.level)}`);
|
||||
break;
|
||||
}
|
||||
case 'super':
|
||||
await ctx.db.set(userId, setLevel(current, 'Super'));
|
||||
await ctx.reply(cmd.raw, `已赋予用户 ${userId} 超级权限`);
|
||||
break;
|
||||
case 'clear':
|
||||
await ctx.db.set(userId, clearLevel(current));
|
||||
await ctx.reply(cmd.raw, `已清除用户 ${userId} 的等级为${levelLabel('Bronze')}`);
|
||||
break;
|
||||
default:
|
||||
await ctx.reply(cmd.raw, `未知的 level 操作: ${action}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ——— 定时任务 ———
|
||||
|
||||
private async dailyReport(ctx: BotContext): Promise<void> {
|
||||
const room = this.cfg.mainRoom ?? this.rooms[0];
|
||||
if (!room) return;
|
||||
|
||||
const entries = await ctx.db.entries<UserState>();
|
||||
const states = new Map(entries);
|
||||
// 已签到且非 Super 的人数(对应 Rust 的 checked_nums)。
|
||||
const checkedNums = entries.filter(
|
||||
([, s]) => s.isCheckinToday && s.level !== 'Super',
|
||||
).length;
|
||||
|
||||
const members = await ctx.getJoinedMembers(room);
|
||||
const allUserNums =
|
||||
members.length > 0 ? members.length : await ctx.getMemberCount(room);
|
||||
const rows = analyzeUnchecked(members, states);
|
||||
|
||||
const date = new Date().toLocaleDateString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
});
|
||||
const text = buildDailyReport({ date, checkedNums, allUserNums, rows });
|
||||
await ctx.send(room, text);
|
||||
|
||||
if (this.cfg.autoKick) {
|
||||
const targets = computeKickTargets(
|
||||
rows,
|
||||
this.cfg.kickDays,
|
||||
this.cfg.whitelist,
|
||||
);
|
||||
for (const userId of targets) {
|
||||
await ctx.kick(room, userId, `超过 ${this.cfg.kickDays} 天未签到`);
|
||||
this.logger.log(`已踢出 ${userId}`);
|
||||
}
|
||||
if (targets.length > 0) {
|
||||
await ctx.send(room, `已踢出 ${targets.length} 名长期未签到用户`);
|
||||
}
|
||||
}
|
||||
|
||||
// 重置当日签到标记。
|
||||
for (const [uid, s] of entries) {
|
||||
if (s.isCheckinToday) {
|
||||
await ctx.db.set(uid, resetDaily(s));
|
||||
}
|
||||
}
|
||||
this.logger.log(`日报完成: checked=${checkedNums} total=${allUserNums}`);
|
||||
}
|
||||
|
||||
private async monthlyReport(ctx: BotContext): Promise<void> {
|
||||
const room = this.cfg.mainRoom ?? this.rooms[0];
|
||||
if (!room) return;
|
||||
|
||||
const entries = await ctx.db.entries<UserState>();
|
||||
const ranked = entries
|
||||
.filter(([, s]) => s.level !== 'Super')
|
||||
.sort((a, b) => b[1].checkinTimesInMonth - a[1].checkinTimesInMonth);
|
||||
|
||||
const date = new Date().toLocaleDateString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
});
|
||||
const lines = ranked.map(
|
||||
([uid, s], i) => `${i + 1}. ${uid} — ${s.checkinTimesInMonth} 次 (${levelLabel(s.level)})`,
|
||||
);
|
||||
const text = `# ${date} 月度签到统计\n${lines.join('\n') || '暂无数据'}`;
|
||||
await ctx.send(room, text);
|
||||
|
||||
// 重置月度计数。
|
||||
for (const [uid, s] of entries) {
|
||||
await ctx.db.set(uid, resetMonthly(s));
|
||||
}
|
||||
this.logger.log(`月报完成: users=${entries.length}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, unlinkSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { PrismaService } from '../../core/db/prisma.service';
|
||||
import { BotStore } from '../../core/db/bot-store';
|
||||
import { BotContext } from '../../core/bot/room-bot.interface';
|
||||
import { InboundMessage, ParsedCommand } from '../../core/command/types';
|
||||
import { parseCommand } from '../../core/command/command-parser';
|
||||
import { CheckinBot } from './checkin.bot';
|
||||
import { UserState } from './user-state';
|
||||
|
||||
const PROJECT_ROOT = resolve(__dirname, '../../..');
|
||||
const TEST_DB_FILE = resolve(PROJECT_ROOT, 'test-checkin-integration.db');
|
||||
const TEST_DB_URL = `file:${TEST_DB_FILE}`;
|
||||
|
||||
function cleanDb(): void {
|
||||
for (const suffix of ['', '-journal', '-wal', '-shm']) {
|
||||
const f = TEST_DB_FILE + suffix;
|
||||
if (existsSync(f)) unlinkSync(f);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- test doubles ----------
|
||||
|
||||
/** BotContext backed by a real BotStore (wraps real Prisma). */
|
||||
class RealStoreContext implements BotContext {
|
||||
readonly account = 'checkin';
|
||||
readonly sent: string[] = [];
|
||||
readonly kicked: Array<{ roomId: string; userId: string; reason?: string }> =
|
||||
[];
|
||||
members: string[] = [];
|
||||
powerLevels: Record<string, number> = {};
|
||||
|
||||
constructor(public readonly db: BotStore) {}
|
||||
|
||||
async send(_roomId: string, text: string): Promise<string> {
|
||||
this.sent.push(text);
|
||||
return 'evt';
|
||||
}
|
||||
async reply(_msg: InboundMessage, text: string): Promise<string> {
|
||||
this.sent.push(text);
|
||||
return 'evt';
|
||||
}
|
||||
async kick(roomId: string, userId: string, reason?: string): Promise<void> {
|
||||
this.kicked.push({ roomId, userId, reason });
|
||||
}
|
||||
async getMemberCount(): Promise<number> {
|
||||
return this.members.length || 10;
|
||||
}
|
||||
async getJoinedMembers(): Promise<string[]> {
|
||||
return this.members;
|
||||
}
|
||||
async getPowerLevel(_roomId: string, userId: string): Promise<number> {
|
||||
return this.powerLevels[userId] ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- helpers ----------
|
||||
|
||||
let prismaService: PrismaService;
|
||||
|
||||
function makeBot(): CheckinBot {
|
||||
const fakeConfig = {
|
||||
bots: [
|
||||
{
|
||||
name: 'checkin',
|
||||
account: 'checkin',
|
||||
rooms: ['!room:hs'],
|
||||
config: { mainRoom: '!room:hs', admins: ['@admin:hs'] },
|
||||
},
|
||||
],
|
||||
} as never;
|
||||
return new CheckinBot(fakeConfig);
|
||||
}
|
||||
|
||||
function makeCtx(): RealStoreContext {
|
||||
return new RealStoreContext(new BotStore(prismaService, 'checkin'));
|
||||
}
|
||||
|
||||
function msg(text: string, userId = '@alice:hs'): InboundMessage {
|
||||
return {
|
||||
eventId: 'e1',
|
||||
account: 'checkin',
|
||||
roomId: '!room:hs',
|
||||
userId,
|
||||
text,
|
||||
timestampMs: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
function cmd(text: string, userId = '@alice:hs'): ParsedCommand {
|
||||
return parseCommand(msg(text, userId), text);
|
||||
}
|
||||
|
||||
// ---------- lifecycle ----------
|
||||
|
||||
beforeAll(async () => {
|
||||
cleanDb();
|
||||
execSync('npx prisma db push --skip-generate', {
|
||||
cwd: PROJECT_ROOT,
|
||||
env: { ...process.env, DATABASE_URL: TEST_DB_URL },
|
||||
stdio: 'pipe',
|
||||
});
|
||||
process.env.DATABASE_URL = TEST_DB_URL;
|
||||
prismaService = new PrismaService();
|
||||
await prismaService.onModuleInit();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await prismaService.onModuleDestroy();
|
||||
cleanDb();
|
||||
delete process.env.DATABASE_URL;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await prismaService.botState.deleteMany();
|
||||
});
|
||||
|
||||
// ---------- tests ----------
|
||||
|
||||
describe('CheckinBot + real BotStore (integration)', () => {
|
||||
describe('checkin command persists state to SQLite', () => {
|
||||
it('writes isCheckinToday=true and increments monthly count', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state).not.toBeNull();
|
||||
expect(state!.isCheckinToday).toBe(true);
|
||||
expect(state!.checkinTimesInMonth).toBe(1);
|
||||
expect(ctx.sent[0]).toContain('签到成功');
|
||||
});
|
||||
|
||||
it('prevents duplicate checkin and persists only one record', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin'), ctx);
|
||||
await bot.onCommand(cmd('checkin'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.checkinTimesInMonth).toBe(1); // not incremented twice
|
||||
expect(ctx.sent[1]).toContain('已签到过');
|
||||
});
|
||||
|
||||
it('state is readable across multiple BotStore instances (same DB)', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx1 = makeCtx();
|
||||
await bot.onCommand(cmd('checkin'), ctx1);
|
||||
|
||||
// Simulate reading from a fresh context (same prismaService → same DB).
|
||||
const ctx2 = makeCtx();
|
||||
const state = await ctx2.db.get<UserState>('@alice:hs');
|
||||
expect(state!.isCheckinToday).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('!reset clears isCheckinToday in the database', () => {
|
||||
it('resets all checked-in users', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin', '@alice:hs'), ctx);
|
||||
await bot.onCommand(cmd('checkin', '@bob:hs'), ctx);
|
||||
|
||||
ctx.sent.length = 0;
|
||||
await bot.onCommand(cmd('reset', '@admin:hs'), ctx);
|
||||
|
||||
const alice = await ctx.db.get<UserState>('@alice:hs');
|
||||
const bob = await ctx.db.get<UserState>('@bob:hs');
|
||||
expect(alice!.isCheckinToday).toBe(false);
|
||||
expect(bob!.isCheckinToday).toBe(false);
|
||||
expect(ctx.sent[0]).toContain('已重置');
|
||||
});
|
||||
|
||||
it('reset is admin-only — non-admin gets rejected and DB is unchanged', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin', '@alice:hs'), ctx);
|
||||
ctx.sent.length = 0;
|
||||
|
||||
await bot.onCommand(cmd('reset', '@alice:hs'), ctx);
|
||||
|
||||
expect(ctx.sent[0]).toContain('无权限');
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.isCheckinToday).toBe(true); // unchanged
|
||||
});
|
||||
});
|
||||
|
||||
describe('!level commands persist level changes to SQLite', () => {
|
||||
it('!level set persists the new level', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('level set @bob:hs 黄金', '@admin:hs'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@bob:hs');
|
||||
expect(state!.level).toBe('Gold');
|
||||
});
|
||||
|
||||
it('!level raise increments the stored level', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
// After one checkin, applyCheckin sets level to Bronze (t=1, t<=7).
|
||||
await bot.onCommand(cmd('checkin', '@alice:hs'), ctx);
|
||||
ctx.sent.length = 0;
|
||||
|
||||
await bot.onCommand(cmd('level raise @alice:hs', '@admin:hs'), ctx);
|
||||
|
||||
// Bronze -> Silver is the expected raise.
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.level).toBe('Silver');
|
||||
});
|
||||
|
||||
it('!level super grants Super level', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('level super @alice:hs', '@admin:hs'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.level).toBe('Super');
|
||||
});
|
||||
|
||||
it('!level clear resets level to Bronze', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('level super @alice:hs', '@admin:hs'), ctx);
|
||||
await bot.onCommand(cmd('level clear @alice:hs', '@admin:hs'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.level).toBe('Bronze');
|
||||
});
|
||||
});
|
||||
|
||||
describe('!list reads from real DB', () => {
|
||||
it('lists all users stored in DB', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin', '@alice:hs'), ctx);
|
||||
await bot.onCommand(cmd('checkin', '@bob:hs'), ctx);
|
||||
ctx.sent.length = 0;
|
||||
|
||||
await bot.onCommand(cmd('list all'), ctx);
|
||||
|
||||
expect(ctx.sent[0]).toContain('@alice:hs');
|
||||
expect(ctx.sent[0]).toContain('@bob:hs');
|
||||
});
|
||||
|
||||
it('lists a specific user', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('checkin', '@alice:hs'), ctx);
|
||||
ctx.sent.length = 0;
|
||||
|
||||
await bot.onCommand(cmd('list @alice:hs'), ctx);
|
||||
|
||||
expect(ctx.sent[0]).toContain('@alice:hs');
|
||||
expect(ctx.sent[0]).toContain('已签到');
|
||||
});
|
||||
|
||||
it('returns "尚未签到" for a user not in DB', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onCommand(cmd('list @nobody:hs'), ctx);
|
||||
|
||||
expect(ctx.sent[0]).toContain('尚未签到');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Chinese text trigger onMessage()', () => {
|
||||
it('signs in when message text is exactly "签到"', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onMessage(msg('签到', '@alice:hs'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.isCheckinToday).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores other Chinese messages', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
|
||||
await bot.onMessage(msg('你好', '@alice:hs'), ctx);
|
||||
|
||||
expect(ctx.sent).toHaveLength(0);
|
||||
expect(await ctx.db.get('@alice:hs')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin authorization via power level reads correct value', () => {
|
||||
it('allows power-level-100 user to use admin commands', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
ctx.powerLevels['@mod:hs'] = 100;
|
||||
|
||||
await bot.onCommand(cmd('level super @alice:hs', '@mod:hs'), ctx);
|
||||
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state!.level).toBe('Super');
|
||||
});
|
||||
|
||||
it('denies power-level-50 user from admin commands', async () => {
|
||||
const bot = makeBot();
|
||||
const ctx = makeCtx();
|
||||
ctx.powerLevels['@halfmod:hs'] = 50;
|
||||
|
||||
await bot.onCommand(cmd('level super @alice:hs', '@halfmod:hs'), ctx);
|
||||
|
||||
expect(ctx.sent[0]).toContain('无权限');
|
||||
expect(await ctx.db.get('@alice:hs')).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CheckinBot } from './checkin.bot';
|
||||
|
||||
/**
|
||||
* 签到 bot 模块。新增 bot 时照此模式新建一个目录与模块,
|
||||
* 在 AppModule 里 import 即可,核心代码无需改动。
|
||||
*/
|
||||
@Module({
|
||||
providers: [CheckinBot],
|
||||
})
|
||||
export class CheckinModule {}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { BotContext } from '../../core/bot/room-bot.interface';
|
||||
import { InboundMessage } from '../../core/command/types';
|
||||
import { parseCommand } from '../../core/command/command-parser';
|
||||
import { CheckinBot } from './checkin.bot';
|
||||
import { UserState } from './user-state';
|
||||
|
||||
/** 内存版 BotContext,用于纯逻辑单测,无需连接 Matrix。 */
|
||||
class FakeContext implements BotContext {
|
||||
readonly account = 'checkin';
|
||||
readonly sent: string[] = [];
|
||||
private readonly store = new Map<string, unknown>();
|
||||
|
||||
readonly db = {
|
||||
get: async <T>(key: string) => (this.store.get(key) ?? null) as T | null,
|
||||
set: async <T>(key: string, value: T) => {
|
||||
this.store.set(key, value);
|
||||
},
|
||||
remove: async (key: string) => {
|
||||
this.store.delete(key);
|
||||
},
|
||||
entries: async <T>() =>
|
||||
[...this.store.entries()] as Array<[string, T]>,
|
||||
} as unknown as BotContext['db'];
|
||||
|
||||
async send(_roomId: string, text: string): Promise<string> {
|
||||
this.sent.push(text);
|
||||
return 'evt';
|
||||
}
|
||||
async reply(_msg: InboundMessage, text: string): Promise<string> {
|
||||
this.sent.push(text);
|
||||
return 'evt';
|
||||
}
|
||||
async kick(): Promise<void> {}
|
||||
async getMemberCount(): Promise<number> {
|
||||
return 10;
|
||||
}
|
||||
members: string[] = [];
|
||||
async getJoinedMembers(): Promise<string[]> {
|
||||
return this.members;
|
||||
}
|
||||
powerLevels: Record<string, number> = {};
|
||||
async getPowerLevel(_roomId: string, userId: string): Promise<number> {
|
||||
return this.powerLevels[userId] ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
function buildBot(): CheckinBot {
|
||||
const fakeConfig = {
|
||||
bots: [
|
||||
{
|
||||
name: 'checkin',
|
||||
account: 'checkin',
|
||||
rooms: ['!room:hs'],
|
||||
config: { mainRoom: '!room:hs', admins: ['@admin:hs'] },
|
||||
},
|
||||
],
|
||||
} as never;
|
||||
return new CheckinBot(fakeConfig);
|
||||
}
|
||||
|
||||
function msg(text: string, userId = '@alice:hs'): InboundMessage {
|
||||
return {
|
||||
eventId: 'e1',
|
||||
account: 'checkin',
|
||||
roomId: '!room:hs',
|
||||
userId,
|
||||
text,
|
||||
timestampMs: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('CheckinBot', () => {
|
||||
it('binds account and rooms from config', () => {
|
||||
const bot = buildBot();
|
||||
expect(bot.name).toBe('checkin');
|
||||
expect(bot.account).toBe('checkin');
|
||||
expect(bot.rooms).toEqual(['!room:hs']);
|
||||
});
|
||||
|
||||
it('records a check-in and prevents duplicates', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
|
||||
await bot.onCommand(parseCommand(msg('checkin'), 'checkin'), ctx);
|
||||
const state = await ctx.db.get<UserState>('@alice:hs');
|
||||
expect(state?.isCheckinToday).toBe(true);
|
||||
expect(state?.checkinTimesInMonth).toBe(1);
|
||||
expect(ctx.sent[0]).toContain('签到成功');
|
||||
|
||||
await bot.onCommand(parseCommand(msg('checkin'), 'checkin'), ctx);
|
||||
expect(ctx.sent[1]).toContain('已签到过');
|
||||
});
|
||||
|
||||
it('lists all users', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
await bot.onCommand(parseCommand(msg('checkin'), 'checkin'), ctx);
|
||||
ctx.sent.length = 0;
|
||||
|
||||
await bot.onCommand(parseCommand(msg('list all'), 'list all'), ctx);
|
||||
expect(ctx.sent[0]).toContain('@alice:hs');
|
||||
});
|
||||
|
||||
it('registers daily and monthly crons', () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
const crons = bot.registerCrons(ctx);
|
||||
expect(crons).toHaveLength(2);
|
||||
expect(crons[0].cron).toBe('0 0 3 * * *');
|
||||
expect(crons[1].cron).toBe('0 5 0 1 * *');
|
||||
});
|
||||
|
||||
it('sets level via Chinese name and displays Chinese label', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
await bot.onCommand(
|
||||
parseCommand(
|
||||
msg('level set @bob:hs 黄金', '@admin:hs'),
|
||||
'level set @bob:hs 黄金',
|
||||
),
|
||||
ctx,
|
||||
);
|
||||
expect(ctx.sent[0]).toContain('黄金');
|
||||
const state = await ctx.db.get<UserState>('@bob:hs');
|
||||
expect(state?.level).toBe('Gold');
|
||||
});
|
||||
|
||||
it('denies privileged commands from non-admins', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
// @alice 非管理员,试图把自己设为超管应被拒绝。
|
||||
await bot.onCommand(
|
||||
parseCommand(
|
||||
msg('level super @alice:hs', '@alice:hs'),
|
||||
'level super @alice:hs',
|
||||
),
|
||||
ctx,
|
||||
);
|
||||
expect(ctx.sent[0]).toContain('无权限');
|
||||
expect(await ctx.db.get<UserState>('@alice:hs')).toBeNull();
|
||||
|
||||
// reset / test 同样受限。
|
||||
await bot.onCommand(parseCommand(msg('reset', '@alice:hs'), 'reset'), ctx);
|
||||
expect(ctx.sent[1]).toContain('无权限');
|
||||
});
|
||||
|
||||
it('allows privileged commands from room admins via power level', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
// @mod 不在 config.admins,但房间 power level=100,应视为管理员。
|
||||
ctx.powerLevels['@mod:hs'] = 100;
|
||||
await bot.onCommand(
|
||||
parseCommand(
|
||||
msg('level set @bob:hs 黄金', '@mod:hs'),
|
||||
'level set @bob:hs 黄金',
|
||||
),
|
||||
ctx,
|
||||
);
|
||||
expect(ctx.sent[0]).toContain('黄金');
|
||||
expect((await ctx.db.get<UserState>('@bob:hs'))?.level).toBe('Gold');
|
||||
});
|
||||
|
||||
it('denies privileged commands when power level below threshold', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
// @mod power level=50(版主),低于阈值 100,应被拒绝。
|
||||
ctx.powerLevels['@mod:hs'] = 50;
|
||||
await bot.onCommand(parseCommand(msg('reset', '@mod:hs'), 'reset'), ctx);
|
||||
expect(ctx.sent[0]).toContain('无权限');
|
||||
});
|
||||
|
||||
it('shows Chinese level on check-in', async () => {
|
||||
const bot = buildBot();
|
||||
const ctx = new FakeContext();
|
||||
await bot.onCommand(parseCommand(msg('checkin'), 'checkin'), ctx);
|
||||
expect(ctx.sent[0]).toContain('青铜');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import {
|
||||
analyzeUnchecked,
|
||||
buildDailyReport,
|
||||
computeKickTargets,
|
||||
} from './report';
|
||||
import { newUserState, UserState } from './user-state';
|
||||
|
||||
function state(partial: Partial<UserState>): UserState {
|
||||
return { ...newUserState(), ...partial };
|
||||
}
|
||||
|
||||
const DAY = 86_400_000;
|
||||
const NOW = 1_000 * DAY; // 固定 now,便于天数计算
|
||||
|
||||
describe('report', () => {
|
||||
it('analyzes unchecked members, skipping checked-in and super', () => {
|
||||
const states = new Map<string, UserState>([
|
||||
['@a:hs', state({ isCheckinToday: true, checkinUnixMs: NOW })],
|
||||
['@b:hs', state({ checkinUnixMs: NOW - 10 * DAY })],
|
||||
['@s:hs', state({ level: 'Super', checkinUnixMs: NOW - 50 * DAY })],
|
||||
]);
|
||||
// @c:hs 不在 DB ⇒ 从未签到
|
||||
const rows = analyzeUnchecked(
|
||||
['@a:hs', '@b:hs', '@s:hs', '@c:hs'],
|
||||
states,
|
||||
NOW,
|
||||
);
|
||||
expect(rows).toEqual([
|
||||
{ userId: '@b:hs', days: 10 },
|
||||
{ userId: '@c:hs', days: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it('builds a markdown report with buckets', () => {
|
||||
const rows = [
|
||||
{ userId: '@b:hs', days: 10 },
|
||||
{ userId: '@d:hs', days: 31 },
|
||||
{ userId: '@c:hs', days: null },
|
||||
];
|
||||
const text = buildDailyReport({
|
||||
date: '2026/6/3',
|
||||
checkedNums: 5,
|
||||
allUserNums: 8,
|
||||
rows,
|
||||
});
|
||||
expect(text).toContain('签到率:63%');
|
||||
expect(text).toContain('未签到人数:3');
|
||||
expect(text).toContain('## 超过7天未签到用户\n@b:hs ,\n@d:hs');
|
||||
expect(text).toContain('## 超过30天未签到用户\n@d:hs');
|
||||
expect(text).toContain('## 从未签到用户\n@c:hs');
|
||||
});
|
||||
|
||||
it('computes kick targets respecting whitelist and never-checked', () => {
|
||||
const rows = [
|
||||
{ userId: '@b:hs', days: 10 },
|
||||
{ userId: '@d:hs', days: 31 },
|
||||
{ userId: '@e:hs', days: 40 },
|
||||
{ userId: '@c:hs', days: null },
|
||||
];
|
||||
const targets = computeKickTargets(rows, 30, ['@e:hs']);
|
||||
expect(targets).toEqual(['@d:hs']); // e 在白名单, c 从未签到不踢, b 未达阈值
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { isSuper, uncheckedDays, UserState } from './user-state';
|
||||
|
||||
export interface UncheckedRow {
|
||||
userId: string;
|
||||
/** null = 从未签到。 */
|
||||
days: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析主房间成员的未签到情况:
|
||||
* - 已今日签到的跳过
|
||||
* - Super 用户跳过(对应 Rust super_filter)
|
||||
* - 不在 DB 里的成员记为「从未签到」(days=null)
|
||||
*/
|
||||
export function analyzeUnchecked(
|
||||
memberIds: string[],
|
||||
states: Map<string, UserState>,
|
||||
now = Date.now(),
|
||||
): UncheckedRow[] {
|
||||
const rows: UncheckedRow[] = [];
|
||||
for (const userId of memberIds) {
|
||||
const state = states.get(userId);
|
||||
if (!state) {
|
||||
rows.push({ userId, days: null });
|
||||
continue;
|
||||
}
|
||||
if (state.isCheckinToday) continue;
|
||||
if (isSuper(state)) continue;
|
||||
rows.push({ userId, days: uncheckedDays(state, now) });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function bucket(rows: UncheckedRow[], minDays: number): string[] {
|
||||
return rows
|
||||
.filter((r) => r.days !== null && r.days >= minDays)
|
||||
.map((r) => r.userId);
|
||||
}
|
||||
|
||||
/** 生成 Markdown 日报(移植自 Rust daily_statistics_and_report)。 */
|
||||
export function buildDailyReport(params: {
|
||||
date: string;
|
||||
checkedNums: number;
|
||||
allUserNums: number;
|
||||
rows: UncheckedRow[];
|
||||
}): string {
|
||||
const { date, checkedNums, allUserNums, rows } = params;
|
||||
const uncheckedNums = Math.max(allUserNums - checkedNums, 0);
|
||||
const checkinRate =
|
||||
allUserNums > 0 ? Math.round((checkedNums / allUserNums) * 100) : 0;
|
||||
|
||||
const today = rows.map((r) => r.userId).join(' ,\n');
|
||||
const join = (ids: string[]) => ids.join(' ,\n');
|
||||
|
||||
return `# ${date}签到统计报告
|
||||
- 今日签到人数:${checkedNums}
|
||||
- 全部人数:${allUserNums}
|
||||
- 未签到人数:${uncheckedNums}
|
||||
- 签到率:${checkinRate}%
|
||||
|
||||
## 今日未签到用户
|
||||
${today}
|
||||
|
||||
## 超过7天未签到用户
|
||||
${join(bucket(rows, 7))}
|
||||
|
||||
## 超过14天未签到用户
|
||||
${join(bucket(rows, 14))}
|
||||
|
||||
## 超过30天未签到用户
|
||||
${join(bucket(rows, 30))}
|
||||
|
||||
## 从未签到用户
|
||||
${join(rows.filter((r) => r.days === null).map((r) => r.userId))}
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算应被踢出的用户:未签到天数 >= kickDays,且不在白名单。
|
||||
* 「从未签到」(days=null)不计入(无法判断时长,保守不踢)。
|
||||
*/
|
||||
export function computeKickTargets(
|
||||
rows: UncheckedRow[],
|
||||
kickDays: number,
|
||||
whitelist: string[] = [],
|
||||
): string[] {
|
||||
const wl = new Set(whitelist);
|
||||
return rows
|
||||
.filter((r) => r.days !== null && r.days >= kickDays)
|
||||
.map((r) => r.userId)
|
||||
.filter((id) => !wl.has(id));
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
export type UserLevel =
|
||||
| 'Super'
|
||||
| 'Bronze'
|
||||
| 'Silver'
|
||||
| 'Gold'
|
||||
| 'Platinum'
|
||||
| 'Diamond';
|
||||
|
||||
/** 非 Super 的等级升序,用于 raise 逻辑。 */
|
||||
export const LEVELS_ASC: UserLevel[] = [
|
||||
'Bronze',
|
||||
'Silver',
|
||||
'Gold',
|
||||
'Platinum',
|
||||
'Diamond',
|
||||
];
|
||||
|
||||
export const VALID_LEVELS: UserLevel[] = ['Super', ...LEVELS_ASC];
|
||||
|
||||
/** 等级的中文显示名(内部仍用英文 key,只在展示层转中文)。 */
|
||||
export const LEVEL_LABELS: Record<UserLevel, string> = {
|
||||
Super: '超级管理',
|
||||
Bronze: '青铜',
|
||||
Silver: '白银',
|
||||
Gold: '黄金',
|
||||
Platinum: '铂金',
|
||||
Diamond: '钻石',
|
||||
};
|
||||
|
||||
/** 中文 → 英文 key 的反查表,供命令输入解析。 */
|
||||
const LABEL_TO_LEVEL: Record<string, UserLevel> = Object.fromEntries(
|
||||
Object.entries(LEVEL_LABELS).map(([k, v]) => [v, k as UserLevel]),
|
||||
) as Record<string, UserLevel>;
|
||||
|
||||
/** 等级的中文显示名。 */
|
||||
export function levelLabel(level: UserLevel): string {
|
||||
return LEVEL_LABELS[level];
|
||||
}
|
||||
|
||||
/** 可选等级的中文列表,用于帮助文案。 */
|
||||
export function levelChoices(): string {
|
||||
return VALID_LEVELS.map((l) => LEVEL_LABELS[l]).join('/');
|
||||
}
|
||||
|
||||
/** 解析等级,兼容中文(青铜)与英文(bronze/Bronze)。 */
|
||||
export function parseLevel(s: string): UserLevel | null {
|
||||
const trimmed = s.trim();
|
||||
if (LABEL_TO_LEVEL[trimmed]) return LABEL_TO_LEVEL[trimmed];
|
||||
const normalized = trimmed.charAt(0).toUpperCase() + trimmed.slice(1).toLowerCase();
|
||||
return VALID_LEVELS.includes(normalized as UserLevel)
|
||||
? (normalized as UserLevel)
|
||||
: null;
|
||||
}
|
||||
|
||||
export interface UserState {
|
||||
isCheckinToday: boolean;
|
||||
level: UserLevel;
|
||||
checkinUnixMs: number;
|
||||
checkinTimesInMonth: number;
|
||||
checkinDays: number[];
|
||||
}
|
||||
|
||||
export function newUserState(): UserState {
|
||||
return {
|
||||
isCheckinToday: false,
|
||||
level: 'Silver',
|
||||
checkinUnixMs: 0,
|
||||
checkinTimesInMonth: 0,
|
||||
checkinDays: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function isSuper(state: UserState): boolean {
|
||||
return state.level === 'Super';
|
||||
}
|
||||
|
||||
/** 执行一次签到,更新状态与等级(移植自 Rust UserState::checkin)。 */
|
||||
export function applyCheckin(state: UserState, now = new Date()): UserState {
|
||||
const next: UserState = { ...state, checkinDays: [...state.checkinDays] };
|
||||
next.isCheckinToday = true;
|
||||
next.checkinUnixMs = now.getTime();
|
||||
next.checkinTimesInMonth += 1;
|
||||
const day = now.getUTCDate();
|
||||
if (!next.checkinDays.includes(day)) {
|
||||
next.checkinDays.push(day);
|
||||
}
|
||||
if (next.level === 'Super') {
|
||||
return next;
|
||||
}
|
||||
const t = next.checkinTimesInMonth;
|
||||
if (t <= 7) next.level = 'Bronze';
|
||||
else if (t <= 14) next.level = 'Silver';
|
||||
else if (t <= 29) next.level = 'Gold';
|
||||
else if (t <= 44) next.level = 'Platinum';
|
||||
else next.level = 'Diamond';
|
||||
return next;
|
||||
}
|
||||
|
||||
/** 升一级(移植自 Rust raise_level):Super 与 Diamond 不变。 */
|
||||
export function raiseLevel(state: UserState): UserState {
|
||||
if (state.level === 'Super') return state;
|
||||
const idx = LEVELS_ASC.indexOf(state.level);
|
||||
const nextIdx = Math.min(idx + 1, LEVELS_ASC.length - 1);
|
||||
return { ...state, level: LEVELS_ASC[nextIdx] };
|
||||
}
|
||||
|
||||
export function setLevel(state: UserState, level: UserLevel): UserState {
|
||||
return { ...state, level };
|
||||
}
|
||||
|
||||
/** 清空等级为 Bronze(移植自 Rust clean_user_level)。 */
|
||||
export function clearLevel(state: UserState): UserState {
|
||||
return { ...state, level: 'Bronze' };
|
||||
}
|
||||
|
||||
/** 重置当日签到标记。 */
|
||||
export function resetDaily(state: UserState): UserState {
|
||||
return { ...state, isCheckinToday: false };
|
||||
}
|
||||
|
||||
/** 重置月度统计(每月初调用)。 */
|
||||
export function resetMonthly(state: UserState): UserState {
|
||||
return { ...state, checkinTimesInMonth: 0, checkinDays: [] };
|
||||
}
|
||||
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
|
||||
/**
|
||||
* 距上次签到的整天数。从未签到(checkinUnixMs=0)返回 null。
|
||||
* 注:Rust 原版此计算有 bug,这里实现的是其本意(now - lastCheckin)。
|
||||
*/
|
||||
export function uncheckedDays(
|
||||
state: UserState,
|
||||
now = Date.now(),
|
||||
): number | null {
|
||||
if (!state.checkinUnixMs) return null;
|
||||
return Math.floor((now - state.checkinUnixMs) / MS_PER_DAY);
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { resolve } from 'node:path';
|
||||
import { ConfigService } from './config.service';
|
||||
|
||||
const FIXTURE_PATH = resolve(__dirname, '../test/fixtures/bots.test.yaml');
|
||||
const MISSING_PATH = resolve(__dirname, '../test/fixtures/nonexistent.yaml');
|
||||
|
||||
function makeService(configPath: string): ConfigService {
|
||||
process.env.BOT_CONFIG_PATH = configPath;
|
||||
return new ConfigService();
|
||||
}
|
||||
|
||||
describe('ConfigService (integration)', () => {
|
||||
afterEach(() => {
|
||||
delete process.env.BOT_CONFIG_PATH;
|
||||
delete process.env.TEST_ACCOUNT_PW;
|
||||
});
|
||||
|
||||
it('loads and validates a well-formed config file', () => {
|
||||
const svc = makeService(FIXTURE_PATH);
|
||||
const cfg = svc.all;
|
||||
|
||||
expect(Object.keys(cfg.accounts)).toEqual(
|
||||
expect.arrayContaining(['main', 'checkin']),
|
||||
);
|
||||
expect(cfg.bots).toHaveLength(1);
|
||||
expect(cfg.bots[0].name).toBe('checkin');
|
||||
expect(cfg.bots[0].rooms).toEqual(['!testroom:example.com']);
|
||||
});
|
||||
|
||||
it('exposes bots and getAccount helpers', () => {
|
||||
const svc = makeService(FIXTURE_PATH);
|
||||
|
||||
expect(svc.bots[0].account).toBe('checkin');
|
||||
|
||||
const acc = svc.getAccount('main');
|
||||
expect(acc.homeServer).toBe('https://matrix.example.com');
|
||||
expect(acc.userId).toBe('@testbot:example.com');
|
||||
});
|
||||
|
||||
it('throws a user-friendly error when config file does not exist', () => {
|
||||
const svc = makeService(MISSING_PATH);
|
||||
expect(() => svc.all).toThrow(/配置文件不存在/);
|
||||
expect(() => svc.all).toThrow(/bots.example.yaml/);
|
||||
});
|
||||
|
||||
it('resolves env() references from environment variables', () => {
|
||||
// Write a temp config that uses env() ref, then verify it resolves.
|
||||
const { writeFileSync, unlinkSync } = require('node:fs');
|
||||
const tmpPath = resolve(__dirname, '../test/fixtures/bots.envref.tmp.yaml');
|
||||
writeFileSync(
|
||||
tmpPath,
|
||||
`
|
||||
accounts:
|
||||
bot:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@bot:example.com"
|
||||
password: "env(TEST_ACCOUNT_PW)"
|
||||
bots:
|
||||
- name: test
|
||||
account: bot
|
||||
rooms:
|
||||
- "!room:example.com"
|
||||
config: {}
|
||||
`,
|
||||
);
|
||||
process.env.TEST_ACCOUNT_PW = 'secret-from-env';
|
||||
const svc = makeService(tmpPath);
|
||||
try {
|
||||
const acc = svc.getAccount('bot');
|
||||
expect(acc.password).toBe('secret-from-env');
|
||||
} finally {
|
||||
unlinkSync(tmpPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('throws when an env() referenced variable is not set', () => {
|
||||
const { writeFileSync, unlinkSync } = require('node:fs');
|
||||
const tmpPath = resolve(__dirname, '../test/fixtures/bots.envmissing.tmp.yaml');
|
||||
writeFileSync(
|
||||
tmpPath,
|
||||
`
|
||||
accounts:
|
||||
bot:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@bot:example.com"
|
||||
password: "env(MISSING_ENV_VAR_XYZ)"
|
||||
bots:
|
||||
- name: test
|
||||
account: bot
|
||||
rooms:
|
||||
- "!room:example.com"
|
||||
config: {}
|
||||
`,
|
||||
);
|
||||
delete process.env.MISSING_ENV_VAR_XYZ;
|
||||
const svc = makeService(tmpPath);
|
||||
try {
|
||||
expect(() => svc.all).toThrow(/MISSING_ENV_VAR_XYZ/);
|
||||
} finally {
|
||||
unlinkSync(tmpPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects config with an invalid homeServer URL', () => {
|
||||
const { writeFileSync, unlinkSync } = require('node:fs');
|
||||
const tmpPath = resolve(__dirname, '../test/fixtures/bots.badurl.tmp.yaml');
|
||||
writeFileSync(
|
||||
tmpPath,
|
||||
`
|
||||
accounts:
|
||||
bot:
|
||||
homeServer: "not-a-url"
|
||||
userId: "@bot:example.com"
|
||||
password: "secret"
|
||||
bots:
|
||||
- name: test
|
||||
account: bot
|
||||
rooms:
|
||||
- "!room:example.com"
|
||||
config: {}
|
||||
`,
|
||||
);
|
||||
const svc = makeService(tmpPath);
|
||||
try {
|
||||
expect(() => svc.all).toThrow();
|
||||
} finally {
|
||||
unlinkSync(tmpPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects config with malformed userId', () => {
|
||||
const { writeFileSync, unlinkSync } = require('node:fs');
|
||||
const tmpPath = resolve(__dirname, '../test/fixtures/bots.baduser.tmp.yaml');
|
||||
writeFileSync(
|
||||
tmpPath,
|
||||
`
|
||||
accounts:
|
||||
bot:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "not-a-matrix-id"
|
||||
password: "secret"
|
||||
bots:
|
||||
- name: test
|
||||
account: bot
|
||||
rooms:
|
||||
- "!room:example.com"
|
||||
config: {}
|
||||
`,
|
||||
);
|
||||
const svc = makeService(tmpPath);
|
||||
try {
|
||||
expect(() => svc.all).toThrow(/userId/);
|
||||
} finally {
|
||||
unlinkSync(tmpPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects config where bot room IDs are malformed', () => {
|
||||
const { writeFileSync, unlinkSync } = require('node:fs');
|
||||
const tmpPath = resolve(__dirname, '../test/fixtures/bots.badroom.tmp.yaml');
|
||||
writeFileSync(
|
||||
tmpPath,
|
||||
`
|
||||
accounts:
|
||||
bot:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@bot:example.com"
|
||||
password: "secret"
|
||||
bots:
|
||||
- name: test
|
||||
account: bot
|
||||
rooms:
|
||||
- "not-a-room-id"
|
||||
config: {}
|
||||
`,
|
||||
);
|
||||
const svc = makeService(tmpPath);
|
||||
try {
|
||||
expect(() => svc.all).toThrow(/roomId/);
|
||||
} finally {
|
||||
unlinkSync(tmpPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('caches the parsed config on subsequent accesses', () => {
|
||||
const svc = makeService(FIXTURE_PATH);
|
||||
const first = svc.all;
|
||||
const second = svc.all;
|
||||
expect(first).toBe(second); // same object reference
|
||||
});
|
||||
|
||||
it('reports isDryRun based on DRY_RUN env var', () => {
|
||||
const svc = makeService(FIXTURE_PATH);
|
||||
|
||||
process.env.DRY_RUN = 'true';
|
||||
expect(svc.isDryRun).toBe(true);
|
||||
|
||||
process.env.DRY_RUN = 'false';
|
||||
expect(svc.isDryRun).toBe(false);
|
||||
|
||||
delete process.env.DRY_RUN;
|
||||
expect(svc.isDryRun).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { ConfigService } from './config.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [ConfigService],
|
||||
exports: [ConfigService],
|
||||
})
|
||||
export class ConfigModule {}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import * as yaml from 'js-yaml';
|
||||
import {
|
||||
AccountConfig,
|
||||
BotConfig,
|
||||
RootConfig,
|
||||
rootConfigSchema,
|
||||
} from './schema';
|
||||
|
||||
/**
|
||||
* 加载并校验 bots.yaml。
|
||||
* 支持把配置里的 "env(VAR_NAME)" 解析为对应环境变量值,避免明文密码入库。
|
||||
* 采用惰性加载,确保即使在其它 provider 构造期被读取也已就绪。
|
||||
*/
|
||||
@Injectable()
|
||||
export class ConfigService {
|
||||
private readonly logger = new Logger(ConfigService.name);
|
||||
private config?: RootConfig;
|
||||
|
||||
private ensureLoaded(): RootConfig {
|
||||
if (this.config) return this.config;
|
||||
const path = resolve(process.env.BOT_CONFIG_PATH ?? './config/bots.yaml');
|
||||
let raw: string;
|
||||
try {
|
||||
raw = readFileSync(path, 'utf8');
|
||||
} catch (err: unknown) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
throw new Error(
|
||||
`配置文件不存在: ${path}\n` +
|
||||
`请复制示例文件并填写配置:\n` +
|
||||
` cp config/bots.example.yaml config/bots.yaml\n` +
|
||||
`然后根据注释修改真实账号、房间等信息。`,
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
const parsed = yaml.load(raw);
|
||||
const resolved = this.resolveEnvRefs(parsed);
|
||||
this.config = rootConfigSchema.parse(resolved);
|
||||
this.logger.log(
|
||||
`已加载配置: ${Object.keys(this.config.accounts).length} 个账号, ${this.config.bots.length} 个 bot`,
|
||||
);
|
||||
return this.config;
|
||||
}
|
||||
|
||||
get all(): RootConfig {
|
||||
return this.ensureLoaded();
|
||||
}
|
||||
|
||||
get bots(): BotConfig[] {
|
||||
return this.ensureLoaded().bots;
|
||||
}
|
||||
|
||||
getAccount(name: string): AccountConfig {
|
||||
const acc = this.ensureLoaded().accounts[name];
|
||||
if (!acc) {
|
||||
throw new Error(`未找到账号配置: ${name}`);
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
get isDryRun(): boolean {
|
||||
return (process.env.DRY_RUN ?? 'false').toLowerCase() === 'true';
|
||||
}
|
||||
|
||||
/** 递归把字符串里的 env(VAR) 替换为 process.env.VAR。 */
|
||||
private resolveEnvRefs(value: unknown): unknown {
|
||||
if (typeof value === 'string') {
|
||||
const match = value.match(/^env\((.+)\)$/);
|
||||
if (match) {
|
||||
const envVal = process.env[match[1]];
|
||||
if (envVal === undefined) {
|
||||
throw new Error(`配置引用了未设置的环境变量: ${match[1]}`);
|
||||
}
|
||||
return envVal;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((v) => this.resolveEnvRefs(v));
|
||||
}
|
||||
if (value && typeof value === 'object') {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([k, v]) => [k, this.resolveEnvRefs(v)]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const accountSchema = z.object({
|
||||
homeServer: z.string().url(),
|
||||
userId: z.string().regex(/^@.+:.+$/, 'userId 必须是 @user:server 形式'),
|
||||
password: z.string().min(1),
|
||||
});
|
||||
|
||||
const botSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
account: z.string().min(1),
|
||||
rooms: z.array(z.string().regex(/^!.+:.+$/, 'roomId 必须是 !id:server 形式')).min(1),
|
||||
config: z.record(z.any()).default({}),
|
||||
});
|
||||
|
||||
export const rootConfigSchema = z.object({
|
||||
accounts: z.record(accountSchema),
|
||||
bots: z.array(botSchema),
|
||||
});
|
||||
|
||||
export type AccountConfig = z.infer<typeof accountSchema>;
|
||||
export type BotConfig = z.infer<typeof botSchema>;
|
||||
export type RootConfig = z.infer<typeof rootConfigSchema>;
|
||||
@@ -0,0 +1,40 @@
|
||||
import { BotStore } from '../db/bot-store';
|
||||
import { InboundMessage } from '../command/types';
|
||||
import { MatrixTransport } from '../matrix/types';
|
||||
import { BotContext } from './room-bot.interface';
|
||||
|
||||
/** BotContext 的默认实现:把出站调用委托给该 bot 账号的 MatrixSession。 */
|
||||
export class DefaultBotContext implements BotContext {
|
||||
constructor(
|
||||
private readonly transport: MatrixTransport,
|
||||
public readonly db: BotStore,
|
||||
) {}
|
||||
|
||||
get account(): string {
|
||||
return this.transport.account;
|
||||
}
|
||||
|
||||
send(roomId: string, text: string, replyToEventId?: string): Promise<string> {
|
||||
return this.transport.send(roomId, text, replyToEventId);
|
||||
}
|
||||
|
||||
reply(msg: InboundMessage, text: string): Promise<string> {
|
||||
return this.transport.send(msg.roomId, text, msg.eventId);
|
||||
}
|
||||
|
||||
kick(roomId: string, userId: string, reason?: string): Promise<void> {
|
||||
return this.transport.kick(roomId, userId, reason);
|
||||
}
|
||||
|
||||
getMemberCount(roomId: string): Promise<number> {
|
||||
return this.transport.getMemberCount(roomId);
|
||||
}
|
||||
|
||||
getJoinedMembers(roomId: string): Promise<string[]> {
|
||||
return this.transport.getJoinedMembers(roomId);
|
||||
}
|
||||
|
||||
getPowerLevel(roomId: string, userId: string): Promise<number> {
|
||||
return this.transport.getPowerLevel(roomId, userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
OnApplicationBootstrap,
|
||||
OnApplicationShutdown,
|
||||
} from '@nestjs/common';
|
||||
import { SessionManager } from '../matrix/session-manager.service';
|
||||
import { BotRegistry } from './bot-registry.service';
|
||||
import { Dispatcher } from './dispatcher.service';
|
||||
import { SchedulerService } from '../scheduler/scheduler.service';
|
||||
|
||||
/**
|
||||
* 平台总装配:
|
||||
* 1. 为每个唯一账号创建会话(共享账号自动去重),sink 指向 Dispatcher
|
||||
* 2. 构建 bot 路由表与 context
|
||||
* 3. 注册各 bot 的定时任务
|
||||
* 4. 启动所有会话(dry-run 下不真正连接)
|
||||
*/
|
||||
@Injectable()
|
||||
export class BotPlatformService
|
||||
implements OnApplicationBootstrap, OnApplicationShutdown
|
||||
{
|
||||
private readonly logger = new Logger(BotPlatformService.name);
|
||||
|
||||
constructor(
|
||||
private readonly registry: BotRegistry,
|
||||
private readonly sessions: SessionManager,
|
||||
private readonly dispatcher: Dispatcher,
|
||||
private readonly scheduler: SchedulerService,
|
||||
) {}
|
||||
|
||||
async onApplicationBootstrap(): Promise<void> {
|
||||
for (const account of this.registry.accounts) {
|
||||
this.sessions.ensureSession(account, this.dispatcher);
|
||||
}
|
||||
|
||||
this.registry.build();
|
||||
|
||||
for (const { bot, ctx } of this.registry.registered) {
|
||||
const specs = bot.registerCrons?.(ctx) ?? [];
|
||||
for (const spec of specs) {
|
||||
this.scheduler.register(bot.name, spec);
|
||||
}
|
||||
}
|
||||
|
||||
await this.sessions.startAll();
|
||||
|
||||
this.logger.log(
|
||||
`平台已启动: ${this.registry.all.length} 个 bot, ${this.registry.accounts.length} 个账号`,
|
||||
);
|
||||
for (const bot of this.registry.all) {
|
||||
this.logger.log(
|
||||
` • ${bot.name} [account=${bot.account}] rooms=${bot.rooms.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
// 所有会话已登录,触发各 bot 的就绪钩子(如发送上线通知)。
|
||||
for (const { bot, ctx } of this.registry.registered) {
|
||||
if (!bot.onReady) continue;
|
||||
try {
|
||||
await bot.onReady(ctx);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`bot ${bot.name} onReady 执行失败: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async onApplicationShutdown(): Promise<void> {
|
||||
await this.sessions.stopAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DiscoveryService } from '@nestjs/core';
|
||||
import { PrismaService } from '../db/prisma.service';
|
||||
import { BotStore } from '../db/bot-store';
|
||||
import { SessionManager } from '../matrix/session-manager.service';
|
||||
import { DefaultBotContext } from './bot-context';
|
||||
import { IS_ROOM_BOT } from './register-bot.decorator';
|
||||
import { BotContext, RoomBot } from './room-bot.interface';
|
||||
|
||||
interface RegisteredBot {
|
||||
bot: RoomBot;
|
||||
ctx: BotContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* 维护路由表:`${account}:${roomId}` → bot(s)。
|
||||
* 通过 DiscoveryService 自动发现所有被 @RegisterBot() 标记的 provider,
|
||||
* 这样新增 bot 只需在 feature module 里 provide,无需改动核心。
|
||||
*/
|
||||
@Injectable()
|
||||
export class BotRegistry {
|
||||
private bots: RoomBot[] = [];
|
||||
private discovered = false;
|
||||
private readonly byRoute = new Map<string, RegisteredBot[]>();
|
||||
private readonly byName = new Map<string, RegisteredBot>();
|
||||
|
||||
constructor(
|
||||
private readonly discovery: DiscoveryService,
|
||||
private readonly sessions: SessionManager,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
private discover(): void {
|
||||
if (this.discovered) return;
|
||||
this.bots = this.discovery
|
||||
.getProviders()
|
||||
.filter((w) => w.metatype && w.instance)
|
||||
.filter(
|
||||
(w) => Reflect.getMetadata(IS_ROOM_BOT, w.metatype as object) === true,
|
||||
)
|
||||
.map((w) => w.instance as RoomBot);
|
||||
this.discovered = true;
|
||||
}
|
||||
|
||||
/** 为每个 bot 建好 context 并填充路由表。须在 session 创建后调用。 */
|
||||
build(): void {
|
||||
this.discover();
|
||||
for (const bot of this.bots) {
|
||||
const session = this.sessions.get(bot.account);
|
||||
if (!session) {
|
||||
throw new Error(`bot ${bot.name} 引用了未初始化的账号 ${bot.account}`);
|
||||
}
|
||||
const ctx = new DefaultBotContext(
|
||||
session,
|
||||
new BotStore(this.prisma, bot.name),
|
||||
);
|
||||
const reg: RegisteredBot = { bot, ctx };
|
||||
this.byName.set(bot.name, reg);
|
||||
for (const roomId of bot.rooms) {
|
||||
const key = routeKey(bot.account, roomId);
|
||||
const list = this.byRoute.get(key) ?? [];
|
||||
list.push(reg);
|
||||
this.byRoute.set(key, list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get all(): RoomBot[] {
|
||||
this.discover();
|
||||
return this.bots;
|
||||
}
|
||||
|
||||
/** 涉及的所有账号集合(供 SessionManager 去重创建)。 */
|
||||
get accounts(): string[] {
|
||||
this.discover();
|
||||
return [...new Set(this.bots.map((b) => b.account))];
|
||||
}
|
||||
|
||||
resolve(account: string, roomId: string): RegisteredBot[] {
|
||||
return this.byRoute.get(routeKey(account, roomId)) ?? [];
|
||||
}
|
||||
|
||||
getByName(name: string): RegisteredBot | undefined {
|
||||
return this.byName.get(name);
|
||||
}
|
||||
|
||||
get registered(): RegisteredBot[] {
|
||||
return [...this.byName.values()];
|
||||
}
|
||||
}
|
||||
|
||||
export function routeKey(account: string, roomId: string): string {
|
||||
return `${account}:${roomId}`;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { DiscoveryModule } from '@nestjs/core';
|
||||
import { BotRegistry } from './bot-registry.service';
|
||||
import { Dispatcher } from './dispatcher.service';
|
||||
import { BotPlatformService } from './bot-platform.service';
|
||||
import { SchedulerService } from '../scheduler/scheduler.service';
|
||||
|
||||
/**
|
||||
* 核心 bot 平台模块。具体 bot 由各自的 feature module 通过
|
||||
* @RegisterBot() 标记并 provide,本模块用 DiscoveryService 自动发现。
|
||||
*/
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [DiscoveryModule],
|
||||
providers: [BotRegistry, Dispatcher, BotPlatformService, SchedulerService],
|
||||
exports: [BotRegistry, Dispatcher, BotPlatformService, SchedulerService],
|
||||
})
|
||||
export class BotModule {}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { InboundMessage, MemberEvent } from '../command/types';
|
||||
import { CommandError, parseCommand } from '../command/command-parser';
|
||||
import { MatrixEventSink } from '../matrix/types';
|
||||
import { BotRegistry } from './bot-registry.service';
|
||||
|
||||
/** 命令前缀。非此前缀的消息只走 onMessage,不解析为命令。 */
|
||||
const COMMAND_PREFIX = '!';
|
||||
|
||||
/**
|
||||
* 把归一化事件按 (account, roomId) 路由到对应 bot 的钩子。
|
||||
* 实现 MatrixEventSink,注册进每个 MatrixSession。
|
||||
*/
|
||||
@Injectable()
|
||||
export class Dispatcher implements MatrixEventSink {
|
||||
private readonly logger = new Logger(Dispatcher.name);
|
||||
|
||||
constructor(private readonly registry: BotRegistry) {}
|
||||
|
||||
async onMessage(msg: InboundMessage): Promise<void> {
|
||||
const targets = this.registry.resolve(msg.account, msg.roomId);
|
||||
if (targets.length === 0) return;
|
||||
|
||||
// 通用归一化:全角叹号→半角、换行→空格,便于中文输入触发命令。
|
||||
const text = msg.text.replace(/!/g, '!').replace(/[\r\n]+/g, ' ').trim();
|
||||
const commandText = text.startsWith(COMMAND_PREFIX)
|
||||
? text.slice(COMMAND_PREFIX.length)
|
||||
: undefined;
|
||||
|
||||
for (const { bot, ctx } of targets) {
|
||||
try {
|
||||
if (bot.onMessage) {
|
||||
await bot.onMessage(msg, ctx);
|
||||
}
|
||||
if (commandText !== undefined && bot.onCommand) {
|
||||
const cmd = parseCommand(msg, commandText);
|
||||
await bot.onCommand(cmd, ctx);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof CommandError) {
|
||||
this.logger.debug(`命令解析失败 (${bot.name}): ${err.message}`);
|
||||
} else {
|
||||
this.logger.warn(
|
||||
`bot ${bot.name} 处理消息失败 (room=${msg.roomId}): ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async onMember(ev: MemberEvent): Promise<void> {
|
||||
if (ev.membership !== 'join') return;
|
||||
const targets = this.registry.resolve(ev.account, ev.roomId);
|
||||
for (const { bot, ctx } of targets) {
|
||||
if (!bot.onMemberJoin) continue;
|
||||
try {
|
||||
await bot.onMemberJoin(ev, ctx);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`bot ${bot.name} 处理成员事件失败: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
/** 标记一个 provider 为 RoomBot,供 BotRegistry 通过 DiscoveryService 发现。 */
|
||||
export const IS_ROOM_BOT = 'daily-bot:is-room-bot';
|
||||
|
||||
export const RegisterBot = (): ClassDecorator => SetMetadata(IS_ROOM_BOT, true);
|
||||
@@ -0,0 +1,43 @@
|
||||
import { BotStore } from '../db/bot-store';
|
||||
import {
|
||||
CronSpec,
|
||||
InboundMessage,
|
||||
MemberEvent,
|
||||
ParsedCommand,
|
||||
} from '../command/types';
|
||||
|
||||
/**
|
||||
* 注入给每个 bot 的运行时上下文:出站能力 + 已隔离的存储。
|
||||
* bot 永远不直接碰 matrix client,便于单测(mock 本接口即可)。
|
||||
*/
|
||||
export interface BotContext {
|
||||
readonly account: string;
|
||||
send(roomId: string, text: string, replyToEventId?: string): Promise<string>;
|
||||
reply(msg: InboundMessage, text: string): Promise<string>;
|
||||
kick(roomId: string, userId: string, reason?: string): Promise<void>;
|
||||
getMemberCount(roomId: string): Promise<number>;
|
||||
getJoinedMembers(roomId: string): Promise<string[]>;
|
||||
/** 读取用户在房间内的 power level,用于按房间权限判断管理员(读不到返回 0)。 */
|
||||
getPowerLevel(roomId: string, userId: string): Promise<number>;
|
||||
readonly db: BotStore;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每个房间机器人实现的契约。一个 bot = 一个独立功能模块。
|
||||
* 所有钩子均可选,bot 只实现自己关心的事件。
|
||||
*/
|
||||
export interface RoomBot {
|
||||
/** 唯一名字,同时作为 DB scope。 */
|
||||
readonly name: string;
|
||||
/** 使用哪个账号(对应 config.accounts 的 key)。 */
|
||||
readonly account: string;
|
||||
/** 管理哪些房间。 */
|
||||
readonly rooms: string[];
|
||||
|
||||
/** 平台完成所有会话登录后调用一次,适合发送上线通知、做初始化等。 */
|
||||
onReady?(ctx: BotContext): Promise<void>;
|
||||
onMessage?(msg: InboundMessage, ctx: BotContext): Promise<void>;
|
||||
onCommand?(cmd: ParsedCommand, ctx: BotContext): Promise<void>;
|
||||
onMemberJoin?(ev: MemberEvent, ctx: BotContext): Promise<void>;
|
||||
registerCrons?(ctx: BotContext): CronSpec[];
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { parseCommand, tokenize, CommandError } from './command-parser';
|
||||
import { InboundMessage } from './types';
|
||||
|
||||
const raw: InboundMessage = {
|
||||
eventId: 'e',
|
||||
account: 'a',
|
||||
roomId: '!r:hs',
|
||||
userId: '@u:hs',
|
||||
text: '',
|
||||
timestampMs: 0,
|
||||
};
|
||||
|
||||
describe('command-parser', () => {
|
||||
it('parses command and positional args', () => {
|
||||
const ast = parseCommand(raw, 'deploy service-a region-cn');
|
||||
expect(ast.command).toBe('deploy');
|
||||
expect(ast.args).toEqual(['service-a', 'region-cn']);
|
||||
expect(ast.options).toEqual({});
|
||||
});
|
||||
|
||||
it('parses --key=value and --key value', () => {
|
||||
const ast = parseCommand(raw, 'deploy --env=prod --region cn');
|
||||
expect(ast.options.env).toBe('prod');
|
||||
expect(ast.options.region).toBe('cn');
|
||||
});
|
||||
|
||||
it('treats trailing flag as true', () => {
|
||||
const ast = parseCommand(raw, 'sync --dry-run --limit=10 --verbose');
|
||||
expect(ast.options['dry-run']).toBe('true');
|
||||
expect(ast.options.limit).toBe('10');
|
||||
expect(ast.options.verbose).toBe('true');
|
||||
});
|
||||
|
||||
it('handles quotes', () => {
|
||||
expect(tokenize('send "hello world" \'to room\'')).toEqual([
|
||||
'send',
|
||||
'hello world',
|
||||
'to room',
|
||||
]);
|
||||
});
|
||||
|
||||
it('throws on unterminated quote', () => {
|
||||
expect(() => tokenize('cmd "oops')).toThrow(CommandError);
|
||||
});
|
||||
|
||||
it('throws on empty command', () => {
|
||||
expect(() => parseCommand(raw, ' ')).toThrow(CommandError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { InboundMessage, ParsedCommand } from './types';
|
||||
|
||||
export class CommandError extends Error {}
|
||||
|
||||
/**
|
||||
* 命令解析器,移植自 Rust 版 command_parser:
|
||||
* - 支持单/双引号、双引号内反斜杠转义
|
||||
* - --key=value / --key value / --flag(无值则为 "true")
|
||||
* 第一个 token 为命令名,其余为位置参数。
|
||||
*/
|
||||
export function tokenize(input: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
let buf = '';
|
||||
let inSingle = false;
|
||||
let inDouble = false;
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const ch = input[i];
|
||||
if (ch === "'" && !inDouble) {
|
||||
inSingle = !inSingle;
|
||||
} else if (ch === '"' && !inSingle) {
|
||||
inDouble = !inDouble;
|
||||
} else if (ch === '\\' && inDouble) {
|
||||
const next = input[i + 1];
|
||||
if (next === undefined) {
|
||||
throw new CommandError('dangling escape');
|
||||
}
|
||||
buf += next;
|
||||
i++;
|
||||
} else if (/\s/.test(ch) && !inSingle && !inDouble) {
|
||||
if (buf.length > 0) {
|
||||
tokens.push(buf);
|
||||
buf = '';
|
||||
}
|
||||
} else {
|
||||
buf += ch;
|
||||
}
|
||||
}
|
||||
|
||||
if (inSingle || inDouble) {
|
||||
throw new CommandError('unterminated quote');
|
||||
}
|
||||
if (buf.length > 0) {
|
||||
tokens.push(buf);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function parseCommand(raw: InboundMessage, text: string): ParsedCommand {
|
||||
const tokens = tokenize(text);
|
||||
if (tokens.length === 0) {
|
||||
throw new CommandError('empty command');
|
||||
}
|
||||
|
||||
const command = tokens[0];
|
||||
const args: string[] = [];
|
||||
const options: Record<string, string> = {};
|
||||
|
||||
let i = 1;
|
||||
while (i < tokens.length) {
|
||||
const token = tokens[i];
|
||||
if (token.startsWith('--')) {
|
||||
const body = token.slice(2);
|
||||
if (body.length === 0) {
|
||||
throw new CommandError('invalid option: --');
|
||||
}
|
||||
const eq = body.indexOf('=');
|
||||
if (eq >= 0) {
|
||||
const key = body.slice(0, eq);
|
||||
if (key.length === 0) {
|
||||
throw new CommandError(`invalid option key in '--${body}'`);
|
||||
}
|
||||
options[key] = body.slice(eq + 1);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
const next = tokens[i + 1];
|
||||
if (next !== undefined && !next.startsWith('-')) {
|
||||
options[body] = next;
|
||||
i += 2;
|
||||
} else {
|
||||
options[body] = 'true';
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
args.push(token);
|
||||
i++;
|
||||
}
|
||||
|
||||
return { raw, command, args, options };
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/** 归一化的入站消息(与底层 Matrix 事件解耦,便于测试与将来接入其它 IM)。 */
|
||||
export interface InboundMessage {
|
||||
eventId: string;
|
||||
account: string;
|
||||
roomId: string;
|
||||
userId: string;
|
||||
text: string;
|
||||
timestampMs: number;
|
||||
}
|
||||
|
||||
/** 成员加入/离开等事件。 */
|
||||
export interface MemberEvent {
|
||||
account: string;
|
||||
roomId: string;
|
||||
userId: string;
|
||||
membership: 'join' | 'leave' | 'invite' | 'ban';
|
||||
}
|
||||
|
||||
/** 解析后的命令。 */
|
||||
export interface ParsedCommand {
|
||||
raw: InboundMessage;
|
||||
command: string;
|
||||
args: string[];
|
||||
options: Record<string, string>;
|
||||
}
|
||||
|
||||
/** bot 注册的定时任务。 */
|
||||
export interface CronSpec {
|
||||
/** 标准 5/6 段 cron 表达式。 */
|
||||
cron: string;
|
||||
run: () => Promise<void>;
|
||||
name?: string;
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, unlinkSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { PrismaService } from './prisma.service';
|
||||
import { BotStore } from './bot-store';
|
||||
|
||||
const PROJECT_ROOT = resolve(__dirname, '../../..');
|
||||
const TEST_DB_FILE = resolve(PROJECT_ROOT, 'test-botstore-integration.db');
|
||||
const TEST_DB_URL = `file:${TEST_DB_FILE}`;
|
||||
|
||||
function cleanDb(): void {
|
||||
for (const suffix of ['', '-journal', '-wal', '-shm']) {
|
||||
const f = TEST_DB_FILE + suffix;
|
||||
if (existsSync(f)) unlinkSync(f);
|
||||
}
|
||||
}
|
||||
|
||||
let prismaService: PrismaService;
|
||||
|
||||
beforeAll(async () => {
|
||||
cleanDb();
|
||||
execSync('npx prisma db push --skip-generate', {
|
||||
cwd: PROJECT_ROOT,
|
||||
env: { ...process.env, DATABASE_URL: TEST_DB_URL },
|
||||
stdio: 'pipe',
|
||||
});
|
||||
process.env.DATABASE_URL = TEST_DB_URL;
|
||||
// PrismaService reads DATABASE_URL at construction time via PrismaClient.
|
||||
prismaService = new PrismaService();
|
||||
await prismaService.onModuleInit();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await prismaService.onModuleDestroy();
|
||||
cleanDb();
|
||||
delete process.env.DATABASE_URL;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Clean all rows between tests to ensure isolation.
|
||||
await prismaService.botState.deleteMany();
|
||||
});
|
||||
|
||||
describe('BotStore (integration with real SQLite)', () => {
|
||||
it('returns null for a key that has never been set', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
expect(await store.get('missing')).toBeNull();
|
||||
});
|
||||
|
||||
it('persists and retrieves a value with set/get round-trip', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
const data = { foo: 'bar', num: 42 };
|
||||
await store.set('mykey', data);
|
||||
expect(await store.get('mykey')).toEqual(data);
|
||||
});
|
||||
|
||||
it('overwrites an existing value on set', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
await store.set('key', { v: 1 });
|
||||
await store.set('key', { v: 2 });
|
||||
expect(await store.get<{ v: number }>('key')).toEqual({ v: 2 });
|
||||
});
|
||||
|
||||
it('removes an existing entry', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
await store.set('todelete', 'value');
|
||||
await store.remove('todelete');
|
||||
expect(await store.get('todelete')).toBeNull();
|
||||
});
|
||||
|
||||
it('does not throw when removing a non-existent key', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
await expect(store.remove('ghost')).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns an empty array from entries() when no keys exist', async () => {
|
||||
const store = new BotStore(prismaService, 'emptybot');
|
||||
expect(await store.entries()).toEqual([]);
|
||||
});
|
||||
|
||||
it('entries() returns all key-value pairs for the bot scope', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
await store.set('a', 1);
|
||||
await store.set('b', 2);
|
||||
await store.set('c', 3);
|
||||
const entries = await store.entries<number>();
|
||||
expect(entries).toHaveLength(3);
|
||||
expect(entries).toEqual(
|
||||
expect.arrayContaining([
|
||||
['a', 1],
|
||||
['b', 2],
|
||||
['c', 3],
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('isolates data between different bot scopes', async () => {
|
||||
const storeA = new BotStore(prismaService, 'botA');
|
||||
const storeB = new BotStore(prismaService, 'botB');
|
||||
|
||||
await storeA.set('shared-key', 'from-A');
|
||||
await storeB.set('shared-key', 'from-B');
|
||||
|
||||
expect(await storeA.get('shared-key')).toBe('from-A');
|
||||
expect(await storeB.get('shared-key')).toBe('from-B');
|
||||
|
||||
const entriesA = await storeA.entries<string>();
|
||||
const entriesB = await storeB.entries<string>();
|
||||
expect(entriesA).toHaveLength(1);
|
||||
expect(entriesB).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('persists complex nested objects', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
const complex = {
|
||||
isCheckinToday: true,
|
||||
level: 'Gold',
|
||||
checkinUnixMs: 1717000000000,
|
||||
checkinTimesInMonth: 15,
|
||||
checkinDays: [1, 3, 5, 7],
|
||||
};
|
||||
await store.set('@user:hs', complex);
|
||||
expect(await store.get('@user:hs')).toEqual(complex);
|
||||
});
|
||||
|
||||
it('handles multiple distinct keys in the same bot scope', async () => {
|
||||
const store = new BotStore(prismaService, 'testbot');
|
||||
await store.set('user1', { count: 1 });
|
||||
await store.set('user2', { count: 2 });
|
||||
|
||||
expect(await store.get<{ count: number }>('user1')).toEqual({ count: 1 });
|
||||
expect(await store.get<{ count: number }>('user2')).toEqual({ count: 2 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
/**
|
||||
* 按 botName 隔离的 KV 存储,对应 Rust 版 DailyBotStore 的 `scope:id` 语义。
|
||||
* 每个 bot 通过 BotContext.db 拿到一个已绑定自身 name 的实例,互不串数据。
|
||||
*/
|
||||
export class BotStore {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly botName: string,
|
||||
) {}
|
||||
|
||||
async get<T = unknown>(key: string): Promise<T | null> {
|
||||
const row = await this.prisma.botState.findUnique({
|
||||
where: { botName_key: { botName: this.botName, key } },
|
||||
});
|
||||
return row ? (JSON.parse(row.valueJson) as T) : null;
|
||||
}
|
||||
|
||||
async set<T = unknown>(key: string, value: T): Promise<void> {
|
||||
const valueJson = JSON.stringify(value);
|
||||
await this.prisma.botState.upsert({
|
||||
where: { botName_key: { botName: this.botName, key } },
|
||||
create: { botName: this.botName, key, valueJson },
|
||||
update: { valueJson },
|
||||
});
|
||||
}
|
||||
|
||||
async remove(key: string): Promise<void> {
|
||||
await this.prisma.botState
|
||||
.delete({ where: { botName_key: { botName: this.botName, key } } })
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
async entries<T = unknown>(): Promise<Array<[string, T]>> {
|
||||
const rows = await this.prisma.botState.findMany({
|
||||
where: { botName: this.botName },
|
||||
});
|
||||
return rows.map((r) => [r.key, JSON.parse(r.valueJson) as T]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class DbModule {}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService
|
||||
extends PrismaClient
|
||||
implements OnModuleInit, OnModuleDestroy
|
||||
{
|
||||
async onModuleInit(): Promise<void> {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import {
|
||||
MatrixAuth,
|
||||
MatrixClient,
|
||||
RustSdkCryptoStorageProvider,
|
||||
SimpleFsStorageProvider,
|
||||
} from 'matrix-bot-sdk';
|
||||
import { StoreType } from '@matrix-org/matrix-sdk-crypto-nodejs';
|
||||
import { AccountConfig } from '../../config/schema';
|
||||
import { InboundMessage, MemberEvent } from '../command/types';
|
||||
import { MatrixEventSink, MatrixTransport } from './types';
|
||||
|
||||
interface PersistedCreds {
|
||||
accessToken: string;
|
||||
userId: string;
|
||||
deviceId?: string;
|
||||
baseUrl: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 包装一个 matrix-bot-sdk client = 一个 Matrix 账号会话。
|
||||
* 负责:登录、sync、把底层事件归一化后交给 sink;并提供出站能力。
|
||||
*
|
||||
* 端到端加密(E2EE):使用 matrix-bot-sdk + @matrix-org/matrix-sdk-crypto-nodejs
|
||||
* 的原生 Rust 加密内核,加密状态持久化到 SQLite(每账号一个目录),
|
||||
* 加密房收发的消息会被自动加/解密。
|
||||
*
|
||||
* 登录策略:首次用密码登录拿 accessToken/deviceId 并落盘,之后复用,
|
||||
* 避免每次启动都重新登录(产生新设备、触发限流、丢失加密会话)。
|
||||
*
|
||||
* dryRun=true 时不连接网络,send/kick 仅记日志,便于本地/CI 启动验证。
|
||||
*/
|
||||
export class MatrixSession implements MatrixTransport {
|
||||
private readonly logger: Logger;
|
||||
private client?: MatrixClient;
|
||||
private selfUserId?: string;
|
||||
private started = false;
|
||||
/** 记录 bot 自己刚发出的 event_id,sync 回流时跳过,避免回应自己(支持与用户同账号自测)。 */
|
||||
private readonly recentSentEventIds = new Set<string>();
|
||||
|
||||
constructor(
|
||||
public readonly account: string,
|
||||
private readonly cfg: AccountConfig,
|
||||
private readonly sink: MatrixEventSink,
|
||||
private readonly dryRun: boolean,
|
||||
// 只同步这些房间(各 bot 关注房间的并集)。为空则同步全部(不推荐:
|
||||
// 账号若加入大量加密房,初始 sync 会拉取并尝试解密海量历史 → 内存暴涨被 OOM)。
|
||||
private readonly watchRoomIds: string[] = [],
|
||||
) {
|
||||
this.logger = new Logger(`MatrixSession:${account}`);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.started) return;
|
||||
this.started = true;
|
||||
|
||||
if (this.dryRun) {
|
||||
this.logger.warn(
|
||||
`[dry-run] 跳过登录,账号 ${this.cfg.userId} 不会真正连接`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const accDir = this.accountDir();
|
||||
fs.mkdirSync(accDir, { recursive: true });
|
||||
|
||||
const storage = new SimpleFsStorageProvider(path.join(accDir, 'state.json'));
|
||||
const crypto = new RustSdkCryptoStorageProvider(
|
||||
path.join(accDir, 'crypto'),
|
||||
StoreType.Sqlite,
|
||||
);
|
||||
|
||||
let client = await this.buildClient(accDir, storage, crypto);
|
||||
this.registerHandlers(client);
|
||||
|
||||
const syncFilter = this.buildSyncFilter();
|
||||
|
||||
try {
|
||||
await client.start(syncFilter);
|
||||
} catch (err) {
|
||||
// accessToken 失效(如服务端登出该设备):清除凭据与加密状态后重登一次。
|
||||
if (this.isTokenError(err)) {
|
||||
this.logger.warn(
|
||||
`账号 ${this.cfg.userId} 的 accessToken 已失效,清除本地凭据后重新登录。`,
|
||||
);
|
||||
this.clearCreds(accDir);
|
||||
client = await this.loginAndBuild(accDir, storage, crypto);
|
||||
this.registerHandlers(client);
|
||||
await client.start(syncFilter);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
this.client = client;
|
||||
this.selfUserId = await client.getUserId();
|
||||
const whoami = await client.getWhoAmI().catch(() => undefined);
|
||||
this.logger.log(
|
||||
`账号 ${this.selfUserId} 已登录并开始 sync` +
|
||||
(whoami?.device_id ? `(device=${whoami.device_id})` : '') +
|
||||
`,E2EE=${client.crypto ? '已启用' : '未启用'}` +
|
||||
(this.watchRoomIds.length
|
||||
? `,仅同步 ${this.watchRoomIds.length} 个房间`
|
||||
: ',同步全部房间'),
|
||||
);
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.client?.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造 sync filter:用房间白名单把同步范围限制在各 bot 关注的房间,
|
||||
* 避免账号加入的其它(尤其大型加密)房间被拉取、解密历史而耗尽内存。
|
||||
* to-device / account_data 不过滤,保证 E2EE 密钥分发正常。
|
||||
* 返回 undefined 表示不限制(同步全部房间)。
|
||||
*/
|
||||
private buildSyncFilter(): Record<string, unknown> | undefined {
|
||||
if (!this.watchRoomIds.length) return undefined;
|
||||
return {
|
||||
room: {
|
||||
rooms: this.watchRoomIds,
|
||||
timeline: { limit: 20, lazy_load_members: true },
|
||||
state: { lazy_load_members: true },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建 client:优先复用落盘的 accessToken;无则用密码登录一次并落盘。
|
||||
*/
|
||||
private async buildClient(
|
||||
accDir: string,
|
||||
storage: SimpleFsStorageProvider,
|
||||
crypto: RustSdkCryptoStorageProvider,
|
||||
): Promise<MatrixClient> {
|
||||
const creds = this.readCreds(accDir);
|
||||
if (creds?.accessToken && creds.baseUrl) {
|
||||
this.logger.log(`复用已保存的登录凭据(${creds.userId})`);
|
||||
return new MatrixClient(creds.baseUrl, creds.accessToken, storage, crypto);
|
||||
}
|
||||
return this.loginAndBuild(accDir, storage, crypto);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用密码登录一次,拿到 accessToken/baseUrl/deviceId 落盘,返回长期使用的 client。
|
||||
* matrix-bot-sdk 的 MatrixAuth 会自行做 .well-known 发现并返回正确的
|
||||
* homeserverUrl(裸域名 tchncs.de → matrix.tchncs.de),无需手动发现。
|
||||
*/
|
||||
private async loginAndBuild(
|
||||
accDir: string,
|
||||
storage: SimpleFsStorageProvider,
|
||||
crypto: RustSdkCryptoStorageProvider,
|
||||
): Promise<MatrixClient> {
|
||||
const loggedIn = await this.passwordLoginWithRetry();
|
||||
|
||||
const baseUrl = loggedIn.homeserverUrl;
|
||||
const accessToken = loggedIn.accessToken;
|
||||
const userId = await loggedIn.getUserId();
|
||||
const whoami = await loggedIn.getWhoAmI().catch(() => undefined);
|
||||
|
||||
this.logger.log(`账号 ${userId} 密码登录成功,凭据已保存,后续复用`);
|
||||
|
||||
this.writeCreds(accDir, {
|
||||
accessToken,
|
||||
userId,
|
||||
deviceId: whoami?.device_id,
|
||||
baseUrl,
|
||||
});
|
||||
|
||||
// 复用已注册事件/加密状态的 storage、crypto,生成长期使用的 client。
|
||||
return new MatrixClient(baseUrl, accessToken, storage, crypto);
|
||||
}
|
||||
|
||||
/**
|
||||
* 密码登录,带 429 限流处理:
|
||||
* 登录被限流时,读 retry_after_ms 在【进程内】等待后重试,而非抛错退出。
|
||||
* 关键原因:若让进程崩溃退出,容器(restart: on-failure)会立刻重启并再次登录,
|
||||
* 每次新登录都会刷新/延长服务端的登录限流窗口,陷入"反复登录→反复限流"的死循环。
|
||||
* 进程内等待则只占用一次登录配额,等窗口过去即可成功,随后凭据落盘不再登录。
|
||||
*/
|
||||
private async passwordLoginWithRetry(): Promise<MatrixClient> {
|
||||
// MatrixAuth 不会自动做服务器发现,它直接拿传入地址打 /login。
|
||||
// 必须先用 .well-known 把账号域名(https://tchncs.de)解析成真实 API 域名
|
||||
// (https://matrix.tchncs.de),否则会打到裸域名的落地页入口被限流(429)。
|
||||
const baseUrl = await this.discoverBaseUrl(this.cfg.homeServer);
|
||||
const auth = new MatrixAuth(baseUrl);
|
||||
const maxWaitMs = 10 * 60_000; // 单次等待上限 10 分钟,避免异常超长阻塞。
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try {
|
||||
return await auth.passwordLogin(
|
||||
this.cfg.userId,
|
||||
this.cfg.password,
|
||||
'🤖 签到机器人 (daily-bot-nest)',
|
||||
);
|
||||
} catch (err) {
|
||||
const e = err as {
|
||||
errcode?: string;
|
||||
statusCode?: number;
|
||||
retryAfterMs?: number;
|
||||
};
|
||||
const isRateLimited =
|
||||
e?.errcode === 'M_LIMIT_EXCEEDED' || e?.statusCode === 429;
|
||||
if (!isRateLimited) throw err;
|
||||
|
||||
const waitMs = Math.min(
|
||||
Math.max((e.retryAfterMs ?? 30_000) + 1_000, 5_000),
|
||||
maxWaitMs,
|
||||
);
|
||||
this.logger.warn(
|
||||
`账号 ${this.cfg.userId} 登录被限流(429),${Math.ceil(
|
||||
waitMs / 1000,
|
||||
)} 秒后在进程内重试(第 ${attempt} 次)。` +
|
||||
' 不退出进程,避免容器重启反复登录刷新限流窗口。',
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, waitMs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 /.well-known/matrix/client 自动发现真实的 homeserver API 地址。
|
||||
* 例如账号域名 https://tchncs.de 会被解析为 https://matrix.tchncs.de。
|
||||
* 这是 Matrix 标准的服务器发现机制(Element 等客户端均如此)。
|
||||
* 若配置里已经是真实 API 地址,发现通常返回同值;发现失败则回退原值。
|
||||
*/
|
||||
private async discoverBaseUrl(configured: string): Promise<string> {
|
||||
const trimmed = configured.replace(/\/$/, '');
|
||||
try {
|
||||
const res = await fetch(`${trimmed}/.well-known/matrix/client`, {
|
||||
method: 'GET',
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = (await res.json()) as {
|
||||
'm.homeserver'?: { base_url?: string };
|
||||
};
|
||||
const baseUrl = data['m.homeserver']?.base_url?.replace(/\/$/, '');
|
||||
if (baseUrl) {
|
||||
if (baseUrl !== trimmed) {
|
||||
this.logger.log(
|
||||
`服务器发现: ${configured} → ${baseUrl}(来自 .well-known)`,
|
||||
);
|
||||
}
|
||||
return baseUrl;
|
||||
}
|
||||
}
|
||||
this.logger.warn(
|
||||
`服务器发现未返回有效地址(HTTP ${res.status}),回退使用 ${configured}`,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`服务器发现失败,回退使用 ${configured}: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
private accountDir(): string {
|
||||
const base = process.env.DATA_DIR ?? './data';
|
||||
return path.resolve(base, 'matrix', this.account);
|
||||
}
|
||||
|
||||
private credsPath(accDir: string): string {
|
||||
return path.join(accDir, 'creds.json');
|
||||
}
|
||||
|
||||
private readCreds(accDir: string): PersistedCreds | undefined {
|
||||
try {
|
||||
const raw = fs.readFileSync(this.credsPath(accDir), 'utf8');
|
||||
return JSON.parse(raw) as PersistedCreds;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private writeCreds(accDir: string, creds: PersistedCreds): void {
|
||||
fs.writeFileSync(this.credsPath(accDir), JSON.stringify(creds, null, 2), {
|
||||
mode: 0o600,
|
||||
});
|
||||
}
|
||||
|
||||
private clearCreds(accDir: string): void {
|
||||
try {
|
||||
fs.rmSync(this.credsPath(accDir), { force: true });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
// 旧 device 已失效,其加密会话不可再用,清空加密 store 让新设备重新建立。
|
||||
try {
|
||||
fs.rmSync(path.join(accDir, 'crypto'), { recursive: true, force: true });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
private isTokenError(err: unknown): boolean {
|
||||
const e = err as { errcode?: string; statusCode?: number };
|
||||
return (
|
||||
e?.errcode === 'M_UNKNOWN_TOKEN' ||
|
||||
e?.errcode === 'M_MISSING_TOKEN' ||
|
||||
e?.statusCode === 401
|
||||
);
|
||||
}
|
||||
|
||||
async send(
|
||||
roomId: string,
|
||||
text: string,
|
||||
replyToEventId?: string,
|
||||
): Promise<string> {
|
||||
if (this.dryRun || !this.client) {
|
||||
this.logger.log(`[dry-run] send → ${roomId}: ${text}`);
|
||||
return 'dry-run-event-id';
|
||||
}
|
||||
const content: Record<string, unknown> = { msgtype: 'm.text', body: text };
|
||||
if (replyToEventId) {
|
||||
content['m.relates_to'] = {
|
||||
'm.in_reply_to': { event_id: replyToEventId },
|
||||
};
|
||||
}
|
||||
// 加密房间下 sendMessage 会自动加密;返回 event_id。
|
||||
const eventId = await this.client.sendMessage(roomId, content);
|
||||
this.rememberSent(eventId);
|
||||
return eventId;
|
||||
}
|
||||
|
||||
/** 登记 bot 自己发出的 event_id,用于在 sync 回流时去重(有界,防内存泄漏)。 */
|
||||
private rememberSent(eventId?: string): void {
|
||||
if (!eventId) return;
|
||||
this.recentSentEventIds.add(eventId);
|
||||
if (this.recentSentEventIds.size > 500) {
|
||||
const oldest = this.recentSentEventIds.values().next().value;
|
||||
if (oldest) this.recentSentEventIds.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
async kick(roomId: string, userId: string, reason?: string): Promise<void> {
|
||||
if (this.dryRun || !this.client) {
|
||||
this.logger.log(
|
||||
`[dry-run] kick ${userId} from ${roomId} (${reason ?? ''})`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await this.client.kickUser(userId, roomId, reason);
|
||||
}
|
||||
|
||||
async getMemberCount(roomId: string): Promise<number> {
|
||||
if (this.dryRun || !this.client) return 0;
|
||||
const members = await this.client
|
||||
.getJoinedRoomMembers(roomId)
|
||||
.catch(() => []);
|
||||
return members.length;
|
||||
}
|
||||
|
||||
async getJoinedMembers(roomId: string): Promise<string[]> {
|
||||
if (this.dryRun || !this.client) return [];
|
||||
return this.client.getJoinedRoomMembers(roomId).catch(() => []);
|
||||
}
|
||||
|
||||
/** 读取用户在房间内的 power level:取 m.room.power_levels 的 users[userId],回落 users_default。 */
|
||||
async getPowerLevel(roomId: string, userId: string): Promise<number> {
|
||||
if (this.dryRun || !this.client) return 0;
|
||||
try {
|
||||
const pl = (await this.client.getRoomStateEvent(
|
||||
roomId,
|
||||
'm.room.power_levels',
|
||||
'',
|
||||
)) as { users?: Record<string, number>; users_default?: number };
|
||||
const users = pl?.users ?? {};
|
||||
if (typeof users[userId] === 'number') return users[userId];
|
||||
return typeof pl?.users_default === 'number' ? pl.users_default : 0;
|
||||
} catch (err) {
|
||||
this.logger.debug?.(
|
||||
`读取 ${roomId} power_levels 失败: ${(err as Error).message}`,
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private registerHandlers(client: MatrixClient): void {
|
||||
// room.message:已自动解密的房间消息(明文与加密房统一在此回调)。
|
||||
client.on('room.message', (roomId: string, event: Record<string, any>) => {
|
||||
const sender = event['sender'] as string | undefined;
|
||||
const eventId = event['event_id'] as string | undefined;
|
||||
// 去重:仅跳过 bot 自己刚发出的消息,用户同账号发的命令仍会处理。
|
||||
if (eventId && this.recentSentEventIds.has(eventId)) {
|
||||
this.recentSentEventIds.delete(eventId);
|
||||
return;
|
||||
}
|
||||
const content = (event['content'] ?? {}) as Record<string, unknown>;
|
||||
this.logger.debug?.(
|
||||
`收到消息 room=${roomId} from=${sender} type=${content['msgtype']}: ${String(content['body'] ?? '').slice(0, 60)}`,
|
||||
);
|
||||
if (content['msgtype'] !== 'm.text') return;
|
||||
|
||||
const msg: InboundMessage = {
|
||||
eventId: (event['event_id'] as string) ?? '',
|
||||
account: this.account,
|
||||
roomId,
|
||||
userId: sender ?? '',
|
||||
text: (content['body'] as string) ?? '',
|
||||
timestampMs: (event['origin_server_ts'] as number) ?? Date.now(),
|
||||
};
|
||||
void this.sink.onMessage(msg);
|
||||
});
|
||||
|
||||
// room.event:所有房间事件;在此筛成员变更。
|
||||
client.on('room.event', (roomId: string, event: Record<string, any>) => {
|
||||
if (event['type'] !== 'm.room.member') return;
|
||||
const content = (event['content'] ?? {}) as Record<string, unknown>;
|
||||
const ev: MemberEvent = {
|
||||
account: this.account,
|
||||
roomId,
|
||||
userId: (event['state_key'] as string) ?? '',
|
||||
membership: content['membership'] as MemberEvent['membership'],
|
||||
};
|
||||
void this.sink.onMember(ev);
|
||||
});
|
||||
|
||||
// 解密失败:最常见是历史消息(bot 加入前的消息,发送方不会共享旧密钥)
|
||||
// 或密钥尚未送达,属正常现象,降为 debug 避免刷屏;库损坏等异常另行排查。
|
||||
client.on(
|
||||
'room.failed_decryption',
|
||||
(roomId: string, event: Record<string, any>, e: Error) => {
|
||||
this.logger.debug(
|
||||
`房间 ${roomId} 事件 ${event?.['event_id']} 解密失败: ${e?.message}`,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { SessionManager } from './session-manager.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [SessionManager],
|
||||
exports: [SessionManager],
|
||||
})
|
||||
export class MatrixModule {}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '../../config/config.service';
|
||||
import { MatrixSession } from './matrix-session';
|
||||
import { MatrixEventSink } from './types';
|
||||
|
||||
/**
|
||||
* 管理所有 Matrix 账号会话。
|
||||
* 多个 bot 引用同一 account ⇒ 只建一个 MatrixSession(共享账号);
|
||||
* 引用不同 account ⇒ 各自独立会话(独立身份)。
|
||||
*/
|
||||
@Injectable()
|
||||
export class SessionManager {
|
||||
private readonly logger = new Logger(SessionManager.name);
|
||||
private readonly sessions = new Map<string, MatrixSession>();
|
||||
|
||||
constructor(private readonly config: ConfigService) {}
|
||||
|
||||
/** 按需创建并缓存某账号的会话(去重)。 */
|
||||
ensureSession(account: string, sink: MatrixEventSink): MatrixSession {
|
||||
const existing = this.sessions.get(account);
|
||||
if (existing) return existing;
|
||||
|
||||
const accCfg = this.config.getAccount(account);
|
||||
// 聚合所有使用该账号的 bot 关注的房间(去重),限制 sync 范围。
|
||||
const watchRoomIds = [
|
||||
...new Set(
|
||||
this.config.bots
|
||||
.filter((b) => b.account === account)
|
||||
.flatMap((b) => b.rooms),
|
||||
),
|
||||
];
|
||||
const session = new MatrixSession(
|
||||
account,
|
||||
accCfg,
|
||||
sink,
|
||||
this.config.isDryRun,
|
||||
watchRoomIds,
|
||||
);
|
||||
this.sessions.set(account, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
get(account: string): MatrixSession | undefined {
|
||||
return this.sessions.get(account);
|
||||
}
|
||||
|
||||
async startAll(): Promise<void> {
|
||||
for (const [account, session] of this.sessions) {
|
||||
this.logger.log(`启动会话: ${account}`);
|
||||
await session.start();
|
||||
}
|
||||
}
|
||||
|
||||
async stopAll(): Promise<void> {
|
||||
for (const session of this.sessions.values()) {
|
||||
await session.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { InboundMessage, MemberEvent } from '../command/types';
|
||||
|
||||
/** bot 与 Matrix 交互的统一出站能力(BotContext 内部依赖它)。 */
|
||||
export interface MatrixTransport {
|
||||
readonly account: string;
|
||||
send(roomId: string, text: string, replyToEventId?: string): Promise<string>;
|
||||
kick(roomId: string, userId: string, reason?: string): Promise<void>;
|
||||
getMemberCount(roomId: string): Promise<number>;
|
||||
getJoinedMembers(roomId: string): Promise<string[]>;
|
||||
/** 读取用户在房间内的 power level(读不到或无权限时返回 0)。 */
|
||||
getPowerLevel(roomId: string, userId: string): Promise<number>;
|
||||
}
|
||||
|
||||
/** 归一化事件回调,由 SessionManager 注册,转交 Dispatcher。 */
|
||||
export interface MatrixEventSink {
|
||||
onMessage(msg: InboundMessage): Promise<void>;
|
||||
onMember(ev: MemberEvent): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
|
||||
import { CronJob } from 'cron';
|
||||
import { CronSpec } from '../command/types';
|
||||
|
||||
/**
|
||||
* 简单的 cron 注册器,封装 cron 库。
|
||||
* bot 通过 registerCrons() 返回 CronSpec,由平台批量注册到此处。
|
||||
*/
|
||||
@Injectable()
|
||||
export class SchedulerService implements OnModuleDestroy {
|
||||
private readonly logger = new Logger(SchedulerService.name);
|
||||
private readonly jobs: CronJob[] = [];
|
||||
|
||||
register(botName: string, spec: CronSpec): void {
|
||||
const job = new CronJob(spec.cron, () => {
|
||||
void this.runSafely(botName, spec);
|
||||
});
|
||||
job.start();
|
||||
this.jobs.push(job);
|
||||
this.logger.log(
|
||||
`已注册定时任务 [${botName}] ${spec.name ?? ''} cron="${spec.cron}"`,
|
||||
);
|
||||
}
|
||||
|
||||
private async runSafely(botName: string, spec: CronSpec): Promise<void> {
|
||||
try {
|
||||
await spec.run();
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`定时任务失败 [${botName}] ${spec.name ?? ''}: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
onModuleDestroy(): void {
|
||||
for (const job of this.jobs) {
|
||||
job.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import 'reflect-metadata';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { LogLevel, LogService } from 'matrix-bot-sdk';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
// 静音 matrix-bot-sdk 的 debug/info 噪音,只保留 warn/error。
|
||||
// 可用 MATRIX_LOG_LEVEL 覆盖(trace/debug/info/warn/error)。
|
||||
LogService.setLevel(
|
||||
LogLevel.fromString(process.env.MATRIX_LOG_LEVEL ?? 'WARN', LogLevel.WARN),
|
||||
);
|
||||
LogService.muteModule('Metrics');
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.createApplicationContext(AppModule, {
|
||||
abortOnError: true,
|
||||
});
|
||||
app.enableShutdownHooks();
|
||||
Logger.log('daily-bot-nest 已启动。Ctrl+C 退出。', 'Bootstrap');
|
||||
}
|
||||
|
||||
bootstrap().catch((err) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('启动失败:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
accounts:
|
||||
main:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@testbot:example.com"
|
||||
password: "test-password-main"
|
||||
checkin:
|
||||
homeServer: "https://matrix.example.com"
|
||||
userId: "@checkin-test:example.com"
|
||||
password: "test-password-checkin"
|
||||
|
||||
bots:
|
||||
- name: checkin
|
||||
account: checkin
|
||||
rooms:
|
||||
- "!testroom:example.com"
|
||||
config:
|
||||
mainRoom: "!testroom:example.com"
|
||||
kickDays: 30
|
||||
autoKick: false
|
||||
adminPowerLevel: 100
|
||||
admins: []
|
||||
whitelist: []
|
||||
Reference in new issue
Block a user