Files

138 lines
7.2 KiB
JavaScript
Raw Permalink Normal View History

// 合并转发内**非文本节点**的降级形态(默认 dry-run,--yes 才发送)。
//
// 上一版把 text 段和 node 段混在一起发,被 NapCat 拒绝:
// retcode=1400「转发消息不能和普通消息混在一起发送,转发需要保证message只有type为node的元素」
// 这条报错本身是有价值的能力约束(已单独记录),但媒体节点的降级形态仍未采到,
// 本版严格只传 node 段。
//
// 观察点:meta.detail.news 里 image / record / at 节点变成什么。
// 已有结论是 news 形如「昵称: 纯文本」,但全部样本都是文本节点,媒体节点未测。
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const GROUP = Number(process.env.PROBE_GROUP || 933280401);
const FRIEND = Number(process.env.PROBE_FRIEND || 2161656029);
const SELF = Number(process.env.PROBE_SELF || 3575608514);
const DO_WRITE = process.argv.includes('--yes');
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const fs = await import('node:fs');
const path = await import('node:path');
fs.mkdirSync('local', { recursive: true });
const OUT = path.join('local', `fwd-media-node-${new Date().toISOString().replace(/[:.]/g, '-')}.jsonl`);
const say = (...a) => console.log(...a);
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
const pending = new Map();
const events = [];
let opened = false, authed = false;
ws.onopen = () => { opened = true; };
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) { pending.get(o.echo).resolve(o); pending.delete(o.echo); return; }
if (o.post_type === 'meta_event') { if (o.meta_event_type === 'lifecycle') authed = true; return; }
events.push({ t: Date.now(), data: o });
};
for (let i = 0; i < 100 && !opened; i++) await new Promise((r) => setTimeout(r, 100));
if (!opened) { console.error('连接超时'); process.exit(1); }
for (let i = 0; i < 100 && !authed; i++) await new Promise((r) => setTimeout(r, 100));
say('认证=' + authed);
if (!authed && DO_WRITE) process.exit(2);
const api = (action, params, ms = 45000) => new Promise((resolve) => {
const echo = `fm-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms);
pending.set(echo, { resolve: (o) => { clearTimeout(to); resolve(o); }, to });
ws.send(JSON.stringify({ action, params, echo }));
});
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const rec = (o) => { fs.appendFileSync(OUT, JSON.stringify(o) + '\n'); return o; };
// 取真实媒体载荷(CDN 直链含时效 rkey,现取现用)
const h = await api('get_group_msg_history', { group_id: GROUP, count: 200 });
const allSegs = (h?.data?.messages ?? []).flatMap((m) => m.message ?? []);
const img = allSegs.find((s) => s.type === 'image');
const rec1 = allSegs.find((s) => s.type === 'record' && String(s.data?.file ?? '').endsWith('.amr'));
let amrB64 = null;
if (rec1?.data?.url) {
try {
const r = await fetch(rec1.data.url);
const b = Buffer.from(await r.arrayBuffer());
if (r.ok && b.length > 6 && b.subarray(0, 5).toString('latin1') === '#!AMR') amrB64 = b.toString('base64');
say(`amr 下载 HTTP=${r.status} ${b.length}B magic=${b.subarray(0, 5).toString('hex')}`);
} catch (e) { say('amr 下载失败 ' + e.message); }
}
say(`素材: image=${img ? '有' : '无'} record(amr)=${amrB64 ? '有' : '无'}`);
const node = (nick, content, useString) => ({
type: 'node',
data: { type: 'node', user_id: String(SELF), nickname: nick,
content: useString ? JSON.stringify(content) : content },
});
const CASES = [
{ id: 'fwd_media_str', desc: '纯 node 段(content 为 JSON 字符串),节点内含 image/record/at',
msgs: () => [
node('雪珂', [{ type: 'text', data: { text: 'FWDIMG-文本对照' } }], true),
node('雪珂', [{ type: 'image', data: { file: img?.data?.file, url: img?.data?.url } }], true),
node('小王', [{ type: 'at', data: { qq: String(FRIEND) } }, { type: 'text', data: { text: 'FWDAT-带at' } }], true),
...(amrB64 ? [node('雪珂', [{ type: 'record', data: { file: 'base64://' + amrB64 } }], true)] : []),
] },
{ id: 'fwd_media_arr', desc: '纯 node 段(content 为段数组),同上',
msgs: () => [
node('雪珂', [{ type: 'text', data: { text: 'FWDIMG2-文本对照' } }], false),
node('雪珂', [{ type: 'image', data: { file: img?.data?.file, url: img?.data?.url } }], false),
node('小王', [{ type: 'at', data: { qq: String(FRIEND) } }, { type: 'text', data: { text: 'FWDAT2-带at' } }], false),
...(amrB64 ? [node('雪珂', [{ type: 'record', data: { file: 'base64://' + amrB64 } }], false)] : []),
] },
];
if (!DO_WRITE) {
say('DRYRUN 计划(message 只含 node 段,避免 1400):');
for (const c of CASES) say(` ${c.id.padEnd(15)} ${c.desc}`);
process.exit(0);
}
const rows = [];
for (const c of CASES) {
const message = c.msgs();
const t0 = Date.now();
const r = await api('send_group_msg', { group_id: GROUP, message });
await sleep(7000);
const mid = Number(r?.data?.message_id);
const ev = events.find((e) => e.t >= t0 && Number(e.data.message_id) === mid);
const js = (ev?.data?.message ?? []).find((s) => s.type === 'json');
let d = {};
try { d = JSON.parse(js?.data?.data)?.meta?.detail ?? {}; } catch {}
const row = {
kind: 'result', id: c.id, desc: c.desc,
retcode: r.__timeout ? 'TIMEOUT' : r.retcode, message: String(r.message ?? r.wording ?? ''),
message_id: r?.data?.message_id ?? null,
event_segs: ev ? (ev.data.message ?? []).map((s) => s.type).join('+') : 'NO_EVENT',
event_seq: ev?.data?.real_seq ?? null,
app: (() => { try { return JSON.parse(js?.data?.data)?.app; } catch { return null; } })(),
tsum: d.tsum ?? null, news: d.news ?? null, summary: d.summary ?? null,
resid: d.resid ?? null, uniseq: d.uniseq ?? null, forward_id: d.forward_id ?? null,
};
rows.push(rec(row));
say(`\n[${c.id}] retcode=${row.retcode} ${row.message.slice(0, 90)}`);
say(` segs=${row.event_segs} seq=${row.event_seq} app=${row.app} tsum=${row.tsum}`);
if (row.news) for (const n of row.news) say(` news: ${JSON.stringify(n)}`);
if (row.summary) say(` summary: ${JSON.stringify(row.summary)}`);
if (row.resid || row.uniseq) say(` resid=${row.resid} uniseq=${row.uniseq} forward_id=${row.forward_id}`);
await sleep(1000);
}
say('\n===== 定性 =====');
for (const r of rows.filter((x) => x.retcode === 0 && Array.isArray(x.news))) {
const flat = r.news.map((n) => (typeof n === 'string' ? n : n?.text ?? JSON.stringify(n)));
const mediaHint = flat.some((t) => /CQ:|https?:\/\/|\.png|\.amr|file_id|\[图片\]|\[语音\]|\[动画表情\]/i.test(t));
say(` ${r.id}: news ${flat.length} 条,${mediaHint ? '含媒体线索' : '**无任何媒体线索,image/record/at 节点被压成纯文本或整体丢弃**'}`);
for (const t of flat) say(` ${t}`);
}
const rejected = rows.filter((x) => x.retcode !== 0);
for (const r of rejected) say(` ${r.id}: retcode=${r.retcode} ${r.message.slice(0, 120)}`);
say('\n证据: ' + OUT);
try { ws.close(); } catch {}
process.exit(0);