diff --git a/README.md b/README.md index a40684c..7a13a36 100644 --- a/README.md +++ b/README.md @@ -86,20 +86,16 @@ docker compose logs -f # 看日志 |---|---| | `!checkin` 或 直接发「签到」 | 今日签到(全角「!签到」也可) | | `!list <用户ID\|all> [--raw]` | 查询签到状态,`--raw` 输出 JSON | -| `!level set <用户ID> <等级>` | 设置等级(等级支持中文「黄金」或英文 `gold`)**🔒 管理员** | -| `!level raise <用户ID>` | 提升一级 **🔒 管理员** | -| `!level super <用户ID>` | 赋予超级管理(免统计/免踢)**🔒 管理员** | -| `!level clear <用户ID>` | 清除等级为青铜 **🔒 管理员** | | `!reset` | 重置所有人当日签到状态 **🔒 管理员** | | `!test daily\|monthly` | 手动触发日报/月报(运维测试用)**🔒 管理员** | | `!echo <文本>` / `!ping` / `!help` | 杂项 | -等级:超级管理 / 青铜 / 白银 / 黄金 / 铂金 / 钻石(内部存英文 key,仅展示转中文)。 +签到等级(青铜 / 白银 / 黄金 / 铂金 / 钻石)将根据用户的累计签到次数纯自动升级,仅作趣味展示。 -> **🔒 管理员命令权限**:`level` / `reset` / `test` 仅 **房间内 power level ≥ `adminPowerLevel`(默认 100)** -> 或在 `config.admins` 白名单中的用户可调用,其他人发送会被拒绝。这是信任根 —— DB 里的「超级管理」 -> 等级只表示免统计/免踢,**不等于**命令权限。power level 在 Element 的「房间设置 → 权限」里给成员调整 -> (100=管理员、50=版主);`admins` 留空即纯按 power level 判定,无需写死名单。 +> **🔒 管理员权限与免死特权**: +> `reset` / `test` 等管理命令仅 **房间内 power level ≥ `adminPowerLevel`(默认 100)** 或在 `config.admins` 白名单中的用户可调用。 +> 同时,**只要用户的原生权限分达到了管理员级别,就会在每天凌晨的清理逻辑中被自动“免死”**(即使长期不签到也不会被踢)。 +> 所有权限调整请直接在 Element 客户端的「房间设置 → 权限」里通过原生 UI 操作,无需手动输入命令。 ### 定时任务 - **每日 03:00**:生成签到日报(按今日未签到 / ≥7 / ≥14 / ≥30 天 / 从未签到分桶), @@ -117,6 +113,30 @@ docker compose logs -f # 看日志 | `adminPowerLevel` | 100 | 房间内 power level ≥ 此值即视为管理员(100=管理员、50=版主) | | `admins` | [] | 额外管理员白名单(power level 之外的补充,可留空) | +## 权限同步机器人 (Room Manager) + +该机器人不靠命令驱动,而是**监听 Matrix 原生的权限分(Power Level)变化以及人员离开事件**。 +1. **权限联动**:管理员只需在客户端(如 Element)的签到房间设置里,点开用户头像修改权限等级,机器人就会自动将该用户跨群调配到不同的工作房或小黑屋中。 +2. **踢出联动**:如果某个用户主动退出了签到房,或者因为长期不打卡被签到机器人踢出了签到房,该机器人也会立即将其视为“失去大本营身份”,自动将其从所有工作房踢出,并丢进失联房。 + +| 原生权限分 | 内部级别 | 默认自动执行的操作 | +|---|---|---| +| `≥ levelA` | 最高权限 (如版主 50) | 邀请进**工作房1**,邀请进**工作房2** | +| `== levelB`| 中等权限 (如默认 0) | 从**工作房1**踢出,邀请进**工作房2** | +| `≤ levelC` | 最低权限 (如受限 -1) | 从**工作房1、2**踢出,邀请进**失联房** | + +### room-manager 配置项(`config/bots.yaml` 的 `config`) +| 字段 | 说明 | +|---|---| +| `workRoom1` | 高级工作群 ID(最高权限才能进) | +| `workRoom2` | 普通工作群 ID(中高权限能进) | +| `lostRoom` | 失联小黑屋 ID(最低权限进入) | +| `levelA` | 最高权限的分数阈值,默认为 `50` | +| `levelB` | 中等权限的分数,默认为 `0` | +| `levelC` | 最低权限的分数阈值,默认为 `-1` | + +> **注意**:`room-manager` 机器人的 `rooms` 数组中,应当**只填写**“签到/管理房”的 ID。机器人只会在这个房间里当“保安”监听原生权限变化,然后往外执行踢/拉操作。 + ## 新增一个机器人(例:notify) 1. 新建 `src/bots/notify/notify.bot.ts`,`implements RoomBot`,类上加 `@RegisterBot()`。 2. 新建 `notify.module.ts`,`providers: [NotifyBot]`。 diff --git a/config/bots.example.yaml b/config/bots.example.yaml index 1d5fe90..9334dec 100644 --- a/config/bots.example.yaml +++ b/config/bots.example.yaml @@ -30,7 +30,7 @@ bots: adminPowerLevel: 100 # 房间内 power level ≥ 此值视为管理员(100=管理员、50=版主) admins: [] # 额外管理员白名单(power level 之外的补充,可留空) # - "@admin:example.com" - whitelist: [] # 永不踢出的用户(Super 等级也永不踢) + whitelist: [] # 额外的免踢白名单(注意:权限分 >= adminPowerLevel 的人已自动免死,无需填在此处。这里只填低权限但免踢的特权用户,比如机器人或老板账号) # - "@vip:example.com" # 示例:共享 main 账号的另一个 bot(实现后取消注释并启用) @@ -38,3 +38,22 @@ bots: # account: main # rooms: # - "!anotherRoom:example.com" + + # ======================================================= + # 原生权限联动保安 (room-manager) + # ======================================================= + # 该机器人不靠命令驱动,而是监听 Matrix 原生权限(Power Level)。 + # 管理员在客户端(Element)直接改成员权限,机器人会自动拉/踢人。 + - name: room-manager + account: main + rooms: + - "!checkinRoomId:example.com" # 【务必】只填签到/管理房的ID!作为控制中枢。 + config: + workRoom1: "!workRoom1Id:example.com" # 工作房 A (核心群) + workRoom2: "!workRoom2Id:example.com" # 工作房 B (普通群) + lostRoom: "!lostRoomId:example.com" # 失联房 (小黑屋) + + # 分数映射 (对应 Element 客户端里的权限设定) + levelA: 50 # 最高权限(如版主50):进工作房1 + 进工作房2 + levelB: 0 # 中等权限(如默认0) :踢出工作房1 + 保留在工作房2 + levelC: -1 # 最低权限(如受限-1):踢出工作房1、2 + 丢进失联房 diff --git a/src/app.module.ts b/src/app.module.ts index c4fb1b5..ed89b54 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -4,6 +4,7 @@ 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'; +import { RoomManagerModule } from './bots/room-manager/room-manager.module'; @Module({ imports: [ @@ -13,6 +14,7 @@ import { CheckinModule } from './bots/checkin/checkin.module'; BotModule, // —— 在此注册各房间机器人 feature module —— CheckinModule, + RoomManagerModule, ], }) export class AppModule {} diff --git a/src/bots/checkin/checkin.bot.ts b/src/bots/checkin/checkin.bot.ts index 642f498..6f8045d 100644 --- a/src/bots/checkin/checkin.bot.ts +++ b/src/bots/checkin/checkin.bot.ts @@ -14,15 +14,12 @@ import { } from './report'; import { applyCheckin, - clearLevel, levelChoices, levelLabel, newUserState, parseLevel, - raiseLevel, resetDaily, resetMonthly, - setLevel, UserState, } from './user-state'; @@ -149,10 +146,6 @@ export class CheckinBot implements RoomBot { 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); @@ -244,10 +237,6 @@ export class CheckinBot implements RoomBot { '签到机器人命令列表:', '!checkin / 签到 — 今日签到', '!list <用户ID|all> [--raw] — 查询签到状态', - '!level set <用户ID> <等级> — 设置等级(管理员)', - '!level raise <用户ID> — 提升一级(管理员)', - '!level super <用户ID> — 赋予超级管理(管理员)', - '!level clear <用户ID> — 清除等级(管理员)', '!reset — 重置所有人当日签到(管理员)', '!test daily|monthly — 手动触发日报/月报(管理员)', '!echo <文本> / !ping / !help', @@ -292,54 +281,6 @@ export class CheckinBot implements RoomBot { await ctx.reply(raw, '已重置所有用户的当日签到状态'); } - private async handleLevel(cmd: ParsedCommand, ctx: BotContext): Promise { - 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(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 { @@ -348,9 +289,9 @@ export class CheckinBot implements RoomBot { const entries = await ctx.db.entries(); const states = new Map(entries); - // 已签到且非 Super 的人数(对应 Rust 的 checked_nums)。 + // 已签到人数(对应 Rust 的 checked_nums)。 const checkedNums = entries.filter( - ([, s]) => s.isCheckinToday && s.level !== 'Super', + ([, s]) => s.isCheckinToday, ).length; const members = await ctx.getJoinedMembers(room); @@ -365,17 +306,34 @@ export class CheckinBot implements RoomBot { await ctx.send(room, text); if (this.cfg.autoKick) { - const targets = computeKickTargets( + let targets = computeKickTargets( rows, this.cfg.kickDays, this.cfg.whitelist, ); + + // 原生权限豁免:如果用户的 Power Level 达到管理员级别,自动免死 + const finalTargets: string[] = []; for (const userId of targets) { + try { + const power = await ctx.getPowerLevel(room, userId); + if (power >= this.cfg.adminPowerLevel) { + this.logger.log(`用户 ${userId} 未签到超期,但权限分(${power})足够,豁免踢出`); + continue; + } + finalTargets.push(userId); + } catch (err) { + this.logger.error(`获取用户 ${userId} 权限分失败,加入踢出名单`, err); + finalTargets.push(userId); + } + } + + for (const userId of finalTargets) { await ctx.kick(room, userId, `超过 ${this.cfg.kickDays} 天未签到`); this.logger.log(`已踢出 ${userId}`); } - if (targets.length > 0) { - await ctx.send(room, `已踢出 ${targets.length} 名长期未签到用户`); + if (finalTargets.length > 0) { + await ctx.send(room, `已踢出 ${finalTargets.length} 名长期未签到用户`); } } @@ -394,7 +352,6 @@ export class CheckinBot implements RoomBot { const entries = await ctx.db.entries(); const ranked = entries - .filter(([, s]) => s.level !== 'Super') .sort((a, b) => b[1].checkinTimesInMonth - a[1].checkinTimesInMonth); const date = new Date().toLocaleDateString('zh-CN', { diff --git a/src/bots/checkin/checkin.integration.spec.ts b/src/bots/checkin/checkin.integration.spec.ts index b7711b8..bd72ef2 100644 --- a/src/bots/checkin/checkin.integration.spec.ts +++ b/src/bots/checkin/checkin.integration.spec.ts @@ -28,11 +28,16 @@ class RealStoreContext implements BotContext { readonly sent: string[] = []; readonly kicked: Array<{ roomId: string; userId: string; reason?: string }> = []; + readonly invited: Array<{ roomId: string; userId: string }> = []; members: string[] = []; powerLevels: Record = {}; constructor(public readonly db: BotStore) {} + async invite(roomId: string, userId: string): Promise { + this.invited.push({ roomId, userId }); + } + async send(_roomId: string, text: string): Promise { this.sent.push(text); return 'evt'; diff --git a/src/bots/checkin/checkin.spec.ts b/src/bots/checkin/checkin.spec.ts index 932d6f1..e27969e 100644 --- a/src/bots/checkin/checkin.spec.ts +++ b/src/bots/checkin/checkin.spec.ts @@ -31,6 +31,7 @@ class FakeContext implements BotContext { return 'evt'; } async kick(): Promise {} + async invite(): Promise {} async getMemberCount(): Promise { return 10; } @@ -110,38 +111,12 @@ describe('CheckinBot', () => { 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('@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('@alice:hs')).toBeNull(); - - // reset / test 同样受限。 + // reset 受限。 await bot.onCommand(parseCommand(msg('reset', '@alice:hs'), 'reset'), ctx); - expect(ctx.sent[1]).toContain('无权限'); + expect(ctx.sent[0]).toContain('无权限'); }); it('allows privileged commands from room admins via power level', async () => { @@ -149,15 +124,8 @@ describe('CheckinBot', () => { 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('@bob:hs'))?.level).toBe('Gold'); + await bot.onCommand(parseCommand(msg('reset', '@mod:hs'), 'reset'), ctx); + expect(ctx.sent[0]).toContain('重置'); }); it('denies privileged commands when power level below threshold', async () => { diff --git a/src/bots/checkin/report.spec.ts b/src/bots/checkin/report.spec.ts index 8a80b13..d38a198 100644 --- a/src/bots/checkin/report.spec.ts +++ b/src/bots/checkin/report.spec.ts @@ -13,15 +13,14 @@ const DAY = 86_400_000; const NOW = 1_000 * DAY; // 固定 now,便于天数计算 describe('report', () => { - it('analyzes unchecked members, skipping checked-in and super', () => { + it('analyzes unchecked members, skipping checked-in', () => { const states = new Map([ ['@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'], + ['@a:hs', '@b:hs', '@c:hs'], states, NOW, ); diff --git a/src/bots/checkin/user-state.ts b/src/bots/checkin/user-state.ts index d265fcb..34837d0 100644 --- a/src/bots/checkin/user-state.ts +++ b/src/bots/checkin/user-state.ts @@ -1,12 +1,11 @@ export type UserLevel = - | 'Super' | 'Bronze' | 'Silver' | 'Gold' | 'Platinum' | 'Diamond'; -/** 非 Super 的等级升序,用于 raise 逻辑。 */ +/** 签到等级升序(已移除手工赋予的 Super)。 */ export const LEVELS_ASC: UserLevel[] = [ 'Bronze', 'Silver', @@ -15,11 +14,10 @@ export const LEVELS_ASC: UserLevel[] = [ 'Diamond', ]; -export const VALID_LEVELS: UserLevel[] = ['Super', ...LEVELS_ASC]; +export const VALID_LEVELS: UserLevel[] = [...LEVELS_ASC]; /** 等级的中文显示名(内部仍用英文 key,只在展示层转中文)。 */ export const LEVEL_LABELS: Record = { - Super: '超级管理', Bronze: '青铜', Silver: '白银', Gold: '黄金', @@ -71,7 +69,7 @@ export function newUserState(): UserState { } export function isSuper(state: UserState): boolean { - return state.level === 'Super'; + return false; // 已废弃,通过原生权限判断 } /** 执行一次签到,更新状态与等级(移植自 Rust UserState::checkin)。 */ @@ -84,9 +82,6 @@ export function applyCheckin(state: UserState, now = new Date()): UserState { 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'; @@ -96,23 +91,6 @@ export function applyCheckin(state: UserState, now = new Date()): UserState { 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 }; diff --git a/src/bots/room-manager/room-manager.bot.ts b/src/bots/room-manager/room-manager.bot.ts new file mode 100644 index 0000000..b5f2e03 --- /dev/null +++ b/src/bots/room-manager/room-manager.bot.ts @@ -0,0 +1,97 @@ +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 { MemberEvent, PowerLevelEvent } from '../../core/command/types'; + +interface RoomManagerConfig { + workRoom1: string; + workRoom2: string; + lostRoom: string; + levelA: number; + levelB: number; + levelC: number; +} + +@RegisterBot() +@Injectable() +export class RoomManagerBot implements RoomBot { + readonly name = 'room-manager'; + readonly account: string; + readonly rooms: string[]; + private readonly logger = new Logger('RoomManagerBot'); + private readonly cfg: RoomManagerConfig; + + // 用一个简单的内存锁防止重复执行(权限变更会发全量 users,只抓取差异比较好, + // 为了简便,这里每次直接同步成员权限状态) + constructor(config: ConfigService) { + const entry = config.bots.find((b) => b.name === this.name); + if (!entry) { + throw new Error(`config 中缺少 name=${this.name} 的 bot 配置`); + } + this.account = entry.account; + this.rooms = entry.rooms; + const c = entry.config || {}; + this.cfg = { + workRoom1: c.workRoom1 as string, + workRoom2: c.workRoom2 as string, + lostRoom: c.lostRoom as string, + levelA: (c.levelA as number) ?? 50, + levelB: (c.levelB as number) ?? 0, + levelC: (c.levelC as number) ?? -1, + }; + } + + async onReady(ctx: BotContext): Promise { + const mainRoom = this.rooms[0]; + if (!mainRoom) return; + const time = new Date().toLocaleString('zh-CN', { + timeZone: 'Asia/Shanghai', + }); + await ctx.send(mainRoom, `✅ 权限同步保安已上线(${time})。正在监听本房间原生权限变更...`); + this.logger.log(`已发送权限管理上线通知到 ${mainRoom}`); + } + + async onPowerLevel(ev: PowerLevelEvent, ctx: BotContext): Promise { + const { workRoom1, workRoom2, lostRoom, levelA, levelB, levelC } = this.cfg; + if (!workRoom1 || !workRoom2 || !lostRoom) { + this.logger.warn('未配置完整的目标房间(workRoom1, workRoom2, lostRoom),跳过权限同步'); + return; + } + + const users = ev.users; + + for (const [userId, power] of Object.entries(users)) { + try { + if (power >= levelA) { + await ctx.invite(workRoom1, userId); + await ctx.invite(workRoom2, userId); + this.logger.log(`同步 ${userId} -> A 级 (进1、2)`); + } else if (power === levelB) { + await ctx.kick(workRoom1, userId, '权限下降,移出高级群'); + await ctx.invite(workRoom2, userId); + this.logger.log(`同步 ${userId} -> B 级 (踢1、进2)`); + } else if (power <= levelC) { + await this.punishUser(userId, ctx); + this.logger.log(`同步 ${userId} -> C 级 (踢1、2,进冷宫)`); + } + } catch (err) { + this.logger.error(`同步用户 ${userId} 失败: ${err}`); + } + } + } + + async onMemberLeave(ev: MemberEvent, ctx: BotContext): Promise { + this.logger.log(`检测到 ${ev.userId} 离开了签到群(主动退出或被签到程序踢出),执行失联处理...`); + await this.punishUser(ev.userId, ctx); + } + + private async punishUser(userId: string, ctx: BotContext): Promise { + const { workRoom1, workRoom2, lostRoom } = this.cfg; + if (!workRoom1 || !workRoom2 || !lostRoom) return; + await ctx.kick(workRoom1, userId, '打入冷宫'); + await ctx.kick(workRoom2, userId, '打入冷宫'); + await ctx.invite(lostRoom, userId); + } +} + diff --git a/src/bots/room-manager/room-manager.module.ts b/src/bots/room-manager/room-manager.module.ts new file mode 100644 index 0000000..83a6baa --- /dev/null +++ b/src/bots/room-manager/room-manager.module.ts @@ -0,0 +1,7 @@ +import { Module } from '@nestjs/common'; +import { RoomManagerBot } from './room-manager.bot'; + +@Module({ + providers: [RoomManagerBot], +}) +export class RoomManagerModule {} diff --git a/src/core/bot/bot-context.ts b/src/core/bot/bot-context.ts index e4bd995..9e6209d 100644 --- a/src/core/bot/bot-context.ts +++ b/src/core/bot/bot-context.ts @@ -26,6 +26,10 @@ export class DefaultBotContext implements BotContext { return this.transport.kick(roomId, userId, reason); } + invite(roomId: string, userId: string): Promise { + return this.transport.invite(roomId, userId); + } + getMemberCount(roomId: string): Promise { return this.transport.getMemberCount(roomId); } diff --git a/src/core/bot/dispatcher.service.ts b/src/core/bot/dispatcher.service.ts index c54ac43..c85bb50 100644 --- a/src/core/bot/dispatcher.service.ts +++ b/src/core/bot/dispatcher.service.ts @@ -1,5 +1,5 @@ import { Injectable, Logger } from '@nestjs/common'; -import { InboundMessage, MemberEvent } from '../command/types'; +import { InboundMessage, MemberEvent, PowerLevelEvent } from '../command/types'; import { CommandError, parseCommand } from '../command/command-parser'; import { MatrixEventSink } from '../matrix/types'; import { BotRegistry } from './bot-registry.service'; @@ -49,12 +49,14 @@ export class Dispatcher implements MatrixEventSink { } async onMember(ev: MemberEvent): Promise { - 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); + if (ev.membership === 'join' && bot.onMemberJoin) { + await bot.onMemberJoin(ev, ctx); + } else if (ev.membership === 'leave' && bot.onMemberLeave) { + await bot.onMemberLeave(ev, ctx); + } } catch (err) { this.logger.warn( `bot ${bot.name} 处理成员事件失败: ${(err as Error).message}`, @@ -62,4 +64,18 @@ export class Dispatcher implements MatrixEventSink { } } } + + async onPowerLevel(ev: PowerLevelEvent): Promise { + const targets = this.registry.resolve(ev.account, ev.roomId); + for (const { bot, ctx } of targets) { + if (!bot.onPowerLevel) continue; + try { + await bot.onPowerLevel(ev, ctx); + } catch (err) { + this.logger.warn( + `bot ${bot.name} 处理权限变更事件失败: ${(err as Error).message}`, + ); + } + } + } } diff --git a/src/core/bot/room-bot.interface.ts b/src/core/bot/room-bot.interface.ts index 5b228b9..1ad7106 100644 --- a/src/core/bot/room-bot.interface.ts +++ b/src/core/bot/room-bot.interface.ts @@ -4,6 +4,7 @@ import { InboundMessage, MemberEvent, ParsedCommand, + PowerLevelEvent, } from '../command/types'; /** @@ -15,6 +16,7 @@ export interface BotContext { send(roomId: string, text: string, replyToEventId?: string): Promise; reply(msg: InboundMessage, text: string): Promise; kick(roomId: string, userId: string, reason?: string): Promise; + invite(roomId: string, userId: string): Promise; getMemberCount(roomId: string): Promise; getJoinedMembers(roomId: string): Promise; /** 读取用户在房间内的 power level,用于按房间权限判断管理员(读不到返回 0)。 */ @@ -39,5 +41,7 @@ export interface RoomBot { onMessage?(msg: InboundMessage, ctx: BotContext): Promise; onCommand?(cmd: ParsedCommand, ctx: BotContext): Promise; onMemberJoin?(ev: MemberEvent, ctx: BotContext): Promise; + onMemberLeave?(ev: MemberEvent, ctx: BotContext): Promise; + onPowerLevel?(ev: PowerLevelEvent, ctx: BotContext): Promise; registerCrons?(ctx: BotContext): CronSpec[]; } diff --git a/src/core/command/types.ts b/src/core/command/types.ts index 5056482..9c8776e 100644 --- a/src/core/command/types.ts +++ b/src/core/command/types.ts @@ -16,6 +16,13 @@ export interface MemberEvent { membership: 'join' | 'leave' | 'invite' | 'ban'; } +/** 房间权限变更事件 */ +export interface PowerLevelEvent { + account: string; + roomId: string; + users: Record; +} + /** 解析后的命令。 */ export interface ParsedCommand { raw: InboundMessage; diff --git a/src/core/matrix/matrix-session.ts b/src/core/matrix/matrix-session.ts index 7832b63..f0c39f7 100644 --- a/src/core/matrix/matrix-session.ts +++ b/src/core/matrix/matrix-session.ts @@ -345,6 +345,14 @@ export class MatrixSession implements MatrixTransport { await this.client.kickUser(userId, roomId, reason); } + async invite(roomId: string, userId: string): Promise { + if (this.dryRun || !this.client) { + this.logger.log(`[dry-run] invite ${userId} to ${roomId}`); + return; + } + await this.client.inviteUser(userId, roomId); + } + async getMemberCount(roomId: string): Promise { if (this.dryRun || !this.client) return 0; const members = await this.client @@ -405,17 +413,27 @@ export class MatrixSession implements MatrixTransport { void this.sink.onMessage(msg); }); - // room.event:所有房间事件;在此筛成员变更。 + // room.event:所有房间事件;在此筛成员变更及权限变更。 client.on('room.event', (roomId: string, event: Record) => { - if (event['type'] !== 'm.room.member') return; + const type = event['type']; const content = (event['content'] ?? {}) as Record; - const ev: MemberEvent = { - account: this.account, - roomId, - userId: (event['state_key'] as string) ?? '', - membership: content['membership'] as MemberEvent['membership'], - }; - void this.sink.onMember(ev); + + if (type === 'm.room.member') { + const ev: MemberEvent = { + account: this.account, + roomId, + userId: (event['state_key'] as string) ?? '', + membership: content['membership'] as MemberEvent['membership'], + }; + void this.sink.onMember(ev); + } else if (type === 'm.room.power_levels') { + const users = (content['users'] ?? {}) as Record; + void this.sink.onPowerLevel({ + account: this.account, + roomId, + users, + }); + } }); // 解密失败:最常见是历史消息(bot 加入前的消息,发送方不会共享旧密钥) diff --git a/src/core/matrix/types.ts b/src/core/matrix/types.ts index 41cdf76..1f0d376 100644 --- a/src/core/matrix/types.ts +++ b/src/core/matrix/types.ts @@ -1,10 +1,11 @@ -import { InboundMessage, MemberEvent } from '../command/types'; +import { InboundMessage, MemberEvent, PowerLevelEvent } from '../command/types'; /** bot 与 Matrix 交互的统一出站能力(BotContext 内部依赖它)。 */ export interface MatrixTransport { readonly account: string; send(roomId: string, text: string, replyToEventId?: string): Promise; kick(roomId: string, userId: string, reason?: string): Promise; + invite(roomId: string, userId: string): Promise; getMemberCount(roomId: string): Promise; getJoinedMembers(roomId: string): Promise; /** 读取用户在房间内的 power level(读不到或无权限时返回 0)。 */ @@ -15,4 +16,5 @@ export interface MatrixTransport { export interface MatrixEventSink { onMessage(msg: InboundMessage): Promise; onMember(ev: MemberEvent): Promise; + onPowerLevel(ev: PowerLevelEvent): Promise; }