diff --git a/packages/onebot/src/config.ts b/packages/onebot/src/config.ts index 828393b2..ae69115a 100644 --- a/packages/onebot/src/config.ts +++ b/packages/onebot/src/config.ts @@ -9,6 +9,7 @@ import type { MessageFormat, OneBotConfig, OneBotNetworks, + StatusCommandConfig, WsClientNetwork, WsRole, WsServerNetwork, @@ -20,6 +21,14 @@ const CONFIG_DIR = 'config'; const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json'); const DEFAULT_ACCESS_TOKEN_BYTES = 32; +const DEFAULT_STATUS_COMMAND: StatusCommandConfig = { enabled: true, swallow: false, cooldownSeconds: 5 }; +/** Upper bound on the `#sl` reply cooldown — a year is effectively "off but sane". */ +const STATUS_COMMAND_COOLDOWN_MAX = 31_536_000; + +function makeDefaultStatusCommand(): StatusCommandConfig { + return { ...DEFAULT_STATUS_COMMAND }; +} + export function makeDefaultOneBotConfig(): OneBotConfig { return { networks: { @@ -46,6 +55,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig { wsClients: [], }, musicSignUrl: '', + statusCommand: makeDefaultStatusCommand(), }; } @@ -98,6 +108,11 @@ function toJsonObject(config: OneBotConfig): JsonObject { wsClients: nets.wsClients.map(wsClientToJson), }, musicSignUrl: config.musicSignUrl ?? '', + statusCommand: { + enabled: config.statusCommand.enabled, + swallow: config.statusCommand.swallow, + cooldownSeconds: config.statusCommand.cooldownSeconds, + }, }; } @@ -181,7 +196,26 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig { } const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients }; - return { networks, musicSignUrl }; + return { networks, musicSignUrl, statusCommand: parseStatusCommand(sources) }; +} + +/** Last-write-wins merge of `statusCommand` across config sources, with + * defaults filled and the cooldown clamped to a sane non-negative range. */ +function parseStatusCommand(sources: JsonObject[]): StatusCommandConfig { + const out = makeDefaultStatusCommand(); + for (const src of sources) { + const raw = src.statusCommand; + if (!isObject(raw)) continue; + if (typeof raw.enabled === 'boolean') out.enabled = raw.enabled; + if (typeof raw.swallow === 'boolean') out.swallow = raw.swallow; + if (raw.cooldownSeconds !== undefined) { + out.cooldownSeconds = Math.min( + STATUS_COMMAND_COOLDOWN_MAX, + asNumber(raw.cooldownSeconds, DEFAULT_STATUS_COMMAND.cooldownSeconds), + ); + } + } + return out; } function collectByName( diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 2b6eedee..95c15169 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -12,6 +12,8 @@ import { MediaStore } from './media-store'; import { MediaUrlResolver } from './media-url-resolver'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id'; import { MessageStore } from './message-store'; +import { sendGroupMessage, sendPrivateMessage } from './modules/message-actions'; +import { buildStatusText, matchesStatusCommand, statusCooldownElapsed } from './modules/status-command'; import { HttpPostAdapter, HttpServerAdapter, @@ -37,6 +39,11 @@ export class OneBotInstance { private readonly reactionStore: ReactionStore; private readonly networkManager: OneBotNetworkManager; private readonly rkeyCache: RKeyCache; + private readonly ctx: OneBotInstanceContext; + /** Process-uptime baseline for the `#sl` status reply. */ + private readonly startedAt = Date.now(); + /** Per-conversation last-reply timestamp for the `#sl` cooldown. */ + private readonly statusCommandCooldown = new Map(); private disposeEventPipeline: (() => void) | null = null; private readonly pids = new Set(); @@ -90,6 +97,7 @@ export class OneBotInstance { cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta), dispatchEvent: (event) => this.dispatchEvent(event), }; + this.ctx = ctx; this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined); this.networkManager = new OneBotNetworkManager(); @@ -104,6 +112,9 @@ export class OneBotInstance { } reloadConfig(config: OneBotConfig): void { + // Keep the shared context's config in sync so live readers (e.g. the + // `#sl` handler reading `statusCommand`) pick up edits without a restart. + this.ctx.config = config; void this.applyConfigDiff(config).catch((err) => { this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); }); @@ -145,11 +156,53 @@ export class OneBotInstance { private dispatchEvent(event: JsonObject): void { this.cacheMessageEvent(event); this.logReceivedMessage(event); + // Built-in `#sl`: always cache + log first (a swallowed `#sl` is still + // observable locally); only forwarding to downstream adapters is gated. + if (this.handleStatusCommand(event)) return; void this.networkManager.emitEvent(event).catch((err) => { this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); }); } + /** + * Built-in `#sl` status command. Returns `true` when the event matched AND + * `swallow` is configured — the caller then skips `emitEvent` so downstream + * adapters never see it. The reply itself is fired async and rate-limited + * per conversation; matching and replying are independent of swallowing. + */ + private handleStatusCommand(event: JsonObject): boolean { + const cfg = this.ctx.config.statusCommand; + if (!cfg.enabled) return false; + const postType = event.post_type; + if (postType !== 'message' && postType !== 'message_sent') return false; + if (!matchesStatusCommand(event.message)) return false; + + const isGroup = event.message_type === 'group'; + const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id); + if (sessionId === 0) return cfg.swallow; + + const key = `${isGroup ? 'g' : 'p'}:${sessionId}`; + const now = Date.now(); + if (statusCooldownElapsed(this.statusCommandCooldown.get(key), now, cfg.cooldownSeconds)) { + this.statusCommandCooldown.set(key, now); + void this.replyStatus(isGroup, sessionId).catch((err) => { + this.log.warn('status command reply failed: %s', err instanceof Error ? err.message : String(err)); + }); + } + return cfg.swallow; + } + + private async replyStatus(isGroup: boolean, sessionId: number): Promise { + const text = buildStatusText({ + version: typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev', + platform: process.platform, + arch: process.arch, + uptimeMs: Date.now() - this.startedAt, + }); + if (isGroup) await sendGroupMessage(this.ctx, sessionId, text, true); + else await sendPrivateMessage(this.ctx, sessionId, text, true); + } + private buildNetworkContext(): NetworkAdapterContext { return { uin: this.uin, diff --git a/packages/onebot/src/modules/status-command.ts b/packages/onebot/src/modules/status-command.ts new file mode 100644 index 00000000..c51ef1b6 --- /dev/null +++ b/packages/onebot/src/modules/status-command.ts @@ -0,0 +1,82 @@ +import type { JsonObject, JsonValue } from '../types'; + +/** + * Hardcoded trigger for the built-in status command — exact match, + * case-insensitive, after trimming. Intentionally NOT configurable: the + * `statusCommand.enabled` toggle is the only knob (the gate is on/off, not + * the word). + */ +export const STATUS_COMMAND_TRIGGER = '#sl'; + +/** + * True iff `message` is exactly the trigger: a single `text` segment (or a + * bare string for string-format adapters) whose trimmed, lowercased content + * equals {@link STATUS_COMMAND_TRIGGER}. + * + * Reads the segment array rather than `raw_message` to avoid CQ-encoding + * ambiguity, and rejects mixed-segment messages (`#sl` + image/at/reply) so + * only a pure `#sl` triggers — no `startsWith`, so `#slogan` never matches. + */ +export function matchesStatusCommand(message: JsonValue | undefined): boolean { + if (typeof message === 'string') { + return normalize(message) === STATUS_COMMAND_TRIGGER; + } + if (!Array.isArray(message) || message.length !== 1) return false; + const seg = message[0]; + if (!isObject(seg) || seg.type !== 'text') return false; + const data = isObject(seg.data) ? seg.data : null; + const text = data && typeof data.text === 'string' ? data.text : ''; + return normalize(text) === STATUS_COMMAND_TRIGGER; +} + +function normalize(s: string): string { + return s.trim().toLowerCase(); +} + +function isObject(value: unknown): value is JsonObject { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** + * Whether a reply is allowed now given the last reply time + cooldown. + * `cooldownSeconds <= 0` disables the cooldown entirely. + */ +export function statusCooldownElapsed( + lastRepliedAtMs: number | undefined, + nowMs: number, + cooldownSeconds: number, +): boolean { + if (lastRepliedAtMs === undefined) return true; + if (cooldownSeconds <= 0) return true; + return nowMs - lastRepliedAtMs >= cooldownSeconds * 1000; +} + +export interface StatusInfo { + version: string; + platform: string; + arch: string; + uptimeMs: number; +} + +/** Render the public-safe `#sl` reply: version + platform/arch + uptime. */ +export function buildStatusText(info: StatusInfo): string { + return [ + 'SnowLuma 状态', + `版本: ${info.version}`, + `平台: ${info.platform}-${info.arch}`, + `运行时长: ${formatUptime(info.uptimeMs)}`, + ].join('\n'); +} + +/** Human-readable uptime (zh-CN), dropping leading zero units. */ +export function formatUptime(ms: number): string { + const totalSec = Math.max(0, Math.floor(ms / 1000)); + const days = Math.floor(totalSec / 86400); + const hours = Math.floor((totalSec % 86400) / 3600); + const minutes = Math.floor((totalSec % 3600) / 60); + const seconds = totalSec % 60; + if (days > 0) return `${days}天 ${hours}小时 ${minutes}分钟`; + if (hours > 0) return `${hours}小时 ${minutes}分钟`; + if (minutes > 0) return `${minutes}分钟 ${seconds}秒`; + return `${seconds}秒`; +} diff --git a/packages/onebot/src/types.ts b/packages/onebot/src/types.ts index 4235978b..e793bb02 100644 --- a/packages/onebot/src/types.ts +++ b/packages/onebot/src/types.ts @@ -63,11 +63,29 @@ export interface OneBotNetworks { wsClients: WsClientNetwork[]; } +/** + * Built-in `#sl` status command. The trigger word is hardcoded (`#sl`, + * exact match, case-insensitive); only these toggles are configurable. + */ +export interface StatusCommandConfig { + /** Master on/off. Default `true` — built-in, but freely disableable. */ + enabled: boolean; + /** + * When `true`, a matched `#sl` is NOT forwarded to downstream adapters + * (it is still cached, logged, and replied to). Default `false` (pass-through). + */ + swallow: boolean; + /** Per-conversation reply cooldown in seconds. `0` disables it. Default `5`. */ + cooldownSeconds: number; +} + /** Per-UIN OneBot configuration. */ export interface OneBotConfig { networks: OneBotNetworks; /** Music card signing service URL (optional). */ musicSignUrl?: string; + /** Built-in `#sl` status command settings. Always present after normalization. */ + statusCommand: StatusCommandConfig; } export interface MessageMeta { diff --git a/packages/onebot/tests/config.test.ts b/packages/onebot/tests/config.test.ts index 5bd9128c..5b8c12d8 100644 --- a/packages/onebot/tests/config.test.ts +++ b/packages/onebot/tests/config.test.ts @@ -25,6 +25,7 @@ describe('makeDefaultOneBotConfig', () => { expect(config.networks.wsServers[0].reportSelfMessage).toBe(false); expect(config.networks.wsClients).toEqual([]); expect(config.musicSignUrl).toBe(''); + expect(config.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5 }); }); }); @@ -57,6 +58,26 @@ describe('loadOneBotConfig', () => { // Legacy keys must not appear in the persisted file. expect(onDisk.httpServers).toBeUndefined(); expect(onDisk.wsServers).toBeUndefined(); + // statusCommand is materialised with defaults on a fresh install. + expect(onDisk.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5 }); + }); + + it('fills statusCommand defaults and clamps a negative cooldown', () => { + const uin = '10042'; + const dir = path.join(tempDir, 'config'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(dir, `onebot_${uin}.json`), + JSON.stringify({ + networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, + statusCommand: { swallow: true, cooldownSeconds: -3 }, + }), + ); + + const config = loadOneBotConfig(uin); + expect(config.statusCommand.enabled).toBe(true); // default filled (absent in file) + expect(config.statusCommand.swallow).toBe(true); // taken from file + expect(config.statusCommand.cooldownSeconds).toBe(0); // negative clamped to 0 }); it('migrates legacy per-type arrays into networks groups', () => { diff --git a/packages/onebot/tests/status-command.test.ts b/packages/onebot/tests/status-command.test.ts new file mode 100644 index 00000000..1a165374 --- /dev/null +++ b/packages/onebot/tests/status-command.test.ts @@ -0,0 +1,103 @@ +import { describe, it, expect } from 'vitest'; +import { + STATUS_COMMAND_TRIGGER, + buildStatusText, + formatUptime, + matchesStatusCommand, + statusCooldownElapsed, +} from '../src/modules/status-command'; +import type { JsonValue } from '../src/types'; + +function textSeg(text: string): JsonValue { + return [{ type: 'text', data: { text } }] as unknown as JsonValue; +} + +describe('matchesStatusCommand', () => { + it('matches a single text segment equal to the trigger', () => { + expect(matchesStatusCommand(textSeg('#sl'))).toBe(true); + }); + + it('is case-insensitive and trims surrounding whitespace', () => { + expect(matchesStatusCommand(textSeg('#SL'))).toBe(true); + expect(matchesStatusCommand(textSeg(' #Sl '))).toBe(true); + }); + + it('matches a bare string (string-format adapters)', () => { + expect(matchesStatusCommand('#sl' as unknown as JsonValue)).toBe(true); + expect(matchesStatusCommand(' #SL ' as unknown as JsonValue)).toBe(true); + }); + + it('does NOT match as a prefix — only exact', () => { + expect(matchesStatusCommand(textSeg('#slogan'))).toBe(false); + expect(matchesStatusCommand(textSeg('#sl help'))).toBe(false); + expect(matchesStatusCommand(textSeg('你好 #sl'))).toBe(false); + }); + + it('rejects mixed-segment messages', () => { + const mixed = [ + { type: 'text', data: { text: '#sl' } }, + { type: 'image', data: { file: 'x.png' } }, + ] as unknown as JsonValue; + expect(matchesStatusCommand(mixed)).toBe(false); + }); + + it('rejects non-text leading segments and empty/garbage input', () => { + expect(matchesStatusCommand([{ type: 'at', data: { qq: '1' } }] as unknown as JsonValue)).toBe(false); + expect(matchesStatusCommand([] as unknown as JsonValue)).toBe(false); + expect(matchesStatusCommand(undefined)).toBe(false); + expect(matchesStatusCommand(123 as unknown as JsonValue)).toBe(false); + }); + + it('exposes the hardcoded trigger', () => { + expect(STATUS_COMMAND_TRIGGER).toBe('#sl'); + }); +}); + +describe('statusCooldownElapsed', () => { + it('allows the first reply (no prior timestamp)', () => { + expect(statusCooldownElapsed(undefined, 1_000, 5)).toBe(true); + }); + + it('ignores the cooldown when set to 0 or negative', () => { + expect(statusCooldownElapsed(1_000, 1_500, 0)).toBe(true); + expect(statusCooldownElapsed(1_000, 1_000, -1)).toBe(true); + }); + + it('blocks within the window and allows once elapsed', () => { + const last = 10_000; + expect(statusCooldownElapsed(last, last + 4_999, 5)).toBe(false); + expect(statusCooldownElapsed(last, last + 5_000, 5)).toBe(true); + expect(statusCooldownElapsed(last, last + 9_999, 5)).toBe(true); + }); +}); + +describe('formatUptime', () => { + it('drops leading zero units', () => { + expect(formatUptime(0)).toBe('0秒'); + expect(formatUptime(45_000)).toBe('45秒'); + expect(formatUptime(90_000)).toBe('1分钟 30秒'); + expect(formatUptime(3_600_000)).toBe('1小时 0分钟'); + expect(formatUptime((26 * 3600 + 12 * 60) * 1000)).toBe('1天 2小时 12分钟'); + }); + + it('never goes negative', () => { + expect(formatUptime(-5_000)).toBe('0秒'); + }); +}); + +describe('buildStatusText', () => { + it('renders version / platform / uptime, no leaked uin or topology', () => { + const text = buildStatusText({ + version: '1.9.3-node', + platform: 'linux', + arch: 'x64', + uptimeMs: 90_000, + }); + expect(text).toContain('SnowLuma'); + expect(text).toContain('版本: 1.9.3-node'); + expect(text).toContain('平台: linux-x64'); + expect(text).toContain('运行时长: 1分钟 30秒'); + // public-safe: must not echo a uin or connection count + expect(text).not.toMatch(/uin|连接|adapter/i); + }); +}); diff --git a/packages/webui/src/components/config/general-settings-tab.tsx b/packages/webui/src/components/config/general-settings-tab.tsx index 3ed5a3cc..93290374 100644 --- a/packages/webui/src/components/config/general-settings-tab.tsx +++ b/packages/webui/src/components/config/general-settings-tab.tsx @@ -1,10 +1,12 @@ // "通用设置" tab — fields that apply to the whole OneBotInstance rather -// than any specific adapter. Currently just the music-sign service URL, -// but the layout has room for additional cross-cutting toggles. +// than any specific adapter: the music-sign service URL and the built-in +// `#sl` status command. Edits here mark the config dirty and are persisted +// via the page's explicit top-right 保存 (a continuously-edited surface). import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; -import type { OneBotConfig } from '@/types'; +import { ToggleSwitch } from '@/components/ui/toggle-switch'; +import type { OneBotConfig, StatusCommandConfig } from '@/types'; interface GeneralSettingsTabProps { config: OneBotConfig; @@ -12,6 +14,10 @@ interface GeneralSettingsTabProps { } export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps) { + const sc = config.statusCommand; + const setStatusCommand = (patch: Partial) => + onChange({ ...config, statusCommand: { ...sc, ...patch } }); + return (
@@ -26,6 +32,57 @@ export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps 用于音乐分享卡片签名。未配置时音乐相关消息段会回落为普通文本。

+ +
+
+
+ +

+ 收到纯文本 #sl 时回复 SnowLuma 版本 / 平台 / 运行时长。任何人可触发,关闭后完全不响应。 +

+
+ setStatusCommand({ enabled: v })} + ariaLabel="启用 #sl 状态命令" + /> +
+ +
+
+ +

+ 开启后,命中的 #sl 不再投递给已连接的 Bot(仍会回复并本地记录)。默认关闭即透传。 +

+
+ setStatusCommand({ swallow: v })} + ariaLabel="吞掉 #sl 不转发给下游" + disabled={!sc.enabled} + /> +
+ +
+ + { + const n = Math.trunc(Number(e.target.value)); + setStatusCommand({ cooldownSeconds: Number.isFinite(n) && n >= 0 ? n : 0 }); + }} + /> +

+ 同一会话在该秒数内重复 #sl 不再回复,防刷屏。0 表示不限制。 +

+
+
); } diff --git a/packages/webui/src/components/config/node-summary-card.tsx b/packages/webui/src/components/config/node-summary-card.tsx index 85eba824..86d28243 100644 --- a/packages/webui/src/components/config/node-summary-card.tsx +++ b/packages/webui/src/components/config/node-summary-card.tsx @@ -7,6 +7,7 @@ import { motion } from 'motion/react'; import { Pencil, Trash2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; +import { ToggleSwitch } from '@/components/ui/toggle-switch'; import { cn } from '@/lib/utils'; import type { AdapterCommon } from './defaults'; import type { AdapterStatus } from '@/types'; @@ -126,30 +127,3 @@ export function NodeSummaryCard({ ); } -interface ToggleSwitchProps { - value: boolean; - onChange: (v: boolean) => void; - ariaLabel: string; -} - -function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) { - return ( - - ); -} diff --git a/packages/webui/src/components/ui/toggle-switch.tsx b/packages/webui/src/components/ui/toggle-switch.tsx new file mode 100644 index 00000000..703b73ae --- /dev/null +++ b/packages/webui/src/components/ui/toggle-switch.tsx @@ -0,0 +1,35 @@ +import { motion } from 'motion/react'; +import { cn } from '@/lib/utils'; + +interface ToggleSwitchProps { + value: boolean; + onChange: (v: boolean) => void; + ariaLabel: string; + disabled?: boolean; +} + +/** Small animated on/off switch (`role="switch"`). Shared across the config + * surfaces — node enable toggle, built-in command toggles, etc. */ +export function ToggleSwitch({ value, onChange, ariaLabel, disabled }: ToggleSwitchProps) { + return ( + + ); +} diff --git a/packages/webui/src/lib/onebot-config.ts b/packages/webui/src/lib/onebot-config.ts index 91db11fb..e12f8229 100644 --- a/packages/webui/src/lib/onebot-config.ts +++ b/packages/webui/src/lib/onebot-config.ts @@ -1,4 +1,20 @@ -import type { MessageFormat, OneBotConfig } from '@/types'; +import type { MessageFormat, OneBotConfig, StatusCommandConfig } from '@/types'; + +const DEFAULT_STATUS_COMMAND: StatusCommandConfig = { enabled: true, swallow: false, cooldownSeconds: 5 }; + +/** Fill the `statusCommand` block with defaults when the backend omits or + * partially supplies it (older configs predate the feature). */ +function normalizeStatusCommand(raw: unknown): StatusCommandConfig { + const src = (raw ?? {}) as Record; + return { + enabled: typeof src.enabled === 'boolean' ? src.enabled : DEFAULT_STATUS_COMMAND.enabled, + swallow: typeof src.swallow === 'boolean' ? src.swallow : DEFAULT_STATUS_COMMAND.swallow, + cooldownSeconds: + typeof src.cooldownSeconds === 'number' && Number.isFinite(src.cooldownSeconds) && src.cooldownSeconds >= 0 + ? Math.trunc(src.cooldownSeconds) + : DEFAULT_STATUS_COMMAND.cooldownSeconds, + }; +} /** * Anti-corruption layer for the per-UIN config payload. Older backends emit @@ -30,5 +46,6 @@ export function normalizeOneBotConfig(raw: unknown): OneBotConfig { wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'], }, musicSignUrl: typeof cfg.musicSignUrl === 'string' ? cfg.musicSignUrl : undefined, + statusCommand: normalizeStatusCommand(cfg.statusCommand), }; } diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index ba814615..58efeef2 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -77,9 +77,17 @@ export interface OneBotNetworks { wsClients: WsClientNetwork[]; } +/** Built-in `#sl` status command settings (trigger word is hardcoded). */ +export interface StatusCommandConfig { + enabled: boolean; + swallow: boolean; + cooldownSeconds: number; +} + export interface OneBotConfig { networks: OneBotNetworks; musicSignUrl?: string; + statusCommand: StatusCommandConfig; } export type NetworkKind = keyof OneBotNetworks;