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

+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}`,
);
}
}
}
}