Files

111 lines
5.7 KiB
JavaScript
Raw Permalink Normal View History

// 补采 URL 形式的图片/视频(矩阵里 g_image_url / g_video_url 被 skipped)。
// 上一轮失败原因:复用了历史 CDN URL,其 rkey 已过期。媒体 CDN URL 具时效,必须现发现用。
// 做法:先从 history 找一条自己发过的 image/video,取其**当前新鲜**的 url 字段,
// 立刻用于 send_group_msg 的 file=<url>,再比对事件段与 history 段。
// 默认 dry-run,--yes 才真实发送。凭据只从环境变量读取。
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 GROUP = Number(process.env.PROBE_GROUP || 933280401);
const DO_WRITE = process.argv.includes('--yes');
const OUT_DIR = process.env.PROBE_OUT || 'local';
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `url-media-${stamp}.jsonl`);
const say = (...a) => console.log(...a);
const pending = new Map();
let opened = false, authed = false;
const events = [];
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
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({ el: Date.now(), data: o });
fs.appendFileSync(OUT, JSON.stringify({ kind: 'event', data: o }) + '\n');
};
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) { console.error('未确认认证,中止。'); process.exit(2); }
const api = (action, params, ms = 40000) => new Promise((resolve) => {
const echo = `um-${action}-${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 }));
});
// 现场取新鲜 URL
const h = await api('get_group_msg_history', { group_id: GROUP, count: 60 });
const fresh = {};
for (const m of h?.data?.messages ?? []) {
for (const s of m.message ?? []) {
if ((s.type === 'image' || s.type === 'video') && s.data?.url && !fresh[s.type]) {
fresh[s.type] = s.data.url;
}
}
}
say('现场取到 URL: ' + Object.keys(fresh).map((k) => k + '=' + fresh[k].slice(0, 55) + '...').join(' / '));
// 先验证 URL 当下是否可下载,避免把「URL 过期」误判成「NapCat 不支持 URL 形式」
for (const [k, u] of Object.entries(fresh)) {
try { const r = await fetch(u); const b = await r.arrayBuffer();
say(` ${k} URL 可达性: HTTP ${r.status} ${b.byteLength} 字节`);
fresh[k + '_ok'] = r.ok && b.byteLength > 0;
} catch (e) { say(` ${k} URL 下载异常: ${e.message}`); fresh[k + '_ok'] = false; }
}
const CASES = [
{ id: 'g_image_url', seg: 'image', text: '[QLu:image_url]' },
{ id: 'g_video_url', seg: 'video', text: '[QLu:video_url]' },
];
const results = [];
say(`\n模式=${DO_WRITE ? '真实发送' : 'DRY-RUN'}\n`);
for (const c of CASES) {
const url = fresh[c.seg];
if (!url || !fresh[c.seg + '_ok']) {
say(`${c.id.padEnd(14)} 跳过:${!url ? 'history 无该类型新鲜 URL' : 'URL 已不可下载'}`);
results.push({ id: c.id, status: 'skipped', reason: !url ? 'no_fresh_url' : 'url_not_downloadable' });
continue;
}
if (!DO_WRITE) { say(`${c.id.padEnd(14)} [计划] ${c.seg} file=<新鲜 CDN url>`); continue; }
const t0 = Date.now();
const r = await api('send_group_msg', { group_id: GROUP,
message: [{ type: c.seg, data: { file: url } }, { type: 'text', data: { text: c.text } }] });
await new Promise((x) => setTimeout(x, 7000));
// 注意:raw_message 里 [ ] , 会被转义成 &#91; &#93; &#44;,文本匹配不可靠,必须用 message_id 关联
const midNum = Number(r?.data?.message_id);
const ev = events.find((e) => e.el >= t0 && Number(e.data.message_id) === midNum);
const rec = { id: c.id, seg: c.seg, retcode: r.__timeout ? 'TIMEOUT' : r.retcode,
message: r.message ?? '', 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,
event_seg_detail: ev ? JSON.stringify((ev.data.message || []).map((s) => ({
t: s.type, size: s.data?.file_size ?? null, url: s.data?.url ? 'Y' : 'N' }))) : null,
status: r.__timeout ? 'timeout' : (r.retcode === 0 ? 'sent' : 'rejected') };
results.push(rec);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'result', ...rec }) + '\n');
say(`${c.id.padEnd(14)} retcode=${String(rec.retcode).padEnd(6)} seq=${String(rec.event_seq ?? '-').padEnd(6)} 事件段=${rec.event_segs} ${rec.event_seg_detail ?? ''}`);
}
const hist = await api('get_group_msg_history', { group_id: GROUP, count: 12 });
say('\nhistory 回读:');
for (const m of hist?.data?.messages ?? []) {
const raw = String(m.raw_message ?? '');
const hit = raw.match(/\[QLu:([a-z_]+)\]/);
if (hit) say(` ${hit[1].padEnd(12)} seq=${m.real_seq} 段=${(m.message ?? []).map((s) => s.type).join('+')}`);
}
fs.appendFileSync(OUT, JSON.stringify({ __summary: true, results }) + '\n');
say('\n结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);