diff --git a/packages/onebot/src/action-docs.ts b/packages/onebot/src/action-docs.ts new file mode 100644 index 00000000..0d89e09b --- /dev/null +++ b/packages/onebot/src/action-docs.ts @@ -0,0 +1,80 @@ +// action-docs — self-generated OneBot API docs (D4). +// +// Walks `ActionSpec.describe()` over every declarative action and renders a +// structured doc list + a Markdown view. The metadata is carried on the same +// values that drive runtime validation, so docs cannot drift from behavior. +// +// Coverage note: the ~15 genuinely irregular actions in `actions/extended.ts` +// that remain on the legacy `h.registerAction(...)` path are NOT ActionSpecs +// and so do not appear here — that is the documented irregular tail. +// +// The serving SURFACE (WebUI panel / OpenAPI export / static markdown) is a +// deferred product decision; this module produces format-agnostic data plus a +// Markdown default. Point any renderer at `collectActionDocs()`. + +import type { ActionDoc, ActionSpec, Field } from './action-kit'; +import { actions as infoActions } from './actions/info'; +import { actions as messageActions } from './actions/message'; +import { actions as friendActions } from './actions/friend'; +import { actions as groupInfoActions } from './actions/group-info'; +import { actions as groupAdminActions } from './actions/group-admin'; +import { actions as groupFileActions } from './actions/group-file'; +import { actions as requestActions } from './actions/request'; +import { actions as extendedActions } from './actions/extended'; +import { actions as groupAlbumActions } from './actions/group-album'; + +type AnySpec = ActionSpec>>; + +const ALL_SPECS: readonly AnySpec[] = [ + ...infoActions, + ...messageActions, + ...friendActions, + ...groupInfoActions, + ...groupAdminActions, + ...groupFileActions, + ...requestActions, + ...extendedActions, + ...groupAlbumActions, +]; + +/** Every declarative action's doc, sorted by name. */ +export function collectActionDocs(specs: readonly AnySpec[] = ALL_SPECS): ActionDoc[] { + return specs.map((s) => s.describe()).sort((a, b) => a.name.localeCompare(b.name)); +} + +function paramRow(p: ActionDoc['params'][number]): string { + const type = p.values ? p.values.map((v) => JSON.stringify(v)).join(' \\| ') : p.type; + const required = p.required ? '✓' : '–'; + const def = !p.required && p.default !== undefined ? `\`${JSON.stringify(p.default)}\`` : ''; + return `| \`${p.name}\` | ${type} | ${required} | ${def} | ${p.desc ?? ''} |`; +} + +function renderAction(doc: ActionDoc): string { + const lines: string[] = []; + const alias = doc.aliases.length ? ` _(别名: ${doc.aliases.map((a) => `\`${a}\``).join(', ')})_` : ''; + lines.push(`### \`${doc.name}\`${alias}`); + if (doc.summary) lines.push('', doc.summary); + if (doc.params.length) { + lines.push('', '| 参数 | 类型 | 必填 | 默认 | 说明 |', '| --- | --- | --- | --- | --- |'); + for (const p of doc.params) lines.push(paramRow(p)); + } else { + lines.push('', '_无参数_'); + } + if (doc.invariants.length) lines.push('', `**约束:** ${doc.invariants.map((i) => `\`${i}\``).join(';')}`); + if (doc.returns) lines.push('', `**返回:** \`${doc.returns}\``); + return lines.join('\n'); +} + +/** Render the full Markdown doc. */ +export function renderActionDocsMarkdown(docs: readonly ActionDoc[] = collectActionDocs()): string { + const header = [ + '# OneBot Actions', + '', + '> 由 `packages/onebot/src/action-docs.ts` 从各 `ActionSpec.describe()` 自动生成,请勿手改。', + '> 仅覆盖声明式 action;`extended.ts` 中少量走 legacy `registerAction` 的不规则 action 不在此列。', + '', + `共 ${docs.length} 个声明式 action。`, + '', + ]; + return header.concat(docs.map(renderAction)).join('\n') + '\n'; +} diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts new file mode 100644 index 00000000..644686a0 --- /dev/null +++ b/packages/onebot/src/action-kit.ts @@ -0,0 +1,418 @@ +// action-kit — declarative OneBot Action definitions. +// +// One Action declares its param contract once (a record of `Field`s + optional +// cross-field `rules`) and a `run` handler. The kit owns param coercion + +// validation + the `BAD_REQUEST` shaping (naming the offending field) + +// doc metadata. The handler receives typed, already-validated params. +// +// Narrow seam (ADR-0006): `ApiHandler` keeps dispatch / try-catch / response +// wrapping. `defineAction(...).register(h, ctx)` ultimately registers a plain +// `(params) => Promise` via `ApiHandler.registerAction`, exactly +// like the legacy style — so old and new actions coexist during migration. +// +// Zero runtime npm deps (ADR-0004). Type inference via `InferParams` — no +// hand-written param interface. Param contract is intentionally a second +// definition from the SDK's client-side types (ADR-0005). +// +// Guard-rail (ADR-0007): the built-in coercers below are strict. Do NOT add a +// lenient `union`/`refine` escape that re-introduces the silent coercion this +// module exists to remove. + +import { RETCODE, failedResponse } from './types'; +import type { ApiResponse, JsonObject, JsonValue } from './types'; +import type { ApiActionContext, ApiHandler } from './api-handler'; + +// ─────────────────────────── result currency ─────────────────────────── + +export type Ok = { ok: true; value: T }; +/** `field` is the offending param ('' for a cross-field rule). */ +export type Err = { ok: false; field: string; reason: string }; +export type CoerceResult = Ok | Err; + +const ok = (value: T): Ok => ({ ok: true, value }); +const err = (field: string, reason: string): Err => ({ ok: false, field, reason }); + +/** Only an absent key produces MISSING — this is what lets a present `0` / + * `''` / `false` be distinguished from "not provided". */ +const MISSING = Symbol('missing'); +type Raw = JsonValue | typeof MISSING; + +// ─────────────────────────── Field (param coercer) ─────────────────────────── + +export interface FieldDoc { + type: string; + required: boolean; + default?: JsonValue; + desc?: string; + values?: readonly (string | number)[]; +} + +export interface Field { + readonly doc: FieldDoc; + /** Coerce the raw value at this field's key (MISSING when the key is absent). */ + coerce(raw: Raw, field: string): CoerceResult; + /** Absent ⇒ value is `undefined`; a present value still must coerce. */ + optional(): Field; + /** Absent ⇒ `value`; a present value still must coerce (so `"abc"` for a + * numeric field is an error, not a silent fallback). */ + default(value: T): Field; + describe(text: string): Field; +} + +/** Core coerces a PRESENT value (never MISSING). Presence policy is applied + * by the wrapping Field. */ +type Core = (raw: JsonValue, field: string) => CoerceResult; + +class FieldImpl implements Field { + constructor( + private readonly core: Core, + readonly doc: FieldDoc, + ) {} + + coerce(raw: Raw, field: string): CoerceResult { + if (raw === MISSING) { + if (this.doc.required) return err(field, 'is required'); + return ok(this.doc.default as T); // default value, or undefined when optional + } + return this.core(raw, field); + } + + optional(): Field { + return new FieldImpl(this.core as Core, { + ...this.doc, + required: false, + default: undefined, + }); + } + + default(value: T): Field { + return new FieldImpl(this.core, { ...this.doc, required: false, default: value as JsonValue }); + } + + describe(text: string): Field { + return new FieldImpl(this.core, { ...this.doc, desc: text }); + } +} + +// ─────────────────────────── coercer vocabulary `f` ─────────────────────────── + +interface IntOpts { min?: number; max?: number; nonZero?: boolean } + +/** Accept a number or numeric string, truncate to integer (matches the legacy + * `asNumber`), then apply bounds. Non-numeric / blank ⇒ Err. */ +function intCore(typeName: string, opts: IntOpts): Core { + return (raw, field) => { + let n: number; + if (typeof raw === 'number' && Number.isFinite(raw)) n = Math.trunc(raw); + else if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) n = Math.trunc(Number(raw)); + else return err(field, `expected ${typeName}`); + if (opts.nonZero && n === 0) return err(field, 'must not be 0'); + if (opts.min !== undefined && n < opts.min) return err(field, `must be >= ${opts.min}`); + if (opts.max !== undefined && n > opts.max) return err(field, `must be <= ${opts.max}`); + return ok(n); + }; +} + +interface StrOpts { allowEmpty?: boolean; maxLen?: number } + +function arrayField(el: Field, mustBeNonEmpty: boolean): Field & { nonEmpty(): Field } { + const core: Core = (raw, field) => { + if (!Array.isArray(raw)) return err(field, 'expected an array'); + const out: E[] = []; + for (let i = 0; i < raw.length; i++) { + const r = el.coerce(raw[i] as JsonValue, `${field}[${i}]`); + if (!r.ok) return r; + out.push(r.value); + } + if (mustBeNonEmpty && out.length === 0) return err(field, 'must not be empty'); + return ok(out); + }; + const base = new FieldImpl(core, { type: `${el.doc.type}[]`, required: true }); + return Object.assign(base, { nonEmpty: () => arrayField(el, true) }); +} + +export const f = { + /** Positive integer (>0): group_id / user_id / message_id. */ + uint(): Field { + return new FieldImpl(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true }); + }, + /** Integer with optional bounds; allows 0 / negatives unless bounded. + * e.g. a duration where 0 is meaningful: `f.int({ min: 0 })`. */ + int(opts: IntOpts = {}): Field { + return new FieldImpl(intCore('an integer', opts), { type: 'int', required: true }); + }, + /** OneBot message id: a non-zero integer. NEGATIVES ARE VALID (ids are a + * signed int32 hash) — do NOT use `uint()` for message_id. */ + messageId(): Field { + return new FieldImpl(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true }); + }, + /** Finite number (fractions allowed). */ + number(): Field { + return new FieldImpl((raw, field) => { + if (typeof raw === 'number' && Number.isFinite(raw)) return ok(raw); + if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) return ok(Number(raw)); + return err(field, 'expected a number'); + }, { type: 'number', required: true }); + }, + /** String. Numbers/booleans stringify (matches legacy `asString`). Empty + * allowed by default; `{ allowEmpty: false }` rejects ''. */ + string(opts: StrOpts = {}): Field { + return new FieldImpl((raw, field) => { + let s: string; + if (typeof raw === 'string') s = raw; + else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw); + else return err(field, 'expected a string'); + if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty'); + if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`); + return ok(s); + }, { type: 'string', required: true }); + }, + /** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */ + bool(): Field { + return new FieldImpl((raw, field) => { + if (typeof raw === 'boolean') return ok(raw); + if (typeof raw === 'number') return ok(raw !== 0); + if (typeof raw === 'string') { + const t = raw.trim().toLowerCase(); + if (t === 'true' || t === '1' || t === 'yes' || t === 'on') return ok(true); + if (t === 'false' || t === '0' || t === 'no' || t === 'off') return ok(false); + } + return err(field, 'expected a boolean'); + }, { type: 'bool', required: true }); + }, + /** OneBot message union: string | segment[] | object. A string that looks + * like a JSON array is parsed (matches legacy `asMessage`); otherwise the + * value passes through. Output stays `JsonValue` — downstream ctx.* accept it. */ + message(): Field { + return new FieldImpl((raw, _field) => { + if (typeof raw === 'string') { + const t = raw.trim(); + if (t.startsWith('[') && t.endsWith(']')) { + try { + const parsed: unknown = JSON.parse(t); + if (Array.isArray(parsed)) return ok(parsed as JsonValue); + } catch { + // fall through to literal text + } + } + } + return ok(raw); + }, { type: 'message', required: true }); + }, + /** Homogeneous array; `.nonEmpty()` rejects []. */ + array(el: Field): Field & { nonEmpty(): Field } { + return arrayField(el, false); + }, + /** Constrained literal set. */ + enum(...values: V): Field { + return new FieldImpl((raw, field) => { + if ((typeof raw === 'string' || typeof raw === 'number') && (values as readonly (string | number)[]).includes(raw)) { + return ok(raw as V[number]); + } + return err(field, `expected one of: ${values.join(', ')}`); + }, { type: 'enum', required: true, values }); + }, + /** Escape hatch — pass the raw value (or undefined) through, validate nothing. */ + raw(): Field { + return new FieldImpl((raw) => ok(raw), { type: 'raw', required: false, default: undefined }); + }, +}; + +// ─────────────────────────── type inference ─────────────────────────── + +type Spec = Record>; +type FieldType = F extends Field ? T : never; +/** Post-validation every key is present; optional/raw fields carry `undefined` + * in their value type. */ +export type InferParams = { [K in keyof S]: FieldType }; + +// ─────────────────────────── cross-field rules ─────────────────────────── + +export interface CrossFieldRule { + readonly doc: string; + check(params: Record): Err | null; +} + +type Key

= Extract; +type Group

= Key

| Key

[]; + +export interface RuleBuilders

{ + /** Exactly one group satisfied. A group is a key, or an array of keys that + * must ALL be present. e.g. `exactlyOneOf('message_id', ['group_id','user_id'])`. */ + exactlyOneOf(...groups: Group

[]): CrossFieldRule; + atLeastOneOf(...keys: Key

[]): CrossFieldRule; + requiredTogether(...keys: Key

[]): CrossFieldRule; + mutuallyExclusive(...keys: Key

[]): CrossFieldRule; + /** Arbitrary predicate; fails with `doc` as the reason. */ + rule(doc: string, ok: (p: P) => boolean): CrossFieldRule; +} + +const present = (p: Record, key: string): boolean => p[key] !== undefined; +const groupOk = (p: Record, g: string | string[]): boolean => + Array.isArray(g) ? g.every((k) => present(p, k)) : present(p, g); +const groupLabel = (g: string | string[]): string => (Array.isArray(g) ? `(${g.join('+')})` : g); + +const RULES: RuleBuilders> = { + exactlyOneOf(...groups) { + const doc = `exactly one of: ${groups.map(groupLabel).join(' | ')}`; + return { + doc, + check: (p) => (groups.filter((g) => groupOk(p, g)).length === 1 ? null : err('', doc)), + }; + }, + atLeastOneOf(...keys) { + const doc = `at least one of: ${keys.join(', ')}`; + return { doc, check: (p) => (keys.some((k) => present(p, k)) ? null : err('', doc)) }; + }, + requiredTogether(...keys) { + const doc = `all or none of: ${keys.join(', ')}`; + return { + doc, + check: (p) => { + const n = keys.filter((k) => present(p, k)).length; + return n === 0 || n === keys.length ? null : err('', doc); + }, + }; + }, + mutuallyExclusive(...keys) { + const doc = `at most one of: ${keys.join(', ')}`; + return { doc, check: (p) => (keys.filter((k) => present(p, k)).length <= 1 ? null : err('', doc)) }; + }, + rule(doc, okFn) { + return { doc, check: (p) => (okFn(p as never) ? null : err('', doc)) }; + }, +}; + +// ─────────────────────────── defineAction ─────────────────────────── + +export interface ParamDoc extends FieldDoc { + name: string; +} +export interface ActionDoc { + name: string; + aliases: string[]; + summary?: string; + returns?: string; + params: ParamDoc[]; + invariants: string[]; +} + +type Handler = (params: JsonObject) => Promise; + +export interface ActionSpec { + readonly names: string[]; + readonly params: S; + /** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */ + parse(raw: JsonObject): CoerceResult>; + /** Bind ctx and produce the `(params) => ApiResponse` for `registerAction`. */ + toHandler(ctx: ApiActionContext): Handler; + /** Doc metadata (D4); a renderer walks this. */ + describe(): ActionDoc; + register(h: ApiHandler, ctx: ApiActionContext): void; +} + +interface ActionDef { + name: string | readonly [string, ...string[]]; + summary?: string; + returns?: string; + params: S; + rules?: (r: RuleBuilders>) => readonly CrossFieldRule[]; + /** `raw` is the original untouched params — an escape hatch for the + * irregular tail (alias-key fallbacks, arbitrary nested objects). Declared + * fields in `p` remain the validated path; reach for `raw` only for keys + * the spec can't express. */ + run: (p: InferParams, ctx: ApiActionContext, raw: JsonObject) => Promise | ApiResponse; +} + +const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason); + +export function defineAction(def: ActionDef): ActionSpec { + const names = typeof def.name === 'string' ? [def.name] : [...def.name]; + const rules: readonly CrossFieldRule[] = def.rules + ? def.rules(RULES as unknown as RuleBuilders>) + : []; + + const parse = (raw: JsonObject): CoerceResult> => { + const out: Record = {}; + for (const key of Object.keys(def.params)) { + const field = def.params[key]; + const value = Object.prototype.hasOwnProperty.call(raw, key) ? (raw[key] as JsonValue) : MISSING; + const r = field.coerce(value, key); + if (!r.ok) return r; + out[key] = r.value; + } + for (const rule of rules) { + const e = rule.check(out); + if (e) return e; + } + return ok(out as InferParams); + }; + + const toHandler = (ctx: ApiActionContext): Handler => async (params: JsonObject) => { + const r = parse(params); + if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r)); + return def.run(r.value, ctx, params); + }; + + return { + names, + params: def.params, + parse, + toHandler, + describe: () => ({ + name: names[0], + aliases: names.slice(1), + summary: def.summary, + returns: def.returns, + params: Object.entries(def.params).map(([name, field]) => ({ name, ...field.doc })), + invariants: rules.map((rule) => rule.doc), + }), + register: (h, ctx) => { + const handler = toHandler(ctx); + for (const name of names) h.registerAction(name, handler); + }, + }; +} + +// ─────────────────────────── presets ─────────────────────────── +// `group_id` appears in 61/142 actions, `user_id` in 27 — these collapse the +// dominant shape. The injected fields are surfaced in `describe()` so docs +// list them even though the caller never typed them (ADR-0006 trade-off). + +type WithGroup = S & { group_id: Field }; +type WithGroupUser = S & { group_id: Field; user_id: Field }; + +interface PresetDef { + name: string | readonly [string, ...string[]]; + summary?: string; + returns?: string; + params?: S; + rules?: (r: RuleBuilders & Extra>) => readonly CrossFieldRule[]; + run: (p: InferParams & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise | ApiResponse; +} + +/** Pre-seeds `group_id` (uint, required). */ +export function groupAction(def: PresetDef): ActionSpec> { + const params = { group_id: f.uint().describe('群号'), ...(def.params ?? {}) } as WithGroup; + return defineAction({ ...def, params } as unknown as ActionDef>); +} + +/** Pre-seeds `group_id` + `user_id` (both uint, required). */ +export function groupUserAction( + def: PresetDef, +): ActionSpec> { + const params = { + group_id: f.uint().describe('群号'), + user_id: f.uint().describe('QQ 号'), + ...(def.params ?? {}), + } as WithGroupUser; + return defineAction({ ...def, params } as unknown as ActionDef>); +} + +// ─────────────────────────── registration helper ─────────────────────────── + +/** Register many specs onto an ApiHandler. Coexists with legacy + * `h.registerAction(name, fn)` in the same `register(h, ctx)`. */ +export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray>): void { + for (const spec of specs) spec.register(h, ctx); +} diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 2a7ad844..2dd846af 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1,8 +1,9 @@ import { readFile } from 'node:fs/promises'; import type { ApiActionContext, ApiHandler } from '../api-handler'; -import { asBoolean, asMessage, asNumber, asString } from '../api-handler'; +import { asNumber, asString } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; import { JsonObject, RETCODE, failedResponse, okResponse } from '../types'; +import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit'; const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB const DOWNLOAD_FILE_TIMEOUT_MS = 60_000; @@ -75,1136 +76,1372 @@ function readForwardPreviewMeta(params: Record): ForwardPreview return { source, summary, prompt, news }; } -export function register(h: ApiHandler, ctx: ApiActionContext): void { +// 群待办三动作(set/complete/cancel)共享:按 message_id 查消息元数据 → 校验归属 → 执行 op。 +async function groupTodoRun( + p: { group_id: number; message_id: number }, + ctx: ApiActionContext, + op: (groupId: number, msgSeq: bigint) => Promise, +) { + const meta = ctx.getMessageMeta(p.message_id); + if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); + if (!meta.isGroup || meta.targetId !== p.group_id) { + return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group'); + } + try { + await op(p.group_id, BigInt(meta.sequence)); + return okResponse(); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } +} + +export const actions = [ // 赞 - h.registerAction('send_like', async (params) => { - const userId = asNumber(params.user_id); - const times = asNumber(params.times) || 1; - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - await ctx.bridge.apis.interaction.sendLike(userId, times); - return okResponse(); - }); + defineAction({ + name: 'send_like', + summary: '点赞', + params: { + user_id: f.uint(), + // 原实现用 `asNumber(times) || 1`,present 0 会被当作缺省 1。 + times: f.int({ min: 0 }).default(1), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.interaction.sendLike(p.user_id, p.times); + return okResponse(); + }, + }), // 拍一拍 - h.registerAction('friend_poke', async (params) => { - const userId = asNumber(params.user_id); - const targetId = asNumber(params.target_id) || undefined; - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - await ctx.bridge.apis.interaction.sendPoke(false, userId, targetId); - return okResponse(); - }); + defineAction({ + name: 'friend_poke', + summary: '好友拍一拍', + params: { + user_id: f.uint(), + target_id: f.uint().optional(), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.interaction.sendPoke(false, p.user_id, p.target_id); + return okResponse(); + }, + }), - h.registerAction('group_poke', async (params) => { - const groupId = asNumber(params.group_id); - const userId = asNumber(params.user_id); - if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.bridge.apis.interaction.sendPoke(true, groupId, userId); - return okResponse(); - }); + groupUserAction({ + name: 'group_poke', + summary: '群拍一拍', + run: async (p, ctx) => { + await ctx.bridge.apis.interaction.sendPoke(true, p.group_id, p.user_id); + return okResponse(); + }, + }), - h.registerAction('send_poke', async (params) => { - const groupId = asNumber(params.group_id); - const userId = asNumber(params.user_id); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - if (groupId) { - await ctx.bridge.apis.interaction.sendPoke(true, groupId, userId); - } else { - await ctx.bridge.apis.interaction.sendPoke(false, userId); - } - return okResponse(); - }); + defineAction({ + name: 'send_poke', + summary: '拍一拍(群聊/私聊自动路由)', + params: { + user_id: f.uint(), + group_id: f.uint().optional(), + }, + run: async (p, ctx) => { + if (p.group_id) { + await ctx.bridge.apis.interaction.sendPoke(true, p.group_id, p.user_id); + } else { + await ctx.bridge.apis.interaction.sendPoke(false, p.user_id); + } + return okResponse(); + }, + }), // 精华消息 - h.registerAction('set_essence_msg', async (params) => { - const messageId = asNumber(params.message_id); - if (!Number.isInteger(messageId) || messageId === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - } - await ctx.setEssenceMsg(messageId); - return okResponse(); - }); + defineAction({ + name: 'set_essence_msg', + summary: '设置精华消息', + params: { message_id: f.messageId() }, + run: async (p, ctx) => { + await ctx.setEssenceMsg(p.message_id); + return okResponse(); + }, + }), - h.registerAction('delete_essence_msg', async (params) => { - const messageId = asNumber(params.message_id); - if (!Number.isInteger(messageId) || messageId === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - } - await ctx.deleteEssenceMsg(messageId); - return okResponse(); - }); + defineAction({ + name: 'delete_essence_msg', + summary: '移除精华消息', + params: { message_id: f.messageId() }, + run: async (p, ctx) => { + await ctx.deleteEssenceMsg(p.message_id); + return okResponse(); + }, + }), - h.registerAction('get_essence_msg_list', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + groupAction({ + name: 'get_essence_msg_list', + summary: '获取精华消息列表', + run: async (p, ctx) => { + try { + const essenceDataAll = await ctx.bridge.apis.web.getEssenceAll(p.group_id); + const allMsgs = essenceDataAll.flatMap((res) => res.data?.msg_list || []); - try { - const essenceDataAll = await ctx.bridge.apis.web.getEssenceAll(groupId); - - const allMsgs = essenceDataAll.flatMap((res) => res.data?.msg_list || []); - - return okResponse(allMsgs); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, `获取精华消息失败: ${e}`); - } - }); + return okResponse(allMsgs); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, `获取精华消息失败: ${e}`); + } + }, + }), // 群聊表情回应 - h.registerAction('set_group_reaction', async (params) => { - const groupId = asNumber(params.group_id); - const messageId = asNumber(params.message_id); - const code = asString(params.code); - const isSet = asBoolean(params.is_set, true); + defineAction({ + name: 'set_group_reaction', + summary: '群聊表情回应', + params: { + group_id: f.uint().optional(), + message_id: f.messageId(), + code: f.string({ allowEmpty: false }), + is_set: f.bool().default(true), + }, + run: async (p, ctx) => { + const meta = ctx.getMessageMeta(p.message_id); + if (!meta || !meta.isGroup) { + return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message'); + } - if (!Number.isInteger(messageId) || messageId === 0 || !code) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id and code are required'); - } + if (p.group_id && p.group_id !== meta.targetId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); + } - const meta = ctx.getMessageMeta(messageId); - if (!meta || !meta.isGroup) { - return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message'); - } - - if (groupId && groupId !== meta.targetId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); - } - - await ctx.bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, code, isSet); - return okResponse(); - }); + await ctx.bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, p.code, p.is_set); + return okResponse(); + }, + }), // 消息历史 - h.registerAction('get_group_msg_history', async (params) => { - const groupId = asNumber(params.group_id); - const messageId = asNumber(params.message_id) || 0; - const count = asNumber(params.count) || 20; - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - const messages = await ctx.getGroupMsgHistory(groupId, messageId, count); - return okResponse({ messages }); - }); + groupAction({ + name: 'get_group_msg_history', + summary: '获取群消息历史', + params: { + // 原实现用 `asNumber(message_id) || 0`,present 0 也映射为 0。 + message_id: f.int({ min: 0 }).default(0), + count: f.int({ min: 0 }).default(20), + }, + run: async (p, ctx) => { + const messages = await ctx.getGroupMsgHistory(p.group_id, p.message_id, p.count); + return okResponse({ messages }); + }, + }), - h.registerAction('get_friend_msg_history', async (params) => { - const userId = asNumber(params.user_id); - const messageId = asNumber(params.message_id) || 0; - const count = asNumber(params.count) || 20; - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - const messages = await ctx.getFriendMsgHistory(userId, messageId, count); - return okResponse({ messages }); - }); + defineAction({ + name: 'get_friend_msg_history', + summary: '获取好友消息历史', + params: { + user_id: f.uint(), + message_id: f.int({ min: 0 }).default(0), + count: f.int({ min: 0 }).default(20), + }, + run: async (p, ctx) => { + const messages = await ctx.getFriendMsgHistory(p.user_id, p.message_id, p.count); + return okResponse({ messages }); + }, + }), // 标记消息已读 - h.registerAction('mark_group_msg_as_read', async (params) => { - const messageId = asNumber(params.message_id); - const groupId = asNumber(params.group_id); + defineAction({ + name: 'mark_group_msg_as_read', + summary: '标记群消息已读', + params: { + message_id: f.messageId(), + group_id: f.uint().optional(), + }, + run: async (p, ctx) => { + const meta = ctx.getMessageMeta(p.message_id); + if (!meta || !meta.isGroup) { + return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message'); + } - if (!Number.isInteger(messageId) || messageId === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - } - const meta = ctx.getMessageMeta(messageId); - if (!meta || !meta.isGroup) { - return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message'); - } + if (p.group_id && p.group_id !== meta.targetId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); + } - if (groupId && groupId !== meta.targetId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); - } - - await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence); - return okResponse(); - }); - - h.registerAction('mark_private_msg_as_read', async (params) => { - const messageId = asNumber(params.message_id); - const userId = asNumber(params.user_id); - - if (!Number.isInteger(messageId) || messageId === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - } - const meta = ctx.getMessageMeta(messageId); - if (!meta || meta.isGroup) { - return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a private message'); - } - - if (userId && userId !== meta.targetId) { - return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session'); - } - - await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence); - return okResponse(); - }); - - h.registerAction('mark_msg_as_read', async (params) => { - const messageId = asNumber(params.message_id); - const targetId = asNumber(params.target_id); - - if (!Number.isInteger(messageId) || messageId === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - } - const meta = ctx.getMessageMeta(messageId); - if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - - if (targetId && targetId !== meta.targetId) { - return failedResponse(RETCODE.BAD_REQUEST, 'target_id does not match message session'); - } - - if (meta.isGroup) { await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence); - } else { + return okResponse(); + }, + }), + + defineAction({ + name: 'mark_private_msg_as_read', + summary: '标记私聊消息已读', + params: { + message_id: f.messageId(), + user_id: f.uint().optional(), + }, + run: async (p, ctx) => { + const meta = ctx.getMessageMeta(p.message_id); + if (!meta || meta.isGroup) { + return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a private message'); + } + + if (p.user_id && p.user_id !== meta.targetId) { + return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session'); + } + await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence); - } - return okResponse(); - }); + return okResponse(); + }, + }), + defineAction({ + name: 'mark_msg_as_read', + summary: '标记消息已读(群聊/私聊自动路由)', + params: { + message_id: f.messageId(), + target_id: f.uint().optional(), + }, + run: async (p, ctx) => { + const meta = ctx.getMessageMeta(p.message_id); + if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - // 下载密钥 - const handleGetRkey = async () => { - if (ctx.getDownloadRKeys) { - return okResponse(await ctx.getDownloadRKeys()); - } - return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); - }; - h.registerAction('get_rkey', handleGetRkey); - h.registerAction('nc_get_rkey', handleGetRkey); + if (p.target_id && p.target_id !== meta.targetId) { + return failedResponse(RETCODE.BAD_REQUEST, 'target_id does not match message session'); + } - // OCR 兜底未实现。 - - h.registerAction('ocr_image', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - h.registerAction('.ocr_image', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); + if (meta.isGroup) { + await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence); + } else { + await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence); + } + return okResponse(); + }, + }), // 群公告 - h.registerAction('_send_group_notice', async (params) => { - const groupId = asNumber(params.group_id); - const content = asString(params.content); - const image = asString(params.image); + groupAction({ + name: '_send_group_notice', + summary: '发送群公告', + params: { + content: f.string({ allowEmpty: false }), + image: f.string().default(''), + pinned: f.raw(), + type: f.raw(), + confirm_required: f.raw(), + }, + run: async (p, ctx) => { + try { + const options = { + image: p.image || undefined, + pinned: p.pinned !== undefined ? Number(p.pinned) : 0, + type: p.type !== undefined ? Number(p.type) : 1, + confirm_required: p.confirm_required !== undefined ? Number(p.confirm_required) : 1, + }; - if (!groupId || !content) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id and content are required'); - } - - - try { - const options = { - image: image || undefined, - pinned: params.pinned !== undefined ? Number(params.pinned) : 0, - type: params.type !== undefined ? Number(params.type) : 1, - confirm_required: params.confirm_required !== undefined ? Number(params.confirm_required) : 1, - }; - - await ctx.bridge.apis.web.sendNotice(groupId, content, options); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('_get_group_notice', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - - - try { - const notices = await ctx.bridge.apis.web.getNotice(groupId); - return okResponse(notices); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('_del_group_notice', async (params) => { - const groupId = asNumber(params.group_id); - const fid = asString(params.fid) || asString(params.notice_id); - - if (!groupId || !fid) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id and fid/notice_id are required'); - } - - - try { - const success = await ctx.bridge.apis.web.deleteNotice(groupId, fid); - if (success) { + await ctx.bridge.apis.web.sendNotice(p.group_id, p.content, options); return okResponse(); - } else { - return failedResponse(RETCODE.ACTION_FAILED, 'delete failed'); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); } - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); + }, + }), - // 转发消息。 - h.registerAction('upload_forward_msg', async (params) => { - const messages = asMessage(params.messages ?? params.message); - const groupId = asNumber(params.group_id); - if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - // 群聊和私聊转发消息的 resId 是分开的(前者是 type=3+groupUin,后者是 type=1+selfUid), - const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); - const data: Record = { - res_id: result.forwardId, - forward_id: result.forwardId, - message_id: 0, - }; - if (groupId > 0) data.group_id = groupId; - return okResponse(data as import('../types').JsonObject); - }); - - h.registerAction('upload_foward_msg', async (params) => { - const messages = asMessage(params.messages ?? params.message); - const groupId = asNumber(params.group_id); - if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); - return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 }); - }); - - h.registerAction('send_forward_msg', async (params) => { - const messageType = asString(params.message_type); - const groupId = asNumber(params.group_id); - const userId = asNumber(params.user_id); - const messages = asMessage(params.messages ?? params.message); - const meta = readForwardPreviewMeta(params); - - if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - - if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) { - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - const result = await ctx.sendGroupForwardMsg(groupId, messages, meta); - return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); - } - - if ((messageType === 'private' || userId > 0) && ctx.sendPrivateForwardMsg) { - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - const result = await ctx.sendPrivateForwardMsg(userId, messages, meta); - return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); - } - - const result = await ctx.sendForwardMsg(messages); - return okResponse({ message_id: 0, res_id: result.forwardId, forward_id: result.forwardId }); - }); - - h.registerAction('send_group_forward_msg', async (params) => { - const groupId = asNumber(params.group_id); - const messages = asMessage(params.messages ?? params.message); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - - const result = await ctx.sendGroupForwardMsg(groupId, messages, readForwardPreviewMeta(params)); - return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); - }); - - h.registerAction('send_private_forward_msg', async (params) => { - const userId = asNumber(params.user_id); - const messages = asMessage(params.messages ?? params.message); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - - const result = await ctx.sendPrivateForwardMsg(userId, messages, readForwardPreviewMeta(params)); - return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); - }); - - h.registerAction('get_forward_msg', async (params) => { - let id = asString(params.id); - if (!id) { - const rawMessageId = params.message_id; - const numericMessageId = asNumber(rawMessageId); - if (numericMessageId > 0) { - const event = ctx.getMessage(numericMessageId); - const segments = Array.isArray(event?.message) ? event.message : []; - for (const seg of segments) { - if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue; - const so = seg as Record; - if (String(so.type ?? '') !== 'forward') continue; - const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data)) - ? so.data as Record - : null; - const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id); - if (candidate) { - id = candidate; - break; - } - } + groupAction({ + name: '_get_group_notice', + summary: '获取群公告', + run: async (p, ctx) => { + try { + const notices = await ctx.bridge.apis.web.getNotice(p.group_id); + return okResponse(notices); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); } + }, + }), - if (!id) { - id = asString(rawMessageId); - } - } + // 转发消息。messages/message 互为别名键,两者皆缺省视为未提供。 + defineAction({ + name: 'upload_forward_msg', + summary: '上传转发消息', + params: { + messages: f.message().optional(), + message: f.message().optional(), + group_id: f.uint().optional(), + }, + run: async (p, ctx) => { + const messages = p.messages ?? p.message; + const groupId = p.group_id ?? 0; + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + // 群聊和私聊转发消息的 resId 是分开的(前者是 type=3+groupUin,后者是 type=1+selfUid), + const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); + const data: Record = { + res_id: result.forwardId, + forward_id: result.forwardId, + message_id: 0, + }; + if (groupId > 0) data.group_id = groupId; + return okResponse(data as import('../types').JsonObject); + }, + }), - if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required'); - - const messages = await ctx.getForwardMsg(id); - return okResponse({ messages }); - }); + defineAction({ + name: 'upload_foward_msg', + summary: '上传转发消息(别名拼写)', + params: { + messages: f.message().optional(), + message: f.message().optional(), + group_id: f.uint().optional(), + }, + run: async (p, ctx) => { + const messages = p.messages ?? p.message; + const groupId = p.group_id ?? 0; + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); + return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 }); + }, + }), // 文件信息 + defineAction({ + name: 'get_image', + summary: '获取图片信息', + params: { + file: f.string().default(''), + file_id: f.string().default(''), + }, + run: async (p, ctx) => { + const file = p.file || p.file_id; + if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); + const info = await ctx.getImageInfo(file); + if (info) return okResponse(info); + return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache'); + }, + }), - h.registerAction('get_image', async (params) => { - const file = asString(params.file) || asString(params.file_id); - if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); - const info = await ctx.getImageInfo(file); - if (info) return okResponse(info); - return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache'); - }); - - h.registerAction('get_record', async (params) => { - const file = asString(params.file) || asString(params.file_id); - if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); - const info = await ctx.getRecordInfo(file); - if (info) return okResponse(info); - return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache'); - }); + defineAction({ + name: 'get_record', + summary: '获取语音信息', + params: { + file: f.string().default(''), + file_id: f.string().default(''), + }, + run: async (p, ctx) => { + const file = p.file || p.file_id; + if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); + const info = await ctx.getRecordInfo(file); + if (info) return okResponse(info); + return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache'); + }, + }), // Cookie、CSRF 令牌和账号信息 + defineAction({ + name: 'get_cookies', + summary: '获取 Cookies', + params: { domain: f.string().default('qun.qq.com') }, + run: async (p, ctx) => { + try { + const cookies = await ctx.bridge.apis.web.getCookiesStr(p.domain || 'qun.qq.com'); + return okResponse({ cookies }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), - h.registerAction('get_cookies', async (params) => { - const domain = asString(params.domain) || 'qun.qq.com'; + defineAction({ + name: 'get_csrf_token', + summary: '获取 CSRF 令牌', + params: {}, + run: async (_p, ctx) => { + try { + const token = await ctx.bridge.apis.web.getCsrfToken(); + return okResponse({ token }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + defineAction({ + name: 'get_credentials', + summary: '获取凭证', + params: { domain: f.string().default('qun.qq.com') }, + run: async (p, ctx) => { + try { + const creds = await ctx.bridge.apis.web.getCredentials(p.domain || 'qun.qq.com'); + return okResponse(creds); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), - try { - const cookies = await ctx.bridge.apis.web.getCookiesStr(domain); - return okResponse({ cookies }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_csrf_token', async () => { - - try { - const token = await ctx.bridge.apis.web.getCsrfToken(); - return okResponse({ token }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_credentials', async (params) => { - const domain = asString(params.domain) || 'qun.qq.com'; - - - try { - const creds = await ctx.bridge.apis.web.getCredentials(domain); - return okResponse(creds); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); // 重启和清理缓存 + defineAction({ + name: 'set_restart', + summary: '重启(不支持)', + params: {}, + run: async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not supported'); + }, + }), - h.registerAction('set_restart', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not supported'); - }); + defineAction({ + name: 'clean_cache', + summary: '清理缓存', + params: {}, + run: async () => { + return okResponse(); + }, + }), - h.registerAction('clean_cache', async () => { - return okResponse(); - }); + // 以下接口在方便用户迁移和兼容现有的 OneBot/NapCat 客户端。 + defineAction({ + name: 'set_friend_remark', + summary: '设置好友备注', + params: { + user_id: f.uint(), + remark: f.string(), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.friend.setRemark(p.user_id, p.remark); + return okResponse(); + }, + }), + defineAction({ + name: 'set_group_remark', + summary: '设置群备注', + params: { + group_id: f.uint(), + remark: f.string(), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.setRemark(p.group_id, p.remark); + return okResponse(); + }, + }), + + defineAction({ + name: 'set_msg_emoji_like', + summary: '设置消息表情回应', + params: { + message_id: f.messageId(), + emoji_id: f.string({ allowEmpty: false }), + set: f.bool().default(true), + }, + run: async (p, ctx) => { + await ctx.setMsgEmojiLike(p.message_id, p.emoji_id, p.set); + return okResponse(); + }, + }), + + defineAction({ + name: '_mark_all_as_read', + summary: '标记全部已读', + params: {}, + run: async () => { + return okResponse(); + }, + }), + + groupAction({ + name: 'get_group_file_system_info', + summary: '获取群文件系统信息', + run: async (p, ctx) => { + const info = await ctx.bridge.apis.groupFile.getCount(p.group_id); + return okResponse({ + file_count: info.fileCount, + limit_count: info.maxCount, + used_space: 0, + total_space: 10737418240, + }); + }, + }), + + defineAction({ + name: 'check_url_safely', + summary: '检查链接安全性', + params: {}, + run: async () => { + return okResponse({ level: 1 }); + }, + }), + + defineAction({ + name: 'set_qq_profile', + summary: '设置 QQ 资料', + params: { + nickname: f.string().optional(), + personal_note: f.string().optional(), + }, + run: async (p, ctx) => { + const nickname = p.nickname; + const personalNote = p.personal_note; + + try { + await ctx.bridge.apis.profile.setProfile(nickname, personalNote); + return okResponse(); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'set_online_status', + summary: '设置在线状态', + params: { + // 原实现用 asNumber+`status===0` 拒绝,等价于必填非零整数。 + status: f.int({ nonZero: true }), + ext_status: f.int({ min: 0 }).default(0), + battery_status: f.int({ min: 0 }).default(100), + }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.profile.setOnlineStatus(p.status, p.ext_status, p.battery_status); + return okResponse(); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + // 自定义在线状态:与 set_online_status 使用相同的网络包。 + // 这里只填充 customExt 子消息,并将 status/extStatus 强制设为 QQ 定义的“我有自定义状态”取值(10 / 2000)。 + // face_id 和 face_type 可接受数字或数字字符串,以兼容 NapCat;wording 是图标旁展示的可读文本。 + defineAction({ + name: 'set_diy_online_status', + summary: '设置自定义在线状态', + params: { + face_id: f.uint(), + // 原实现用 `asNumber(face_type) || 1`,present 0 会被当作缺省 1。 + face_type: f.int({ min: 0 }).default(1), + wording: f.string().default(''), + }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.profile.setDiyOnlineStatus(p.face_id, p.wording, p.face_type); + return okResponse(); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + defineAction({ + name: 'get_group_ignored_notifies', + summary: '获取被过滤的入群请求', + params: {}, + run: async (_p, ctx) => { + const reqs = await fetchFilteredGroupRequests(ctx); + return okResponse(reqs.map((r) => ({ + group_id: r.groupId, + group_name: r.groupName, + request_id: r.sequence, + requester_uin: r.targetUin, + requester_nick: r.targetName, + message: r.comment, + checked: r.state !== 1, + actor: r.operatorUin, + invitor_uin: r.invitorUin, + invitor_nick: r.invitorName, + flag: `${r.eventType}:${r.groupId}:${r.targetUid}:filtered`, + }))); + }, + }), + + // NapCat 对“被忽略通知中属于入群请求的子集”的命名(notify type == 7)。 + // 这里把经过过滤的 0x10c8_2 每一项映射成 NapCat 结构。 + // eventType 已经在当前流水线中编码了请求类别。 + defineAction({ + name: 'get_group_ignore_add_request', + summary: '获取被忽略的入群请求(NapCat)', + params: {}, + run: async (_p, ctx) => { + const reqs = await fetchFilteredGroupRequests(ctx); + return okResponse(reqs.map((r) => ({ + request_id: r.sequence, + invitor_uin: r.invitorUin, + invitor_nick: r.invitorName, + group_id: r.groupId, + message: r.comment, + group_name: r.groupName, + checked: r.state !== 1, + actor: r.operatorUin, + requester_nick: r.targetName, + }))); + }, + }), + + // get_group_shut_list 依赖尚未封装的 oidb。 + // 这里遵循 NapCat 约定返回空列表,避免调用方出错。 + defineAction({ + name: 'get_group_shut_list', + summary: '获取群禁言列表(占位)', + params: {}, + run: async () => { + return okResponse([]); + }, + }), + + defineAction({ + name: 'forward_friend_single_msg', + summary: '转发单条消息给好友', + params: { + message_id: f.messageId(), + user_id: f.uint(), + }, + run: async (p, ctx) => { + try { + const result = await ctx.forwardSingleMsg(p.message_id, { userId: p.user_id }); + return okResponse({ message_id: result.messageId }); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + defineAction({ + name: 'forward_group_single_msg', + summary: '转发单条消息到群', + params: { + message_id: f.messageId(), + group_id: f.uint(), + }, + run: async (p, ctx) => { + try { + const result = await ctx.forwardSingleMsg(p.message_id, { groupId: p.group_id }); + return okResponse({ message_id: result.messageId }); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + defineAction({ + name: 'get_profile_like', + summary: '获取资料点赞', + params: { + // 原实现 user_id 经 asNumber,无校验(0 也透传)。 + user_id: f.int({ min: 0 }).default(0), + start: f.int({ min: 0 }).default(0), + count: f.int({ min: 0 }).default(10), + }, + run: async (p, ctx) => { + try { + const data = await ctx.bridge.apis.profile.getLike(p.user_id, p.start, p.count); + return okResponse(data); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'fetch_custom_face', + summary: '获取自定义表情', + params: { count: f.int({ min: 0 }).default(10) }, + run: async (p, ctx) => { + try { + const urls = await ctx.bridge.apis.profile.fetchCustomFace(p.count); + return okResponse(urls); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_emoji_likes', + summary: '获取表情回应用户', + params: { + message_id: f.messageId(), + emoji_id: f.string({ allowEmpty: false }), + }, + run: async (p, ctx) => { + try { + const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emoji_id, 1000); + return okResponse({ + emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })), + }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'fetch_emoji_like', + summary: '获取表情回应用户(NapCat 分页)', + params: { + message_id: f.messageId(), + emojiId: f.string({ allowEmpty: false }), + count: f.int({ min: 0 }).default(10), + cookie: f.string().default(''), + }, + run: async (p, ctx) => { + try { + const offset = p.cookie ? Number.parseInt(p.cookie, 10) || 0 : 0; + const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emojiId, p.count, offset); + const nextOffset = offset + result.users.length; + const isLastPage = nextOffset >= result.cachedCount; + return okResponse({ + result: 0, + errMsg: '', + emojiLikesList: result.users.map(u => ({ tinyId: String(u.uin), nickName: '', headUrl: '' })), + cookie: isLastPage ? '' : String(nextOffset), + isLastPage, + isFirstPage: offset === 0, + }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_friends_with_category', + summary: '获取分组好友列表', + params: {}, + run: async (_p, ctx) => { + if (ctx.getFriendList) { + return okResponse(await ctx.getFriendList()); + } + return okResponse([]); + }, + }), + + // NapCat 似乎也用不了,暂时不处理。 + defineAction({ + name: 'get_online_clients', + summary: '获取在线客户端(占位)', + params: {}, + run: async () => { + return okResponse({ clients: [] }); + }, + }), + + defineAction({ + name: '_get_model_show', + summary: '获取机型展示(占位)', + params: {}, + run: async () => { + return okResponse({ variants: [] }); + }, + }), + + defineAction({ + name: '_set_model_show', + summary: '设置机型展示(占位)', + params: {}, + run: async () => { + return okResponse(); + }, + }), + + groupAction({ + name: 'get_group_at_all_remain', + summary: '获取群 @全体成员 剩余次数', + run: async (p, ctx) => { + try { + const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(p.group_id); + return okResponse(data); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_unidirectional_friend_list', + summary: '获取单向好友列表', + params: {}, + run: async (_p, ctx) => { + try { + const data = await ctx.bridge.apis.profile.getUnidirectionalFriendList(); + return okResponse(data); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_clientkey', + summary: '获取 clientkey', + params: {}, + run: async (_p, ctx) => { + const clientKeyInfo = await ctx.bridge.apis.web.forceFetchClientKey(); + if (!clientKeyInfo.clientKey) { + return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error'); + } + return okResponse({ ...clientKeyInfo }); + }, + }), + + defineAction({ + name: 'get_collection_list', + summary: '获取收藏列表(占位)', + params: {}, + run: async () => { + return okResponse([]); + }, + }), + + defineAction({ + name: 'create_collection', + summary: '创建收藏(未实现)', + params: {}, + run: async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }, + }), + + defineAction({ + name: '.get_word_slices', + summary: '分词(未实现)', + params: {}, + run: async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }, + }), + + defineAction({ + name: 'set_qq_avatar', + summary: '设置 QQ 头像', + params: { file: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.profile.setAvatar(p.file); + return okResponse(); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'set_input_status', + summary: '设置输入状态', + params: { + user_id: f.uint(), + // event_type 可能为 0(取消输入状态);缺省也按 0 处理(与旧 asNumber 行为一致)。 + event_type: f.int().default(0), + }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.profile.setInputStatus(p.user_id, p.event_type); + return okResponse({}); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_group_info_ex', + summary: '获取群信息(扩展)', + params: { group_id: f.uint() }, + run: async (p, ctx) => { + if (ctx.getGroupInfo) { + return okResponse(await ctx.getGroupInfo(p.group_id)); + } + return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + }, + }), + + defineAction({ + name: 'get_group_detail_info', + summary: '获取群详细信息', + params: { group_id: f.uint() }, + run: async (p, ctx) => { + if (ctx.getGroupInfo) { + return okResponse(await ctx.getGroupInfo(p.group_id)); + } + return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + }, + }), + + defineAction({ + name: 'trans_group_file', + summary: '转存群文件(未实现)', + params: {}, + run: async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }, + }), + + defineAction({ + name: 'rename_group_file', + summary: '重命名群文件(未实现)', + params: {}, + run: async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }, + }), + + defineAction({ + name: 'get_file', + summary: '获取文件(未实现)', + params: { + file_id: f.string().default(''), + file: f.string().default(''), + }, + run: async (p) => { + const fileId = p.file_id || p.file; + if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required'); + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }, + }), + + // 机器人生命周期(兼容 NapCat)。 + defineAction({ + name: 'bot_exit', + summary: '退出机器人', + params: {}, + run: async () => { + setTimeout(() => process.exit(0), 50); + return okResponse(); + }, + }), + + defineAction({ + name: 'nc_get_packet_status', + summary: '获取 packet 状态(占位)', + params: {}, + run: async () => { + return okResponse(null); + }, + }), + + // NapCat 暴露 delete_group_folder。 + // SnowLuma 现有的 delete_group_file_folder 是相同操作。 + // 添加别名以便遵循 NapCat 文档的客户端无需重写载荷。 + groupAction({ + name: 'delete_group_folder', + summary: '删除群文件夹', + params: { folder_id: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupFile.deleteFolder(p.group_id, p.folder_id); + return okResponse(); + }, + }), + + // 用户在线/扩展状态(NapCat:nc_get_user_status)。 + defineAction({ + name: 'nc_get_user_status', + summary: '获取用户在线/扩展状态', + params: { user_id: f.uint() }, + run: async (p, ctx) => { + const status = await ctx.bridge.apis.extras.getStrangerStatus(p.user_id); + if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status'); + return okResponse({ ...status }); + }, + }), + + // AI 语音(oidb 0x929D / 0x929B)。 + groupAction({ + name: 'get_ai_characters', + summary: '获取 AI 语音角色', + params: { chat_type: f.int({ min: 0 }).default(1) }, + run: async (p, ctx) => { + try { + const list = await ctx.bridge.apis.extras.fetchAiVoiceList(p.group_id, p.chat_type); + return okResponse(list.map((cat) => ({ + type: cat.category, + characters: cat.voices.map((v) => ({ + character_id: v.voiceId, + character_name: v.voiceDisplayName, + preview_url: v.voiceExampleUrl, + })), + }))); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + groupAction({ + name: 'get_ai_record', + summary: '生成 AI 语音', + params: { + character: f.string({ allowEmpty: false }), + text: f.string({ allowEmpty: false }), + chat_type: f.int({ min: 0 }).default(1), + }, + run: async (p, ctx) => { + try { + const node = await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type); + const url = await ctx.bridge.apis.groupFile.getPttUrl(p.group_id, node); + return okResponse(url); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + // NapCat 的 send_group_ai_record 是仅产生副作用的调用。 + // 调用 fetchAiVoice 会把语音发布到群里。 + // 返回的 message_id 始终为 0,因为 oidb 调用不会回显消息 ID。 + groupAction({ + name: 'send_group_ai_record', + summary: '发送 AI 语音到群', + params: { + character: f.string({ allowEmpty: false }), + text: f.string({ allowEmpty: false }), + chat_type: f.int({ min: 0 }).default(1), + }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type); + return okResponse({ message_id: 0 }); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + defineAction({ + name: 'request_decrypt_key', + summary: '请求数据库解密密钥', + params: { db_path: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + try { + const buffer = Buffer.alloc(128); + const fileHandle = await readFile(p.db_path); + + if (fileHandle.length < 0xaf) { + return failedResponse(RETCODE.ACTION_FAILED, 'Database file too short'); + } + + fileHandle.copy(buffer, 0, 0x2f, 0xaf); + const dbSalt = buffer.toString('utf8'); + + if (!/^[0-9a-fA-F]{128}$/.test(dbSalt)) { + return failedResponse(RETCODE.ACTION_FAILED, 'Invalid db_salt: not a valid 128-character hex string'); + } + + const dbKey = await ctx.bridge.apis.misc.getDecryptKey(dbSalt.toLowerCase()); + + return okResponse({ db_key: dbKey }); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + // ===== 原 legacy registerAction,现并入 kit(ctx 调用与逻辑逐字保留; + // 别名键 / 原始参数透传 / 任意对象经 run 第三参 raw 或 f.raw() 表达)===== + + defineAction({ + name: ['get_rkey', 'nc_get_rkey'], + summary: '获取下载 rkey', + params: {}, + run: async (_p, ctx) => + ctx.getDownloadRKeys + ? okResponse(await ctx.getDownloadRKeys()) + : failedResponse(RETCODE.ACTION_FAILED, 'not implemented'), + }), + + defineAction({ + name: ['ocr_image', '.ocr_image'], + summary: 'OCR 图片(未实现)', + params: {}, + run: () => failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'), + }), + + groupAction({ + name: '_del_group_notice', + summary: '删除群公告(fid 或 notice_id 二选一)', + params: { fid: f.string().optional(), notice_id: f.string().optional() }, + run: async (p, ctx) => { + const fid = p.fid || p.notice_id; + if (!fid) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and fid/notice_id are required'); + try { + const success = await ctx.bridge.apis.web.deleteNotice(p.group_id, fid); + return success ? okResponse() : failedResponse(RETCODE.ACTION_FAILED, 'delete failed'); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'send_forward_msg', + summary: '发送合并转发(按 message_type/群号自动路由)', + returns: '{ message_id, res_id, forward_id }', + // group_id/user_id 是“路由提示”而非身份字段:原实现用 asNumber + `>0` 判断, + // 占位的 0 表示“该分支不适用”、不应报错。故从 raw 读取(保持旧语义), + // 只声明 messages/message。 + params: { messages: f.message().optional(), message: f.message().optional() }, + run: async (p, ctx, raw) => { + const messageType = asString(raw.message_type); + const groupId = asNumber(raw.group_id); + const userId = asNumber(raw.user_id); + const messages = p.messages ?? p.message; + const meta = readForwardPreviewMeta(raw); + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) { + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + const result = await ctx.sendGroupForwardMsg(groupId, messages, meta); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + } + if ((messageType === 'private' || userId > 0) && ctx.sendPrivateForwardMsg) { + if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + const result = await ctx.sendPrivateForwardMsg(userId, messages, meta); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + } + const result = await ctx.sendForwardMsg(messages); + return okResponse({ message_id: 0, res_id: result.forwardId, forward_id: result.forwardId }); + }, + }), + + groupAction({ + name: 'send_group_forward_msg', + summary: '发送群合并转发', + returns: '{ message_id, res_id, forward_id }', + params: { messages: f.message().optional(), message: f.message().optional() }, + run: async (p, ctx, raw) => { + const messages = p.messages ?? p.message; + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + const result = await ctx.sendGroupForwardMsg(p.group_id, messages, readForwardPreviewMeta(raw)); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + }, + }), + + defineAction({ + name: 'send_private_forward_msg', + summary: '发送私聊合并转发', + returns: '{ message_id, res_id, forward_id }', + params: { user_id: f.uint(), messages: f.message().optional(), message: f.message().optional() }, + run: async (p, ctx, raw) => { + const messages = p.messages ?? p.message; + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + const result = await ctx.sendPrivateForwardMsg(p.user_id, messages, readForwardPreviewMeta(raw)); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + }, + }), + + defineAction({ + name: 'get_forward_msg', + summary: '获取合并转发消息(id 或 message_id)', + returns: '{ messages }', + params: { id: f.string().optional() }, + run: async (p, ctx, raw) => { + let id = p.id || ''; + if (!id) { + const rawMessageId = raw.message_id; + const numericMessageId = asNumber(rawMessageId); + if (numericMessageId > 0) { + const event = ctx.getMessage(numericMessageId); + const segments = Array.isArray(event?.message) ? event.message : []; + for (const seg of segments) { + if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue; + const so = seg as Record; + if (String(so.type ?? '') !== 'forward') continue; + const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data)) + ? so.data as Record + : null; + const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id); + if (candidate) { id = candidate; break; } + } + } + if (!id) id = asString(rawMessageId); + } + if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required'); + const messages = await ctx.getForwardMsg(id); + return okResponse({ messages }); + }, + }), + + defineAction({ + name: 'download_file', + summary: '下载文件(url 或 base64)到 data/downloads', + returns: '{ file }', + params: { url: f.string().default(''), base64: f.string().default(''), name: f.string().default('') }, + run: async (p, _ctx, raw) => { + const url = p.url; + const base64 = p.base64; + const name = p.name; + if (!url && !base64) return failedResponse(RETCODE.BAD_REQUEST, 'url or base64 is required'); + const fs = await import('fs'); + const pathMod = await import('path'); + const cryptoMod = await import('crypto'); + const tempDir = pathMod.resolve('data', 'downloads'); + if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); + const resolveSafePath = (preferredName: string, fallbackBuf: Buffer): string | null => { + const rawName = preferredName || cryptoMod.createHash('md5').update(fallbackBuf).digest('hex'); + const safeName = pathMod.basename(rawName); + if (!safeName || safeName === '.' || safeName === '..' || /[\\/]/.test(safeName)) return null; + const resolved = pathMod.resolve(tempDir, safeName); + const rel = pathMod.relative(tempDir, resolved); + if (rel.startsWith('..') || pathMod.isAbsolute(rel)) return null; + return resolved; + }; + let buf: Buffer; + if (base64) { + const upperBound = Math.floor((base64.length * 3) / 4); + if (upperBound > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); + buf = Buffer.from(base64, 'base64'); + if (buf.length > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); + } else { + try { + buf = await fetchDownloadFile(url, parseDownloadHeaders(raw.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + } + const safe = resolveSafePath(name, buf); + if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); + await fs.promises.writeFile(safe, buf); + return okResponse({ file: safe }); + }, + }), + + defineAction({ + name: 'translate_en2zh', + summary: '英译中', + returns: '{ words }', + params: { words: f.raw() }, + run: async (p, ctx) => { + const rawWords = p.words; + if (!Array.isArray(rawWords)) return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array'); + const words = rawWords.map((w) => String(w)); + try { + const translated = await ctx.bridge.apis.misc.translateEn2Zh(words); + return okResponse({ words: translated }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'set_self_longnick', + summary: '设置个性签名(longNick/long_nick,严格 string)', + params: { longNick: f.raw(), long_nick: f.raw() }, + run: async (p, ctx) => { + const longNick = p.longNick || p.long_nick; + if (typeof longNick !== 'string') return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick'); + try { + await ctx.bridge.apis.profile.setSelfLongNick(longNick); + return okResponse({}); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_mini_app_ark', + summary: '获取小程序卡片 ark', + params: {}, + run: async (_p, ctx, raw) => { + const type = raw.type || 'bili'; + const title = raw.title || ''; + const desc = raw.desc || ''; + const picUrl = raw.picUrl || raw.pic_url || ''; + const jumpUrl = raw.jumpUrl || raw.jump_url || ''; + try { + const data = await ctx.bridge.apis.misc.getMiniAppArk(String(type), String(title), String(desc), String(picUrl), String(jumpUrl)); + return okResponse(data); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + groupAction({ + name: 'click_inline_keyboard_button', + summary: '点击内联键盘按钮', + params: { bot_appid: f.uint(), msg_seq: f.uint() }, + run: async (p, ctx, raw) => { + const buttonId = raw.button_id; + const callbackData = raw.callback_data || ''; + if (!buttonId) return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters'); + try { + const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(p.group_id, p.bot_appid, String(buttonId), String(callbackData), p.msg_seq); + return okResponse(data); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + groupAction({ + name: ['set_group_sign', 'send_group_sign'], + summary: '群签到', + run: async (p, ctx) => { + try { + await ctx.bridge.apis.misc.sendGroupSign(p.group_id); + return okResponse({}); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: ['send_packet', '.send_packet'], + summary: '发送原始 SSO 包(cmd + hex data)', + params: { cmd: f.string({ allowEmpty: false }), data: f.string().default(''), rsp: f.bool().default(true) }, + run: async (p, ctx) => { + if (!/^[0-9a-fA-F]*$/.test(p.data) || p.data.length % 2 !== 0) { + return failedResponse(RETCODE.BAD_REQUEST, 'data must be a hex string of even length'); + } + try { + const body = hexToBytes(p.data); + const result = await ctx.bridge.sendRawPacket(p.cmd, body); + if (!result.success) return failedResponse(RETCODE.ACTION_FAILED, result.errorMessage || 'send failed'); + if (!p.rsp) return okResponse(null); + const respHex = result.responseData ? bytesToHex(result.responseData) : ''; + return okResponse(respHex); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + groupAction({ + name: 'set_group_todo', + summary: '设置群待办', + params: { message_id: f.messageId() }, + run: (p, ctx) => groupTodoRun(p, ctx, (g, s) => ctx.bridge.apis.extras.setGroupTodo(g, s)), + }), + + groupAction({ + name: 'complete_group_todo', + summary: '完成群待办', + params: { message_id: f.messageId() }, + run: (p, ctx) => groupTodoRun(p, ctx, (g, s) => ctx.bridge.apis.extras.completeGroupTodo(g, s)), + }), + + groupAction({ + name: 'cancel_group_todo', + summary: '取消群待办', + params: { message_id: f.messageId() }, + run: (p, ctx) => groupTodoRun(p, ctx, (g, s) => ctx.bridge.apis.extras.cancelGroupTodo(g, s)), + }), +]; + +// 已过滤(机器人/被忽略)的入群请求。 +// SnowLuma 已通过 fetchGroupRequests 实现底层 oidb 0x10c8_2 拉取。 +// 这几个动作只是为实际使用中的 OneBot 方言客户端重命名并投影相同数据。 +async function fetchFilteredGroupRequests(ctx: ApiActionContext) { + try { + return await ctx.bridge.apis.contacts.fetchGroupRequests(true); + } catch { + return []; + } +} + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + registerActions(h, ctx, actions); + + // .handle_quick_operation 仍保留 legacy:它需要把 ApiHandler 本身 (h) 交给 + // executeQuickOperation 去回灌动作,而 action-kit 的 run 只提供 (p, ctx, raw)、不含 h。 h.registerAction('.handle_quick_operation', async (params) => { - const context = params.context as import('../types').JsonObject | undefined; + const context = params.context as JsonObject | undefined; const operation = params.operation as Record | undefined; if (!context || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required'); const { executeQuickOperation } = await import('../network/quick-operation'); await executeQuickOperation(context, operation, h); return okResponse(); }); - - // 以下接口在方便用户迁移和兼容现有的 OneBot/NapCat 客户端。 - h.registerAction('set_friend_remark', async (params) => { - const userId = asNumber(params.user_id); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - if (params.remark === undefined) { - return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)'); - } - await ctx.bridge.apis.friend.setRemark(userId, asString(params.remark)); - return okResponse(); - }); - - h.registerAction('set_group_remark', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (params.remark === undefined) { - return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)'); - } - await ctx.bridge.apis.groupAdmin.setRemark(groupId, asString(params.remark)); - return okResponse(); - }); - - h.registerAction('set_msg_emoji_like', async (params) => { - const messageId = asNumber(params.message_id); - const emojiId = asString(params.emoji_id); - const set = asBoolean(params.set, true); - if (!Number.isInteger(messageId) || messageId === 0 || !emojiId) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required'); - } - await ctx.setMsgEmojiLike(messageId, emojiId, set); - return okResponse(); - }); - - - h.registerAction('_mark_all_as_read', async () => { - return okResponse(); - }); - - h.registerAction('get_group_file_system_info', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - const info = await ctx.bridge.apis.groupFile.getCount(groupId); - return okResponse({ - file_count: info.fileCount, - limit_count: info.maxCount, - used_space: 0, - total_space: 10737418240, - }); - }); - - h.registerAction('check_url_safely', async () => { - return okResponse({ level: 1 }); - }); - - h.registerAction('download_file', async (params) => { - const url = asString(params.url); - const base64 = asString(params.base64); - const name = asString(params.name); - if (!url && !base64) return failedResponse(RETCODE.BAD_REQUEST, 'url or base64 is required'); - - const fs = await import('fs'); - const pathMod = await import('path'); - const cryptoMod = await import('crypto'); - const tempDir = pathMod.resolve('data', 'downloads'); - if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); - - // 清理文件名:移除所有路径部分,并拒绝任何会解析到 tempDir 外部的路径。 - // 如果没有这个保护,name = "../../config/onebot_x.json" 会让已认证的 OneBot 客户端覆盖工作目录下的任意文件。 - // 例如 config、dist、node_modules 等目录中的文件。 - const resolveSafePath = (preferredName: string, fallbackBuf: Buffer): string | null => { - const raw = preferredName || cryptoMod.createHash('md5').update(fallbackBuf).digest('hex'); - const safeName = pathMod.basename(raw); - if (!safeName || safeName === '.' || safeName === '..' || /[\\/]/.test(safeName)) return null; - const resolved = pathMod.resolve(tempDir, safeName); - const rel = pathMod.relative(tempDir, resolved); - if (rel.startsWith('..') || pathMod.isAbsolute(rel)) return null; - return resolved; - }; - - let buf: Buffer; - if (base64) { - // 每 4 个 base64 字符最多解码成 3 个字节。 - // 在 Buffer.from 分配内存前先拒绝过大的载荷,避免最终也无法通过解码后检查的大载荷导致内存溢出。 - const upperBound = Math.floor((base64.length * 3) / 4); - if (upperBound > DOWNLOAD_FILE_MAX_BYTES) { - return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); - } - buf = Buffer.from(base64, 'base64'); - if (buf.length > DOWNLOAD_FILE_MAX_BYTES) { - return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); - } - } else { - try { - buf = await fetchDownloadFile( - url!, - parseDownloadHeaders(params.headers), - DOWNLOAD_FILE_MAX_BYTES, - DOWNLOAD_FILE_TIMEOUT_MS, - ); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - } - - const safe = resolveSafePath(name, buf); - if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); - // 使用异步写入,避免 GiB 级下载阻塞事件循环。 - // 之前的 writeFileSync 会在运行期间卡住其他所有机器人动作。 - await fs.promises.writeFile(safe, buf); - return okResponse({ file: safe }); - }); - - h.registerAction('set_qq_profile', async (params) => { - - const nickname = params.nickname !== undefined ? asString(params.nickname) : undefined; - const personalNote = params.personal_note !== undefined ? asString(params.personal_note) : undefined; - - - try { - await ctx.bridge.apis.profile.setProfile(nickname, personalNote); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('set_online_status', async (params) => { - const status = asNumber(params.status); - const extStatus = asNumber(params.ext_status) || 0; - const batteryStatus = asNumber(params.battery_status) || 100; - - // 参数校验 - if (status === undefined || status === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'status is required'); - } - - - try { - await ctx.bridge.apis.profile.setOnlineStatus(status, extStatus, batteryStatus); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - // 自定义在线状态:与 set_online_status 使用相同的网络包。 - // 这里只填充 customExt 子消息,并将 status/extStatus 强制设为 QQ 定义的“我有自定义状态”取值(10 / 2000)。 - // face_id 和 face_type 可接受数字或数字字符串,以兼容 NapCat;wording 是图标旁展示的可读文本。 - h.registerAction('set_diy_online_status', async (params) => { - const faceId = asNumber(params.face_id); - const faceType = asNumber(params.face_type) || 1; - const wording = asString(params.wording); - if (!faceId) return failedResponse(RETCODE.BAD_REQUEST, 'face_id is required'); - try { - await ctx.bridge.apis.profile.setDiyOnlineStatus(faceId, wording, faceType); - return okResponse(); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - // 已过滤(机器人/被忽略)的入群请求。 - // SnowLuma 已通过 fetchGroupRequests 实现底层 oidb 0x10c8_2 拉取。 - // 这几个动作只是为实际使用中的 OneBot 方言客户端重命名并投影相同数据。 - const fetchFilteredGroupRequests = async () => { - try { - return await ctx.bridge.apis.contacts.fetchGroupRequests(true); - } catch { - return []; - } - }; - - h.registerAction('get_group_ignored_notifies', async () => { - const reqs = await fetchFilteredGroupRequests(); - return okResponse(reqs.map((r) => ({ - group_id: r.groupId, - group_name: r.groupName, - request_id: r.sequence, - requester_uin: r.targetUin, - requester_nick: r.targetName, - message: r.comment, - checked: r.state !== 1, - actor: r.operatorUin, - invitor_uin: r.invitorUin, - invitor_nick: r.invitorName, - flag: `${r.eventType}:${r.groupId}:${r.targetUid}:filtered`, - }))); - }); - - // NapCat 对“被忽略通知中属于入群请求的子集”的命名(notify type == 7)。 - // 这里把经过过滤的 0x10c8_2 每一项映射成 NapCat 结构。 - // eventType 已经在当前流水线中编码了请求类别。 - h.registerAction('get_group_ignore_add_request', async () => { - const reqs = await fetchFilteredGroupRequests(); - return okResponse(reqs.map((r) => ({ - request_id: r.sequence, - invitor_uin: r.invitorUin, - invitor_nick: r.invitorName, - group_id: r.groupId, - message: r.comment, - group_name: r.groupName, - checked: r.state !== 1, - actor: r.operatorUin, - requester_nick: r.targetName, - }))); - }); - - // get_group_shut_list 依赖尚未封装的 oidb。 - // 这里遵循 NapCat 约定返回空列表,避免调用方出错。 - h.registerAction('get_group_shut_list', async () => { - return okResponse([]); - }); - - h.registerAction('forward_friend_single_msg', async (params) => { - const messageId = asNumber(params.message_id); - const userId = asNumber(params.user_id); - if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - try { - const result = await ctx.forwardSingleMsg(messageId, { userId }); - return okResponse({ message_id: result.messageId }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - h.registerAction('forward_group_single_msg', async (params) => { - const messageId = asNumber(params.message_id); - const groupId = asNumber(params.group_id); - if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - try { - const result = await ctx.forwardSingleMsg(messageId, { groupId }); - return okResponse({ message_id: result.messageId }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - h.registerAction('get_profile_like', async (params) => { - const userId = asNumber(params.user_id); - const start = asNumber(params.start) || 0; - const count = asNumber(params.count) || 10; - try { - const data = await ctx.bridge.apis.profile.getLike(userId, start, count); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('fetch_custom_face', async (params) => { - const count = asNumber(params.count) || 10; - try { - const urls = await ctx.bridge.apis.profile.fetchCustomFace(count); - return okResponse(urls); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_emoji_likes', async (params) => { - const messageId = asNumber(params.message_id); - const emojiId = asString(params.emoji_id) || ''; - if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required'); - try { - const result = await ctx.fetchEmojiLikeUsers(messageId, emojiId, 1000); - return okResponse({ - emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })), - }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('fetch_emoji_like', async (params) => { - const messageId = asNumber(params.message_id); - const emojiId = asString(params.emojiId) || ''; - const count = asNumber(params.count) || 10; - const cookie = asString(params.cookie) || ''; - if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emojiId are required'); - try { - const offset = cookie ? Number.parseInt(cookie, 10) || 0 : 0; - const result = await ctx.fetchEmojiLikeUsers(messageId, emojiId, count, offset); - const nextOffset = offset + result.users.length; - const isLastPage = nextOffset >= result.cachedCount; - return okResponse({ - result: 0, - errMsg: '', - emojiLikesList: result.users.map(u => ({ tinyId: String(u.uin), nickName: '', headUrl: '' })), - cookie: isLastPage ? '' : String(nextOffset), - isLastPage, - isFirstPage: offset === 0, - }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_friends_with_category', async () => { - if (ctx.getFriendList) { - return okResponse(await ctx.getFriendList()); - } - return okResponse([]); - }); - - // NapCat 似乎也用不了,暂时不处理。 - h.registerAction('get_online_clients', async () => { - return okResponse({ clients: [] }); - }); - - h.registerAction('_get_model_show', async () => { - return okResponse({ variants: [] }); - }); - - h.registerAction('_set_model_show', async () => { - return okResponse(); - }); - - h.registerAction('.get_word_slices', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - h.registerAction('get_group_at_all_remain', async (params) => { - const groupId = asNumber(params.group_id); - - if (!groupId) { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id'); - } - try { - const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(groupId); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_unidirectional_friend_list', async () => { - - try { - const data = await ctx.bridge.apis.profile.getUnidirectionalFriendList(); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('set_self_longnick', async (params) => { - const longNick = params.longNick || params.long_nick; - - if (typeof longNick !== 'string') { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick'); - } - try { - await ctx.bridge.apis.profile.setSelfLongNick(longNick); - return okResponse({}); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_collection_list', async () => { - return okResponse([]); - }); - - h.registerAction('create_collection', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - h.registerAction('set_qq_avatar', async (params) => { - const file = asString(params.file); - if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); - - - try { - await ctx.bridge.apis.profile.setAvatar(file); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('set_input_status', async (params) => { - const userId = asNumber(params.user_id); - const eventType = asNumber(params.event_type); - - if (!userId) { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid user_id'); - } - - // event_type 有可能是 0 (取消输入状态),所以这里严格判断 undefined 或 isNaN - if (eventType === undefined || isNaN(eventType)) { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid event_type'); - } - - try { - await ctx.bridge.apis.profile.setInputStatus(userId, eventType); - return okResponse({}); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('translate_en2zh', async (params) => { - const rawWords = params.words; - - if (!Array.isArray(rawWords)) { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array'); - } - - const words = rawWords.map(w => String(w)); - - - try { - const translated = await ctx.bridge.apis.misc.translateEn2Zh(words); - return okResponse({ words: translated }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_clientkey', async () => { - const clientKeyInfo = await ctx.bridge.apis.web.forceFetchClientKey(); - if (!clientKeyInfo.clientKey) { - return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error'); - } - return okResponse({ ...clientKeyInfo }); - }); - - h.registerAction('get_mini_app_ark', async (params) => { - const type = params.type || 'bili'; - const title = params.title || ''; - const desc = params.desc || ''; - const picUrl = params.picUrl || params.pic_url || ''; - const jumpUrl = params.jumpUrl || params.jump_url || ''; - - - try { - const data = await ctx.bridge.apis.misc.getMiniAppArk( - String(type), - String(title), - String(desc), - String(picUrl), - String(jumpUrl) - ); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('click_inline_keyboard_button', async (params) => { - const groupId = asNumber(params.group_id); - const botAppid = asNumber(params.bot_appid); - const buttonId = params.button_id; - const callbackData = params.callback_data || ''; - const msgSeq = asNumber(params.msg_seq); - - if (!groupId || !botAppid || !buttonId || !msgSeq) { - return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters'); - } - - - try { - const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton( - groupId, - botAppid, - String(buttonId), - String(callbackData), - msgSeq - ); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - const handleGroupSign = async (params: import('../types').JsonObject) => { - const groupId = asNumber(params.group_id); - - if (!groupId) { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id'); - } - - - try { - await ctx.bridge.apis.misc.sendGroupSign(groupId); - return okResponse({}); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }; - - h.registerAction('set_group_sign', handleGroupSign); - h.registerAction('send_group_sign', handleGroupSign); - - h.registerAction('get_group_info_ex', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (ctx.getGroupInfo) { - return okResponse(await ctx.getGroupInfo(groupId)); - } - return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); - }); - - h.registerAction('get_group_detail_info', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (ctx.getGroupInfo) { - return okResponse(await ctx.getGroupInfo(groupId)); - } - return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); - }); - - h.registerAction('trans_group_file', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - h.registerAction('rename_group_file', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - h.registerAction('get_file', async (params) => { - const fileId = asString(params.file_id) || asString(params.file); - if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required'); - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - const handleSendPacket = async (params: JsonObject) => { - const cmd = asString(params.cmd); - const dataHex = asString(params.data); - const rsp = asBoolean(params.rsp, true); - if (!cmd) return failedResponse(RETCODE.BAD_REQUEST, 'cmd is required'); - if (!/^[0-9a-fA-F]*$/.test(dataHex) || dataHex.length % 2 !== 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'data must be a hex string of even length'); - } - try { - const body = hexToBytes(dataHex); - const result = await ctx.bridge.sendRawPacket(cmd, body); - if (!result.success) { - return failedResponse(RETCODE.ACTION_FAILED, result.errorMessage || 'send failed'); - } - if (!rsp) return okResponse(null); - const respHex = result.responseData ? bytesToHex(result.responseData) : ''; - return okResponse(respHex); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }; - h.registerAction('send_packet', handleSendPacket); - h.registerAction('.send_packet', handleSendPacket); - - // 机器人生命周期(兼容 NapCat)。 - h.registerAction('bot_exit', async () => { - setTimeout(() => process.exit(0), 50); - return okResponse(); - }); - - h.registerAction('nc_get_packet_status', async () => { - return okResponse(null); - }); - - // NapCat 暴露 delete_group_folder。 - // SnowLuma 现有的 delete_group_file_folder 是相同操作。 - // 添加别名以便遵循 NapCat 文档的客户端无需重写载荷。 - h.registerAction('delete_group_folder', async (params) => { - const groupId = asNumber(params.group_id); - const folderId = asString(params.folder_id); - if (!groupId || !folderId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required'); - } - await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId); - return okResponse(); - }); - - // 群待办(oidb 0xF90)。 - // 三个子命令共享相同载荷(群号 + msgSeq)。 - // 这里统一提取一次,并按动作名称分发。 - // msgSeq 来自消息元数据缓存;设置、完成、取消总是指向机器人见过的真实消息。 - type GroupTodoOp = (groupId: number, msgSeq: bigint | number | string) => Promise; - const handleGroupTodo = (op: GroupTodoOp) => async (params: import('../types').JsonObject) => { - const groupId = asNumber(params.group_id); - const messageId = asNumber(params.message_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - const meta = ctx.getMessageMeta(messageId); - if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - if (!meta.isGroup || meta.targetId !== groupId) { - return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group'); - } - try { - await op(groupId, BigInt(meta.sequence)); - return okResponse(); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }; - h.registerAction('set_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.setGroupTodo(g, BigInt(s)))); - h.registerAction('complete_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.completeGroupTodo(g, BigInt(s)))); - h.registerAction('cancel_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.cancelGroupTodo(g, BigInt(s)))); - - // 用户在线/扩展状态(NapCat:nc_get_user_status)。 - - h.registerAction('nc_get_user_status', async (params) => { - const userId = asNumber(params.user_id); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - const status = await ctx.bridge.apis.extras.getStrangerStatus(userId); - if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status'); - return okResponse({ ...status }); - }); - - // AI 语音(oidb 0x929D / 0x929B)。 - - h.registerAction('get_ai_characters', async (params) => { - const groupId = asNumber(params.group_id); - const chatType = asNumber(params.chat_type) || 1; - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - try { - const list = await ctx.bridge.apis.extras.fetchAiVoiceList(groupId, chatType); - return okResponse(list.map((cat) => ({ - type: cat.category, - characters: cat.voices.map((v) => ({ - character_id: v.voiceId, - character_name: v.voiceDisplayName, - preview_url: v.voiceExampleUrl, - })), - }))); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - h.registerAction('get_ai_record', async (params) => { - const groupId = asNumber(params.group_id); - const character = asString(params.character); - const text = asString(params.text); - const chatType = asNumber(params.chat_type) || 1; - if (!groupId || !character || !text) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required'); - } - try { - const node = await ctx.bridge.apis.extras.fetchAiVoice(groupId, character, text, chatType); - const url = await ctx.bridge.apis.groupFile.getPttUrl(groupId, node); - return okResponse(url); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - // NapCat 的 send_group_ai_record 是仅产生副作用的调用。 - // 调用 fetchAiVoice 会把语音发布到群里。 - // 返回的 message_id 始终为 0,因为 oidb 调用不会回显消息 ID。 - h.registerAction('send_group_ai_record', async (params) => { - const groupId = asNumber(params.group_id); - const character = asString(params.character); - const text = asString(params.text); - const chatType = asNumber(params.chat_type) || 1; - if (!groupId || !character || !text) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required'); - } - try { - await ctx.bridge.apis.extras.fetchAiVoice(groupId, character, text, chatType); - return okResponse({ message_id: 0 }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - h.registerAction('request_decrypt_key', async (params) => { - const dbPath = asString(params.db_path); - if (!dbPath) { - return failedResponse(RETCODE.BAD_REQUEST, 'db_path is required'); - } - - try { - const buffer = Buffer.alloc(128); - const fileHandle = await readFile(dbPath); - - if (fileHandle.length < 0xaf) { - return failedResponse(RETCODE.ACTION_FAILED, 'Database file too short'); - } - - fileHandle.copy(buffer, 0, 0x2f, 0xaf); - const dbSalt = buffer.toString('utf8'); - - if (!/^[0-9a-fA-F]{128}$/.test(dbSalt)) { - return failedResponse(RETCODE.ACTION_FAILED, 'Invalid db_salt: not a valid 128-character hex string'); - } - - const dbKey = await ctx.bridge.apis.misc.getDecryptKey(dbSalt.toLowerCase()); - - return okResponse({ db_key: dbKey }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); } function hexToBytes(hex: string): Uint8Array { diff --git a/packages/onebot/src/actions/friend.ts b/packages/onebot/src/actions/friend.ts index 7e638c99..f1ca2b02 100644 --- a/packages/onebot/src/actions/friend.ts +++ b/packages/onebot/src/actions/friend.ts @@ -1,30 +1,45 @@ -import type { ApiHandler, ApiActionContext } from '../api-handler'; -import { asNumber, asBoolean } from '../api-handler'; -import { RETCODE, failedResponse, okResponse } from '../types'; +import { defineAction, registerActions, f } from '../action-kit'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { okResponse } from '../types'; + +export const actions = [ + defineAction({ + name: 'get_friend_list', + summary: '获取好友列表', + params: {}, + run: async (_p, ctx) => { + if (ctx.getFriendList) { + return okResponse(await ctx.getFriendList()); + } + return okResponse([]); + }, + }), + + defineAction({ + name: 'get_stranger_info', + summary: '获取陌生人信息', + params: { user_id: f.uint().describe('QQ 号') }, + run: async (p, ctx) => { + const userId = p.user_id; + if (ctx.getStrangerInfo) { + const info = await ctx.getStrangerInfo(userId); + return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 }); + } + return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 }); + }, + }), + + defineAction({ + name: 'delete_friend', + summary: '删除好友', + params: { user_id: f.uint().describe('QQ 号'), block: f.bool().default(false) }, + run: async (p, ctx) => { + await ctx.bridge.apis.friend.delete(p.user_id, p.block); + return okResponse(); + }, + }), +]; export function register(h: ApiHandler, ctx: ApiActionContext): void { - h.registerAction('get_friend_list', async () => { - if (ctx.getFriendList) { - return okResponse(await ctx.getFriendList()); - } - return okResponse([]); - }); - - h.registerAction('get_stranger_info', async (params) => { - const userId = asNumber(params.user_id); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - if (ctx.getStrangerInfo) { - const info = await ctx.getStrangerInfo(userId); - return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 }); - } - return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 }); - }); - - h.registerAction('delete_friend', async (params) => { - const userId = asNumber(params.user_id); - const block = asBoolean(params.block, false); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - await ctx.bridge.apis.friend.delete(userId, block); - return okResponse(); - }); + registerActions(h, ctx, actions); } diff --git a/packages/onebot/src/actions/group-admin.ts b/packages/onebot/src/actions/group-admin.ts index 2eda8977..19441311 100644 --- a/packages/onebot/src/actions/group-admin.ts +++ b/packages/onebot/src/actions/group-admin.ts @@ -1,118 +1,135 @@ +import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit'; import type { ApiActionContext, ApiHandler } from '../api-handler'; -import { asBoolean, asNumber, asString } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - h.registerAction('set_group_kick', async (params) => { - const groupId = asNumber(params.group_id); - const userId = asNumber(params.user_id); - const reject = asBoolean(params.reject_add_request, false); - if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.bridge.apis.groupAdmin.kickMember(groupId, userId, reject); - return okResponse(); - }); - - h.registerAction('set_group_kick_members', async (params) => { - const groupId = asNumber(params.group_id); - const userIds = Array.isArray(params.user_id) ? params.user_id.map(asNumber).filter(Boolean) : []; - const reject = asBoolean(params.reject_add_request, false); - if (!groupId || userIds.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id array are required'); - await ctx.bridge.apis.groupAdmin.kickMembers(groupId, userIds, reject); - return okResponse(); - }); - - h.registerAction('set_group_ban', async (params) => { - const groupId = asNumber(params.group_id); - const userId = asNumber(params.user_id); - const duration = asNumber(params.duration) || 1800; - if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.bridge.apis.groupAdmin.muteMember(groupId, userId, duration); - return okResponse(); - }); - - h.registerAction('set_group_whole_ban', async (params) => { - const groupId = asNumber(params.group_id); - const enable = asBoolean(params.enable, true); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - await ctx.bridge.apis.groupAdmin.muteAll(groupId, enable); - return okResponse(); - }); - - h.registerAction('set_group_add_option', async (params) => { - const groupId = asNumber(params.group_id); - const addType = asNumber(params.add_type); - if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required'); - await ctx.bridge.apis.groupAdmin.setAddOption(groupId, addType); - return okResponse(); - }); - - h.registerAction('set_group_search', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - await ctx.bridge.apis.groupAdmin.setSearch(groupId); - return okResponse(); - }); - - h.registerAction('set_group_admin', async (params) => { - const groupId = asNumber(params.group_id); - const userId = asNumber(params.user_id); - const enable = asBoolean(params.enable, true); - if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.bridge.apis.groupAdmin.setAdmin(groupId, userId, enable); - return okResponse(); - }); - - h.registerAction('set_group_card', async (params) => { - const groupId = asNumber(params.group_id); - const userId = asNumber(params.user_id); - const card = asString(params.card); - if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.bridge.apis.groupAdmin.setCard(groupId, userId, card); - return okResponse(); - }); - - h.registerAction('set_group_name', async (params) => { - const groupId = asNumber(params.group_id); - const name = asString(params.group_name); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - await ctx.bridge.apis.groupAdmin.setName(groupId, name); - return okResponse(); - }); - - h.registerAction('set_group_leave', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - await ctx.bridge.apis.groupAdmin.leave(groupId); - return okResponse(); - }); - - h.registerAction('set_group_special_title', async (params) => { - const groupId = asNumber(params.group_id); - const userId = asNumber(params.user_id); - const title = asString(params.special_title); - if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - await ctx.bridge.apis.groupAdmin.setSpecialTitle(groupId, userId, title); - return okResponse(); - }); - - h.registerAction('set_group_anonymous', async () => { - return okResponse(); - }); - - h.registerAction('set_group_anonymous_ban', async () => { - return okResponse(); - }); - - h.registerAction('set_group_portrait', async (params) => { - const groupId = asNumber(params.group_id); - const file = asString(params.file); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); - try { - await ctx.bridge.apis.profile.setGroupAvatar(groupId, file); +export const actions = [ + groupUserAction({ + name: 'set_group_kick', + summary: '踢出群成员', + params: { reject_add_request: f.bool().default(false) }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.kickMember(p.group_id, p.user_id, p.reject_add_request); return okResponse(); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); + }, + }), + + groupAction({ + name: 'set_group_kick_members', + summary: '批量踢出群成员', + params: { user_id: f.array(f.uint()).nonEmpty(), reject_add_request: f.bool().default(false) }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.kickMembers(p.group_id, p.user_id, p.reject_add_request); + return okResponse(); + }, + }), + + groupUserAction({ + name: 'set_group_ban', + summary: '禁言群成员(duration=0 解除)', + params: { duration: f.int({ min: 0 }).default(1800) }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.muteMember(p.group_id, p.user_id, p.duration); + return okResponse(); + }, + }), + + groupAction({ + name: 'set_group_whole_ban', + summary: '全员禁言开关', + params: { enable: f.bool().default(true) }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.muteAll(p.group_id, p.enable); + return okResponse(); + }, + }), + + groupAction({ + name: 'set_group_add_option', + summary: '设置加群选项', + params: { add_type: f.int({ min: 0 }).default(0) }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.setAddOption(p.group_id, p.add_type); + return okResponse(); + }, + }), + + groupAction({ + name: 'set_group_search', + summary: '允许群被搜索', + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.setSearch(p.group_id); + return okResponse(); + }, + }), + + groupUserAction({ + name: 'set_group_admin', + summary: '设置/取消管理员', + params: { enable: f.bool().default(true) }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.setAdmin(p.group_id, p.user_id, p.enable); + return okResponse(); + }, + }), + + groupUserAction({ + name: 'set_group_card', + summary: '设置群名片(空字符串清除)', + params: { card: f.string().default('') }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.setCard(p.group_id, p.user_id, p.card); + return okResponse(); + }, + }), + + groupAction({ + name: 'set_group_name', + summary: '设置群名', + params: { group_name: f.string().default('') }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.setName(p.group_id, p.group_name); + return okResponse(); + }, + }), + + groupAction({ + name: 'set_group_leave', + summary: '退群', + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.leave(p.group_id); + return okResponse(); + }, + }), + + groupUserAction({ + name: 'set_group_special_title', + summary: '设置群头衔', + params: { special_title: f.string().default('') }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.setSpecialTitle(p.group_id, p.user_id, p.special_title); + return okResponse(); + }, + }), + + // No-op stubs (accept and ignore any params, as before). + defineAction({ name: 'set_group_anonymous', summary: '匿名开关(未实现,返回 ok)', params: {}, run: () => okResponse() }), + defineAction({ name: 'set_group_anonymous_ban', summary: '匿名禁言(未实现,返回 ok)', params: {}, run: () => okResponse() }), + + groupAction({ + name: 'set_group_portrait', + summary: '设置群头像', + params: { file: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file); + return okResponse(); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), +]; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + registerActions(h, ctx, actions); } diff --git a/packages/onebot/src/actions/group-album.ts b/packages/onebot/src/actions/group-album.ts index 80628ded..fa646639 100644 --- a/packages/onebot/src/actions/group-album.ts +++ b/packages/onebot/src/actions/group-album.ts @@ -1,133 +1,130 @@ +import { groupAction, registerActions, f } from '../action-kit'; import type { ApiActionContext, ApiHandler } from '../api-handler'; -import { asNumber, asString } from '../api-handler'; import type { JsonValue } from '../types'; import { RETCODE, failedResponse, okResponse } from '../types'; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - h.registerAction('get_group_album_list', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); +export const actions = [ + groupAction({ + name: 'get_group_album_list', + run: async (p, ctx) => { + try { + const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id); + return okResponse(albumList); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to get group album list'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }, + }), - try { - const albumList = await ctx.bridge.apis.groupAlbum.list(groupId); - return okResponse(albumList); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to get group album list'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } - }); + groupAction({ + name: 'upload_image_to_qun_album', + params: { + album_id: f.string({ allowEmpty: false }), + album_name: f.string({ allowEmpty: false }), + file: f.string({ allowEmpty: false }), + }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.groupAlbum.upload(p.group_id, p.album_id, p.album_name, p.file); + return okResponse(null); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to upload image to group album'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }, + }), - h.registerAction('upload_image_to_qun_album', async (params) => { - const groupId = asNumber(params.group_id); - const albumId = asString(params.album_id); - const albumName = asString(params.album_name); - const file = asString(params.file); + groupAction({ + name: 'get_group_album_media_list', + params: { + album_id: f.string({ allowEmpty: false }), + attach_info: f.string().default(''), + }, + run: async (p, ctx) => { + try { + const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(p.group_id, p.album_id, p.attach_info); + return okResponse(mediaList as unknown as JsonValue); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to get group album media list'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }, + }), - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required'); - if (!albumName) return failedResponse(RETCODE.BAD_REQUEST, 'album_name is required'); - if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); + groupAction({ + name: 'do_group_album_comment', + params: { + album_id: f.string({ allowEmpty: false }), + lloc: f.string({ allowEmpty: false }), + content: f.string({ allowEmpty: false }), + }, + run: async (p, ctx) => { + try { + const comment = await ctx.bridge.apis.groupAlbum.comment(p.group_id, p.album_id, p.lloc, p.content); + return okResponse(comment as unknown as JsonValue); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to comment on album media'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }, + }), - try { - await ctx.bridge.apis.groupAlbum.upload(groupId, albumId, albumName, file); - return okResponse(null); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to upload image to group album'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } - }); - - h.registerAction('get_group_album_media_list', async (params) => { - const groupId = asNumber(params.group_id); - const albumId = asString(params.album_id); - const attachInfo = asString(params.attach_info) || ''; - - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required'); - - try { - const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(groupId, albumId, attachInfo); - return okResponse(mediaList as unknown as JsonValue); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to get group album media list'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } - }); - - h.registerAction('do_group_album_comment', async (params) => { - const groupId = asNumber(params.group_id); - const albumId = asString(params.album_id); - const lloc = asString(params.lloc); - const content = asString(params.content); - - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required'); - if (!lloc) return failedResponse(RETCODE.BAD_REQUEST, 'lloc is required'); - if (!content) return failedResponse(RETCODE.BAD_REQUEST, 'content is required'); - - try { - const comment = await ctx.bridge.apis.groupAlbum.comment(groupId, albumId, lloc, content); - return okResponse(comment as unknown as JsonValue); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to comment on album media'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } - }); - - h.registerAction('set_group_album_media_like', async (params) => { - const groupId = asNumber(params.group_id); - const albumId = asString(params.album_id); - const batchId = asString(params.batch_id); - const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数 - - if (!groupId || !albumId || !batchId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required'); - } - - try { - const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, true); - return okResponse(res); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to set like on album media'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } - }); + groupAction({ + name: 'set_group_album_media_like', + params: { + album_id: f.string({ allowEmpty: false }), + batch_id: f.string({ allowEmpty: false }), + lloc: f.string().optional(), // 可选参数(空串按未传处理) + }, + run: async (p, ctx) => { + try { + const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, true); + return okResponse(res); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to set like on album media'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }, + }), // 取消点赞群相册媒体 - h.registerAction('cancel_group_album_media_like', async (params) => { - const groupId = asNumber(params.group_id); - const albumId = asString(params.album_id); - const batchId = asString(params.batch_id); - const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数 + groupAction({ + name: 'cancel_group_album_media_like', + params: { + album_id: f.string({ allowEmpty: false }), + batch_id: f.string({ allowEmpty: false }), + lloc: f.string().optional(), // 可选参数(空串按未传处理) + }, + run: async (p, ctx) => { + try { + const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, false); + return okResponse(res); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to cancel like on album media'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }, + }), - if (!groupId || !albumId || !batchId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required'); - } + groupAction({ + name: 'del_group_album_media', + params: { + album_id: f.string({ allowEmpty: false }), + lloc: f.string({ allowEmpty: false }), + }, + run: async (p, ctx) => { + try { + const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc); + return okResponse(res); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to delete album media'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }, + }), +]; - try { - const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, false); - return okResponse(res); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to cancel like on album media'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } - }); - - h.registerAction('del_group_album_media', async (params) => { - const groupId = asNumber(params.group_id); - const albumId = asString(params.album_id); - const lloc = asString(params.lloc); - - if (!groupId || !albumId || !lloc) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and lloc are required'); - } - - try { - const res = await ctx.bridge.apis.groupAlbum.delete(groupId, albumId, lloc); - return okResponse(res); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to delete album media'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } - }); +export function register(h: ApiHandler, ctx: ApiActionContext): void { + registerActions(h, ctx, actions); } diff --git a/packages/onebot/src/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts index 4f459099..7792ec4e 100644 --- a/packages/onebot/src/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -1,118 +1,153 @@ +import { defineAction, groupAction, registerActions, f } from '../action-kit'; import type { ApiHandler, ApiActionContext } from '../api-handler'; -import { asBoolean, asNumber, asString } from '../api-handler'; -import { RETCODE, failedResponse } from '../types'; -import { okResponse } from '../types'; +import { RETCODE, failedResponse, okResponse } from '../types'; + +export const actions = [ + groupAction({ + name: 'upload_group_file', + summary: '上传群文件', + returns: '{ file_id: string }', + // `folder` / `folder_id` are two aliases for one target dir; the first + // non-empty wins, else '/'. Both default '' so the `||` chain matches the + // legacy `asString(folder) || asString(folder_id) || '/'`. + params: { + file: f.string({ allowEmpty: false }), + name: f.string().default(''), + folder: f.string().default(''), + folder_id: f.string().default(''), + upload_file: f.bool().default(true), + }, + run: async (p, ctx) => { + const folderId = p.folder || p.folder_id || '/'; + const result = await ctx.bridge.apis.groupFile.upload(p.group_id, p.file, p.name, folderId, p.upload_file); + return okResponse({ file_id: result.fileId }); + }, + }), + + defineAction({ + name: 'upload_private_file', + summary: '上传私聊文件', + returns: '{ file_id: string }', + params: { + user_id: f.uint(), + file: f.string({ allowEmpty: false }), + name: f.string().default(''), + upload_file: f.bool().default(true), + }, + run: async (p, ctx) => { + const result = await ctx.bridge.apis.groupFile.uploadPrivate(p.user_id, p.file, p.name, p.upload_file); + return okResponse({ file_id: result.fileId }); + }, + }), + + groupAction({ + name: 'get_group_file_url', + summary: '获取群文件下载链接', + returns: '{ url: string }', + // busid: legacy `asNumber(busid) || 102` mapped absent/0/invalid → 102. + // f.int({min:0}).default(102) keeps absent → 102, but a present 0 now + // stays 0 and a non-numeric busid is now rejected (BAD_REQUEST) instead + // of silently becoming 102. + params: { file_id: f.string({ allowEmpty: false }), busid: f.int({ min: 0 }).default(102) }, + run: async (p, ctx) => { + return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(p.group_id, p.file_id, p.busid) }); + }, + }), + + groupAction({ + name: 'get_group_root_files', + summary: '获取群根目录文件列表', + run: async (p, ctx) => { + return okResponse(await ctx.getGroupFiles(p.group_id, '/')); + }, + }), + + groupAction({ + name: 'get_group_files_by_folder', + summary: '获取群子目录文件列表', + // folder_id / folder are aliases; first non-empty wins, else '/'. + params: { folder_id: f.string().default(''), folder: f.string().default('') }, + run: async (p, ctx) => { + const folderId = p.folder_id || p.folder || '/'; + return okResponse(await ctx.getGroupFiles(p.group_id, folderId)); + }, + }), + + groupAction({ + name: 'delete_group_file', + summary: '删除群文件', + params: { file_id: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupFile.delete(p.group_id, p.file_id); + return okResponse(); + }, + }), + + groupAction({ + name: 'move_group_file', + summary: '移动群文件', + params: { + file_id: f.string({ allowEmpty: false }), + parent_directory: f.string({ allowEmpty: false }), + target_directory: f.string({ allowEmpty: false }), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupFile.move(p.group_id, p.file_id, p.parent_directory, p.target_directory); + return okResponse(); + }, + }), + + groupAction({ + name: 'create_group_file_folder', + summary: '创建群文件夹', + params: { name: f.string({ allowEmpty: false }), parent_id: f.string().default('/') }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupFile.createFolder(p.group_id, p.name, p.parent_id || '/'); + return okResponse(); + }, + }), + + groupAction({ + name: 'delete_group_file_folder', + summary: '删除群文件夹', + params: { folder_id: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupFile.deleteFolder(p.group_id, p.folder_id); + return okResponse(); + }, + }), + + groupAction({ + name: 'rename_group_file_folder', + summary: '重命名群文件夹', + // new_folder_name / name are aliases; first non-empty wins and must be + // non-empty (legacy `asString(new_folder_name) || asString(name)` + `!newName`). + params: { folder_id: f.string({ allowEmpty: false }), new_folder_name: f.string().default(''), name: f.string().default('') }, + run: async (p, ctx) => { + const newName = p.new_folder_name || p.name; + if (!newName) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required'); + } + await ctx.bridge.apis.groupFile.renameFolder(p.group_id, p.folder_id, newName); + return okResponse(); + }, + }), + + defineAction({ + name: 'get_private_file_url', + summary: '获取私聊文件下载链接', + returns: '{ url: string }', + params: { + user_id: f.uint(), + file_id: f.string({ allowEmpty: false }), + file_hash: f.string({ allowEmpty: false }), + }, + run: async (p, ctx) => { + return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(p.user_id, p.file_id, p.file_hash) }); + }, + }), +]; export function register(h: ApiHandler, ctx: ApiActionContext): void { - h.registerAction('upload_group_file', async (params) => { - const groupId = asNumber(params.group_id); - const file = asString(params.file); - const name = asString(params.name); - const folderId = asString(params.folder) || asString(params.folder_id) || '/'; - const uploadFile = asBoolean(params.upload_file, true); - if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required'); - const result = await ctx.bridge.apis.groupFile.upload(groupId, file, name, folderId, uploadFile); - return okResponse({ file_id: result.fileId }); - }); - - h.registerAction('upload_private_file', async (params) => { - const userId = asNumber(params.user_id); - const file = asString(params.file); - const name = asString(params.name); - const uploadFile = asBoolean(params.upload_file, true); - if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required'); - const result = await ctx.bridge.apis.groupFile.uploadPrivate(userId, file, name, uploadFile); - return okResponse({ file_id: result.fileId }); - }); - - h.registerAction('get_group_file_url', async (params) => { - const groupId = asNumber(params.group_id); - const fileId = asString(params.file_id); - const busId = asNumber(params.busid) || 102; - if (!groupId || !fileId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required'); - } - return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(groupId, fileId, busId) }); - }); - - h.registerAction('get_group_root_files', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - } - return okResponse(await ctx.getGroupFiles(groupId, '/')); - }); - - h.registerAction('get_group_files_by_folder', async (params) => { - const groupId = asNumber(params.group_id); - const folderId = asString(params.folder_id) || asString(params.folder) || '/'; - if (!groupId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - } - return okResponse(await ctx.getGroupFiles(groupId, folderId)); - }); - - h.registerAction('delete_group_file', async (params) => { - const groupId = asNumber(params.group_id); - const fileId = asString(params.file_id); - if (!groupId || !fileId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required'); - } - await ctx.bridge.apis.groupFile.delete(groupId, fileId); - return okResponse(); - }); - - h.registerAction('move_group_file', async (params) => { - const groupId = asNumber(params.group_id); - const fileId = asString(params.file_id); - const parentDirectory = asString(params.parent_directory); - const targetDirectory = asString(params.target_directory); - if (!groupId || !fileId || !parentDirectory || !targetDirectory) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required'); - } - await ctx.bridge.apis.groupFile.move(groupId, fileId, parentDirectory, targetDirectory); - return okResponse(); - }); - - h.registerAction('create_group_file_folder', async (params) => { - const groupId = asNumber(params.group_id); - const name = asString(params.name); - const parentId = asString(params.parent_id) || '/'; - if (!groupId || !name) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required'); - } - await ctx.bridge.apis.groupFile.createFolder(groupId, name, parentId); - return okResponse(); - }); - - h.registerAction('delete_group_file_folder', async (params) => { - const groupId = asNumber(params.group_id); - const folderId = asString(params.folder_id); - if (!groupId || !folderId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required'); - } - await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId); - return okResponse(); - }); - - h.registerAction('rename_group_file_folder', async (params) => { - const groupId = asNumber(params.group_id); - const folderId = asString(params.folder_id); - const newName = asString(params.new_folder_name) || asString(params.name); - if (!groupId || !folderId || !newName) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required'); - } - await ctx.bridge.apis.groupFile.renameFolder(groupId, folderId, newName); - return okResponse(); - }); - - h.registerAction('get_private_file_url', async (params) => { - const userId = asNumber(params.user_id); - const fileId = asString(params.file_id); - const fileHash = asString(params.file_hash); - if (!userId || !fileId || !fileHash) { - return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required'); - } - return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(userId, fileId, fileHash) }); - }); + registerActions(h, ctx, actions); } diff --git a/packages/onebot/src/actions/group-info.ts b/packages/onebot/src/actions/group-info.ts index 0e4d7eee..15c89d84 100644 --- a/packages/onebot/src/actions/group-info.ts +++ b/packages/onebot/src/actions/group-info.ts @@ -1,84 +1,114 @@ +import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit'; import type { ApiHandler, ApiActionContext } from '../api-handler'; -import { asNumber, asBoolean, asString } from '../api-handler'; +import { asString } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; import { WebHonorType } from '@snowluma/protocol/web/group-honor'; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - h.registerAction('get_group_list', async (params) => { - const noCache = asBoolean(params.no_cache, false); - if (ctx.getGroupList) { - return okResponse(await ctx.getGroupList(noCache)); - } - return okResponse([]); - }); +export const actions = [ + defineAction({ + name: 'get_group_list', + summary: '获取群列表', + params: { no_cache: f.bool().default(false) }, + run: async (p, ctx) => { + const noCache = p.no_cache; + if (ctx.getGroupList) { + return okResponse(await ctx.getGroupList(noCache)); + } + return okResponse([]); + }, + }), - h.registerAction('get_group_info', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - const noCache = asBoolean(params.no_cache, false); - if (ctx.getGroupInfo) { - const info = await ctx.getGroupInfo(groupId, noCache); - return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 }); - } - return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 }); - }); + groupAction({ + name: 'get_group_info', + summary: '获取群信息', + params: { no_cache: f.bool().default(false) }, + run: async (p, ctx) => { + const groupId = p.group_id; + const noCache = p.no_cache; + if (ctx.getGroupInfo) { + const info = await ctx.getGroupInfo(groupId, noCache); + return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 }); + } + return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 }); + }, + }), - h.registerAction('get_group_member_list', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - const noCache = asBoolean(params.no_cache, false); - if (ctx.getGroupMemberList) { - return okResponse(await ctx.getGroupMemberList(groupId, noCache)); - } - return okResponse([]); - }); + groupAction({ + name: 'get_group_member_list', + summary: '获取群成员列表', + params: { no_cache: f.bool().default(false) }, + run: async (p, ctx) => { + const groupId = p.group_id; + const noCache = p.no_cache; + if (ctx.getGroupMemberList) { + return okResponse(await ctx.getGroupMemberList(groupId, noCache)); + } + return okResponse([]); + }, + }), - h.registerAction('get_group_member_info', async (params) => { - const groupId = asNumber(params.group_id); - const userId = asNumber(params.user_id); - if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); - const noCache = asBoolean(params.no_cache, false); - if (ctx.getGroupMemberInfo) { - const info = await ctx.getGroupMemberInfo(groupId, userId, noCache); - return okResponse(info ?? { + groupUserAction({ + name: 'get_group_member_info', + summary: '获取群成员信息', + params: { no_cache: f.bool().default(false) }, + run: async (p, ctx) => { + const groupId = p.group_id; + const userId = p.user_id; + const noCache = p.no_cache; + if (ctx.getGroupMemberInfo) { + const info = await ctx.getGroupMemberInfo(groupId, userId, noCache); + return okResponse(info ?? { + group_id: groupId, user_id: userId, nickname: '', card: '', + sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0, + level: '0', role: 'member', title: '', + }); + } + return okResponse({ group_id: groupId, user_id: userId, nickname: '', card: '', sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0, level: '0', role: 'member', title: '', }); - } - return okResponse({ - group_id: groupId, user_id: userId, nickname: '', card: '', - sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0, - level: '0', role: 'member', title: '', - }); - }); + }, + }), - h.registerAction('get_group_honor_info', async (params) => { - const groupId = asNumber(params.group_id); - const typeStr = asString(params.type) || 'all'; + // `type` keeps the legacy `asString(x) || 'all'` semantics (absent / non-string + // / empty-string all collapse to 'all'), which a typed string field can't + // replicate exactly — so it stays a raw param coerced in run(). + groupAction({ + name: 'get_group_honor_info', + summary: '获取群荣誉信息', + params: { type: f.raw() }, + run: async (p, ctx) => { + const groupId = p.group_id; + const typeStr = asString(p.type) || 'all'; - if (!groupId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - } + const typeValues = Object.values(WebHonorType) as string[]; + if (!typeValues.includes(typeStr)) { + return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`); + } + try { + const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType); + return okResponse(honorInfo); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`); + } + }, + }), - const typeValues = Object.values(WebHonorType) as string[]; - if (!typeValues.includes(typeStr)) { - return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`); - } + defineAction({ + name: 'get_group_system_msg', + summary: '获取群系统消息', + params: {}, + run: async (_p, ctx) => { + if (ctx.handleGetGroupSystemMsg) { + return okResponse(await ctx.handleGetGroupSystemMsg()); + } + return okResponse([]); + }, + }), +]; - try { - const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType); - return okResponse(honorInfo); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`); - } - }); - - h.registerAction('get_group_system_msg', async () => { - if (ctx.handleGetGroupSystemMsg) { - return okResponse(await ctx.handleGetGroupSystemMsg()); - } - return okResponse([]); - }); +export function register(h: ApiHandler, ctx: ApiActionContext): void { + registerActions(h, ctx, actions); } diff --git a/packages/onebot/src/actions/info.ts b/packages/onebot/src/actions/info.ts index ee8457e1..1b9657c3 100644 --- a/packages/onebot/src/actions/info.ts +++ b/packages/onebot/src/actions/info.ts @@ -1,32 +1,58 @@ +import { defineAction, registerActions } from '../action-kit'; import type { ApiActionContext, ApiHandler } from '../api-handler'; import { okResponse } from '../types'; +// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。 +const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev'; + +export const actions = [ + defineAction({ + name: 'get_login_info', + params: {}, + run: (_p, ctx) => { + const login = ctx.getLoginInfo(); + return okResponse({ user_id: login.userId, nickname: login.nickname }); + }, + }), + + defineAction({ + name: 'get_status', + params: {}, + run: (_p, ctx) => { + const online = ctx.isOnline(); + return okResponse({ online, good: online }); + }, + }), + + defineAction({ + name: 'get_version_info', + params: {}, + run: () => { + return okResponse({ + app_name: 'SnowLuma', + app_version: `${appVersion}-node`, + protocol_version: 'v11', + }); + }, + }), + + defineAction({ + name: 'can_send_image', + params: {}, + run: (_p, ctx) => { + return okResponse({ yes: ctx.canSendImage?.() ?? false }); + }, + }), + + defineAction({ + name: 'can_send_record', + params: {}, + run: (_p, ctx) => { + return okResponse({ yes: ctx.canSendRecord?.() ?? false }); + }, + }), +]; + export function register(h: ApiHandler, ctx: ApiActionContext): void { - h.registerAction('get_login_info', async () => { - const login = ctx.getLoginInfo(); - return okResponse({ user_id: login.userId, nickname: login.nickname }); - }); - - h.registerAction('get_status', async () => { - const online = ctx.isOnline(); - return okResponse({ online, good: online }); - }); - - // 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。 - const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev'; - h.registerAction('get_version_info', async () => { - return okResponse({ - app_name: 'SnowLuma', - app_version: `${appVersion}-node`, - protocol_version: 'v11', - }); - }); - - h.registerAction('can_send_image', async () => { - return okResponse({ yes: ctx.canSendImage?.() ?? false }); - }); - - h.registerAction('can_send_record', async () => { - return okResponse({ yes: ctx.canSendRecord?.() ?? false }); - }); + registerActions(h, ctx, actions); } diff --git a/packages/onebot/src/actions/message.ts b/packages/onebot/src/actions/message.ts index b2fbe754..73fd711f 100644 --- a/packages/onebot/src/actions/message.ts +++ b/packages/onebot/src/actions/message.ts @@ -1,6 +1,6 @@ import type { JsonObject, JsonValue } from '../types'; import type { ApiHandler, ApiActionContext } from '../api-handler'; -import { asNumber, asString, asBoolean, asMessage } from '../api-handler'; +import { defineAction, groupAction, registerActions, f } from '../action-kit'; import { RETCODE, failedResponse, okResponse } from '../types'; /** @@ -32,96 +32,85 @@ async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext): } } -export function register(h: ApiHandler, ctx: ApiActionContext): void { - h.registerAction('send_msg', async (params) => { - const messageType = asString(params.message_type); - const message = asMessage(params.message); - const autoEscape = asBoolean(params.auto_escape, false); - - if (message === undefined) { - return failedResponse(RETCODE.BAD_REQUEST, 'message is required'); - } - - if (messageType === 'group' || params.group_id !== undefined) { - const groupId = asNumber(params.group_id); - if (!Number.isInteger(groupId) || groupId <= 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); +export const actions = [ + // send_msg routes on message_type / group_id presence, so the *required* + // id is conditional — that branch stays in run(). The fields themselves + // (message required; group_id/user_id valid uints when present) are + // validated by the spec; message_type is left lenient for parity. + defineAction({ + name: 'send_msg', + summary: '发送消息(按 message_type/群号 自动路由群聊或私聊)', + returns: '{ message_id: number }', + params: { + message: f.message(), + message_type: f.string().optional(), + group_id: f.uint().optional(), + user_id: f.uint().optional(), + auto_escape: f.bool().default(false), + }, + run: async (p, ctx) => { + if (p.message_type === 'group' || p.group_id !== undefined) { + if (p.group_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape); + return okResponse({ message_id: result.messageId }); } - const result = await ctx.sendGroupMessage(groupId, message, autoEscape); + if (p.user_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape); return okResponse({ message_id: result.messageId }); - } + }, + }), - const userId = asNumber(params.user_id); - if (!Number.isInteger(userId) || userId <= 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - } - const result = await ctx.sendPrivateMessage(userId, message, autoEscape); - return okResponse({ message_id: result.messageId }); - }); + defineAction({ + name: 'send_private_msg', + summary: '发送私聊消息', + returns: '{ message_id: number }', + params: { user_id: f.uint(), message: f.message(), auto_escape: f.bool().default(false) }, + run: async (p, ctx) => { + const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape); + return okResponse({ message_id: result.messageId }); + }, + }), - h.registerAction('send_private_msg', async (params) => { - const userId = asNumber(params.user_id); - const message = asMessage(params.message); - const autoEscape = asBoolean(params.auto_escape, false); + groupAction({ + name: 'send_group_msg', + summary: '发送群消息', + returns: '{ message_id: number }', + params: { message: f.message(), auto_escape: f.bool().default(false) }, + run: async (p, ctx) => { + const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape); + return okResponse({ message_id: result.messageId }); + }, + }), - if (!Number.isInteger(userId) || userId <= 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - } - if (message === undefined) { - return failedResponse(RETCODE.BAD_REQUEST, 'message is required'); - } + defineAction({ + name: 'get_msg', + summary: '获取消息', + params: { message_id: f.messageId() }, + run: async (p, ctx) => { + const data = ctx.getMessage(p.message_id); + if (!data) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); + const result: JsonObject = { ...data }; + delete result.post_type; + delete result.self_id; + result.real_id = (result.message_id ?? p.message_id) as JsonValue; + await refreshStoredImageUrls(result, ctx); + return okResponse(result); + }, + }), - const result = await ctx.sendPrivateMessage(userId, message, autoEscape); - return okResponse({ message_id: result.messageId }); - }); + defineAction({ + name: 'delete_msg', + summary: '撤回消息', + params: { message_id: f.messageId() }, + run: async (p, ctx) => { + const meta = ctx.getMessageMeta(p.message_id); + if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable'); + await ctx.deleteMessage(p.message_id, meta); + return okResponse(); + }, + }), +]; - h.registerAction('send_group_msg', async (params) => { - const groupId = asNumber(params.group_id); - const message = asMessage(params.message); - const autoEscape = asBoolean(params.auto_escape, false); - - if (!Number.isInteger(groupId) || groupId <= 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - } - if (message === undefined) { - return failedResponse(RETCODE.BAD_REQUEST, 'message is required'); - } - - const result = await ctx.sendGroupMessage(groupId, message, autoEscape); - return okResponse({ message_id: result.messageId }); - }); - - h.registerAction('get_msg', async (params) => { - const messageId = asNumber(params.message_id); - if (!Number.isInteger(messageId) || messageId === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - } - - const data = ctx.getMessage(messageId); - if (!data) { - return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - } - - const result: JsonObject = { ...data }; - delete result.post_type; - delete result.self_id; - result.real_id = (result.message_id ?? messageId) as JsonValue; - await refreshStoredImageUrls(result, ctx); - return okResponse(result); - }); - - h.registerAction('delete_msg', async (params) => { - const messageId = asNumber(params.message_id); - if (!Number.isInteger(messageId) || messageId === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - } - - const meta = ctx.getMessageMeta(messageId); - if (!meta) { - return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable'); - } - - await ctx.deleteMessage(messageId, meta); - return okResponse(); - }); +export function register(h: ApiHandler, ctx: ApiActionContext): void { + registerActions(h, ctx, actions); } diff --git a/packages/onebot/src/actions/request.ts b/packages/onebot/src/actions/request.ts index e76bade9..18348c76 100644 --- a/packages/onebot/src/actions/request.ts +++ b/packages/onebot/src/actions/request.ts @@ -1,23 +1,42 @@ -import type { ApiHandler, ApiActionContext } from '../api-handler'; -import { asString, asBoolean } from '../api-handler'; -import { RETCODE, failedResponse, okResponse } from '../types'; +import { defineAction, registerActions, f } from '../action-kit'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { asString } from '../api-handler'; +import { okResponse } from '../types'; + +export const actions = [ + defineAction({ + name: 'set_friend_add_request', + summary: '处理好友添加请求', + params: { + flag: f.string({ allowEmpty: false }), + approve: f.bool().default(true), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.friend.handleRequest(p.flag, p.approve); + return okResponse(); + }, + }), + + defineAction({ + name: 'set_group_add_request', + summary: '处理加群请求', + params: { + flag: f.string({ allowEmpty: false }), + // sub_type/type pass through with a nested fallback (sub_type → type → 'add'); + // kept raw so the original asString resolution is preserved verbatim. + sub_type: f.raw(), + type: f.raw(), + approve: f.bool().default(true), + reason: f.string().default(''), + }, + run: async (p, ctx) => { + const subType = asString(p.sub_type, asString(p.type, 'add')); + await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason); + return okResponse(); + }, + }), +]; export function register(h: ApiHandler, ctx: ApiActionContext): void { - h.registerAction('set_friend_add_request', async (params) => { - const flag = asString(params.flag); - const approve = asBoolean(params.approve, true); - if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required'); - await ctx.bridge.apis.friend.handleRequest(flag, approve); - return okResponse(); - }); - - h.registerAction('set_group_add_request', async (params) => { - const flag = asString(params.flag); - const subType = asString(params.sub_type, asString(params.type, 'add')); - const approve = asBoolean(params.approve, true); - const reason = asString(params.reason); - if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required'); - await ctx.handleGroupRequest(flag, subType, approve, reason); - return okResponse(); - }); + registerActions(h, ctx, actions); } diff --git a/packages/onebot/tests/action-docs.test.ts b/packages/onebot/tests/action-docs.test.ts new file mode 100644 index 00000000..9f9170a5 --- /dev/null +++ b/packages/onebot/tests/action-docs.test.ts @@ -0,0 +1,31 @@ +// Tests the self-generated docs (D4): the describe()-walker aggregates every +// declarative action and renders coherent metadata/markdown. +import { describe, it, expect } from 'vitest'; +import { collectActionDocs, renderActionDocsMarkdown } from '../src/action-docs'; + +describe('action-docs', () => { + const docs = collectActionDocs(); + + it('covers the migrated declarative actions with unique names', () => { + expect(docs.length).toBeGreaterThanOrEqual(120); + const names = docs.map((d) => d.name); + expect(new Set(names).size).toBe(names.length); // no duplicates + }); + + it('surfaces preset-injected fields + defaults (set_group_ban)', () => { + const ban = docs.find((d) => d.name === 'set_group_ban'); + expect(ban).toBeDefined(); + expect(ban!.params.map((p) => p.name)).toEqual(['group_id', 'user_id', 'duration']); + const groupId = ban!.params.find((p) => p.name === 'group_id')!; + expect(groupId).toMatchObject({ type: 'uint', required: true }); + const duration = ban!.params.find((p) => p.name === 'duration')!; + expect(duration).toMatchObject({ type: 'int', required: false, default: 1800 }); + }); + + it('renders markdown with header + an action section', () => { + const md = renderActionDocsMarkdown(docs); + expect(md).toContain('# OneBot Actions'); + expect(md).toContain('`set_group_ban`'); + expect(md).toContain('| 参数 | 类型 | 必填 | 默认 | 说明 |'); + }); +}); diff --git a/packages/onebot/tests/action-kit.test.ts b/packages/onebot/tests/action-kit.test.ts new file mode 100644 index 00000000..6ddf74d6 --- /dev/null +++ b/packages/onebot/tests/action-kit.test.ts @@ -0,0 +1,184 @@ +// Interface tests for action-kit — the deepened param-validation module. +// The interface IS the test surface: we drive `parse()` (pure, no ctx) for +// coercion/validation/cross-field, `describe()` for doc metadata, and +// `toHandler()` for the BAD_REQUEST shaping + ctx threading. + +import { describe, it, expect } from 'vitest'; +import { f, defineAction, groupUserAction, type CoerceResult } from '../src/action-kit'; +import type { ApiActionContext } from '../src/api-handler'; +import { RETCODE, okResponse } from '../src/types'; + +const ctx = {} as unknown as ApiActionContext; + +function expectErr(r: CoerceResult): { field: string; reason: string } { + if (r.ok) throw new Error(`expected Err, got Ok(${JSON.stringify(r.value)})`); + return { field: r.field, reason: r.reason }; +} +function expectOk(r: CoerceResult): T { + if (!r.ok) throw new Error(`expected Ok, got Err(${r.field}: ${r.reason})`); + return r.value; +} + +describe('f.uint — positive integer, missing≠0', () => { + const spec = defineAction({ name: 't', params: { x: f.uint() }, run: () => okResponse() }); + it('accepts number and numeric string, truncates', () => { + expect(expectOk(spec.parse({ x: 123 }))).toEqual({ x: 123 }); + expect(expectOk(spec.parse({ x: '456' }))).toEqual({ x: 456 }); + expect(expectOk(spec.parse({ x: 5.7 }))).toEqual({ x: 5 }); + }); + it('rejects missing / 0 / negative / garbage, naming the field', () => { + expect(expectErr(spec.parse({})).field).toBe('x'); + expect(expectErr(spec.parse({})).reason).toBe('is required'); + expect(expectErr(spec.parse({ x: 0 })).field).toBe('x'); // 0 is not a valid id + expect(expectErr(spec.parse({ x: -3 })).field).toBe('x'); + expect(expectErr(spec.parse({ x: 'abc' })).field).toBe('x'); + }); +}); + +describe('f.int({min:0}).default — the duration / unmute fix', () => { + const spec = defineAction({ name: 't', params: { d: f.int({ min: 0 }).default(1800) }, run: () => okResponse() }); + it('missing ⇒ default; present 0 ⇒ 0 (not the default); negative ⇒ err', () => { + expect(expectOk(spec.parse({}))).toEqual({ d: 1800 }); + expect(expectOk(spec.parse({ d: 0 }))).toEqual({ d: 0 }); // the bug the old `|| 1800` had + expect(expectErr(spec.parse({ d: -1 })).field).toBe('d'); + }); + it('present garbage is an error, not a silent fallback', () => { + expect(expectErr(spec.parse({ d: 'abc' })).field).toBe('d'); + }); +}); + +describe('f.messageId — non-zero integer, negatives allowed', () => { + const spec = defineAction({ name: 't', params: { id: f.messageId() }, run: () => okResponse() }); + it('accepts negative ids (signed int32 hash), rejects 0 and garbage', () => { + expect(expectOk(spec.parse({ id: -2147483648 }))).toEqual({ id: -2147483648 }); + expect(expectOk(spec.parse({ id: 123 }))).toEqual({ id: 123 }); + expect(expectErr(spec.parse({ id: 0 })).reason).toBe('must not be 0'); + expect(expectErr(spec.parse({ id: 'x' })).field).toBe('id'); + }); +}); + +describe('f.bool / f.string / f.enum', () => { + it('bool synonyms', () => { + const s = defineAction({ name: 't', params: { b: f.bool() }, run: () => okResponse() }); + expect(expectOk(s.parse({ b: 'on' }))).toEqual({ b: true }); + expect(expectOk(s.parse({ b: 0 }))).toEqual({ b: false }); + expect(expectErr(s.parse({ b: 'maybe' })).field).toBe('b'); + }); + it('string allowEmpty toggle', () => { + const s = defineAction({ name: 't', params: { c: f.string({ allowEmpty: false }) }, run: () => okResponse() }); + expect(expectErr(s.parse({ c: '' })).field).toBe('c'); + expect(expectOk(s.parse({ c: 'x' }))).toEqual({ c: 'x' }); + }); + it('enum literal set', () => { + const s = defineAction({ name: 't', params: { e: f.enum('a', 'b') }, run: () => okResponse() }); + expect(expectOk(s.parse({ e: 'a' }))).toEqual({ e: 'a' }); + expect(expectErr(s.parse({ e: 'c' })).field).toBe('e'); + }); +}); + +describe('f.array(...).nonEmpty — per-element + non-empty', () => { + const spec = defineAction({ name: 't', params: { ids: f.array(f.uint()).nonEmpty() }, run: () => okResponse() }); + it('accepts a non-empty uint array', () => { + expect(expectOk(spec.parse({ ids: [1, 2, 3] }))).toEqual({ ids: [1, 2, 3] }); + }); + it('rejects empty and names the bad element index', () => { + expect(expectErr(spec.parse({ ids: [] })).field).toBe('ids'); + expect(expectErr(spec.parse({ ids: [1, 'x'] })).field).toBe('ids[1]'); + }); +}); + +describe('f.message — union passthrough + JSON-array string', () => { + const spec = defineAction({ name: 't', params: { m: f.message() }, run: () => okResponse() }); + it('parses a JSON-array string, passes plain string / array through', () => { + expect(expectOk(spec.parse({ m: '[{"type":"text","data":{"text":"hi"}}]' })).m).toEqual([ + { type: 'text', data: { text: 'hi' } }, + ]); + expect(expectOk(spec.parse({ m: 'hello' })).m).toBe('hello'); + expect(expectOk(spec.parse({ m: [{ type: 'face' }] })).m).toEqual([{ type: 'face' }]); + }); + it('required when missing', () => { + expect(expectErr(spec.parse({})).reason).toBe('is required'); + }); +}); + +describe('optional fields', () => { + const spec = defineAction({ name: 't', params: { x: f.uint().optional() }, run: () => okResponse() }); + it('missing ⇒ undefined value, present-invalid ⇒ err', () => { + expect(expectOk(spec.parse({}))).toEqual({ x: undefined }); + expect(expectErr(spec.parse({ x: 'abc' })).field).toBe('x'); + }); +}); + +describe('cross-field rules', () => { + const spec = defineAction({ + name: 'set_msg_emoji_like', + params: { + message_id: f.uint().optional(), + group_id: f.uint().optional(), + user_id: f.uint().optional(), + emoji_id: f.uint(), + }, + rules: (r) => [r.exactlyOneOf('message_id', ['group_id', 'user_id'])], + run: () => okResponse(), + }); + it('passes when exactly one locator group present', () => { + expect(spec.parse({ message_id: 5, emoji_id: 1 }).ok).toBe(true); + expect(spec.parse({ group_id: 9, user_id: 8, emoji_id: 1 }).ok).toBe(true); + }); + it('fails when zero or both groups present', () => { + expect(expectErr(spec.parse({ emoji_id: 1 })).reason).toContain('exactly one of'); + expect(expectErr(spec.parse({ message_id: 5, group_id: 9, user_id: 8, emoji_id: 1 })).reason).toContain('exactly one of'); + }); + it('field errors take priority over rule errors (per-field first)', () => { + expect(expectErr(spec.parse({ emoji_id: 0 })).field).toBe('emoji_id'); + }); +}); + +describe('toHandler — BAD_REQUEST shaping + ctx threading', () => { + const spec = groupUserAction({ + name: 'set_group_ban', + params: { duration: f.int({ min: 0 }).default(1800) }, + run: (p) => okResponse({ seen: [p.group_id, p.user_id, p.duration] }), + }); + it('success path returns run output with typed/defaulted params', async () => { + const res = await spec.toHandler(ctx)({ group_id: 10, user_id: 20 }); + expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { seen: [10, 20, 1800] } }); + }); + it('bad params ⇒ BAD_REQUEST naming the field (not INTERNAL_ERROR)', async () => { + const res = await spec.toHandler(ctx)({ user_id: 20 }); // missing group_id + expect(res.retcode).toBe(RETCODE.BAD_REQUEST); + expect(res.status).toBe('failed'); + expect(res.wording).toContain('group_id'); + }); +}); + +describe('run raw escape hatch — original params as 3rd arg', () => { + it('exposes untouched params for undeclared keys (alias fallbacks etc.)', async () => { + const spec = defineAction({ + name: 't', + params: { user_id: f.uint() }, + run: (_p, _ctx, raw) => okResponse({ extra: (raw.long_nick ?? raw.longNick ?? null) as never }), + }); + const res = await spec.toHandler(ctx)({ user_id: 1, longNick: 'hi' }); + expect(res).toMatchObject({ status: 'ok', data: { extra: 'hi' } }); + }); +}); + +describe('describe — doc metadata for self-generated docs (D4)', () => { + const spec = groupUserAction({ + name: ['set_group_ban', 'ban'], + summary: 'Mute a member', + params: { duration: f.int({ min: 0 }).default(1800).describe('seconds; 0 unmutes') }, + run: () => okResponse(), + }); + it('exposes name, aliases, and per-param metadata (incl. preset-injected fields)', () => { + const doc = spec.describe(); + expect(doc.name).toBe('set_group_ban'); + expect(doc.aliases).toEqual(['ban']); + expect(doc.summary).toBe('Mute a member'); + const names = doc.params.map((p) => p.name); + expect(names).toEqual(['group_id', 'user_id', 'duration']); // presets surfaced + const duration = doc.params.find((p) => p.name === 'duration'); + expect(duration).toMatchObject({ type: 'int', required: false, default: 1800, desc: 'seconds; 0 unmutes' }); + }); +});