This commit is contained in:
eskima committed 2026-06-04 15:45:20 +08:00
commit 440f572834
53 files changed
+12776

No files matched your search

+40
View File
@@ -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);
}
}
+73
View File
@@ -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();
}
}
+94
View File
@@ -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}`;
}
+18
View File
@@ -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 {}
+65
View File
@@ -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}`,
);
}
}
}
}
+6
View File
@@ -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);
+43
View File
@@ -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[];
}