feat(onebot): add napcat-parity actions (Tier 1 + Tier 2)
Wires 16 OneBot actions that napcat exposes but SnowLuma previously either lacked or stubbed: Tier 1 (pure glue over existing Bridge capabilities) - send_packet / .send_packet: real impl over Bridge.sendRawPacket - bot_exit, nc_get_packet_status, nc_get_rkey - get_group_ignored_notifies / get_group_ignore_add_request: project fetchGroupRequests(filtered=true) into napcat shapes (was empty stub) - delete_group_folder alias for delete_group_file_folder Tier 2 (new oidb proto + Bridge method) - set_/complete_/cancel_group_todo (oidb 0xF90_1/2/3) - nc_get_user_status (oidb 0xFE1_2 with napcat's status decode) - get_ai_characters / get_ai_record / send_group_ai_record (oidb 0x929D / 0x929B; AI voice reuses the existing fetchGroupPttUrlByNode) BridgeInterface now exposes sendRawPacket as the deliberate escape hatch for send_packet — every other surface method already wraps it. 46 new tests: 13 bridge-action (mocked runOidb dispatch checks) + 33 OneBot-action (ApiHandler.handle end-to-end).
This commit is contained in:
7 files changed
+1138
-6
No files matched your search
@@ -0,0 +1,155 @@
|
||||
// Tier-2 napcat-parity actions ported as pure oidb calls. Each function
|
||||
// here corresponds to one napcat PacketApi.pkt.operation.* entry; the
|
||||
// schemas live in proto/oidb-action.ts. Nothing in this file touches
|
||||
// the NTQQ NodeIKernel — every wire trip is one runOidb round-trip.
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import { runOidb } from '../bridge-oidb';
|
||||
import {
|
||||
OidbGroupTodoSchema,
|
||||
OidbStrangerStatusReqSchema,
|
||||
OidbStrangerStatusRespSchema,
|
||||
OidbAiVoiceListReqSchema,
|
||||
OidbAiVoiceListRespSchema,
|
||||
OidbAiVoiceReqSchema,
|
||||
OidbAiVoiceRespSchema,
|
||||
} from '../proto/oidb-action';
|
||||
import type { MediaIndexNode } from './shared';
|
||||
|
||||
// ─────────────── Group todo (0xF90) ───────────────
|
||||
|
||||
export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
|
||||
await runOidb(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0xf90_1',
|
||||
oidbCmd: 0xF90, subCmd: 1,
|
||||
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
|
||||
await runOidb(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0xf90_2',
|
||||
oidbCmd: 0xF90, subCmd: 2,
|
||||
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
|
||||
await runOidb(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0xf90_3',
|
||||
oidbCmd: 0xF90, subCmd: 3,
|
||||
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
|
||||
});
|
||||
}
|
||||
|
||||
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
|
||||
|
||||
export interface StrangerStatus {
|
||||
status: number;
|
||||
ext_status: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror napcat's GetStrangerStatus: decode the extBigInt status word.
|
||||
* Values ≤10 fold into a 10×status; everything else is split into the
|
||||
* high-byte / low-byte ext_status the OneBot dialect uses.
|
||||
*
|
||||
* Returns null on transport / decode failure rather than throwing, so
|
||||
* the OneBot action can produce a clean retcode without try/catch
|
||||
* gymnastics.
|
||||
*/
|
||||
export async function getStrangerStatus(bridge: Bridge, uin: number): Promise<StrangerStatus | null> {
|
||||
try {
|
||||
const resp = await runOidb<{ data?: { status?: { value?: bigint | number } } }>(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
|
||||
oidbCmd: 0xFE1, subCmd: 2,
|
||||
request: {
|
||||
schema: OidbStrangerStatusReqSchema,
|
||||
value: { uin, key: [{ key: 27372 }] },
|
||||
},
|
||||
response: { schema: OidbStrangerStatusRespSchema },
|
||||
});
|
||||
const raw = resp?.data?.status?.value;
|
||||
if (raw === undefined || raw === null) return null;
|
||||
const extBig = typeof raw === 'bigint' ? raw : BigInt(raw);
|
||||
if (extBig <= 10n) {
|
||||
return { status: Number(extBig) * 10, ext_status: 0 };
|
||||
}
|
||||
const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn));
|
||||
return { status: 10, ext_status: status };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
|
||||
|
||||
export const AiVoiceChatType = {
|
||||
Unknown: 0,
|
||||
Sound: 1,
|
||||
Sing: 2,
|
||||
} as const;
|
||||
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
|
||||
|
||||
export interface AiVoiceItem {
|
||||
voiceId: string;
|
||||
voiceDisplayName: string;
|
||||
voiceExampleUrl: string;
|
||||
}
|
||||
|
||||
export interface AiVoiceCategory {
|
||||
category: string;
|
||||
voices: AiVoiceItem[];
|
||||
}
|
||||
|
||||
export async function fetchAiVoiceList(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
chatType: AiVoiceChatType,
|
||||
): Promise<AiVoiceCategory[]> {
|
||||
const resp = await runOidb<{ content?: AiVoiceCategory[] }>(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0x929d_0',
|
||||
oidbCmd: 0x929D, subCmd: 0,
|
||||
request: { schema: OidbAiVoiceListReqSchema, value: { groupUin: groupId, chatType } },
|
||||
response: { schema: OidbAiVoiceListRespSchema },
|
||||
});
|
||||
return resp?.content ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger AI voice synthesis. Server may return an empty msgInfo while
|
||||
* the render is in-flight; we retry until a node materialises or the
|
||||
* cap is hit. napcat uses the same 30-retry budget.
|
||||
*
|
||||
* The returned MediaIndexNode plugs directly into
|
||||
* `bridge.fetchGroupPttUrlByNode`, which already handles every other
|
||||
* download-URL fetch in SnowLuma.
|
||||
*/
|
||||
export async function fetchAiVoice(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AiVoiceChatType,
|
||||
maxRetries = 30,
|
||||
): Promise<MediaIndexNode> {
|
||||
// Random 32-bit session id — server uses this to deduplicate polls.
|
||||
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
const resp = await runOidb<{
|
||||
statusCode?: number;
|
||||
msgInfo?: { msgInfoBody?: Array<{ index?: MediaIndexNode }> };
|
||||
}>(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0x929b_0',
|
||||
oidbCmd: 0x929B, subCmd: 0,
|
||||
request: {
|
||||
schema: OidbAiVoiceReqSchema,
|
||||
value: { groupUin: groupId, voiceId, text, chatType, session: { sessionId } },
|
||||
},
|
||||
response: { schema: OidbAiVoiceRespSchema },
|
||||
});
|
||||
const node = resp?.msgInfo?.msgInfoBody?.[0]?.index;
|
||||
if (node) return node;
|
||||
}
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import type {
|
||||
DownloadRKeyInfo,
|
||||
ClientKeyInfo,
|
||||
} from './bridge';
|
||||
import type { SendPacketResult } from '../protocol/packet-sender';
|
||||
|
||||
export interface BridgeInterface {
|
||||
// ─── Shared state ───
|
||||
@@ -33,6 +34,12 @@ export interface BridgeInterface {
|
||||
// ─── Resolution ───
|
||||
resolveUserUid(uin: number, groupId?: number): Promise<string>;
|
||||
|
||||
// ─── Raw packet (deliberate escape hatch for `send_packet` action) ───
|
||||
// OneBot clients use this to debug or invoke commands SnowLuma has no
|
||||
// typed wrapper for. Every other method on this interface eventually
|
||||
// routes through here.
|
||||
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
|
||||
|
||||
// ─── Send (messages) ───
|
||||
sendGroupMessage(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
|
||||
sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
|
||||
@@ -127,4 +134,12 @@ export interface BridgeInterface {
|
||||
getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<any>;
|
||||
clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number): Promise<any>;
|
||||
sendGroupSign(groupId: number): Promise<any>;
|
||||
|
||||
// ─── Tier-2 napcat parity extras ───
|
||||
setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
|
||||
completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
|
||||
cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
|
||||
getStrangerStatus(uin: number): Promise<{ status: number; ext_status: number } | null>;
|
||||
fetchAiVoiceList(groupId: number, chatType: number): Promise<Array<{ category: string; voices: Array<{ voiceId: string; voiceDisplayName: string; voiceExampleUrl: string }> }>>;
|
||||
fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: number): Promise<MediaIndexNode>;
|
||||
}
|
||||
@@ -99,6 +99,20 @@ import {
|
||||
clickInlineKeyboardButton as clickInlineKeyboardButton_,
|
||||
sendGroupSign as sendGroupSign_,
|
||||
} from './actions/misc';
|
||||
import {
|
||||
setGroupTodo as setGroupTodo_,
|
||||
completeGroupTodo as completeGroupTodo_,
|
||||
cancelGroupTodo as cancelGroupTodo_,
|
||||
getStrangerStatus as getStrangerStatus_,
|
||||
fetchAiVoiceList as fetchAiVoiceList_,
|
||||
fetchAiVoice as fetchAiVoice_,
|
||||
AiVoiceChatType,
|
||||
type AiVoiceCategory,
|
||||
type AiVoiceChatType as AiVoiceChatTypeT,
|
||||
type StrangerStatus,
|
||||
} from './actions/extras';
|
||||
export { AiVoiceChatType };
|
||||
export type { AiVoiceCategory, StrangerStatus };
|
||||
import {
|
||||
getGroupHonorInfo as getGroupHonorInfo_,
|
||||
forceFetchClientKey as forceFetchClientKey_,
|
||||
@@ -528,5 +542,26 @@ export class Bridge implements BridgeInterface {
|
||||
async getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) {
|
||||
return getEmojiLikes_(this, groupId, sequence, emojiId, emojiType, count, cookie);
|
||||
}
|
||||
|
||||
// --- Tier-2 napcat-parity extras (group todo, stranger status, AI voice) ---
|
||||
|
||||
async setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
|
||||
return setGroupTodo_(this, groupId, BigInt(msgSeq));
|
||||
}
|
||||
async completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
|
||||
return completeGroupTodo_(this, groupId, BigInt(msgSeq));
|
||||
}
|
||||
async cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
|
||||
return cancelGroupTodo_(this, groupId, BigInt(msgSeq));
|
||||
}
|
||||
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
|
||||
return getStrangerStatus_(this, uin);
|
||||
}
|
||||
async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatTypeT): Promise<AiVoiceCategory[]> {
|
||||
return fetchAiVoiceList_(this, groupId, chatType);
|
||||
}
|
||||
async fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: AiVoiceChatTypeT) {
|
||||
return fetchAiVoice_(this, groupId, voiceId, text, chatType);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1125,4 +1125,121 @@ export const Oidb0xf16ReqSchema = {
|
||||
field12: { field: 12, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const Oidb0xf16RespSchema = {} satisfies ProtoSchema;
|
||||
export const Oidb0xf16RespSchema = {} satisfies ProtoSchema;
|
||||
|
||||
// --- 0xF90_{1,2,3}: Set / complete / cancel group todo ---
|
||||
// All three subCmds share the same body (groupUin + msgSeq); only the
|
||||
// envelope subCmd differs. Sources: napcat
|
||||
// packet/transformer/action/{Set,Complete,Cancel}GroupTodo.ts.
|
||||
|
||||
export const OidbGroupTodoSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
msgSeq: { field: 2, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0xFE1_2: Get stranger profile (used for online/ext status lookup) ---
|
||||
|
||||
export const OidbStrangerStatusKeySchema = {
|
||||
key: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbStrangerStatusReqSchema = {
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
key: { field: 3, type: 'repeated_message' as const, schema: OidbStrangerStatusKeySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbStrangerStatusRespStatusSchema = {
|
||||
key: { field: 1, type: 'uint32' as const },
|
||||
value: { field: 2, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbStrangerStatusRespDataSchema = {
|
||||
status: { field: 2, type: 'message' as const, schema: OidbStrangerStatusRespStatusSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbStrangerStatusRespSchema = {
|
||||
data: { field: 1, type: 'message' as const, schema: OidbStrangerStatusRespDataSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x929D_0: Fetch AI voice character list ---
|
||||
|
||||
export const OidbAiVoiceListReqSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
chatType: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbAiVoiceListEntrySchema = {
|
||||
voiceId: { field: 1, type: 'string' as const },
|
||||
voiceDisplayName: { field: 2, type: 'string' as const },
|
||||
voiceExampleUrl: { field: 3, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbAiVoiceListCategorySchema = {
|
||||
category: { field: 1, type: 'string' as const },
|
||||
voices: { field: 2, type: 'repeated_message' as const, schema: OidbAiVoiceListEntrySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbAiVoiceListRespSchema = {
|
||||
content: { field: 1, type: 'repeated_message' as const, schema: OidbAiVoiceListCategorySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x929B_0: Trigger AI voice synthesis (returns server-side IndexNode) ---
|
||||
|
||||
export const OidbAiVoiceSessionSchema = {
|
||||
sessionId: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbAiVoiceReqSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
voiceId: { field: 2, type: 'string' as const },
|
||||
text: { field: 3, type: 'string' as const },
|
||||
chatType: { field: 4, type: 'uint32' as const },
|
||||
session: { field: 5, type: 'message' as const, schema: OidbAiVoiceSessionSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// We only need the fields the OneBot adapter consumes back: the
|
||||
// IndexNode payload (which feeds fetchGroupPttUrlByNode) and the
|
||||
// statusCode that the server uses to signal "still rendering, retry".
|
||||
|
||||
export const OidbAiVoiceFileTypeSchema = {
|
||||
type: { field: 1, type: 'uint32' as const },
|
||||
picFormat: { field: 2, type: 'uint32' as const },
|
||||
videoFormat: { field: 3, type: 'uint32' as const },
|
||||
voiceFormat: { field: 4, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbAiVoiceFileInfoSchema = {
|
||||
fileSize: { field: 1, type: 'uint32' as const },
|
||||
fileHash: { field: 2, type: 'string' as const },
|
||||
fileSha1: { field: 3, type: 'string' as const },
|
||||
fileName: { field: 4, type: 'string' as const },
|
||||
type: { field: 5, type: 'message' as const, schema: OidbAiVoiceFileTypeSchema },
|
||||
width: { field: 6, type: 'uint32' as const },
|
||||
height: { field: 7, type: 'uint32' as const },
|
||||
time: { field: 8, type: 'uint32' as const },
|
||||
original: { field: 9, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbAiVoiceIndexNodeSchema = {
|
||||
info: { field: 1, type: 'message' as const, schema: OidbAiVoiceFileInfoSchema },
|
||||
fileUuid: { field: 2, type: 'string' as const },
|
||||
storeId: { field: 3, type: 'uint32' as const },
|
||||
uploadTime: { field: 4, type: 'uint32' as const },
|
||||
ttl: { field: 5, type: 'uint32' as const },
|
||||
subType: { field: 6, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbAiVoiceMsgInfoBodySchema = {
|
||||
index: { field: 1, type: 'message' as const, schema: OidbAiVoiceIndexNodeSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbAiVoiceMsgInfoSchema = {
|
||||
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: OidbAiVoiceMsgInfoBodySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbAiVoiceRespSchema = {
|
||||
statusCode: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
field3: { field: 3, type: 'uint32' as const },
|
||||
msgInfo: { field: 4, type: 'message' as const, schema: OidbAiVoiceMsgInfoSchema },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -221,12 +221,16 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
|
||||
// --- RKey ---
|
||||
|
||||
h.registerAction('get_rkey', async () => {
|
||||
const handleGetRkey = async () => {
|
||||
if (ctx.getDownloadRKeys) {
|
||||
return okResponse(await ctx.getDownloadRKeys());
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
});
|
||||
};
|
||||
h.registerAction('get_rkey', handleGetRkey);
|
||||
// napcat exposes the same payload under `nc_get_rkey`; mirror the alias
|
||||
// so clients that follow napcat's docs work out-of-the-box.
|
||||
h.registerAction('nc_get_rkey', handleGetRkey);
|
||||
|
||||
// --- OCR stubs ---
|
||||
|
||||
@@ -597,10 +601,56 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
}
|
||||
});
|
||||
|
||||
// Filtered (机器人/被忽略) group join requests. SnowLuma already
|
||||
// implements the underlying oidb 0x10c8_2 fetch via fetchGroupRequests;
|
||||
// these three actions just rename / project the same data for the
|
||||
// OneBot dialects clients use in the wild.
|
||||
const fetchFilteredGroupRequests = async () => {
|
||||
try {
|
||||
return await ctx.bridge.fetchGroupRequests(true);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
h.registerAction('get_group_ignored_notifies', async () => {
|
||||
return okResponse([]);
|
||||
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 name for the subset of ignored notifies that are join requests
|
||||
// (notify type==7). We map every entry that flowed through filtered
|
||||
// 0x10c8_2 into napcat's shape — eventType already encodes the request
|
||||
// category in our pipeline.
|
||||
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 lives behind an oidb we don't yet wrap; honour
|
||||
// the napcat contract (empty list) so callers don't blow up.
|
||||
h.registerAction('get_group_shut_list', async () => {
|
||||
return okResponse([]);
|
||||
});
|
||||
@@ -934,9 +984,170 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('.send_packet', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
// --- Raw packet escape hatch (napcat parity) ---
|
||||
//
|
||||
// napcat exposes both names; the dot-prefix variant is the original
|
||||
// gocqhttp-era backdoor, the no-prefix one is the modern API. They do
|
||||
// the same thing in SnowLuma: encode hex → Bridge.sendRawPacket → hex.
|
||||
const handleSendPacket = async (params: import('../types').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);
|
||||
|
||||
// --- Bot lifecycle (napcat parity) ---
|
||||
|
||||
h.registerAction('bot_exit', async () => {
|
||||
// Defer so the OK response actually flushes before the process dies.
|
||||
setTimeout(() => process.exit(0), 50);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
// SnowLuma has no separate packet-backend process (napcat's packet
|
||||
// service runs out-of-process and can fail independently). Always
|
||||
// report healthy.
|
||||
h.registerAction('nc_get_packet_status', async () => {
|
||||
return okResponse(null);
|
||||
});
|
||||
|
||||
// napcat exposes `delete_group_folder`; SnowLuma's existing
|
||||
// `delete_group_file_folder` is the same operation. Alias so clients
|
||||
// following napcat docs work without rewriting payloads.
|
||||
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.deleteGroupFileFolder(groupId, folderId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
// --- Group todo (oidb 0xF90) ---
|
||||
//
|
||||
// The three subcommands share an identical payload (group + msgSeq);
|
||||
// we extract once and dispatch by action name. msgSeq comes from the
|
||||
// message metadata cache (set/complete/cancel always target a real
|
||||
// message the bot has seen).
|
||||
type GroupTodoOp = (groupId: number, msgSeq: bigint | number | string) => Promise<void>;
|
||||
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.setGroupTodo(g, s)));
|
||||
h.registerAction('complete_group_todo', handleGroupTodo((g, s) => ctx.bridge.completeGroupTodo(g, s)));
|
||||
h.registerAction('cancel_group_todo', handleGroupTodo((g, s) => ctx.bridge.cancelGroupTodo(g, s)));
|
||||
|
||||
// --- User online/ext status (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.getStrangerStatus(userId);
|
||||
if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status');
|
||||
return okResponse(status);
|
||||
});
|
||||
|
||||
// --- AI voice (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.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.fetchAiVoice(groupId, character, text, chatType);
|
||||
const url = await ctx.bridge.fetchGroupPttUrlByNode(groupId, node);
|
||||
return okResponse(url);
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
});
|
||||
|
||||
// napcat's send_group_ai_record is a side-effect-only call: invoking
|
||||
// fetchAiVoice publishes the voice into the group; the returned
|
||||
// message_id is always 0 because the oidb call doesn't echo one back.
|
||||
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.fetchAiVoice(groupId, character, text, chatType);
|
||||
return okResponse({ message_id: 0 });
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function hexToBytes(hex: string): Uint8Array {
|
||||
const out = new Uint8Array(hex.length / 2);
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
out[i] = parseInt(hex.substr(i * 2, 2), 16);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function bytesToHex(buf: Buffer | Uint8Array): string {
|
||||
const arr = buf instanceof Buffer ? buf : Buffer.from(buf);
|
||||
return arr.toString('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user