feat(messages): support animated face results
Allow selecting animated face results and preserve received results in messages and history. Keep the default selection when no result is supplied. Fixes #487
This commit is contained in:
13 files changed
+185
-15
No files matched your search
@@ -150,12 +150,27 @@ export const ELEMENT_CODECS = {
|
||||
|
||||
face: {
|
||||
async toSegment(element) {
|
||||
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
|
||||
return {
|
||||
type: 'face',
|
||||
data: {
|
||||
id: String(element.faceId ?? 0),
|
||||
...(element.resultId !== undefined ? { resultId: element.resultId } : {}),
|
||||
},
|
||||
};
|
||||
},
|
||||
async fromSegment(data) {
|
||||
const id = intOr(data.id, -1);
|
||||
if (id < 0) return null;
|
||||
const element: MessageElementOf<'face'> = { type: 'face', faceId: id };
|
||||
if (data.resultId !== undefined) {
|
||||
if (typeof data.resultId === 'string') {
|
||||
element.resultId = data.resultId;
|
||||
} else if (typeof data.resultId === 'number' && Number.isSafeInteger(data.resultId) && data.resultId >= 0) {
|
||||
element.resultId = String(data.resultId);
|
||||
} else {
|
||||
throw new MessageElementValidationError('INVALID_FIELD', 'face.resultId must be a string or non-negative safe integer', 'face', 'resultId');
|
||||
}
|
||||
}
|
||||
if (data.large !== undefined) {
|
||||
if (data.large === true || data.large === 'true' || data.large === 1 || data.large === '1') {
|
||||
element.large = true;
|
||||
|
||||
@@ -10,7 +10,7 @@ export function segmentToCQ(seg: JsonObject): string {
|
||||
case 'text':
|
||||
return cqEscape(String(data.text ?? ''));
|
||||
case 'face':
|
||||
return `[CQ:face,id=${data.id ?? 0}]`;
|
||||
return `[CQ:face,id=${data.id ?? 0}${data.resultId !== undefined ? `,resultId=${cqEscape(String(data.resultId))}` : ''}]`;
|
||||
case 'image':
|
||||
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||
case 'at':
|
||||
@@ -77,4 +77,3 @@ export async function parseFromCQString(message: string, options?: ParseMessageO
|
||||
|
||||
return elements;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { decodeRichBody } from '@snowluma/protocol/msg-push/rich-body-decoder';
|
||||
import { convertEvent, type ConverterContext } from '../src/event-converter';
|
||||
import { MessageStore } from '../src/message-store';
|
||||
import { GROUP_MESSAGE_EVENT } from '../src/message-id';
|
||||
import { parseMessage } from '../src/message-parser';
|
||||
import { getGroupMsgHistory } from '../src/modules/message-actions';
|
||||
import { segmentsToRawMessage } from '../src/helper/cq';
|
||||
|
||||
const ctx: ConverterContext = {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
};
|
||||
|
||||
describe('face animation results', () => {
|
||||
it('preserves zero from an incoming message through CQ, persistence and history', async () => {
|
||||
const elements = decodeRichBody({
|
||||
richText: { elems: [{ commonElem: {
|
||||
serviceType: 37,
|
||||
businessType: 2,
|
||||
pbElem: Buffer.from('1872320130', 'hex'),
|
||||
} }] },
|
||||
}, true);
|
||||
expect(elements).toEqual([{ type: 'face', faceId: 114, resultId: '0' }]);
|
||||
|
||||
const event = await convertEvent(ctx, {
|
||||
kind: 'group_message',
|
||||
groupId: 30001,
|
||||
groupName: 'group',
|
||||
senderUin: 20001,
|
||||
senderNick: 'sender',
|
||||
senderCard: '',
|
||||
senderRole: 'member',
|
||||
selfUin: 10001,
|
||||
time: 1_700_000_000,
|
||||
msgSeq: 42,
|
||||
msgId: 10042,
|
||||
elements,
|
||||
});
|
||||
if (!event) throw new Error('message conversion returned no event');
|
||||
const message = [{ type: 'face', data: { id: '114', resultId: '0' } }];
|
||||
expect(event.message).toEqual(message);
|
||||
expect(event.raw_message).toBe('[CQ:face,id=114,resultId=0]');
|
||||
await expect(parseMessage(String(event.raw_message), false)).resolves.toEqual(elements);
|
||||
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-face-animation-'));
|
||||
const dbPath = path.join(dir, 'messages.db');
|
||||
let store = new MessageStore(dbPath);
|
||||
try {
|
||||
store.storeEvent(Number(event.message_id), true, 30001, 42, GROUP_MESSAGE_EVENT, event);
|
||||
store.close();
|
||||
store = new MessageStore(dbPath);
|
||||
expect(store.findEvent(Number(event.message_id))?.message).toEqual(message);
|
||||
const history = await getGroupMsgHistory(store, 30001, undefined, 20);
|
||||
expect(history).toHaveLength(1);
|
||||
expect(history[0].message).toEqual(message);
|
||||
expect(history[0].raw_message).toBe(event.raw_message);
|
||||
} finally {
|
||||
store.close();
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('escapes an opaque result identifier without changing its value', async () => {
|
||||
const resultId = 'a,b&[c]';
|
||||
const raw = segmentsToRawMessage([{ type: 'face', data: { id: '114', resultId } }]);
|
||||
await expect(parseMessage(raw, false)).resolves.toEqual([{ type: 'face', faceId: 114, resultId }]);
|
||||
});
|
||||
});
|
||||
@@ -36,6 +36,21 @@ describe('parseMessage', () => {
|
||||
});
|
||||
|
||||
describe('CQ code parsing', () => {
|
||||
it.each(['0', '2', 0, 2])('preserves an animation result %s', async (resultId) => {
|
||||
expect(await parseMessage([{ type: 'face', data: { id: 114, resultId } }], false))
|
||||
.toEqual([{ type: 'face', faceId: 114, resultId: String(resultId) }]);
|
||||
});
|
||||
|
||||
it.each([null, false, {}, [], '', ' ', -1, 1.5, Number.MAX_SAFE_INTEGER + 1])('rejects an invalid animation result %j', async (resultId) => {
|
||||
await expect(parseMessage([{ type: 'face', data: { id: 114, resultId } }], false))
|
||||
.rejects.toMatchObject({ code: 'INVALID_FIELD', field: 'resultId' });
|
||||
});
|
||||
|
||||
it('rejects a selected animation on a small face', async () => {
|
||||
await expect(parseMessage('[CQ:face,id=114,large=false,resultId=0]', false))
|
||||
.rejects.toMatchObject({ code: 'INVALID_FIELD', field: 'resultId' });
|
||||
});
|
||||
|
||||
it('parses face CQ code', async () => {
|
||||
const result = await parseMessage('[CQ:face,id=123]', false);
|
||||
expect(result).toHaveLength(1);
|
||||
|
||||
@@ -58,7 +58,7 @@ function makeTextElem(text: string): ProtoElem {
|
||||
// animated (unless large=false) → CommonElem 37 + QFaceExtra
|
||||
// other id ≥ 260 → CommonElem 33 + QSmallFaceExtra
|
||||
// classic id < 260 → legacy FaceElem
|
||||
async function makeFaceElem(faceId: number, large: boolean, ctx?: SendContext): Promise<ProtoElem> {
|
||||
async function makeFaceElem(faceId: number, large: boolean, resultId: string | undefined, ctx?: SendContext): Promise<ProtoElem> {
|
||||
// With a live bridge, wait for the authoritative catalog. Login normally
|
||||
// preloads it, while this await closes the reconnect / first-send race.
|
||||
const resolved = ctx
|
||||
@@ -75,12 +75,21 @@ async function makeFaceElem(faceId: number, large: boolean, ctx?: SendContext):
|
||||
qsid: faceId,
|
||||
sourceType: 1,
|
||||
stickerType: wire.stickerType,
|
||||
resultId,
|
||||
randomType: 1,
|
||||
}),
|
||||
businessType: wire.stickerType < 4 ? wire.stickerType : 1,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (resultId !== undefined) {
|
||||
throw new MessageElementValidationError(
|
||||
'INVALID_FIELD',
|
||||
`face.resultId requires animation metadata for face ${faceId}`,
|
||||
'face',
|
||||
'resultId',
|
||||
);
|
||||
}
|
||||
if (wire.kind === 'small') {
|
||||
return {
|
||||
commonElem: {
|
||||
@@ -578,7 +587,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
|
||||
break;
|
||||
|
||||
case 'face':
|
||||
result.push(await makeFaceElem(elem.faceId, elem.large ?? true, ctx));
|
||||
result.push(await makeFaceElem(elem.faceId, elem.large ?? true, elem.resultId, ctx));
|
||||
break;
|
||||
|
||||
case 'poke':
|
||||
|
||||
@@ -141,7 +141,7 @@ export const ELEMENT_MANIFEST = {
|
||||
},
|
||||
face: {
|
||||
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
|
||||
fields: fieldsFor<'face'>()(['faceId', 'large']),
|
||||
fields: fieldsFor<'face'>()(['faceId', 'large', 'resultId']),
|
||||
requiredFields: ['faceId'],
|
||||
},
|
||||
reply: {
|
||||
@@ -250,7 +250,7 @@ const STRING_FIELDS: ReadonlySet<string> = new Set([
|
||||
'text', 'uid', 'imageUrl', 'fileId', 'fileName', 'fileHash', 'url',
|
||||
'thumbUrl', 'summary', 'emojiId', 'emojiKey', 'resId', 'filesetId',
|
||||
'forwardSource', 'forwardSummary', 'forwardPrompt', 'forwardUuid',
|
||||
'md5Hex', 'sha1Hex', 'botAppid',
|
||||
'md5Hex', 'sha1Hex', 'botAppid', 'resultId',
|
||||
]);
|
||||
const NUMBER_FIELDS: ReadonlySet<string> = new Set([
|
||||
'faceId', 'targetUin', 'fileSize', 'replySeq', 'replyMessageId',
|
||||
@@ -452,6 +452,14 @@ function validateSemantics(
|
||||
if (!Number.isInteger(element.faceId) || element.faceId < 0) {
|
||||
throwValidation('INVALID_FIELD', 'message element "face" field "faceId" must be a non-negative integer', element.type, 'faceId');
|
||||
}
|
||||
if (element.resultId !== undefined && (direction === 'P' || direction === 'W')) {
|
||||
if (!element.resultId.trim()) {
|
||||
throwValidation('INVALID_FIELD', 'face.resultId must not be empty', element.type, 'resultId');
|
||||
}
|
||||
if (element.large === false) {
|
||||
throwValidation('INVALID_FIELD', 'face.resultId requires an animated face; large cannot be false', element.type, 'resultId');
|
||||
}
|
||||
}
|
||||
return;
|
||||
case 'reply':
|
||||
if (!Number.isInteger(element.replySeq) || element.replySeq <= 0) {
|
||||
|
||||
@@ -41,6 +41,8 @@ export interface FaceElement {
|
||||
faceId: number;
|
||||
/** Send the catalog animation when available (default true). */
|
||||
large?: boolean;
|
||||
/** Selected animation result; omitted to keep the default animation choice. */
|
||||
resultId?: string;
|
||||
}
|
||||
|
||||
export interface ReplyElement {
|
||||
|
||||
@@ -921,7 +921,11 @@ function convertElements(elems: ElemDecoded[], isGroup: boolean): MessageElement
|
||||
// this protobuf twice.
|
||||
const extra = decodedBigFaces.get(elem);
|
||||
if (isValidBigFace(extra)) {
|
||||
result.push({ type: 'face', faceId: extra.qsid });
|
||||
result.push({
|
||||
type: 'face',
|
||||
faceId: extra.qsid,
|
||||
...(extra.resultId != null ? { resultId: extra.resultId } : {}),
|
||||
});
|
||||
}
|
||||
} else if (svcType === 45 && ce.pbElem && ce.pbElem.length > 0) {
|
||||
const markdown = decodedMarkdown.get(elem);
|
||||
|
||||
@@ -466,6 +466,33 @@ describe('SysFaceStore — persistent catalog and query seam', () => {
|
||||
describe('makeFaceElem (via buildSendElems) — three-way wire encoding', () => {
|
||||
const ctx = { bridge: {} as never };
|
||||
|
||||
it.each(['0', '2', 'variant'])('preserves an explicit animation result %s', async (resultId) => {
|
||||
sysFaceStore.load(CATALOG);
|
||||
const [element] = await buildSendElems([{ type: 'face', faceId: 392, resultId }], ctx);
|
||||
expect(protobuf_decode<QFaceExtra>(element.commonElem!.pbElem!)).toMatchObject({
|
||||
qsid: 392, resultId, randomType: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the default animation choice when no result is supplied', async () => {
|
||||
sysFaceStore.load(CATALOG);
|
||||
const [element] = await buildSendElems([{ type: 'face', faceId: 392 }], ctx);
|
||||
const payload = protobuf_decode<QFaceExtra>(element.commonElem!.pbElem!);
|
||||
expect(payload.resultId).toBeNull();
|
||||
expect(payload.randomType).toBe(1);
|
||||
});
|
||||
|
||||
it.each([14, 504])('rejects an animation result without animation metadata for %i', async (faceId) => {
|
||||
sysFaceStore.load(CATALOG);
|
||||
await expect(buildSendElems([{ type: 'face', faceId, resultId: '0' }]))
|
||||
.rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'face', field: 'resultId' });
|
||||
});
|
||||
|
||||
it('rejects incompatible animation options before loading the catalog', async () => {
|
||||
await expect(buildSendElems([{ type: 'face', faceId: 392, large: false, resultId: '0' }], ctx))
|
||||
.rejects.toMatchObject({ code: 'INVALID_FIELD', field: 'resultId' });
|
||||
});
|
||||
|
||||
it('awaits an authoritative refresh when the first send misses the persisted catalog', async () => {
|
||||
sysFaceStore.load(CATALOG.slice(0, 1));
|
||||
let requests = 0;
|
||||
|
||||
@@ -126,6 +126,8 @@ bot.when(
|
||||
|
||||
## Raw Action
|
||||
|
||||
动画系统表情可通过 `face(id, { resultId: '0' })` 指定结果,收到的结果保留在 `face.data.resultId` 中。不传时沿用默认选择;有效结果取决于具体表情,不能与 `large: false` 同用。
|
||||
|
||||
`await bot.getStatus()` 的 `time` 为当前账号服务实例的运行秒数,与 `#sl` 使用相同计时起点;实例重建后重新计时。
|
||||
|
||||
高频接口提供 camelCase 方法;其它 SnowLuma action 可以用 `raw` 或 `rawResponse`:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { normalizeMessage, chain } from './chain';
|
||||
import { escapeCqText, segmentsToCQString } from './cq-format';
|
||||
import { segments } from './segments';
|
||||
import type { AnyMessageSegment, OutgoingMessage } from '../types/index';
|
||||
import type { AnyMessageSegment, FaceSegment, OutgoingMessage } from '../types/index';
|
||||
|
||||
const CQ_REGEX = /\[CQ:([a-zA-Z0-9_.-]+)(?:,([^\]]*))?\]/g;
|
||||
|
||||
@@ -69,11 +69,16 @@ function segmentFromCq(type: string, data: Record<string, string>): AnyMessageSe
|
||||
switch (type) {
|
||||
case 'text':
|
||||
return segments.text(data.text ?? '');
|
||||
case 'face':
|
||||
if (data.large === undefined) return segments.face(data.id ?? '0');
|
||||
if (data.large === 'true' || data.large === '1') return segments.face(data.id ?? '0', { large: true });
|
||||
if (data.large === 'false' || data.large === '0') return segments.face(data.id ?? '0', { large: false });
|
||||
throw new Error('face.large must be true, false, 1, or 0');
|
||||
case 'face': {
|
||||
const options: Omit<FaceSegment['data'], 'id'> = {};
|
||||
if (data.resultId !== undefined) options.resultId = data.resultId;
|
||||
if (data.large !== undefined) {
|
||||
if (data.large === 'true' || data.large === '1') options.large = true;
|
||||
else if (data.large === 'false' || data.large === '0') options.large = false;
|
||||
else throw new Error('face.large must be true, false, 1, or 0');
|
||||
}
|
||||
return segments.face(data.id ?? '0', options);
|
||||
}
|
||||
case 'at':
|
||||
if (data.qq === 'all') return segments.at('all');
|
||||
{
|
||||
|
||||
@@ -9,7 +9,7 @@ export interface MessageSegment<
|
||||
}
|
||||
|
||||
export type TextSegment = MessageSegment<'text', { text: string }>;
|
||||
export type FaceSegment = MessageSegment<'face', { id: string; large?: boolean }>;
|
||||
export type FaceSegment = MessageSegment<'face', { id: string; large?: boolean; resultId?: string }>;
|
||||
export type AtSegment = MessageSegment<'at', { qq: string; name?: string; uid?: string }>;
|
||||
export type ReplySegment = MessageSegment<'reply', { id: string }>;
|
||||
export type ImageSegment = MessageSegment<'image', {
|
||||
|
||||
@@ -11,6 +11,15 @@ import {
|
||||
} from '../src';
|
||||
|
||||
describe('MessageChain', () => {
|
||||
it.each([undefined, true])('preserves animation results through builders and CQ with large=%s', (large) => {
|
||||
const options = { resultId: '0', ...(large !== undefined ? { large } : {}) };
|
||||
const expected = [{ type: 'face', data: { id: '114', ...options } }];
|
||||
expect(face(114, options).toSegments()).toEqual(expected);
|
||||
expect(chain().face(114, options).toSegments()).toEqual(expected);
|
||||
expect(message.face(114, options)).toEqual(expected[0]);
|
||||
expect(parseSegments(toCQString(face(114, options)))).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each([false, true])('preserves face animation selection through builders and CQ, large=%s', (large) => {
|
||||
const expected = [{ type: 'face', data: { id: '451', large } }];
|
||||
const built = face(451, { large });
|
||||
|
||||
Reference in new issue
Block a user