NapCatQQ/packages/napcat-onebot/action/extends/OCRImage.ts
手瓜一十雪 b69352f6a1 Add payload and return schemas to OneBot actions
Introduced explicit payloadSchema and returnSchema definitions for all OneBotAction classes using @sinclair/typebox. This improves type safety, API documentation, and validation for action payloads and return values. Also refactored method signatures and types for consistency across the codebase.
2026-01-25 14:50:58 +08:00

49 lines
1.5 KiB
TypeScript

import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { checkFileExist, uriToLocalFile } from 'napcat-common/src/file';
import fs from 'fs';
import { Static, Type } from '@sinclair/typebox';
const PayloadSchema = Type.Object({
image: Type.String({ description: '图片路径、URL或Base64' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Any({ description: 'OCR结果' });
type ReturnType = Static<typeof ReturnSchema>;
class OCRImageBase extends OneBotAction<PayloadType, ReturnType> {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType): Promise<ReturnType> {
const { path, success } = await uriToLocalFile(this.core.NapCatTempPath, payload.image);
if (!success) {
throw new Error(`OCR ${payload.image}失败, image字段可能格式不正确`);
}
if (path) {
try {
await checkFileExist(path, 5000); // 避免崩溃
const ret = await this.core.apis.SystemApi.ocrImage(path);
if (!ret) {
throw new Error(`OCR ${payload.image}失败`);
}
return ret.result;
} finally {
fs.unlink(path, () => { });
}
}
throw new Error(`OCR ${payload.image}失败, 文件可能不存在`);
}
}
export class OCRImage extends OCRImageBase {
override actionName = ActionName.OCRImage;
}
export class IOCRImage extends OCRImageBase {
override actionName = ActionName.IOCRImage;
}