feat(onebot): voice-to-text action fetch_ptt_text (#79)

Adds NapCat-compatible voice-to-text. New `fetch_ptt_text` action (aliases
`get_ptt_text` / `get_record_text`) takes a message_id, resolves the cached
`record` fingerprint (uuid + md5 + duration/size/format), drives QQ's native
`pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq`, and returns { text }.

The response carries the text inline once transcription is done; an empty
text means the server is still transcribing (there is no dedicated push
command — confirmed via RE), so the bridge re-sends with a short backoff
until the text lands, mirroring NapCat's fire-then-re-read shape.

Layers:
- proto-defs/ptt-trans: PttTransReq/Resp + per-scene items.
- core ExtrasApi.translatePttToText: encode -> sendRawPacket -> decode -> poll.
- onebot media-actions.fetchPttText + api-handler/instance-context wiring.
- onebot extended: register the action + aliases.

The commands + request/response field tags were reverse-engineered from
QQ-NT wrapper.node (im_core/msg/ptt/ptt_trans_worker.cc). The numeric tags
are solid; the length-delimited fields (uuid/md5) and the response text tag
are RE-derived and want one live capture to confirm before relying on them.
This commit is contained in:
DrSmoothl committed 2026-06-02 20:47:06 +08:00
1 parent 9b92f3825d
commit 7336352cd3
7 files changed
+237

No files matched your search

+19
View File
@@ -426,6 +426,25 @@ export const actions = [
},
}),
defineAction({
// Primary name matches NapCat for drop-in migration; the rest are aliases.
name: ['fetch_ptt_text', 'get_ptt_text', 'get_record_text'],
summary: '获取语音转文字结果',
params: {
message_id: f.string().default(''),
},
// `raw` so message_id works whether the client sends a number or a string.
run: async (_p, ctx, raw) => {
const messageId = asNumber(raw.message_id);
if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
try {
return okResponse(await ctx.fetchPttText(messageId));
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : '获取语音转文字结果失败');
}
},
}),
// Cookie、CSRF 令牌和账号信息
defineAction({
name: 'get_cookies',
+1
View File
@@ -76,6 +76,7 @@ export interface ApiActionContext {
}>;
getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (file: string) => Promise<JsonObject | null>;
fetchPttText: (messageId: number) => Promise<{ text: string }>;
}
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
+2
View File
@@ -18,6 +18,7 @@ import {
getStrangerInfo,
} from './modules/contact-actions';
import {
fetchPttText as fetchPttTextAction,
getImageInfo as getCachedImageInfo,
getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions';
@@ -116,6 +117,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
},
getImageInfo: (file) => getCachedImageInfo(mediaStore, file, ref.converterCtx.imageUrlResolver),
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
fetchPttText: (messageId) => fetchPttTextAction(messageStore, mediaStore, bridge, ref.selfId, messageId),
};
}
@@ -3,10 +3,61 @@ import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MessageElement } from '@snowluma/protocol/events';
import type { ImageUrlResolver } from '../event-converter';
import type { MediaStore } from '../media-store';
import type { MessageStore } from '../message-store';
import type { JsonObject } from '../types';
const log = createLogger('OneBot');
/**
* Voice-to-text for a received ptt (issue #79 / NapCat `fetch_ptt_text`).
* Resolves the message's `record` segment to its cached fingerprint
* (uuid + md5 + duration/size/format), then drives QQ's native
* `pttTrans.Trans{C2C,Group}PttReq` via the bridge and returns the text.
*/
export async function fetchPttText(
messageStore: MessageStore,
mediaStore: MediaStore,
bridge: BridgeInterface,
selfId: number,
messageId: number,
): Promise<{ text: string }> {
const event = messageStore.findEvent(messageId);
if (!event) throw new Error('消息不存在或已被撤回');
const segments = Array.isArray(event.message) ? event.message : [];
let file = '';
for (const seg of segments) {
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
const so = seg as JsonObject;
if (so.type !== 'record') continue;
const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data)) ? so.data as JsonObject : {};
file = String(data.file ?? data.url ?? '');
break;
}
if (!file) throw new Error('消息中不包含语音');
const cached = mediaStore.findRecord(file);
if (!cached) throw new Error('语音不在缓存中,无法转写');
const isGroup = event.message_type === 'group' || cached.isGroup;
const senderUin = Number(event.user_id) || 0;
// c2c: receiver is self (inbound voice); group: the group uin.
const peerUin = isGroup ? (Number(event.group_id) || cached.sessionId) : selfId;
const text = await bridge.apis.extras.translatePttToText({
isGroup,
msgId: messageId,
senderUin,
peerUin,
uuid: cached.fileId || '',
md5Hex: cached.md5Hex ?? '',
duration: cached.duration ?? 0,
size: cached.fileSize ?? 0,
format: cached.voiceFormat ?? 0,
});
return { text };
}
export async function getImageInfo(
mediaStore: MediaStore,
file: string,