-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
714 lines (629 loc) · 22.6 KB
/
Copy pathindex.js
File metadata and controls
714 lines (629 loc) · 22.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
/*
* JM 插件(Yunzai v3:Miao-Yunzai / TRSS-Yunzai)
* 基于 jmcomic 库,经 jmcomic-bridge.py 调用。
* 依赖:Python 3.9+ 与 pip install jmcomic。发送「#jm帮助」查看全部命令。
*/
import { execFile, spawn } from 'node:child_process'
import path from 'node:path'
import fs from 'node:fs'
import { fileURLToPath } from 'node:url'
import { DEFAULT_CONFIG, readConfig } from './components/config.js'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
// ==================== 配置 ====================
// 优先级:默认 < config.js(手动导入)< config.json(锅巴写入,最终生效)
let CONFIG = { ...DEFAULT_CONFIG }
/** 惰性加载配置(避免顶层 await,兼容更多加载器) */
async function loadUserConfig () {
let manual = {}
try {
const mod = await import(path.join(__dirname, 'config.js') + '?t=' + Date.now())
manual = mod.default || {}
} catch (e) { /* config.js 不存在,忽略 */ }
CONFIG = { ...DEFAULT_CONFIG, ...manual, ...readConfig() }
}
// ==================== Python 调用封装 ====================
let pythonCmd = null
let pythonProbePromise = null
function probePython () {
if (pythonProbePromise) return pythonProbePromise
const candidates = Array.isArray(CONFIG.python) ? CONFIG.python : [CONFIG.python]
pythonProbePromise = new Promise((resolve) => {
let i = 0
const tryNext = () => {
if (i >= candidates.length) return resolve(null)
const cmd = candidates[i++]
execFile(cmd, ['--version'], { timeout: 8000 }, (err) => {
if (err) return tryNext()
resolve(cmd)
})
}
tryNext()
})
return pythonProbePromise
}
/**
* 执行 bridge 脚本并解析 JSON(失败不抛异常,resolve { success:false, error })
*/
function runBridge (cmd, args = [], timeoutMs = 90000) {
return new Promise(async (resolve) => {
const py = await probePython()
if (!py) {
return resolve({ success: false, error: '未找到 Python,请先安装 Python 3 并执行 pip install jmcomic' })
}
const bridge = path.join(__dirname, 'jmcomic-bridge.py')
const env = { ...process.env }
if (CONFIG.proxy) env.JM_PROXY = CONFIG.proxy
if (CONFIG.baseUrl) env.JM_BASE_URL = CONFIG.baseUrl
execFile(py, [bridge, cmd, ...args], { timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024, env }, (err, stdout, stderr) => {
if (err) {
const stderrText = (stderr || '').trim()
// 优先解析 stderr 中的 JSON 错误
try {
const obj = JSON.parse(stderrText)
if (obj && obj.success === false) return resolve(obj)
} catch (e) { /* not json */ }
return resolve({ success: false, error: stderrText || (err.killed ? '执行超时' : String(err.message || err)) })
}
try {
resolve(JSON.parse(stdout))
} catch (e) {
resolve({ success: false, error: 'bridge 返回非 JSON: ' + String(stdout).slice(0, 200) })
}
})
})
}
// ==================== 数据(用户记忆,redis 持久化) ====================
const PREFIX = 'jm:user:'
function redisGet (key) {
return new Promise((resolve) => {
if (globalThis.redis?.get) {
globalThis.redis.get(key).then(resolve).catch(() => resolve(null))
} else resolve(null)
})
}
function redisSet (key, value, ttl) {
return new Promise((resolve) => {
if (globalThis.redis?.set) {
const p = ttl ? globalThis.redis.set(key, value, 'EX', ttl) : globalThis.redis.set(key, value)
p.then(() => resolve(true)).catch(() => resolve(false))
} else resolve(false)
})
}
function redisDel (key) {
return new Promise((resolve) => {
if (globalThis.redis?.del) {
globalThis.redis.del(key).then(() => resolve(true)).catch(() => resolve(false))
} else resolve(false)
})
}
async function getUserData (userId) {
const raw = await redisGet(PREFIX + userId)
if (!raw) return null
try { return JSON.parse(raw) } catch (e) { return null }
}
async function saveUserData (userId, data) {
// Cookie 持久化 30 天
return redisSet(PREFIX + userId, JSON.stringify(data), 30 * 24 * 3600)
}
async function clearUserData (userId) {
return redisDel(PREFIX + userId)
}
// ==================== 辅助:文本格式化 ====================
function fmtSize (bytes) {
if (!bytes && bytes !== 0) return '未知'
const n = Number(bytes)
if (n < 1024) return `${n} B`
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`
return `${(n / 1024 / 1024 / 1024).toFixed(2)} GB`
}
function fmtList (title, items, page, totalPages, opts = {}) {
const lines = [`${title}(第 ${page}/${totalPages} 页)`, '']
const showIndex = opts.showIndex !== false
items.forEach((it, i) => {
const idx = showIndex ? `${i + 1}. ` : ''
lines.push(`${idx}【${it.id}】${String(it.title).slice(0, 80)}`)
})
lines.push('', '发送「#jm详情 <ID>」查看详情')
return lines.join('\n')
}
function fmtDetail (d) {
const lines = []
lines.push(`📖 ${d.title}`)
lines.push(`🆔 ID: ${d.id}`)
if (d.author) lines.push(`✍️ 作者: ${d.author}`)
if (d.authors?.length) lines.push(`👥 全部作者: ${d.authors.join(', ')}`)
lines.push(`📅 发布: ${d.pubDate || '未知'}|更新: ${d.updateDate || '未知'}`)
lines.push(`📄 页数: ${d.pageCount}|章节: ${d.episodeCount}|评论: ${d.commentCount ?? '未知'}`)
if (d.views) lines.push(`👀 观看: ${d.views}|❤️ 点赞: ${d.likes ?? '未知'}`)
if (d.tags?.length) lines.push(`🏷️ 标签: ${d.tags.join(', ')}`)
if (d.works?.length) lines.push(`📚 作品: ${d.works.join(', ')}`)
if (d.actors?.length) lines.push(`🎭 角色: ${d.actors.join(', ')}`)
if (d.description) lines.push(`💬 简介: ${String(d.description).slice(0, 200)}`)
lines.push('', '发送「#jm下载 ' + d.id + '」下载PDF')
return lines.join('\n')
}
// 默认帮助文档(锅巴 WebUI 可自定义覆盖)
const DEFAULT_HELP = `📖 JM 插件帮助
━━━━━━━━━━━━
📋 命令列表
#jm帮助 查看帮助
#jm登录 <账号> <密码> 登录
#jm收藏 [页码] 我的收藏
#jm添加 <ID> 添加收藏
#jm搜索 <关键词> [页码]
#jm详情 <ID> 查看详情
#jm排行 [日|周|月] [页码]
#jm分类 [页码] 分类浏览
#jm下载 <ID> 下载转 PDF 并发送
#jm退出 退出登录
━━━━━━━━━━━━
💡 提示
· #jm、jm、禁漫 可触发,可忽略空格、搜索
· 例:「jm114514」`
// 获取帮助:优先锅巴配置的自定义帮助,否则内置默认
function getHelpText () {
const custom = (CONFIG.help || '').trim()
return custom || DEFAULT_HELP
}
// 快捷ID:纯数字或 JM+数字(如 jm114514、114514)
function parseQuickDownloadId (token) {
if (!token) return null
const m = token.match(/^(jm)?(\d{4,})$/i)
if (!m) return null
return m[2]
}
// ==================== 插件主体 ====================
export class jm extends plugin {
constructor () {
super({
name: 'jm-plugin',
dsc: 'JM 漫画插件:登录/收藏/搜索/详情/排行/下载',
event: 'message',
priority: 100,
rule: [
{
reg: '^#?(jm|禁漫)(帮助|登录|收藏|添加|搜索|详情|排行|分类|下载|退出|\\s|$|\\d)',
fnc: 'jmMain'
}
]
})
// 下载目录:优先环境变量 JM_DOWNLOAD_DIR,未设置时回退插件目录 downloads/
this.downloadsDir = process.env.JM_DOWNLOAD_DIR || path.join(__dirname, 'downloads')
if (!fs.existsSync(this.downloadsDir)) {
fs.mkdirSync(this.downloadsDir, { recursive: true })
}
}
// ---------- 权限 ----------
isMaster (e) {
return e?.isMaster || false
}
async checkPermission (e) {
if (!CONFIG.masterOnly) return true
if (this.isMaster(e)) return true
this.e.reply('该命令仅限主人使用')
return false
}
// ---------- 主入口 ----------
async jmMain () {
await loadUserConfig()
const e = this.e
const raw = (e.msg || '').replace(/^#/, '').trim()
const m = raw.match(/^(jm|禁漫)\s*([\s\S]*)$/i)
if (!m) return true
const args = (m[2] || '').trim().split(/\s+/).filter(Boolean)
let sub = (args.shift() || '').toLowerCase()
logger?.info?.(`[jm-plugin] 收到命令: ${sub} ${args.join(' ')}(用户 ${e.user_id})`)
// 容错:子命令与参数粘连时拆分,如 #jm详情123 → sub=详情, args=[123]
const sticky = sub.match(/^(帮助|登录|收藏|添加|搜索|详情|排行|分类|下载|退出)(.+)$/)
if (sticky) {
sub = sticky[1]
args.push(...sticky[2].split(/\s+/).filter(Boolean))
}
// 快捷详情:#jm114514 / #jm 114514 / #禁漫114514 → 直接查看详情
const quickId = parseQuickDownloadId(sub)
if (quickId) {
logger?.info?.(`[jm-plugin] 快捷详情: JM${quickId}(用户 ${e.user_id})`)
return this.cmdDetail(e, [quickId])
}
switch (sub) {
case '':
case '帮助':
case 'help':
await e.reply(getHelpText())
return true
case '登录':
case 'login':
return this.cmdLogin(e, args)
case '收藏':
case 'fav':
case 'favorites':
return this.cmdFavorites(e, args)
case '添加':
case 'add':
return this.cmdAdd(e, args)
case '搜索':
case 'search':
return this.cmdSearch(e, args)
case '详情':
case 'detail':
case 'info':
return this.cmdDetail(e, args)
case '排行':
case 'ranking':
case 'rank':
return this.cmdRanking(e, args)
case '分类':
case 'categories':
return this.cmdCategories(e, args)
case '下载':
case 'download':
case 'dl':
return this.cmdDownload(e, args)
case '退出':
case 'logout':
return this.cmdLogout(e)
default:
await e.reply(`未知命令「${sub}」,发送「#jm帮助」查看用法`)
return true
}
}
// ---------- 登录 ----------
async cmdLogin (e, args) {
if (!(await this.checkPermission(e))) return true
if (args.length < 2) {
await e.reply('用法:\n#jm 登录 <用户名> <密码>')
return true
}
const [username, password] = args
await e.reply('正在登录 JM,请稍候…')
const data = await runBridge('login', [username, password])
if (!data.success) {
await e.reply(`❌ 登录失败:${data.error}`)
return true
}
const saved = await saveUserData(e.user_id, {
username: data.username,
cookie: data.cookie,
loginAt: Date.now()
})
await e.reply(
saved
? `✅ 登录成功!\n👤 用户:${data.username}\nCookie 已保存(30 天内无需重新登录)`
: `✅ 登录成功,但 Cookie 持久化失败(redis 不可用?),本次会话内有效`
)
return true
}
// ---------- 收藏 ----------
async cmdFavorites (e, args) {
if (!(await this.checkPermission(e))) return true
const user = await getUserData(e.user_id)
if (!user?.cookie) {
await e.reply('尚未登录,请先发送「#jm 登录 <用户名> <密码>」')
return true
}
const page = parseInt(args[0], 10) || 1
const data = await runBridge('favorites', [JSON.stringify(user.cookie), String(page)])
if (!data.success) {
await e.reply(`❌ 获取收藏失败:${data.error}`)
return true
}
const items = data.favorites || []
if (!items.length) {
await e.reply(`📚 第 ${page} 页没有收藏(共 ${data.total ?? 0} 本)`)
return true
}
const coverUrl = items[0].coverUrl
const msg = fmtList('📚 我的收藏', items, page, data.totalPages || 1)
await this.replyWithCover(e, coverUrl, msg)
return true
}
// ---------- 添加收藏 ----------
async cmdAdd (e, args) {
if (!(await this.checkPermission(e))) return true
const user = await getUserData(e.user_id)
if (!user?.cookie) {
await e.reply('尚未登录,请先发送「#jm 登录 <用户名> <密码>」')
return true
}
if (!args.length) {
await e.reply('用法:\n#jm 添加 <漫画ID>')
return true
}
const albumId = args[0].replace(/^JM/i, '')
const data = await runBridge('add', [JSON.stringify(user.cookie), albumId])
if (!data.success) {
await e.reply(`❌ 添加收藏失败:${data.error}`)
return true
}
await e.reply(`✅ 已收藏 ${albumId}`)
return true
}
// ---------- 搜索 ----------
async cmdSearch (e, args) {
if (!(await this.checkPermission(e))) return true
if (!args.length) {
await e.reply('用法:\n#jm 搜索 <关键词> [页码]')
return true
}
const keyword = args[0]
const page = parseInt(args[1], 10) || 1
await e.reply(`🔍 正在搜索「${keyword}」…`)
const data = await runBridge('search', [keyword, String(page)])
if (!data.success) {
await e.reply(`❌ 搜索失败:${data.error}`)
return true
}
const items = data.results || []
if (!items.length) {
await e.reply(`没有找到与「${keyword}」相关的漫画`)
return true
}
const coverUrl = items[0].coverUrl
const msg = fmtList(`🔍 搜索「${keyword}」结果`, items, page, data.totalPages || 1)
await this.replyWithCover(e, coverUrl, msg)
return true
}
// ---------- 详情 ----------
async cmdDetail (e, args) {
if (!(await this.checkPermission(e))) return true
if (!args.length) {
await e.reply('用法:\n#jm 详情 <漫画ID>')
return true
}
const albumId = args[0].replace(/^JM/i, '')
await e.reply(`🔍 正在获取 ${albumId} 详情…`)
const data = await runBridge('detail', [albumId])
if (!data.success) {
await e.reply(`❌ 获取详情失败:${data.error}`)
return true
}
await this.replyWithCover(e, data.coverUrl, fmtDetail(data))
return true
}
// ---------- 排行榜 ----------
async cmdRanking (e, args) {
if (!(await this.checkPermission(e))) return true
const typeMap = { day: '日', week: '周', month: '月' }
let type = 'week'
let page = 1
if (args.length) {
const a0 = args[0]
for (const [key, value] of Object.entries(typeMap)) {
if (value === a0) {
type = key
break
}
}
if (args.length > 1) {
page = parseInt(args[1], 10) || 1
}else {
page = parseInt(args[0], 10) || 1
}
}
await e.reply(`🏆 正在获取${typeMap[type]}…`)
const data = await runBridge('ranking', [String(page), type])
if (!data.success) {
await e.reply(`❌ 获取排行榜失败:${data.error}`)
return true
}
const items = data.ranking || []
if (!items.length) {
await e.reply('排行榜暂无数据')
return true
}
const coverUrl = items[0].coverUrl
const msg = fmtList(`🏆 ${typeMap[type]}`, items, page, data.totalPages || 1)
await this.replyWithCover(e, coverUrl, msg)
return true
}
// ---------- 分类 ----------
async cmdCategories (e, args) {
if (!(await this.checkPermission(e))) return true
const page = parseInt(args[0], 10) || 1
await e.reply('🗂️ 正在获取分类列表…')
const data = await runBridge('categories', [String(page)])
if (!data.success) {
await e.reply(`❌ 获取分类失败:${data.error}`)
return true
}
const items = data.categories || []
if (!items.length) {
await e.reply('分类暂无数据')
return true
}
const coverUrl = items[0].coverUrl
const msg = fmtList('🗂️ 分类浏览', items, page, data.totalPages || 1)
await this.replyWithCover(e, coverUrl, msg)
return true
}
// ---------- 下载转 PDF(后台任务 + 完成后通知) ----------
async cmdDownload (e, args) {
if (!(await this.checkPermission(e))) return true
const user = await getUserData(e.user_id)
const albumId = (args[0] || '').replace(/^JM/i, '')
if (!albumId) {
await e.reply('用法:\n#jm 下载 <漫画ID>')
return true
}
await e.reply(`⏬ 已开始下载 ${albumId} 并转换为 PDF(后台执行,完成后将通知你)`)
// 后台任务:保留 e 的快照信息用于完成后通知
const replyInfo = {
type: e.message_type === 'group' ? 'group' : 'private',
groupId: e.group_id,
userId: e.user_id,
selfId: e.self_id
}
const cookieJson = user?.cookie ? JSON.stringify(user.cookie) : '{}'
const py = await probePython()
if (!py) {
await e.reply('❌ 未找到 Python,请先安装 Python 3 并执行 pip install jmcomic')
return true
}
const bridge = path.join(__dirname, 'jmcomic-bridge.py')
const env = { ...process.env }
if (CONFIG.proxy) env.JM_PROXY = CONFIG.proxy
if (CONFIG.baseUrl) env.JM_BASE_URL = CONFIG.baseUrl
const pdfCacheMax = Number(CONFIG.pdfCacheMax) || 20
const child = spawn(
py,
[bridge, 'pdf', cookieJson, albumId, this.downloadsDir, String(pdfCacheMax)],
{ env }
)
let stdout = ''
let stderr = ''
child.stdout.on('data', (d) => { stdout += d })
child.stderr.on('data', (d) => { stderr += d })
child.on('error', (err) => {
this.notifyDone(replyInfo, `❌ 下载 ${albumId} 失败:无法启动 Python(${err.message})`)
})
child.on('close', async (code) => {
if (code !== 0) {
const errText = (stderr || '').trim()
let msg = `❌ 下载 ${albumId} 失败`
try {
const obj = JSON.parse(errText)
if (obj?.error) msg += `:${obj.error}`
} catch (e) { if (errText) msg += `:${errText.slice(0, 300)}` }
this.notifyDone(replyInfo, msg)
return
}
let data
try { data = JSON.parse(stdout) } catch (e) { data = null }
if (!data?.success) {
this.notifyDone(replyInfo, `❌ 下载 ${albumId} 失败:${data?.error || '未知错误'}`)
return
}
const files = data.files || []
const summary =
`✅ 下载完成并转 PDF\n📖 ${data.title}\n🆔 ${data.albumId}${data.author ? `\n✍️ ${data.author}` : ''}` +
`\n📄 共 ${data.totalImages || 0} 张图片 / ${data.chapterCount || 0} 个章节 → ${files.length} 个 PDF`
const sent = await this.sendPdfFiles(replyInfo, files, summary)
if (!sent) {
this.notifyDone(replyInfo,
summary + this.pdfFallbackText(files, data.downloadDir))
}
})
return true
}
/**
* 发送 PDF 文件(群/私聊),失败退化为「文件名 + 路径」文本。
*
* TRSS-Yunzai 适配器会把 file:// 前缀剥掉再传给 NapCat 导致「识别URL失败」,
* 因此直接调用 Bot.sendApi 的 upload_group_file / upload_private_file,
* file 参数保留完整 file:// URI 以绕开适配器逻辑。
*
* @returns {Promise<boolean>} 是否至少成功发送一个文件
*/
async sendPdfFiles (replyInfo, files, summary) {
// 多文件时按章节名命名,单文件直接用原文件名
const named = []
if (files?.length === 1) {
const f = files[0]
named.push({ path: f.path, size: f.size, name: path.basename(f.path) })
} else if (files && files.length > 1) {
for (const f of files) {
if (!f?.path || !f.size) continue
const label = f.chapterTitle
? `${String(f.chapterTitle).replace(/[\\/:*?"<>|]/g, '-')}.pdf`
: path.basename(f.path)
named.push({ path: f.path, size: f.size, name: label })
}
}
const bot = this.getBot(replyInfo.selfId)
if (!bot?.sendApi) return false
let anyOk = false
for (const f of named) {
if (!f?.path || !fs.existsSync(f.path)) continue
// 与 toFileUri 同款转换:Linux 绝对路径 → file:///path,Windows → file:///C:/...
const abs = f.path.replace(/\\/g, '/').trim()
const fileUri = abs.startsWith('/') ? `file://${abs}` : `file:///${abs}`
const fileName = f.name || path.basename(f.path)
try {
if (replyInfo.type === 'group') {
await bot.sendApi('upload_group_file', {
group_id: replyInfo.groupId,
file: fileUri,
name: fileName
})
} else {
await bot.sendApi('upload_private_file', {
user_id: replyInfo.userId,
file: fileUri,
name: fileName
})
}
anyOk = true
} catch (err) {
logger?.info?.(`[jm-plugin] 文件上传失败(${fileName}): ${err.message}`)
try {
await this.notifyDone(replyInfo, `📁 ${fileName}\n${f.path}`)
anyOk = true
} catch (e) { /* 忽略 */ }
}
}
if (anyOk) {
try {
await this.notifyDone(replyInfo, summary)
} catch (e) { /* 忽略 */ }
}
return anyOk
}
/** 获取 TRSS Bot 实例(按 selfId,缺省取第一个在线的) */
getBot (selfId) {
const Bot = globalThis.Bot
if (!Bot) return null
if (selfId && Bot[String(selfId)]) return Bot[String(selfId)]
if (Array.isArray(Bot.uin) && Bot.uin[0] && Bot[String(Bot.uin[0])]) {
return Bot[String(Bot.uin[0])]
}
for (const k of Object.keys(Bot)) {
if (Bot[k]?.sendApi && Bot[k]?.connect) return Bot[k]
}
return null
}
/** 发送失败时的路径提示文本 */
pdfFallbackText (files, downloadDir) {
const lines = ['\n📁 文件已保存在服务器本地,可自行下载:']
for (const f of files || []) {
lines.push(`· ${f.path}(${fmtSize(f.size)})`)
}
if (downloadDir) lines.push(`\n📂 目录:${downloadDir}`)
return lines.join('\n')
}
// ---------- 退出登录 ----------
async cmdLogout (e) {
if (!(await this.checkPermission(e))) return true
await clearUserData(e.user_id)
await e.reply('✅ 已退出登录,本用户登录状态已清除')
return true
}
// ---------- 工具 ----------
async replyWithCover (e, coverUrl, msg) {
try {
if (coverUrl && typeof segment !== 'undefined') {
await e.reply([segment.image(coverUrl), msg])
} else {
await e.reply(msg)
}
} catch (err) {
await e.reply(msg)
}
}
async notifyDone (replyInfo, msg) {
try {
if (CONFIG.notify === 'text') throw new Error('text mode')
if (replyInfo.type === 'group' && replyInfo.groupId && globalThis.Bot?.pickGroup) {
await globalThis.Bot.pickGroup(replyInfo.groupId).sendMsg(msg)
return
}
if (globalThis.Bot?.pickFriend) {
await globalThis.Bot.pickFriend(replyInfo.userId).sendMsg(msg)
return
}
throw new Error('Bot API 不可用')
} catch (e) {
logger?.mark?.(msg) || logger?.info?.(msg)
}
}
}