// OneBot11 消息段发送矩阵探测。 // 目的: 逐段类型实测 NapCat 4.18.41 是否接受、返回什么 retcode/字段、事件回推长什么样。 // 默认 dry-run 只打印将要发送的内容;加 --yes 才真实发送到测试群/测试号。 // // 用法: // NAPCAT_WS_TOKEN=xxx node tools/probe/seg-probe.mjs # dry-run 全量 // NAPCAT_WS_TOKEN=xxx node tools/probe/seg-probe.mjs --yes poke # 真发指定用例 // NAPCAT_WS_TOKEN=xxx node tools/probe/seg-probe.mjs --yes --all // 目标: KIND=group TARGET=933280401(默认)/ KIND=private TARGET= // 事件侧: LOG_FILE=local/seg-events.jsonl 可把发送期间收到的事件原样落盘,供结构分析 // 发送后等待: SETTLE_MS 默认 4000,用于等事件回推 // // ⚠ 会产生真实外部副作用(向真实 QQ 群/号发消息),仅在已授权的测试群/测试号上使用。 import fs from 'node:fs'; import path from 'node:path'; const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099'; const TOKEN = process.env.NAPCAT_WS_TOKEN; const KIND = process.env.KIND || 'group'; const TARGET = Number(process.env.TARGET || (KIND === 'group' ? 933280401 : 2161656029)); const SELF_QQ = Number(process.env.SELF_QQ || 3575608514); const LOG_FILE = process.env.LOG_FILE || ''; const RESULT_DIR = process.env.RESULT_DIR || 'local'; const STAMP = new Date().toISOString().replace(/[:.]/g, '-'); const SETTLE_MS = Number(process.env.SETTLE_MS || 4000); // 上一轮实测得到的真实 message_id,用于 reply 引用 const REPLY_TO = process.env.REPLY_TO || ''; const argv = process.argv.slice(2); const DO_WRITE = argv.includes('--yes'); const names = argv.filter((a) => !a.startsWith('--')); const RUN_ALL = names.includes('--all') || names.length === 0; if (!TOKEN) { console.error('缺少 NAPCAT_WS_TOKEN'); process.exit(1); } if (LOG_FILE) fs.mkdirSync(path.dirname(LOG_FILE), { recursive: true }); const logEvent = (caseName, o) => { if (!LOG_FILE) return; fs.appendFileSync(LOG_FILE, JSON.stringify({ t: new Date().toISOString(), case: caseName, data: o }) + '\n'); }; const TAG = (n) => `[QLinker段探测:${n}]`; const arr = (...segs) => segs; // 1x1 透明 PNG const PNG_1PX = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='; // 最小合法 WAV: 8kHz / 8bit / 单声道 / 8 字节静音,共 52 字节 const u32 = (v) => { const b = Buffer.alloc(4); b.writeUInt32LE(v, 0); return b; }; const u16 = (v) => { const b = Buffer.alloc(2); b.writeUInt16LE(v, 0); return b; }; const WAV_DATA = Buffer.alloc(8, 128); const WAV_MIN = Buffer.concat([ Buffer.from('RIFF', 'ascii'), u32(36 + WAV_DATA.length), Buffer.from('WAVE', 'ascii'), Buffer.from('fmt ', 'ascii'), u32(16), u16(1), u16(1), u32(8000), u32(8000), u16(1), u16(8), Buffer.from('data', 'ascii'), u32(WAV_DATA.length), WAV_DATA, ]).toString('base64'); // 每个用例: { name, desc, message, expect } // expect: 'ok' 预期被接受;'reject' 预期被拒绝(拒绝本身也是有价值的结论) const CASES = [ { name: 'poke', desc: '戳一戳(群内 @ 目标成员)', message: arr( { type: 'text', data: { text: `${TAG('poke')} 文本段` } }, { type: 'poke', data: { type: 'qq', id: String(TARGET === 933280401 ? 2161656029 : TARGET) } }, ), expect: 'ok', }, { name: 'location', desc: '位置分享', message: arr( { type: 'text', data: { text: `${TAG('location')} 文本段` } }, { type: 'location', data: { lat: '39.90469', lon: '116.40717', title: '测试地点', content: 'QLinker 探测' } }, ), expect: 'ok', }, { name: 'json', desc: 'JSON 卡片(未注册业务 appid,预期可能被拒)', message: arr({ type: 'json', data: { data: JSON.stringify({ app: 'com.example.unknown', view: 'library', config: { width: 600, height: 400 }, prompt: '探测', summary: '探测', meta: { detail: { title: { title: 'QLinker 段探测' } } } }) } }), expect: 'unknown', }, { name: 'music', desc: '音乐分享(id 形式)', message: arr({ type: 'music', data: { type: '163', id: '1408551584' } }), expect: 'unknown', }, { name: 'image_base64', desc: '图片段 base64(1x1 PNG,走 base64:// 协议,不依赖外部 URL)', message: arr( { type: 'text', data: { text: `${TAG('image_base64')} 文本段` } }, { type: 'image', data: { file: 'base64://' + PNG_1PX } }, ), expect: 'ok', }, { name: 'record_base64', desc: '语音段 base64(WAV 头,QQ 语音通常为 silk/amr,观察是否接受)', message: arr({ type: 'record', data: { file: 'base64://' + WAV_MIN } }), expect: 'unknown', }, { name: 'video_base64', desc: '视频段 base64(非合法 MP4 内容,观察校验强度)', message: arr({ type: 'video', data: { file: 'base64://' + PNG_1PX } }), expect: 'unknown', }, { name: 'file_base64', desc: '文件段 base64(群文件上传路径)', message: arr({ type: 'file', data: { file: 'base64://' + Buffer.from('QLinker seg probe file payload\n').toString('base64'), name: 'qlinker-probe.txt' } }), expect: 'unknown', }, { name: 'forward', desc: '转发节点(forward + node 数组,自定义节点)', message: arr( { type: 'text', data: { text: `${TAG('forward')} 文本段` } }, { type: 'forward', data: { forward: true, nodes: JSON.stringify([ { type: 'node', user_id: String(SELF_QQ), nickname: '雪珂', content: [{ type: 'text', data: { text: '转发的第一条' } }] }, { type: 'node', user_id: '2161656029', nickname: '小王', content: [{ type: 'text', data: { text: '转发的第二条' } }] }, ]), }, }, ), expect: 'unknown', }, { name: 'forward_array', desc: '转发变体:nodes 传真正的数组而非 JSON 字符串', message: arr( { type: 'text', data: { text: `${TAG('forward_array')} 文本段` } }, { type: 'forward', data: { nodes: [ { type: 'node', user_id: String(SELF_QQ), nickname: '雪珂', content: [{ type: 'text', data: { text: '数组节点第一条' } }] }, { type: 'node', user_id: '2161656029', nickname: '小王', content: [{ type: 'text', data: { text: '数组节点第二条' } }] }, ], }, }, ), expect: 'unknown', }, { name: 'node_single', desc: '转发变体:单个 node 段(非 forward 容器)', message: arr({ type: 'node', data: { type: 'node', user_id: String(SELF_QQ), nickname: '雪珂', content: [{ type: 'text', data: { text: '单节点内容' } }] }, }), expect: 'unknown', }, { name: 'node_multi', desc: '转发变体:message 数组里并列多个 node 段(node_single 已证明单节点生效)', message: arr( { type: 'node', data: { type: 'node', user_id: String(SELF_QQ), nickname: '雪珂', content: [{ type: 'text', data: { text: '并列节点一' } }] } }, { type: 'node', data: { type: 'node', user_id: '2161656029', nickname: '小王', content: [{ type: 'text', data: { text: '并列节点二' } }] } }, { type: 'node', data: { type: 'node', user_id: String(SELF_QQ), nickname: '雪珂', content: [{ type: 'text', data: { text: '并列节点三' } }] } }, ), expect: 'unknown', }, { name: 'reply', desc: '引用回复(reply + 文本,引用上一条真实 message_id)', skipIf: !REPLY_TO, skipWhy: '未提供 REPLY_TO 环境变量(需真实 message_id)', message: arr( { type: 'reply', data: { id: String(REPLY_TO) } }, { type: 'text', data: { text: `${TAG('reply')} 引用回复文本` } }, ), expect: 'ok', }, { name: 'unknown_type', desc: '未知段类型(验证是否会污染或整条失败)', message: arr( { type: 'text', data: { text: `${TAG('unknown_type')} 文本段` } }, { type: 'qlinker_nonexistent_segment', data: { foo: 'bar' } }, ), expect: 'reject', }, { name: 'empty_seg', desc: '空消息段数组', message: [], expect: 'reject', }, { name: 'long_text', desc: '超长文本(5000 字符,观察截断/拒绝阈值)', message: arr({ type: 'text', data: { text: TAG('long_text') + '甲'.repeat(5000) } }), expect: 'unknown', }, ]; const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`); const pending = new Map(); let n = 0; let currentCase = '(idle)'; let sawLifecycle = false; const lifecycle = new Promise((resolve) => { const to = setTimeout(() => resolve(false), 10000); ws.__onLifecycle = resolve; ws.__lifecycleTimeout = to; }); ws.onmessage = (ev) => { let o; try { o = JSON.parse(String(ev.data)); } catch { return; } if (o.post_type) { if (o.post_type === 'meta_event' && o.meta_event_type === 'lifecycle') { sawLifecycle = true; ws.__onLifecycle?.(true); clearTimeout(ws.__lifecycleTimeout); } if (o.post_type === 'meta_event' && o.meta_event_type === 'heartbeat') return; const brief = o.message_id ?? o.notice_type ?? o.meta_event_type ?? ''; console.log(` · 事件 ${o.post_type}/${brief}`); logEvent(currentCase, o); return; } if (o.echo && pending.has(o.echo)) { const p = pending.get(o.echo); pending.delete(o.echo); clearTimeout(p.to); p.resolve(o); } }; ws.onerror = (e) => { console.error('WS 错误:', e?.message ?? e); process.exit(1); }; await new Promise((res, rej) => { ws.onopen = res; setTimeout(() => rej(new Error('连接超时')), 10000); }) .catch((e) => { console.error(e.message); process.exit(1); }); // 握手成功不等于认证成功,等 lifecycle 再动手 const authed = await lifecycle; console.log(`握手完成,认证确认=${authed}(未确认时发送可能全部 1403)`); const call = (action, params, ms = 30000) => new Promise((resolve) => { const echo = `seg-${++n}-${Date.now()}`; const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms); pending.set(echo, { resolve, to }); ws.send(JSON.stringify({ action, params, echo })); }); const action = KIND === 'group' ? 'send_group_msg' : 'send_private_msg'; const targetKey = KIND === 'group' ? 'group_id' : 'user_id'; console.log(`模式: ${DO_WRITE ? '*** 真实发送 ***' : 'dry-run(不发)'} 目标: ${KIND} ${TARGET} 通道: ${action}`); console.log('='.repeat(90)); const results = []; for (const c of CASES) { if (!RUN_ALL && !names.includes(c.name)) continue; console.log(`\n【${c.name}】${c.desc} (预期 ${c.expect})`); console.log(' message =', JSON.stringify(c.message).slice(0, 320)); if (c.skipIf) { console.log(` → 跳过: ${c.skipWhy}`); results.push({ name: c.name, verdict: 'SKIPPED' }); continue; } if (!DO_WRITE) { results.push({ name: c.name, verdict: 'DRYRUN' }); continue; } currentCase = c.name; const t0 = Date.now(); const r = await call(action, { [targetKey]: TARGET, message: c.message }); const ms = Date.now() - t0; if (r.__timeout) { console.log(` → ${ms}ms 无响应(超时,属「结果未知」场景)`); results.push({ name: c.name, verdict: 'TIMEOUT', ms }); } else { const mid = r?.data?.message_id; console.log(` → ${ms}ms retcode=${r.retcode} status=${r.status} message_id=${mid ?? '-'}`); if (r.retcode !== 0) console.log(' errmsg:', JSON.stringify(r).slice(0, 400)); results.push({ name: c.name, verdict: r.retcode === 0 ? 'ACCEPTED' : 'REJECTED', retcode: r.retcode, ms, message_id: mid }); } await new Promise((r) => setTimeout(r, SETTLE_MS)); } currentCase = '(done)'; console.log('\n' + '='.repeat(90)); console.log('汇总:'); for (const r of results) console.log(` ${r.verdict.padEnd(9)} ${r.name}${r.retcode !== undefined ? ` retcode=${r.retcode} ${r.ms}ms` : ''}`); // 结果落盘,字段名与 capability-check 的回归比对对齐(id / retcode / event_segs) fs.mkdirSync(RESULT_DIR, { recursive: true }); const resultFile = path.join(RESULT_DIR, `seg-result-${STAMP}.jsonl`); const evByCase = new Map(); if (LOG_FILE && fs.existsSync(LOG_FILE)) { for (const l of fs.readFileSync(LOG_FILE, 'utf8').trim().split('\n')) { let o; try { o = JSON.parse(l); } catch { continue; } if (!o.case || o.case === '(idle)' || o.case === '(done)') continue; const segs = Array.isArray(o.data?.message) ? o.data.message.map((s) => s.type).join('+') : null; if (segs && !evByCase.has(o.case)) evByCase.set(o.case, segs); } } fs.writeFileSync(resultFile, results.map((r) => JSON.stringify({ id: r.name, status: r.verdict, retcode: r.retcode ?? null, message_id: r.message_id ?? null, event_segs: evByCase.get(r.name) ?? null, ms: r.ms ?? null, })).join('\n') + '\n'); console.log('结果 -> ' + resultFile); console.log(LOG_FILE ? `事件侧结构见 ${LOG_FILE},按 case 字段检索。` : '提示: 设 LOG_FILE 可采集事件侧结构。'); try { ws.close(); } catch {} process.exit(0);