From 3ac4bc79f0874ac516603349160d92d46b1eaea7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Thu, 7 May 2026 09:35:35 +0800 Subject: [PATCH] Make OneBot message parsing defensive Harden parsing of message segments in OneBot instance: skip non-object or array segments, normalize a local `type` string and a safe `data` object, and use those for all branch checks. This prevents runtime errors when segments or segment.data are missing or malformed, while preserving existing previews and placeholder labels (image, face, at, reply, record, video, fallback). --- packages/core/src/onebot/instance.ts | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/packages/core/src/onebot/instance.ts b/packages/core/src/onebot/instance.ts index 35abd040..eb09876b 100644 --- a/packages/core/src/onebot/instance.ts +++ b/packages/core/src/onebot/instance.ts @@ -173,24 +173,30 @@ export class OneBotInstance { if (Array.isArray(message)) { for (const seg of message) { - if (seg.type === 'text' && seg.data?.text) { - const text = String(seg.data.text); + if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue; + const type = String(seg.type ?? ''); + const data: Record = ( + typeof seg.data === 'object' && seg.data !== null && !Array.isArray(seg.data) + ) ? seg.data : {}; + + if (type === 'text' && data.text) { + const text = String(data.text); const preview = text.length > 50 ? text.substring(0, 50) + '...' : text; parts.push(preview); - } else if (seg.type === 'image') { + } else if (type === 'image') { parts.push('[图片]'); - } else if (seg.type === 'face') { + } else if (type === 'face') { parts.push('[表情]'); - } else if (seg.type === 'at') { - parts.push(`@${seg.data?.qq || ''}`); - } else if (seg.type === 'reply') { - parts.push(`[回复:${seg.data?.id || ''}]`); - } else if (seg.type === 'record') { + } else if (type === 'at') { + parts.push(`@${data.qq || ''}`); + } else if (type === 'reply') { + parts.push(`[回复:${data.id || ''}]`); + } else if (type === 'record') { parts.push('[语音]'); - } else if (seg.type === 'video') { + } else if (type === 'video') { parts.push('[视频]'); } else { - parts.push(`[${seg.type}]`); + parts.push(`[${type}]`); } } }