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:
7 files changed
+237
No files matched your search
@@ -5,9 +5,38 @@ import {
|
||||
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
|
||||
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
|
||||
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { MediaIndexNode } from './shared';
|
||||
|
||||
/** Inputs for a voice-to-text request, gathered from the received `record`
|
||||
* element + its message meta. `uuid`/`md5Hex` come from the cached record;
|
||||
* the uins + scene from the message meta. */
|
||||
export interface PttTransInput {
|
||||
isGroup: boolean;
|
||||
msgId: number;
|
||||
senderUin: number;
|
||||
/** Receiver uin (c2c) or group uin (group). */
|
||||
peerUin: number;
|
||||
uuid: string;
|
||||
md5Hex: string;
|
||||
duration: number;
|
||||
size: number;
|
||||
format: number;
|
||||
/** Group ptt numeric file id (group only; optional). */
|
||||
fileId?: number;
|
||||
}
|
||||
|
||||
function hexToBytes(hex: string): Uint8Array {
|
||||
const s = (hex || '').trim();
|
||||
if (!s) return new Uint8Array(0);
|
||||
const len = s.length >> 1;
|
||||
const out = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) out[i] = parseInt(s.substr(i * 2, 2), 16);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ─────────────── public types (re-exported from bridge.ts as before) ───
|
||||
|
||||
export type StrangerStatus = NamespaceStrangerStatus;
|
||||
@@ -88,4 +117,57 @@ export class ExtrasApi {
|
||||
}
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
|
||||
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
|
||||
|
||||
/**
|
||||
* Trigger QQ's native voice-to-text on a received ptt and return the text.
|
||||
*
|
||||
* Sends `pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq` (RE'd from
|
||||
* wrapper.node). The response carries the text inline when transcription is
|
||||
* already done; an empty text + errCode 0 means the server is transcribing
|
||||
* asynchronously (there is no dedicated push command), so we re-send with a
|
||||
* short backoff until the text lands or the retry budget is spent — the same
|
||||
* "fire then re-read" shape NapCat uses.
|
||||
*
|
||||
* NOTE: the wire field tags here are reverse-engineered and not yet verified
|
||||
* against a live server; confirm with one capture before trusting failures.
|
||||
*/
|
||||
async translatePttToText(input: PttTransInput, maxRetries = 5, retryDelayMs = 1000): Promise<string> {
|
||||
const md5 = hexToBytes(input.md5Hex);
|
||||
const req: PttTransReq = input.isGroup
|
||||
? {
|
||||
type: 1,
|
||||
groupItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), groupUin: BigInt(input.peerUin),
|
||||
fileId: input.fileId ?? 0, md5, duration: input.duration, size: input.size,
|
||||
format: input.format, uuid: input.uuid,
|
||||
},
|
||||
}
|
||||
: {
|
||||
type: 2,
|
||||
c2cItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), receiverUin: BigInt(input.peerUin),
|
||||
uuid: input.uuid, duration: input.duration, size: input.size, format: input.format, md5,
|
||||
},
|
||||
};
|
||||
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
|
||||
|
||||
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
||||
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'ptt translate request failed');
|
||||
}
|
||||
const resp = protobuf_decode<PttTransResp>(result.responseData);
|
||||
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
|
||||
if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`);
|
||||
const text = item?.text ?? '';
|
||||
if (text) return text;
|
||||
// Empty → still transcribing; back off and retry.
|
||||
if (attempt < maxRetries - 1) {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, retryDelayMs));
|
||||
}
|
||||
}
|
||||
throw new Error('ptt translate timed out (no text returned)');
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -35,6 +35,10 @@
|
||||
"types": "./src/notify.ts",
|
||||
"default": "./src/notify.ts"
|
||||
},
|
||||
"./ptt-trans": {
|
||||
"types": "./src/ptt-trans.ts",
|
||||
"default": "./src/ptt-trans.ts"
|
||||
},
|
||||
"./oidb": {
|
||||
"types": "./src/oidb.ts",
|
||||
"default": "./src/oidb.ts"
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { pb, uint_32, uint_64, bytes } from '@snowluma/proton';
|
||||
|
||||
/**
|
||||
* Voice-to-text (语音转文字) request/response protobufs for the
|
||||
* `pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq` SSO commands.
|
||||
*
|
||||
* Reverse-engineered from QQ-NT `wrapper.node` (macOS 9.9.x) —
|
||||
* `im_core/msg/ptt/ptt_trans_worker.cc` (`EncodeC2CPtt` / `EncodeTroopPtt`
|
||||
* build the request, `OnTranslateResp` decodes the response). The wire shape
|
||||
* here is RE-derived and NOT yet verified against a live server: the numeric
|
||||
* field tags are read straight from the encoder, but the length-delimited
|
||||
* fields (uuid / md5) and the response `text` tag should be confirmed with a
|
||||
* single live capture before relying on them.
|
||||
*
|
||||
* Flow: send Trans{C2C,Group}PttReq → response carries the text inline when
|
||||
* transcription is already done; when it's empty the server transcribes
|
||||
* asynchronously (no dedicated push command exists — see NotifyTransUpdate),
|
||||
* so the caller re-sends with backoff until the text arrives or it times out.
|
||||
*/
|
||||
|
||||
/** Source ptt-element field (NT internal tag) noted in the comment after each. */
|
||||
export interface C2CPttTransItem {
|
||||
msgId?: pb<1, uint_64>;
|
||||
senderUin?: pb<2, uint_64>;
|
||||
receiverUin?: pb<3, uint_64>;
|
||||
uuid?: pb<4, string>; // element 45503 (c2c ptt uuid)
|
||||
duration?: pb<5, uint_32>; // element 45906 (seconds)
|
||||
size?: pb<6, uint_32>; // element 45405 (bytes)
|
||||
format?: pb<7, uint_32>; // element 45907 (voice codec)
|
||||
eventType?: pb<8, uint_32>; // element 45921
|
||||
md5?: pb<9, bytes>; // element 45406 (raw 16-byte md5)
|
||||
}
|
||||
|
||||
export interface GroupPttTransItem {
|
||||
msgId?: pb<1, uint_64>;
|
||||
senderUin?: pb<2, uint_64>;
|
||||
groupUin?: pb<3, uint_64>;
|
||||
fileId?: pb<4, uint_32>; // element 45903 (group ptt numeric file id)
|
||||
md5?: pb<5, bytes>; // element 45406
|
||||
duration?: pb<6, uint_32>; // element 45906
|
||||
size?: pb<7, uint_32>; // element 45405
|
||||
format?: pb<8, uint_32>; // element 45907
|
||||
uuid?: pb<9, string>; // element 45503
|
||||
eventType?: pb<10, uint_32>; // element 45921
|
||||
ext?: pb<11, uint_32>; // element 49202 (optional)
|
||||
}
|
||||
|
||||
/**
|
||||
* Outer request. `type` selects the scene (1 = group, 2 = c2c) and only the
|
||||
* matching item is populated — group at field 2, c2c at field 3.
|
||||
*/
|
||||
export interface PttTransReq {
|
||||
type?: pb<1, uint_32>;
|
||||
groupItem?: pb<2, GroupPttTransItem>;
|
||||
c2cItem?: pb<3, C2CPttTransItem>;
|
||||
}
|
||||
|
||||
/** Per-scene result. `errCode` 0 = ok; `text` carries the recognised speech. */
|
||||
export interface C2CPttTransResult {
|
||||
errCode?: pb<2, uint_32>;
|
||||
text?: pb<8, string>; // VERIFY LIVE: text tag from OnTranslateResp
|
||||
}
|
||||
|
||||
export interface GroupPttTransResult {
|
||||
errCode?: pb<2, uint_32>;
|
||||
text?: pb<9, string>; // VERIFY LIVE: text tag from OnTranslateResp
|
||||
}
|
||||
|
||||
/**
|
||||
* Outer response. `type` echoes the scene; result is at field 2 (group) /
|
||||
* field 3 (c2c). An empty `text` with `errCode == 0` means "transcribing,
|
||||
* retry later".
|
||||
*/
|
||||
export interface PttTransResp {
|
||||
type?: pb<1, uint_32>;
|
||||
groupResult?: pb<2, GroupPttTransResult>;
|
||||
c2cResult?: pb<3, C2CPttTransResult>;
|
||||
}
|
||||
Reference in new issue
Block a user