190 lines
7.2 KiB
JavaScript
190 lines
7.2 KiB
JavaScript
#!/usr/bin/env node
|
||
// qq-notify.cjs —— 把小肥鱼(dsh-bili-whale)的推送转成 QQ 消息(默认发语音条)
|
||
//
|
||
// 用法: node qq-notify.cjs "消息正文"
|
||
// 或 WHALE_NOTIFY_TEXT="消息正文" node qq-notify.cjs
|
||
//
|
||
// 它会被 dsh-bili-whale 的 notify.mjs 以 type=command 调起,正文作为最后一个参数传入。
|
||
// 走 SnowLuma 的 OneBot HTTP 接口发私聊。token 每次从 SnowLuma 的账号配置里现读,
|
||
// 换了 token 也不用改这里。
|
||
//
|
||
// 主动推送默认走语音:正文先交给自建 TTS 合成 wav,再以 record 段发出;
|
||
// 合成失败 / 太长(>58s)/ QQ_NOTIFY_VOICE=0 时退回文字。
|
||
//
|
||
// 环境变量(都可选):
|
||
// QQ_NOTIFY_CONFIG_DIR SnowLuma 配置目录,默认 C:\Users\GuoAn\Desktop\SnowLuma-v2.4.0-win-x64\config
|
||
// QQ_NOTIFY_BASE OneBot HTTP 地址,默认 http://127.0.0.1:3000
|
||
// QQ_NOTIFY_TARGET 收信人 QQ,默认 419177984
|
||
// QQ_NOTIFY_TOKEN 手动指定 accessToken(跳过读配置)
|
||
// QQ_NOTIFY_TTS TTS 服务地址,默认 http://192.168.1.17:8080;置空则不发语音
|
||
// QQ_NOTIFY_VOICE 0 = 强制发文字;默认发语音
|
||
|
||
const fs = require('node:fs')
|
||
const os = require('node:os')
|
||
const path = require('node:path')
|
||
|
||
const CONFIG_DIR = process.env.QQ_NOTIFY_CONFIG_DIR || 'C:\\Users\\GuoAn\\Desktop\\SnowLuma-v2.4.0-win-x64\\config'
|
||
const BASE = (process.env.QQ_NOTIFY_BASE || 'http://127.0.0.1:3000').replace(/\/+$/, '')
|
||
const TARGET = Number(process.env.QQ_NOTIFY_TARGET || 419177984)
|
||
const TTS_BASE = (process.env.QQ_NOTIFY_TTS ?? 'http://192.168.1.17:8080').replace(/\/+$/, '')
|
||
const VOICE_ON = process.env.QQ_NOTIFY_VOICE !== '0' && TTS_BASE !== ''
|
||
const LOG = path.join(os.homedir(), '.dsh', 'bin', 'qq-notify.log')
|
||
|
||
/** 语音条上限 60s,留 2s 余量。 */
|
||
const MAX_VOICE_SECONDS = 58
|
||
|
||
function log(line) {
|
||
try {
|
||
fs.mkdirSync(path.dirname(LOG), { recursive: true })
|
||
fs.appendFileSync(LOG, `[${new Date().toISOString()}] ${line}\n`)
|
||
} catch {}
|
||
}
|
||
|
||
/** 从 SnowLuma 的 onebot_<uin>.json 里找出 HTTP 服务的 accessToken。 */
|
||
function findToken() {
|
||
if (process.env.QQ_NOTIFY_TOKEN) return process.env.QQ_NOTIFY_TOKEN
|
||
let files = []
|
||
try {
|
||
files = fs.readdirSync(CONFIG_DIR).filter((f) => /^onebot_.*\.json$/.test(f))
|
||
} catch (e) {
|
||
throw new Error(`读不到 SnowLuma 配置目录:${CONFIG_DIR}(${e.message})`)
|
||
}
|
||
// 优先取最近写过的那个账号
|
||
files.sort((a, b) => {
|
||
try {
|
||
return fs.statSync(path.join(CONFIG_DIR, b)).mtimeMs - fs.statSync(path.join(CONFIG_DIR, a)).mtimeMs
|
||
} catch { return 0 }
|
||
})
|
||
for (const f of files) {
|
||
try {
|
||
const cfg = JSON.parse(fs.readFileSync(path.join(CONFIG_DIR, f), 'utf8'))
|
||
// SnowLuma 的账号级快照把网络配置放在 networks 下面
|
||
const servers = cfg?.httpServers || cfg?.networks?.httpServers || cfg?.onebot?.httpServers || []
|
||
for (const s of servers) {
|
||
if (s && s.accessToken) return String(s.accessToken)
|
||
}
|
||
} catch {}
|
||
}
|
||
throw new Error('没在 SnowLuma 配置里找到 HTTP accessToken')
|
||
}
|
||
|
||
/** 只留下能念出来的字:去代码块、行内码、链接、Markdown 符号、emoji。 */
|
||
function speechText(text) {
|
||
return String(text ?? '')
|
||
.replace(/```[\s\S]*?```/g, ' ')
|
||
.replace(/`([^`]*)`/g, '$1')
|
||
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
|
||
.replace(/https?:\/\/\S+/g, ' ')
|
||
.replace(/[*_~#>|]+/g, ' ')
|
||
.replace(/[\p{Extended_Pictographic}\u{FE0F}\u{200D}\u{20E3}]/gu, ' ')
|
||
.replace(/\s+/g, ' ')
|
||
.trim()
|
||
}
|
||
|
||
/** 读 wav 头的时长(秒);不是 wav 或读不出来时返回 0。 */
|
||
function wavDurationSeconds(bytes) {
|
||
if (!Buffer.isBuffer(bytes) || bytes.length < 44) return 0
|
||
if (bytes.toString('ascii', 0, 4) !== 'RIFF' || bytes.toString('ascii', 8, 12) !== 'WAVE') return 0
|
||
let offset = 12
|
||
let byteRate = 0
|
||
let dataSize = 0
|
||
while (offset + 8 <= bytes.length) {
|
||
const id = bytes.toString('ascii', offset, offset + 4)
|
||
const size = bytes.readUInt32LE(offset + 4)
|
||
const body = offset + 8
|
||
if (id === 'fmt ' && body + 16 <= bytes.length) {
|
||
byteRate = bytes.readUInt32LE(body + 8)
|
||
} else if (id === 'data') {
|
||
dataSize = size
|
||
break
|
||
}
|
||
offset = body + size + (size % 2)
|
||
}
|
||
if (byteRate <= 0 || dataSize <= 0) return 0
|
||
return dataSize / byteRate
|
||
}
|
||
|
||
/** 合成语音;失败返回 null(调用方退回文字)。 */
|
||
async function synthesize(text) {
|
||
const spoken = speechText(text)
|
||
if (!spoken) return null
|
||
try {
|
||
const res = await fetch(`${TTS_BASE}/api/tts`, {
|
||
method: 'POST',
|
||
headers: { 'content-type': 'application/json' },
|
||
body: JSON.stringify({ text: spoken }),
|
||
signal: AbortSignal.timeout(120000),
|
||
})
|
||
if (!res.ok) {
|
||
log(`TTS FAIL http=${res.status} ${(await res.text().catch(() => '')).slice(0, 200)}`)
|
||
return null
|
||
}
|
||
const bytes = Buffer.from(await res.arrayBuffer())
|
||
if (bytes.length < 100) {
|
||
log('TTS FAIL empty audio')
|
||
return null
|
||
}
|
||
const seconds = wavDurationSeconds(bytes)
|
||
if (seconds > MAX_VOICE_SECONDS) {
|
||
log(`TTS SKIP ${seconds.toFixed(1)}s > ${MAX_VOICE_SECONDS}s`)
|
||
return null
|
||
}
|
||
log(`TTS OK ${bytes.length}B ${seconds.toFixed(1)}s`)
|
||
return bytes
|
||
} catch (e) {
|
||
log('TTS ERR ' + (e && e.message ? e.message : String(e)))
|
||
return null
|
||
}
|
||
}
|
||
|
||
async function send(token, message) {
|
||
const res = await fetch(`${BASE}/send_private_msg`, {
|
||
method: 'POST',
|
||
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
|
||
body: JSON.stringify({ user_id: TARGET, message }),
|
||
signal: AbortSignal.timeout(60000),
|
||
})
|
||
const raw = await res.text().catch(() => '')
|
||
let data = null
|
||
try { data = JSON.parse(raw) } catch {}
|
||
return { ok: res.ok && !(data && data.retcode !== 0 && data.status !== 'ok'), raw, data, status: res.status }
|
||
}
|
||
|
||
async function main() {
|
||
const text = (process.argv[2] ?? process.env.WHALE_NOTIFY_TEXT ?? '').trim()
|
||
if (!text) {
|
||
console.error('用法: node qq-notify.cjs "消息正文"')
|
||
process.exit(2)
|
||
}
|
||
const token = findToken()
|
||
const body = text.length > 3000 ? text.slice(0, 3000) + '\n…' : text
|
||
|
||
if (VOICE_ON) {
|
||
const bytes = await synthesize(body)
|
||
if (bytes) {
|
||
const sent = await send(token, [{ type: 'record', data: { file: 'base64://' + bytes.toString('base64') } }])
|
||
if (sent.ok) {
|
||
log(`OK-voice ${JSON.stringify(sent.data?.data ?? null).slice(0, 200)}`)
|
||
console.log('QQ 已送达(语音)✓', JSON.stringify(sent.data?.data ?? null))
|
||
return
|
||
}
|
||
log(`VOICE SEND FAIL http=${sent.status} ${sent.raw.slice(0, 300)};改发文字`)
|
||
}
|
||
}
|
||
|
||
const sent = await send(token, body)
|
||
if (!sent.ok) {
|
||
log(`FAIL http=${sent.status} ${sent.raw.slice(0, 300)}`)
|
||
console.error(`QQ 推送失败:HTTP ${sent.status} ${sent.raw.slice(0, 300)}`)
|
||
process.exit(1)
|
||
}
|
||
log(`OK ${JSON.stringify(sent.data?.data ?? null).slice(0, 200)}`)
|
||
console.log('QQ 已送达 ✓', JSON.stringify(sent.data?.data ?? null))
|
||
}
|
||
|
||
main().catch((e) => {
|
||
log('ERR ' + (e && e.message ? e.message : String(e)))
|
||
console.error('QQ 推送失败:' + (e && e.message ? e.message : String(e)))
|
||
process.exit(1)
|
||
})
|