Merge pull request #34 from SnowLuma/dev
chore: promote dev → main (564eec2)
This commit is contained in:
12 files changed
+260
-49
No files matched your search
@@ -30,8 +30,13 @@ export async function sendLike(bridge: Bridge, userId: number, count: number): P
|
||||
export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
|
||||
const subCmd = isSet ? 1 : 2;
|
||||
const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2';
|
||||
// Same heuristic NapCat uses: QQ face ids are 1–3 digits ("76"),
|
||||
// unicode codepoints are longer ("128516"). Server requires the
|
||||
// type field to pick the right resolution table; omitting it makes
|
||||
// unicode reactions silently fail.
|
||||
const type = code.length > 3 ? 2 : 1;
|
||||
await sendOidbAndCheck(bridge, cmd, 0x9082, subCmd,
|
||||
{ groupUin: groupId, sequence, code }, OidbGroupReactionSchema);
|
||||
{ groupUin: groupId, sequence, code, type }, OidbGroupReactionSchema);
|
||||
}
|
||||
|
||||
export async function getEmojiLikes(
|
||||
|
||||
@@ -115,13 +115,59 @@ function makeMarkdownElem(element: MessageElement): ProtoElem {
|
||||
};
|
||||
}
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function makeForwardElem(element: MessageElement): ProtoElem {
|
||||
const resId = (element.resId ?? '').trim();
|
||||
if (!resId) {
|
||||
throw new Error('forward resId is required');
|
||||
}
|
||||
|
||||
const xml = `<?xml version="1.0" encoding="utf-8"?><msg templateID="1" action="viewMultiMsg" serviceID="35" brief="[聊天记录]" m_resid="${resId}" m_fileName="${resId}" actionData="${resId}" tSum="2" sourceMsgId="0" flag="3" adverSign="0" multiMsgFlag="0"><item layout="1"><title size="34" color="#000000">聊天记录</title><title size="26" color="#777777">查看转发消息</title><summary size="26" color="#808080">查看转发消息</summary></item><source name="" icon="" action="" appid="-1"/></msg>`;
|
||||
// Multi-msg preview bubble — modelled on the go-cqhttp / NapCat XML.
|
||||
// `source` becomes the bold header (e.g. "群聊的聊天记录"), `news`
|
||||
// entries become per-line previews ("nick: text"), `summary` is the
|
||||
// grey footer ("查看 N 条转发消息"), `prompt` is the chat-list brief.
|
||||
const source = element.forwardSource && element.forwardSource.length > 0
|
||||
? element.forwardSource
|
||||
: '聊天记录';
|
||||
const summary = element.forwardSummary && element.forwardSummary.length > 0
|
||||
? element.forwardSummary
|
||||
: '查看转发消息';
|
||||
const prompt = element.forwardPrompt && element.forwardPrompt.length > 0
|
||||
? element.forwardPrompt
|
||||
: '[聊天记录]';
|
||||
const news = Array.isArray(element.forwardNews) ? element.forwardNews : [];
|
||||
const tSum = element.forwardTSum && element.forwardTSum > 0
|
||||
? element.forwardTSum
|
||||
: Math.max(news.length, 1);
|
||||
|
||||
const newsTitles = news
|
||||
.map(n => `<title size="26" color="#777777">${escapeXml(n.text ?? '')}</title>`)
|
||||
.join('');
|
||||
|
||||
const resIdAttr = escapeXml(resId);
|
||||
const xml =
|
||||
`<?xml version="1.0" encoding="utf-8"?>` +
|
||||
`<msg templateID="1" action="viewMultiMsg" serviceID="35"` +
|
||||
` brief="${escapeXml(prompt)}"` +
|
||||
` m_resid="${resIdAttr}" m_fileName="${resIdAttr}" actionData="${resIdAttr}"` +
|
||||
` tSum="${tSum}" sourceMsgId="0" flag="3" adverSign="0" multiMsgFlag="0">` +
|
||||
`<item layout="1">` +
|
||||
`<title size="34" color="#000000">${escapeXml(source)}</title>` +
|
||||
newsTitles +
|
||||
`<hr hidden="false" style="0"/>` +
|
||||
`<summary size="26" color="#808080">${escapeXml(summary)}</summary>` +
|
||||
`</item>` +
|
||||
`<source name="${escapeXml(source)}" icon="" action="" appid="-1"/>` +
|
||||
`</msg>`;
|
||||
|
||||
const encodedXml = new TextEncoder().encode(xml);
|
||||
const payload = new Uint8Array(encodedXml.length + 1);
|
||||
payload[0] = 0x00;
|
||||
|
||||
@@ -27,6 +27,15 @@ export interface MessageElement {
|
||||
flash?: boolean;
|
||||
resId?: string;
|
||||
fileHash?: string;
|
||||
// Preview-bubble metadata for the `forward` element. Drives the XML
|
||||
// template (brief/title/news/summary/tSum) the recipient renders before
|
||||
// they tap to expand. When unset, the element builder falls back to
|
||||
// generic defaults so old call sites keep working.
|
||||
forwardSource?: string;
|
||||
forwardSummary?: string;
|
||||
forwardPrompt?: string;
|
||||
forwardNews?: Array<{ text: string }>;
|
||||
forwardTSum?: number;
|
||||
// Server-side fingerprints carried from receive side so a forward can do a
|
||||
// pure md5/sha1 fast-upload without re-downloading the original bytes.
|
||||
// Set together with `noByteFallback: true` to make the upload modules throw
|
||||
|
||||
@@ -460,10 +460,14 @@ export async function uploadVideoMsgInfo(
|
||||
fileHash: video.md5Hex,
|
||||
fileSha1: video.sha1Hex,
|
||||
fileName: 'nya.mp4',
|
||||
type: { type: 2, picFormat: 0, videoFormat: video.videoFormat, voiceFormat: 0 },
|
||||
height: video.height,
|
||||
width: video.width,
|
||||
time: video.duration,
|
||||
// NapCat sends type.videoFormat=0 and width/height/time=0
|
||||
// for the main video sub-file (only the thumb carries
|
||||
// dimensions). The QQ NT server treats non-zero values
|
||||
// here as a schema mismatch on c2c sends.
|
||||
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
|
||||
height: 0,
|
||||
width: 0,
|
||||
time: 0,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
|
||||
@@ -234,35 +234,17 @@ export const NTV2UploadInfoSchema = {
|
||||
subFileType: { field: 2, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2PicReserveC2CSchema = {
|
||||
subType: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2PicReserveTroopSchema = {
|
||||
subType: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2PicExtBizInfoSchema = {
|
||||
bizType: { field: 1, type: 'uint32' as const },
|
||||
textSummary: { field: 2, type: 'string' as const },
|
||||
reserveC2c: { field: 11, type: 'message' as const, schema: NTV2PicReserveC2CSchema },
|
||||
reserveTroop: { field: 12, type: 'message' as const, schema: NTV2PicReserveTroopSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2VideoExtBizInfoSchema = {
|
||||
bytesPbReserve: { field: 3, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const NTV2PttExtBizInfoSchema = {
|
||||
bytesReserve: { field: 11, type: 'bytes' as const },
|
||||
bytesPbReserve: { field: 12, type: 'bytes' as const },
|
||||
bytesGeneralFlags: { field: 13, type: 'bytes' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// The NTV2 upload request + response carry the same ExtBizInfo shape that
|
||||
// element-side incoming-message decoding uses. Pulling those schemas in
|
||||
// directly (instead of redefining stub copies) keeps the round-trip
|
||||
// `server response → finalizeMediaMsgInfo → commonElem.pbElem` from
|
||||
// silently dropping fields the QQ NT server later validates against —
|
||||
// the video `fromScene`/`toScene` drop was already responsible for c2c
|
||||
// `result=79` rejections on `send_private_msg [{type:'video'}]`.
|
||||
export const NTV2ExtBizInfoSchema = {
|
||||
pic: { field: 1, type: 'message' as const, schema: NTV2PicExtBizInfoSchema },
|
||||
video: { field: 2, type: 'message' as const, schema: NTV2VideoExtBizInfoSchema },
|
||||
ptt: { field: 3, type: 'message' as const, schema: NTV2PttExtBizInfoSchema },
|
||||
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
|
||||
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
|
||||
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
|
||||
busiType: { field: 10, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
@@ -395,6 +395,11 @@ export const OidbGroupReactionSchema = {
|
||||
groupUin: { field: 1, type: 'uint32' as const },
|
||||
sequence: { field: 2, type: 'uint32' as const },
|
||||
code: { field: 3, type: 'string' as const },
|
||||
// 1 = legacy QQ face (short numeric id like "76"), 2 = unicode emoji
|
||||
// (decimal codepoint string like "128516" for 😄). Omitting this
|
||||
// field used to make unicode reactions fail server-side because the
|
||||
// server defaulted to type=1 and couldn't resolve a 6-digit code.
|
||||
type: { field: 4, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// --- 0x6D8_1: Group file list ---
|
||||
|
||||
@@ -1,7 +1,34 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asMessage, asNumber, asString, asBoolean } from '../api-handler';
|
||||
import type { ForwardPreviewMeta } from '../modules/message-actions';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
/**
|
||||
* Pull NapCat-compatible forward preview overrides off a send_*_forward_msg
|
||||
* payload. All four fields are optional — when omitted, the module layer
|
||||
* derives sensible defaults from the actual node list.
|
||||
*/
|
||||
function readForwardPreviewMeta(params: Record<string, unknown>): ForwardPreviewMeta | undefined {
|
||||
const source = asString(params.source) || undefined;
|
||||
const summary = asString(params.summary) || undefined;
|
||||
const prompt = asString(params.prompt) || undefined;
|
||||
let news: Array<{ text: string }> | undefined;
|
||||
if (Array.isArray(params.news)) {
|
||||
const collected: Array<{ text: string }> = [];
|
||||
for (const item of params.news) {
|
||||
if (typeof item === 'string') {
|
||||
collected.push({ text: item });
|
||||
} else if (item && typeof item === 'object' && !Array.isArray(item)) {
|
||||
const text = asString((item as Record<string, unknown>).text);
|
||||
if (text) collected.push({ text });
|
||||
}
|
||||
}
|
||||
if (collected.length > 0) news = collected;
|
||||
}
|
||||
if (!source && !summary && !prompt && !news) return undefined;
|
||||
return { source, summary, prompt, news };
|
||||
}
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
// --- Likes & Pokes ---
|
||||
|
||||
@@ -301,18 +328,19 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
const meta = readForwardPreviewMeta(params);
|
||||
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
|
||||
if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) {
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const result = await ctx.sendGroupForwardMsg(groupId, messages);
|
||||
const result = await ctx.sendGroupForwardMsg(groupId, messages, meta);
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
}
|
||||
|
||||
if ((messageType === 'private' || userId > 0) && ctx.sendPrivateForwardMsg) {
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
const result = await ctx.sendPrivateForwardMsg(userId, messages);
|
||||
const result = await ctx.sendPrivateForwardMsg(userId, messages, meta);
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
}
|
||||
|
||||
@@ -326,7 +354,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
|
||||
const result = await ctx.sendGroupForwardMsg(groupId, messages);
|
||||
const result = await ctx.sendGroupForwardMsg(groupId, messages, readForwardPreviewMeta(params));
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
});
|
||||
|
||||
@@ -336,7 +364,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
|
||||
const result = await ctx.sendPrivateForwardMsg(userId, messages);
|
||||
const result = await ctx.sendPrivateForwardMsg(userId, messages, readForwardPreviewMeta(params));
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
import type { ForwardPreviewMeta } from './modules/message-actions';
|
||||
import { RETCODE, failedResponse } from './types';
|
||||
|
||||
import { register as registerInfo } from './actions/info';
|
||||
@@ -97,8 +98,8 @@ export interface ApiActionContext {
|
||||
handleGetGroupSystemMsg: () => Promise<JsonObject[]>;
|
||||
getDownloadRKeys: () => Promise<JsonObject[]>;
|
||||
// Forward message
|
||||
sendGroupForwardMsg: (groupId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
|
||||
sendPrivateForwardMsg: (userId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
|
||||
sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
|
||||
sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
|
||||
sendForwardMsg: (messages: JsonValue) => Promise<{ forwardId: string }>;
|
||||
getForwardMsg: (resId: string) => Promise<JsonObject[]>;
|
||||
forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>;
|
||||
|
||||
@@ -163,8 +163,8 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count),
|
||||
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
|
||||
getDownloadRKeys: () => getDownloadRKeys(bridge),
|
||||
sendGroupForwardMsg: (groupId, messages) => sendGroupForwardMessage(ref, groupId, messages),
|
||||
sendPrivateForwardMsg: (userId, messages) => sendPrivateForwardMessage(ref, userId, messages),
|
||||
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
|
||||
sendPrivateForwardMsg: (userId, messages, meta) => sendPrivateForwardMessage(ref, userId, messages, meta),
|
||||
sendForwardMsg: (messages) => uploadForwardMessage(ref, messages),
|
||||
getForwardMsg: (resId) => getForwardMessage(ref, resId),
|
||||
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
|
||||
|
||||
@@ -60,6 +60,10 @@ export class OneBotManager {
|
||||
instance.addPid(activePid);
|
||||
}
|
||||
|
||||
// Seed nickname with the UIN so the WebUI never renders blank while
|
||||
// warmup is in flight or if warmup never resolves a real nickname.
|
||||
if (!qqInfo.nickname) qqInfo.nickname = uin;
|
||||
|
||||
this.instances.set(uin, instance);
|
||||
log.info('session started: UIN=%s', uin);
|
||||
|
||||
@@ -81,12 +85,17 @@ export class OneBotManager {
|
||||
}
|
||||
|
||||
async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): Promise<void> {
|
||||
// Step 1: Fetch friend list + derive self profile
|
||||
const selfUin = parseInt(uin, 10) || 0;
|
||||
let selfResolved = false;
|
||||
|
||||
// Step 1: Fetch friend list + derive self profile when QQ happens to
|
||||
// include self in the response. Some accounts / versions omit self,
|
||||
// which used to leave qqInfo.nickname empty — see step 1b for the
|
||||
// explicit fallback.
|
||||
try {
|
||||
const friends = await bridge.fetchFriendList();
|
||||
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
|
||||
|
||||
const selfUin = parseInt(uin, 10) || 0;
|
||||
for (const f of friends) {
|
||||
if (f.uin === selfUin) {
|
||||
qqInfo.setSelfProfile({
|
||||
@@ -96,6 +105,7 @@ async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): P
|
||||
});
|
||||
qqInfo.nickname = f.nickname || uin;
|
||||
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
|
||||
selfResolved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -103,6 +113,23 @@ async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): P
|
||||
log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
// Step 1b: friend-list path didn't resolve self → fetch user profile
|
||||
// directly via OIDB 0xFE1_2 so multi-account WebUI shows a nickname
|
||||
// for every injected session, not just the ones where QQ echoed self
|
||||
// back in the friend list.
|
||||
if (!selfResolved && selfUin > 0) {
|
||||
try {
|
||||
const profile = await bridge.fetchUserProfile(selfUin);
|
||||
qqInfo.setSelfProfile(profile);
|
||||
qqInfo.nickname = profile.nickname || uin;
|
||||
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
|
||||
uin, profile.uid, profile.nickname);
|
||||
} catch (e) {
|
||||
log.warn('failed to load self profile for UIN %s: %s',
|
||||
uin, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
// Step 2: Fetch group list
|
||||
let groups: { groupId: number }[] = [];
|
||||
try {
|
||||
|
||||
@@ -180,14 +180,23 @@ export async function sendGroupMessage(
|
||||
return { messageId };
|
||||
}
|
||||
|
||||
export interface ForwardPreviewMeta {
|
||||
source?: string;
|
||||
summary?: string;
|
||||
prompt?: string;
|
||||
news?: Array<{ text: string }>;
|
||||
}
|
||||
|
||||
export async function sendGroupForwardMessage(
|
||||
ref: OneBotInstanceContext,
|
||||
groupId: number,
|
||||
messages: JsonValue,
|
||||
meta?: ForwardPreviewMeta,
|
||||
): Promise<{ messageId: number; forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages);
|
||||
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
|
||||
const receipt = await ref.bridge.sendGroupMessage(groupId, [{ type: 'forward', resId: forwardId }]);
|
||||
const previewElement = buildForwardPreviewElement(forwardId, nodes, true, meta);
|
||||
const receipt = await ref.bridge.sendGroupMessage(groupId, [previewElement]);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
@@ -207,10 +216,12 @@ export async function sendPrivateForwardMessage(
|
||||
ref: OneBotInstanceContext,
|
||||
userId: number,
|
||||
messages: JsonValue,
|
||||
meta?: ForwardPreviewMeta,
|
||||
): Promise<{ messageId: number; forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages);
|
||||
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
|
||||
const receipt = await ref.bridge.sendPrivateMessage(userId, [{ type: 'forward', resId: forwardId }]);
|
||||
const previewElement = buildForwardPreviewElement(forwardId, nodes, false, meta);
|
||||
const receipt = await ref.bridge.sendPrivateMessage(userId, [previewElement]);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
|
||||
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
@@ -563,6 +574,88 @@ async function parseForwardNodes(
|
||||
return nodes;
|
||||
}
|
||||
|
||||
// Per-element preview string for the forward bubble's `news` lines.
|
||||
// Mirrors NapCat's `PacketMsg.toPreview()` mapping; keeps text trim short
|
||||
// so a chain of segments doesn't blow past the bubble's 80-char display.
|
||||
function elementPreview(element: MessageElement): string {
|
||||
switch (element.type) {
|
||||
case 'text': {
|
||||
const t = element.text ?? '';
|
||||
return t.length > 40 ? `${t.slice(0, 40)}…` : t;
|
||||
}
|
||||
case 'at': return element.text?.trim() || '@';
|
||||
case 'face': return '[表情]';
|
||||
case 'mface': return element.text ? `[${element.text}]` : '[表情]';
|
||||
case 'image': return '[图片]';
|
||||
case 'record': return '[语音]';
|
||||
case 'video': return '[视频]';
|
||||
case 'file': return element.fileName ? `[文件:${element.fileName}]` : '[文件]';
|
||||
case 'reply': return '';
|
||||
case 'json': return '[JSON消息]';
|
||||
case 'xml': return '[XML消息]';
|
||||
case 'markdown': return '[Markdown]';
|
||||
case 'forward': return '[聊天记录]';
|
||||
case 'poke': return '[戳一戳]';
|
||||
default: return '';
|
||||
}
|
||||
}
|
||||
|
||||
function buildNewsFromNodes(nodes: ForwardNodePayload[]): Array<{ text: string }> {
|
||||
// Match NapCat ForwardMsgBuilder: each line is "<nickname>: <preview>".
|
||||
// Cap to the first 4 lines — that's what QQ's bubble can actually render
|
||||
// before it truncates; anything beyond is silently dropped by the client.
|
||||
const lines: Array<{ text: string }> = [];
|
||||
for (const node of nodes) {
|
||||
const preview = node.elements.map(elementPreview).filter(Boolean).join(' ').trim();
|
||||
const nickname = node.nickname || String(node.userUin);
|
||||
lines.push({ text: `${nickname}: ${preview || '[消息]'}` });
|
||||
if (lines.length >= 4) break;
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function deriveForwardSource(nodes: ForwardNodePayload[], isGroup: boolean): string {
|
||||
if (nodes.length === 0) return '聊天记录';
|
||||
if (isGroup) return '群聊的聊天记录';
|
||||
// Private chat: stitch up to 4 distinct sender nicks, NapCat-style.
|
||||
const seen = new Set<string>();
|
||||
const nicks: string[] = [];
|
||||
for (const node of nodes) {
|
||||
const nick = (node.nickname || String(node.userUin)).trim();
|
||||
if (!nick || seen.has(nick)) continue;
|
||||
seen.add(nick);
|
||||
nicks.push(nick);
|
||||
if (nicks.length >= 4) break;
|
||||
}
|
||||
return nicks.length > 0 ? `${nicks.join('和')}的聊天记录` : '聊天记录';
|
||||
}
|
||||
|
||||
function buildForwardPreviewElement(
|
||||
resId: string,
|
||||
nodes: ForwardNodePayload[],
|
||||
isGroup: boolean,
|
||||
meta: ForwardPreviewMeta | undefined,
|
||||
): MessageElement {
|
||||
const news = meta?.news && meta.news.length > 0 ? meta.news : buildNewsFromNodes(nodes);
|
||||
const source = meta?.source && meta.source.length > 0
|
||||
? meta.source
|
||||
: deriveForwardSource(nodes, isGroup);
|
||||
const summary = meta?.summary && meta.summary.length > 0
|
||||
? meta.summary
|
||||
: `查看${nodes.length}条转发消息`;
|
||||
const prompt = meta?.prompt && meta.prompt.length > 0 ? meta.prompt : '[聊天记录]';
|
||||
|
||||
return {
|
||||
type: 'forward',
|
||||
resId,
|
||||
forwardSource: source,
|
||||
forwardSummary: summary,
|
||||
forwardPrompt: prompt,
|
||||
forwardNews: news,
|
||||
forwardTSum: nodes.length,
|
||||
};
|
||||
}
|
||||
|
||||
function asJsonObject(value: JsonValue | undefined): JsonObject | null {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
|
||||
return value as JsonObject;
|
||||
|
||||
@@ -222,7 +222,18 @@ export interface GroupNoticeParams extends GroupIdParams {
|
||||
confirm_required?: number;
|
||||
}
|
||||
|
||||
export interface ForwardMessageParams extends JsonObject {
|
||||
export interface ForwardPreviewParams {
|
||||
// Header above the preview ("群聊的聊天记录"). Default: "聊天记录" / nicks.
|
||||
source?: string;
|
||||
// Per-line preview entries ("nick: text"). Default: derived from nodes.
|
||||
news?: Array<{ text: string }>;
|
||||
// Grey footer ("查看 N 条转发消息"). Default: "查看 N 条转发消息".
|
||||
summary?: string;
|
||||
// Chat-list brief ("[聊天记录]"). Default: "[聊天记录]".
|
||||
prompt?: string;
|
||||
}
|
||||
|
||||
export interface ForwardMessageParams extends JsonObject, ForwardPreviewParams {
|
||||
message_type?: 'private' | 'group' | string;
|
||||
user_id?: number;
|
||||
group_id?: number;
|
||||
@@ -230,12 +241,12 @@ export interface ForwardMessageParams extends JsonObject {
|
||||
messages?: JsonValue;
|
||||
}
|
||||
|
||||
export interface GroupForwardMessageParams extends GroupIdParams {
|
||||
export interface GroupForwardMessageParams extends GroupIdParams, ForwardPreviewParams {
|
||||
message?: JsonValue;
|
||||
messages?: JsonValue;
|
||||
}
|
||||
|
||||
export interface PrivateForwardMessageParams extends UserIdParams {
|
||||
export interface PrivateForwardMessageParams extends UserIdParams, ForwardPreviewParams {
|
||||
message?: JsonValue;
|
||||
messages?: JsonValue;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user