feat(onebot): built-in #sl status command (toggleable, non-plugin)

A hardcoded `#sl` status command — deliberately NOT a plugin system.
Matched at the instance dispatch choke point: a pure-text message equal
to `#sl` (exact, trimmed, case-insensitive — no startsWith) replies with
SnowLuma version / platform / uptime in the same conversation.

- Anyone can trigger; the per-UIN `statusCommand.enabled` toggle is the
  only gate (default on). Per-conversation cooldown (default 5s,
  configurable) prevents flood/风控 from repeated triggers.
- `swallow` (default false / pass-through): when set, a matched `#sl` is
  not forwarded to downstream adapters — still cached, logged, replied.
- Config on OneBotConfig.statusCommand (per-UIN): defaulted + clamped in
  config.ts, mirrored/normalized in the WebUI; edits hot-reload via the
  shared instance context.
- WebUI: a "内置命令" section in the 通用设置 tab (enable / swallow /
  cooldown). Node enable toggle extracted into a shared ui/ToggleSwitch.

Pure matcher / cooldown / uptime / text helpers live in
modules/status-command with unit tests; config defaults + clamp covered.
This commit is contained in:
DrSmoothl committed 2026-06-01 14:58:13 +08:00
1 parent 0d63bf7415
commit 003e8c2deb
11 files changed
+434 -32

No files matched your search

+35 -1
View File
@@ -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<T extends { name: string }>(
+53
View File
@@ -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<string, number>();
private disposeEventPipeline: (() => void) | null = null;
private readonly pids = new Set<number>();
@@ -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<void> {
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,
@@ -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}秒`;
}
+18
View File
@@ -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 {