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:
11 files changed
+434
-32
No files matched your search
@@ -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 }>(
|
||||
|
||||
@@ -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}秒`;
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<StatusCommandConfig>) =>
|
||||
onChange({ ...config, statusCommand: { ...sc, ...patch } });
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5 rounded-lg border bg-card/40 p-4">
|
||||
@@ -26,6 +32,57 @@ export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps
|
||||
用于音乐分享卡片签名。未配置时音乐相关消息段会回落为普通文本。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 rounded-lg border bg-card/40 p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<Label>
|
||||
内置状态命令 <code className="font-mono text-xs">#sl</code>
|
||||
</Label>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
|
||||
收到纯文本 <code className="font-mono">#sl</code> 时回复 SnowLuma 版本 / 平台 / 运行时长。任何人可触发,关闭后完全不响应。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={sc.enabled}
|
||||
onChange={(v) => setStatusCommand({ enabled: v })}
|
||||
ariaLabel="启用 #sl 状态命令"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start justify-between gap-3 border-t pt-3">
|
||||
<div className="min-w-0">
|
||||
<Label className={sc.enabled ? undefined : 'text-muted-foreground'}>不转发给下游(swallow)</Label>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
|
||||
开启后,命中的 <code className="font-mono">#sl</code> 不再投递给已连接的 Bot(仍会回复并本地记录)。默认关闭即透传。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={sc.swallow}
|
||||
onChange={(v) => setStatusCommand({ swallow: v })}
|
||||
ariaLabel="吞掉 #sl 不转发给下游"
|
||||
disabled={!sc.enabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5 border-t pt-3">
|
||||
<Label className={sc.enabled ? undefined : 'text-muted-foreground'}>回复冷却(秒)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
className="w-32 tabular-nums"
|
||||
value={sc.cooldownSeconds}
|
||||
disabled={!sc.enabled}
|
||||
onChange={(e) => {
|
||||
const n = Math.trunc(Number(e.target.value));
|
||||
setStatusCommand({ cooldownSeconds: Number.isFinite(n) && n >= 0 ? n : 0 });
|
||||
}}
|
||||
/>
|
||||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||||
同一会话在该秒数内重复 <code className="font-mono">#sl</code> 不再回复,防刷屏。<code className="font-mono">0</code> 表示不限制。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<T extends AdapterCommon>({
|
||||
);
|
||||
}
|
||||
|
||||
interface ToggleSwitchProps {
|
||||
value: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={value ? 'true' : 'false'}
|
||||
aria-label={ariaLabel}
|
||||
onClick={() => onChange(!value)}
|
||||
className={cn(
|
||||
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border transition-colors',
|
||||
value ? 'border-primary bg-primary' : 'border-input bg-muted',
|
||||
)}
|
||||
>
|
||||
<motion.span
|
||||
className="inline-block size-4 rounded-full bg-background shadow-sm"
|
||||
animate={{ x: value ? 22 : 4 }}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={value ? 'true' : 'false'}
|
||||
aria-label={ariaLabel}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(!value)}
|
||||
className={cn(
|
||||
'relative inline-flex h-6 w-11 shrink-0 items-center rounded-full border transition-colors',
|
||||
disabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer',
|
||||
value ? 'border-primary bg-primary' : 'border-input bg-muted',
|
||||
)}
|
||||
>
|
||||
<motion.span
|
||||
className="inline-block size-4 rounded-full bg-background shadow-sm"
|
||||
animate={{ x: value ? 22 : 4 }}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -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<string, unknown>;
|
||||
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),
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user