koishi-plugin-rina-llevents 0.0.2 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/commands.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  import { Context } from 'koishi';
2
+ import { Config } from './config';
2
3
  import { LlEventService } from './service';
3
- export declare function registerCommands(ctx: Context, service: LlEventService): void;
4
+ export declare function registerCommands(ctx: Context, service: LlEventService, config: Config): void;
package/lib/config.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Schema } from 'koishi';
2
+ import { QqUrlMode } from './qq';
2
3
  export interface BroadcastTarget {
3
4
  enabled: boolean;
4
5
  platform: string;
@@ -14,6 +15,8 @@ export interface Config {
14
15
  setlistPollIntervalMinutes: number;
15
16
  setlistPollHours: number;
16
17
  syncOnStart: boolean;
18
+ qqUrlMode: QqUrlMode;
19
+ qqCombineImageAndText: boolean;
17
20
  targets: BroadcastTarget[];
18
21
  }
19
22
  export declare const Config: Schema<Config>;
@@ -1,3 +1,3 @@
1
1
  import { LlConcert, LlEvent, LlPerformance } from './model';
2
- export declare function formatReminder(event: LlEvent | undefined, concert: LlConcert | undefined, performance: LlPerformance, start: Date, minutes: number): string;
3
- export declare function formatSetlistCaption(event: LlEvent | undefined, concert: LlConcert | undefined, performance: LlPerformance, updated: boolean): string;
2
+ export declare function formatReminder(event: LlEvent | undefined, concert: LlConcert | undefined, performance: LlPerformance, start: Date, minutes: number, urlText?: string): string;
3
+ export declare function formatSetlistCaption(event: LlEvent | undefined, concert: LlConcert | undefined, performance: LlPerformance, updated: boolean, urlText?: string): string;
package/lib/index.js CHANGED
@@ -32,9 +32,9 @@ var import_koishi_plugin_cron = require("koishi-plugin-cron");
32
32
  var import_koishi = require("koishi");
33
33
  var Target = import_koishi.Schema.object({
34
34
  enabled: import_koishi.Schema.boolean().default(true).description("启用此群推送目标"),
35
- platform: import_koishi.Schema.string().required().description("平台名,例如 onebot、qq、telegram"),
36
- selfId: import_koishi.Schema.string().required().description("发送消息的机器人 ID"),
37
- channelId: import_koishi.Schema.string().required().description("群组或频道 ID")
35
+ platform: import_koishi.Schema.string().required().description("平台名,例如 qq、onebot、telegram"),
36
+ selfId: import_koishi.Schema.string().required().description("发送消息的机器人 ID(QQ 官方机器人填 AppID)"),
37
+ channelId: import_koishi.Schema.string().required().description("群组或频道 ID(QQ 官方支持 group_openid,或在启用 rina-qq-bridge 时填已映射群号)")
38
38
  });
39
39
  var Config = import_koishi.Schema.object({
40
40
  requestTimeout: import_koishi.Schema.number().min(1e3).max(6e4).default(15e3).description("LL-Fans 请求超时(毫秒)"),
@@ -45,12 +45,17 @@ var Config = import_koishi.Schema.object({
45
45
  setlistPollIntervalMinutes: import_koishi.Schema.number().min(1).max(60).default(5).description("演出后歌单轮询间隔(分钟)"),
46
46
  setlistPollHours: import_koishi.Schema.number().min(1).max(72).default(24).description("演出后歌单轮询最长时长"),
47
47
  syncOnStart: import_koishi.Schema.boolean().default(true).description("配置了推送目标时,插件启动后立即同步活动列表"),
48
+ qqUrlMode: import_koishi.Schema.union([
49
+ import_koishi.Schema.const("auto").description("跟随 rina-qq-bridge 配置(未启用桥接服务时默认脱敏)"),
50
+ import_koishi.Schema.const("defang").description("脱敏展示(去掉 https:// 并替换域名点号,避免 40054010 外链拦截)"),
51
+ import_koishi.Schema.const("markdown").description("Markdown 链接格式(仅纯文本消息走 qq:markdown)"),
52
+ import_koishi.Schema.const("strip").description("在 QQ 群消息中隐藏外链"),
53
+ import_koishi.Schema.const("raw").description("保留原始 URL(官方放行或域名加白后使用)")
54
+ ]).default("auto").description("QQ 官方群(platform=qq)消息中 LL-Fans 链接的处理方式"),
55
+ qqCombineImageAndText: import_koishi.Schema.boolean().default(true).description("在 QQ 官方群下合并发送说明文字与截图,节省消息配额"),
48
56
  targets: import_koishi.Schema.array(Target).default([]).description("提醒与歌单推送目标")
49
57
  });
50
58
 
51
- // src/commands.ts
52
- var import_koishi2 = require("koishi");
53
-
54
59
  // src/service.ts
55
60
  var import_node_crypto = require("node:crypto");
56
61
  var DAY = 24 * 60 * 60 * 1e3;
@@ -289,27 +294,124 @@ function title(event, concert, performance) {
289
294
  return [event?.name, concert?.name, performance?.name].filter(Boolean).join(" · ");
290
295
  }
291
296
  __name(title, "title");
292
- function formatReminder(event, concert, performance, start, minutes) {
297
+ function formatReminder(event, concert, performance, start, minutes, urlText) {
298
+ const link = urlText !== void 0 ? urlText : canonicalUrl(performance.eventId, performance.concertId, performance.id);
293
299
  return [
294
300
  `【演出还有 ${minutes} 分钟】`,
295
301
  title(event, concert, performance),
296
302
  `开演:${formatTime(start)}(日本时间)`,
297
303
  performance.openTime ? `开场:${performance.openTime}(日本时间)` : "",
298
304
  concert?.venue ? `会场:${concert.venue}` : "",
299
- canonicalUrl(performance.eventId, performance.concertId, performance.id)
305
+ link
300
306
  ].filter(Boolean).join("\n");
301
307
  }
302
308
  __name(formatReminder, "formatReminder");
303
- function formatSetlistCaption(event, concert, performance, updated) {
309
+ function formatSetlistCaption(event, concert, performance, updated, urlText) {
310
+ const link = urlText !== void 0 ? urlText : canonicalUrl(performance.eventId, performance.concertId, performance.id);
304
311
  return [
305
312
  updated ? "【歌单更新】" : "【演出歌单】",
306
313
  title(event, concert, performance),
307
314
  performance.date && performance.startTime ? `开演:${performance.date} ${performance.startTime}(日本时间)` : "",
308
- canonicalUrl(performance.eventId, performance.concertId, performance.id)
315
+ link
309
316
  ].filter(Boolean).join("\n");
310
317
  }
311
318
  __name(formatSetlistCaption, "formatSetlistCaption");
312
319
 
320
+ // src/qq.ts
321
+ var import_koishi2 = require("koishi");
322
+ function getQqBridge(ctx) {
323
+ return ctx.rinaQq;
324
+ }
325
+ __name(getQqBridge, "getQqBridge");
326
+ function isPlainNumericId(value) {
327
+ return /^\d{5,16}$/.test(value.trim());
328
+ }
329
+ __name(isPlainNumericId, "isPlainNumericId");
330
+ function defangUrl(url) {
331
+ return url.replace(/^https?:\/\//i, "").replace(/^([^/?#]+)/, (host) => host.replace(/\./g, "·"));
332
+ }
333
+ __name(defangUrl, "defangUrl");
334
+ function formatUrlForPlatform(ctx, platform, url, mode = "auto", label = "LL-Fans 页面") {
335
+ if (!url) return "";
336
+ if (platform !== "qq") return url;
337
+ const bridge = getQqBridge(ctx);
338
+ if (bridge) {
339
+ return bridge.formatLink("qq", url, label, mode === "auto" ? void 0 : mode);
340
+ }
341
+ switch (mode) {
342
+ case "raw":
343
+ return url;
344
+ case "strip":
345
+ return "";
346
+ case "markdown":
347
+ return `[${label}](${url})`;
348
+ case "auto":
349
+ case "defang":
350
+ default:
351
+ return defangUrl(url);
352
+ }
353
+ }
354
+ __name(formatUrlForPlatform, "formatUrlForPlatform");
355
+ function extractPlainPromptText(input) {
356
+ const stripped = input.stripped?.content;
357
+ if (typeof stripped === "string" && stripped.trim()) {
358
+ return stripped.replace(/<[^>]+>/g, "").trim();
359
+ }
360
+ const elements = input.elements?.length ? input.elements : import_koishi2.h.parse(input.content || "");
361
+ const text = import_koishi2.h.select(elements, "text").map((el) => String(el.attrs?.content ?? "")).join(" ").trim();
362
+ if (text) return text;
363
+ return (input.content ?? "").replace(/<[^>]+>/g, "").trim();
364
+ }
365
+ __name(extractPlainPromptText, "extractPlainPromptText");
366
+ async function sendSessionReply(session, text, image, options) {
367
+ if (session.platform === "qq") {
368
+ if (image && text && options.combineImageAndText) {
369
+ await session.send([import_koishi2.h.image(image, "image/png"), import_koishi2.h.text(text)]);
370
+ return;
371
+ }
372
+ if (text) {
373
+ await session.send(options.markdown && !image ? (0, import_koishi2.h)("qq:markdown", {}, text) : text);
374
+ }
375
+ if (image) {
376
+ await session.send(import_koishi2.h.image(image, "image/png"));
377
+ }
378
+ return;
379
+ }
380
+ if (text) await session.send(text);
381
+ if (image) await session.send(import_koishi2.h.image(image, "image/png"));
382
+ }
383
+ __name(sendSessionReply, "sendSessionReply");
384
+ async function sendScheduledMessage(ctx, logger, bot, channelId, text, image, options) {
385
+ const bridge = getQqBridge(ctx);
386
+ if (bridge) {
387
+ await bridge.sendGroupMessage(bot, channelId, {
388
+ text,
389
+ image,
390
+ mimeType: "image/png",
391
+ markdown: options.markdown && !image,
392
+ combineImageAndText: options.combineImageAndText
393
+ });
394
+ return;
395
+ }
396
+ if (bot.platform === "qq") {
397
+ if (isPlainNumericId(channelId)) {
398
+ logger.warn(`QQ 群目标 ${channelId} 看起来是纯数字群号,且未启用 rina-qq-bridge 映射服务,可能无法被官方接口识别为 group_openid。`);
399
+ }
400
+ if (image && text && options.combineImageAndText) {
401
+ await bot.sendMessage(channelId, [import_koishi2.h.image(image, "image/png"), import_koishi2.h.text(text)]);
402
+ return;
403
+ }
404
+ if (text) {
405
+ await bot.sendMessage(channelId, options.markdown && !image ? (0, import_koishi2.h)("qq:markdown", {}, text) : text);
406
+ }
407
+ if (image) await bot.sendMessage(channelId, import_koishi2.h.image(image, "image/png"));
408
+ return;
409
+ }
410
+ await bot.sendMessage(channelId, text);
411
+ if (image) await bot.sendMessage(channelId, import_koishi2.h.image(image, "image/png"));
412
+ }
413
+ __name(sendScheduledMessage, "sendScheduledMessage");
414
+
313
415
  // src/renderer.ts
314
416
  var import_koishi_plugin_puppeteer = require("koishi-plugin-puppeteer");
315
417
  function escapeHtml(value) {
@@ -424,25 +526,32 @@ function eventLine(event, index) {
424
526
  return `${index + 1}. ${event.name}${date ? `(${date})` : ""}`;
425
527
  }
426
528
  __name(eventLine, "eventLine");
427
- async function choose(ctx, session, values, title2, line) {
428
- if (values.length === 1) return values[0];
529
+ async function choose(ctx, session, config, values, title2, line) {
530
+ if (values.length === 1) return { value: values[0], session };
429
531
  const lines = values.map(line);
430
- await session.send(`${title2},请在 60 秒内回复序号。`);
532
+ const promptHint = session.platform === "qq" ? `${title2},请在 60 秒内回复序号(未开启全量消息时请 @机器人 回复)。` : `${title2},请在 60 秒内回复序号。`;
431
533
  try {
432
- await session.send(import_koishi2.h.image(await renderChoiceList(ctx, title2, lines), "image/png"));
534
+ const image = await renderChoiceList(ctx, title2, lines);
535
+ await sendSessionReply(session, promptHint, image, { combineImageAndText: config.qqCombineImageAndText });
433
536
  } catch {
434
- await session.send(lines.join("\n"));
537
+ await session.send(`${promptHint}
538
+ ${lines.join("\n")}`);
435
539
  }
540
+ let latestSession = session;
436
541
  const choice = await session.prompt((input) => {
437
- const value = Number(input.content?.trim());
438
- return Number.isInteger(value) && value >= 1 && value <= values.length ? value : void 0;
542
+ const value = Number(extractPlainPromptText(input));
543
+ if (Number.isInteger(value) && value >= 1 && value <= values.length) {
544
+ latestSession = input;
545
+ return value;
546
+ }
439
547
  }, { timeout: 6e4 });
440
- return choice ? values[choice - 1] : void 0;
548
+ return choice ? { value: values[choice - 1], session: latestSession } : void 0;
441
549
  }
442
550
  __name(choose, "choose");
443
- function registerCommands(ctx, service) {
551
+ function registerCommands(ctx, service, config) {
444
552
  ctx.command("ll演出近期 [days:number]", "查询近期已缓存的 LoveLive! 演出").alias("ll近期演出").action(async ({ session }, days) => {
445
- const items = await service.upcoming(Math.min(Math.max(days || 30, 1), 365));
553
+ const shownDays = Math.min(Math.max(days || 30, 1), 365);
554
+ const items = await service.upcoming(shownDays);
446
555
  if (!items.length) return "暂无近期已缓存的、具有明确开演时间的演出。";
447
556
  const lines = items.slice(0, 20).map(({ event, concert, performance, start }) => [
448
557
  new Intl.DateTimeFormat("zh-CN", { timeZone: "Asia/Tokyo", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hour12: false }).format(start),
@@ -450,12 +559,13 @@ function registerCommands(ctx, service) {
450
559
  performance.canceled ? "(已取消)" : ""
451
560
  ].filter(Boolean).join(" ")).join("\n");
452
561
  if (!session) return lines;
453
- const shownDays = Math.min(Math.max(days || 30, 1), 365);
454
- await session.send(`未来 ${shownDays} 天内有 ${items.length} 个已缓存场次(日本时间)。`);
562
+ const header = `未来 ${shownDays} 天内有 ${items.length} 个已缓存场次(日本时间)。`;
455
563
  try {
456
- await session.send(import_koishi2.h.image(await renderChoiceList(ctx, `近期演出 · ${shownDays} 天`, lines.split("\n"), ""), "image/png"));
564
+ const image = await renderChoiceList(ctx, `近期演出 · ${shownDays} 天`, lines.split("\n"), "");
565
+ await sendSessionReply(session, header, image, { combineImageAndText: config.qqCombineImageAndText });
457
566
  } catch {
458
- await session.send(lines);
567
+ await session.send(`${header}
568
+ ${lines}`);
459
569
  }
460
570
  });
461
571
  ctx.command("ll演出下场", "查询下一场已缓存的 LoveLive! 演出").action(async ({ session }) => {
@@ -464,20 +574,24 @@ function registerCommands(ctx, service) {
464
574
  const sourceUrl = canonicalUrl(next.performance.eventId, next.performance.concertId, next.performance.id);
465
575
  const title2 = [next.event?.name, next.concert?.name, next.performance.name].filter(Boolean).join(" · ");
466
576
  if (!session) return [title2, sourceUrl].join("\n");
467
- await session.send(`【下一场演出】
468
- ${title2}
469
- ${sourceUrl}`);
577
+ const displayUrl = formatUrlForPlatform(ctx, session.platform, sourceUrl, config.qqUrlMode);
578
+ const header = ["【下一场演出】", title2, displayUrl].filter(Boolean).join("\n");
470
579
  try {
471
- await session.send(import_koishi2.h.image(await captureEventDetailPage(ctx, sourceUrl), "image/png"));
580
+ const image = await captureEventDetailPage(ctx, sourceUrl);
581
+ await sendSessionReply(session, header, image, { combineImageAndText: config.qqCombineImageAndText });
472
582
  } catch (error) {
473
- return `详情页截图失败:${String(error)}
474
- ${sourceUrl}`;
583
+ const fallback = [header, `详情页截图失败:${String(error)}`].filter(Boolean).join("\n");
584
+ await sendSessionReply(session, fallback, void 0, {
585
+ combineImageAndText: config.qqCombineImageAndText,
586
+ markdown: config.qqUrlMode === "markdown"
587
+ });
475
588
  }
476
589
  });
477
590
  ctx.command("ll歌单 <keyword:text>", "模糊查找活动或场次并截取 LL-Fans 原页面歌单").action(async ({ session }, keyword = "") => {
478
591
  const needle = keyword.trim().toLocaleLowerCase();
479
592
  if (!needle) return "请输入活动、公演或场次关键词。";
480
593
  if (!session) return "请在群聊或私聊中使用 ll歌单,以便选择匹配的场次。";
594
+ let activeSession = session;
481
595
  let cached = await cachedCandidates(ctx);
482
596
  const scoredEvents = cached.events.map((event) => ({ event, score: eventScore(needle, event) })).filter((item) => item.score > 0).sort((left, right) => right.score - left.score || right.event.startsOn.localeCompare(left.event.startsOn));
483
597
  const bestScore = scoredEvents[0]?.score || 0;
@@ -485,11 +599,12 @@ ${sourceUrl}`;
485
599
  if (eventMatches.length > 20) return `关键词过宽,匹配到 ${eventMatches.length} 个活动;请补充团体、届次或地点,例如“虹咲8th大阪”。`;
486
600
  let candidates;
487
601
  if (eventMatches.length) {
488
- const event = await choose(ctx, session, eventMatches.map((item) => item.event), `找到 ${eventMatches.length} 个活动`, eventLine);
489
- if (!event) return "未收到有效序号,已取消歌单查询。";
490
- await service.syncEventDetails(event.id);
602
+ const pickedEvent = await choose(ctx, activeSession, config, eventMatches.map((item) => item.event), `找到 ${eventMatches.length} 个活动`, eventLine);
603
+ if (!pickedEvent) return "未收到有效序号,已取消歌单查询。";
604
+ activeSession = pickedEvent.session;
605
+ await service.syncEventDetails(pickedEvent.value.id);
491
606
  cached = await cachedCandidates(ctx);
492
- const allPerformances = cached.candidates.filter((candidate) => candidate.performance.eventId === event.id);
607
+ const allPerformances = cached.candidates.filter((candidate) => candidate.performance.eventId === pickedEvent.value.id);
493
608
  candidates = allPerformances.filter((candidate) => matchesCandidate(needle, candidate));
494
609
  if (!candidates.length) candidates = allPerformances;
495
610
  } else {
@@ -497,20 +612,31 @@ ${sourceUrl}`;
497
612
  }
498
613
  if (!candidates.length) return "未找到匹配场次;可先执行 ll演出同步,或使用更具体的活动名称。";
499
614
  if (candidates.length > 20) return `找到 ${candidates.length} 个场次,请补充公演地点或 Day,例如“大阪d1”。`;
500
- const selected = await choose(ctx, session, candidates, `找到 ${candidates.length} 个场次`, candidateLine);
501
- if (!selected) return "未收到有效序号,已取消歌单查询。";
615
+ const pickedCandidate = await choose(ctx, activeSession, config, candidates, `找到 ${candidates.length} 个场次`, candidateLine);
616
+ if (!pickedCandidate) return "未收到有效序号,已取消歌单查询。";
617
+ activeSession = pickedCandidate.session;
618
+ const selected = pickedCandidate.value;
502
619
  const result = await service.refreshSetlist(selected.performance);
503
620
  const sourceUrl = canonicalUrl(selected.performance.eventId, selected.performance.concertId, selected.performance.id);
504
- if (!result?.setlist.length) return `LL-Fans 尚未收录该场次歌单:
505
- ${sourceUrl}`;
506
- const caption = formatSetlistCaption(selected.event, selected.concert, result.performance, false);
507
- await session.send(caption);
621
+ const displayUrl = formatUrlForPlatform(ctx, activeSession.platform, sourceUrl, config.qqUrlMode);
622
+ if (!result?.setlist.length) {
623
+ const emptyText = ["LL-Fans 尚未收录该场次歌单:", displayUrl].filter(Boolean).join("\n");
624
+ await sendSessionReply(activeSession, emptyText, void 0, {
625
+ combineImageAndText: config.qqCombineImageAndText,
626
+ markdown: config.qqUrlMode === "markdown"
627
+ });
628
+ return;
629
+ }
630
+ const caption = formatSetlistCaption(selected.event, selected.concert, result.performance, false, displayUrl);
508
631
  try {
509
632
  const image = await captureSetlistPage(ctx, sourceUrl);
510
- await session.send(import_koishi2.h.image(image, "image/png"));
633
+ await sendSessionReply(activeSession, caption, image, { combineImageAndText: config.qqCombineImageAndText });
511
634
  } catch (error) {
512
- return `歌单已确认,但原页面截图失败:${String(error)}
513
- ${sourceUrl}`;
635
+ const errText = [caption, `歌单已确认,但原页面截图失败:${String(error)}`].filter(Boolean).join("\n");
636
+ await sendSessionReply(activeSession, errText, void 0, {
637
+ combineImageAndText: config.qqCombineImageAndText,
638
+ markdown: config.qqUrlMode === "markdown"
639
+ });
514
640
  }
515
641
  });
516
642
  ctx.command("ll演出同步", "立即同步 LL-Fans 活动列表与近期详情").action(async () => {
@@ -623,18 +749,6 @@ function extendModel(ctx) {
623
749
  __name(extendModel, "extendModel");
624
750
 
625
751
  // src/scheduler.ts
626
- var import_koishi3 = require("koishi");
627
- function describeError(error) {
628
- const message = error instanceof Error ? error.message : String(error);
629
- const safe = message.replace(/(?:base64:\/\/|data:image\/[^;,]+;base64,)[A-Za-z0-9+/=]+/g, "[image omitted]").slice(0, 500);
630
- const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
631
- return code === void 0 ? safe : `${safe} (code=${String(code)})`;
632
- }
633
- __name(describeError, "describeError");
634
- function isUncertainMessageResult(error) {
635
- return !!error && typeof error === "object" && "url" in error && ["send_msg", "send_group_msg", "send_private_msg"].includes(String(error.url));
636
- }
637
- __name(isUncertainMessageResult, "isUncertainMessageResult");
638
752
  var Scheduler = class {
639
753
  constructor(ctx, logger, service, config) {
640
754
  this.ctx = ctx;
@@ -646,35 +760,21 @@ var Scheduler = class {
646
760
  __name(this, "Scheduler");
647
761
  }
648
762
  running = false;
649
- remindersRunning = false;
650
763
  start() {
651
764
  this.ctx.on("ready", async () => {
652
- this.ctx.cron("* * * * *", () => this.tick());
653
765
  if (this.config.syncOnStart && this.activeTargets().length) {
654
- await this.service.syncIfDue(true).catch((error) => this.logger.warn(`初始活动同步失败:${describeError(error)}`));
766
+ await this.service.syncIfDue(true).catch((error) => this.logger.warn(`初始活动同步失败:${String(error)}`));
655
767
  }
768
+ this.ctx.cron("* * * * *", () => void this.run());
656
769
  });
657
770
  }
658
- async tick() {
659
- await Promise.all([this.runReminders(), this.run()]);
660
- }
661
- async runReminders() {
662
- if (this.remindersRunning) return;
663
- this.remindersRunning = true;
664
- try {
665
- await this.sendReminders();
666
- } catch (error) {
667
- this.logger.warn(`检查开演提醒失败:${describeError(error)}`);
668
- } finally {
669
- this.remindersRunning = false;
670
- }
671
- }
672
771
  async run() {
673
772
  if (this.running) return;
674
773
  this.running = true;
675
774
  try {
676
775
  if (!this.activeTargets().length) return;
677
- await this.service.syncIfDue().catch((error) => this.logger.warn(`活动列表同步失败:${describeError(error)}`));
776
+ await this.service.syncIfDue().catch((error) => this.logger.warn(`活动列表同步失败:${String(error)}`));
777
+ await this.sendReminders();
678
778
  await this.pollSetlists();
679
779
  } finally {
680
780
  this.running = false;
@@ -686,44 +786,24 @@ var Scheduler = class {
686
786
  targetKey(target) {
687
787
  return `${target.platform}:${target.selfId}:${target.channelId}`;
688
788
  }
689
- async send(target, content) {
789
+ async send(target, content, image) {
690
790
  const bot = this.ctx.bots.find((bot2) => bot2.platform === target.platform && bot2.selfId === target.selfId);
691
791
  if (!bot) throw new Error(`找不到机器人 ${target.platform}:${target.selfId}`);
692
- await bot.sendMessage(target.channelId, content);
792
+ await sendScheduledMessage(this.ctx, this.logger, bot, target.channelId, content, image, {
793
+ combineImageAndText: this.config.qqCombineImageAndText,
794
+ markdown: target.platform === "qq" && this.config.qqUrlMode === "markdown"
795
+ });
693
796
  }
694
797
  async sendOnce(target, performanceId, kind, contentHash, content, image) {
695
798
  const targetKey = this.targetKey(target);
696
799
  const id = `${performanceId}:${targetKey}:${kind}`;
697
800
  const old = (await this.ctx.database.get("rina_llevent_delivery", { id }))[0];
698
- const previous = kind === "setlist" ? await this.setlistDelivery(target, performanceId) : old;
699
- if (previous && (kind === "setlist" || kind === "setlist-caption" || previous.contentHash === contentHash)) return false;
700
- if (image) {
701
- await this.sendOnce(target, performanceId, `${kind}-caption`, contentHash, content);
702
- try {
703
- await this.send(target, import_koishi3.h.image(image, "image/png"));
704
- } catch (error) {
705
- if (!isUncertainMessageResult(error)) throw error;
706
- await this.recordDelivery(`${id}-image-uncertain`, contentHash);
707
- this.logger.warn(`歌单图片发送结果未确认(${performanceId},${targetKey}),已保留文字链接并停止此场次图片自动重试:${describeError(error)}`);
708
- return false;
709
- }
710
- } else {
711
- await this.send(target, content);
712
- }
713
- await this.recordDelivery(id, contentHash);
801
+ if (old?.contentHash === contentHash) return false;
802
+ await this.send(target, content, image);
803
+ if (old) await this.ctx.database.set("rina_llevent_delivery", id, { contentHash, sentAt: /* @__PURE__ */ new Date() });
804
+ else await this.ctx.database.create("rina_llevent_delivery", { id, contentHash, sentAt: /* @__PURE__ */ new Date() });
714
805
  return true;
715
806
  }
716
- async recordDelivery(id, contentHash) {
717
- const old = (await this.ctx.database.get("rina_llevent_delivery", { id }))[0];
718
- const sentAt = /* @__PURE__ */ new Date();
719
- if (old) await this.ctx.database.set("rina_llevent_delivery", id, { contentHash, sentAt });
720
- else await this.ctx.database.create("rina_llevent_delivery", { id, contentHash, sentAt });
721
- }
722
- async setlistDelivery(target, performanceId) {
723
- const id = `${performanceId}:${this.targetKey(target)}:setlist`;
724
- const deliveries = await this.ctx.database.get("rina_llevent_delivery", { id: [id, `${id}-update`, `${id}-image-uncertain`] });
725
- return deliveries[0];
726
- }
727
807
  async maps() {
728
808
  const [events, concerts] = await Promise.all([
729
809
  this.ctx.database.get("rina_llevent_event", {}),
@@ -737,21 +817,22 @@ var Scheduler = class {
737
817
  async sendReminders() {
738
818
  const targets = this.activeTargets();
739
819
  if (!targets.length) return;
820
+ const now = /* @__PURE__ */ new Date();
740
821
  const performances = await this.ctx.database.get("rina_llevent_performance", { canceled: false });
741
822
  const { events, concerts } = await this.maps();
742
823
  for (const performance of performances) {
743
824
  const start = performanceStart(performance);
744
825
  if (!start) continue;
745
- const now = Date.now();
746
826
  const due = start.getTime() - this.config.reminderMinutes * 6e4;
747
- if (now < due || now >= start.getTime()) continue;
748
- const minutes = Math.ceil((start.getTime() - now) / 6e4);
749
- const content = formatReminder(events.get(performance.eventId), concerts.get(performance.concertId), performance, start, minutes);
827
+ if (now.getTime() < due || now.getTime() >= due + 2 * 6e4) continue;
828
+ const sourceUrl = canonicalUrl(performance.eventId, performance.concertId, performance.id);
750
829
  for (const target of targets) {
751
830
  try {
831
+ const urlText = formatUrlForPlatform(this.ctx, target.platform, sourceUrl, this.config.qqUrlMode);
832
+ const content = formatReminder(events.get(performance.eventId), concerts.get(performance.concertId), performance, start, this.config.reminderMinutes, urlText);
752
833
  await this.sendOnce(target, performance.id, "reminder", String(due), content);
753
834
  } catch (error) {
754
- this.logger.warn(`发送开演提醒失败:${describeError(error)}`);
835
+ this.logger.warn(`发送开演提醒失败:${String(error)}`);
755
836
  }
756
837
  }
757
838
  }
@@ -770,26 +851,20 @@ var Scheduler = class {
770
851
  const last = performance.setlistCheckedAt?.getTime() || 0;
771
852
  if (now.getTime() < pollStart || now.getTime() > pollEnd || now.getTime() - last < this.config.setlistPollIntervalMinutes * 6e4) continue;
772
853
  try {
773
- const deliveries = await Promise.all(targets.map(async (target) => ({
774
- target,
775
- previous: await this.setlistDelivery(target, performance.id)
776
- })));
777
- const pending = deliveries.filter(({ previous }) => !previous);
778
- if (!pending.length) continue;
854
+ const oldHash = performance.setlistHash;
779
855
  const result = await this.service.refreshSetlist(performance);
780
856
  if (!result?.setlist.length) continue;
781
857
  const refreshed = result.performance;
782
- const image = await captureSetlistPage(this.ctx, canonicalUrl(refreshed.eventId, refreshed.concertId, refreshed.id));
783
- for (const { target } of pending) {
784
- try {
785
- const content = formatSetlistCaption(events.get(refreshed.eventId), concerts.get(refreshed.concertId), refreshed, false);
786
- await this.sendOnce(target, refreshed.id, "setlist", refreshed.setlistHash, content, image);
787
- } catch (error) {
788
- this.logger.warn(`发送歌单失败(${refreshed.id},${this.targetKey(target)}):${describeError(error)}`);
789
- }
858
+ const updated = oldHash !== refreshed.setlistHash && oldHash !== EMPTY_SETLIST_HASH;
859
+ const sourceUrl = canonicalUrl(refreshed.eventId, refreshed.concertId, refreshed.id);
860
+ const image = await captureSetlistPage(this.ctx, sourceUrl);
861
+ for (const target of targets) {
862
+ const urlText = formatUrlForPlatform(this.ctx, target.platform, sourceUrl, this.config.qqUrlMode);
863
+ const content = formatSetlistCaption(events.get(refreshed.eventId), concerts.get(refreshed.concertId), refreshed, updated, urlText);
864
+ await this.sendOnce(target, refreshed.id, updated ? "setlist-update" : "setlist", refreshed.setlistHash, content, image);
790
865
  }
791
866
  } catch (error) {
792
- this.logger.warn(`轮询歌单失败(${performance.id}):${describeError(error)}`);
867
+ this.logger.warn(`轮询歌单失败(${performance.id}):${String(error)}`);
793
868
  }
794
869
  }
795
870
  }
@@ -797,13 +872,13 @@ var Scheduler = class {
797
872
 
798
873
  // src/index.ts
799
874
  var name = "rina-llevents";
800
- var inject = { required: ["database", "cron", "http"], optional: ["puppeteer"] };
875
+ var inject = { required: ["database", "cron", "http"], optional: ["puppeteer", "rinaQq"] };
801
876
  var Config2 = Config;
802
877
  function apply(ctx, config) {
803
878
  extendModel(ctx);
804
879
  const logger = ctx.logger(name);
805
880
  const service = new LlEventService(ctx, logger, new LlFansClient(ctx, config.requestTimeout), config);
806
- registerCommands(ctx, service);
881
+ registerCommands(ctx, service, config);
807
882
  new Scheduler(ctx, logger, service, config).start();
808
883
  }
809
884
  __name(apply, "apply");
package/lib/qq.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { Bot, Context, Logger, Session } from 'koishi';
2
+ export type QqUrlMode = 'auto' | 'defang' | 'markdown' | 'strip' | 'raw';
3
+ export interface OptionalQqBridge {
4
+ resolveGroupId(platform: string, botSelfId: string, configuredGroupId: string): Promise<string>;
5
+ formatLink(platform: string | undefined, url: string, label?: string, mode?: Exclude<QqUrlMode, 'auto'>): string;
6
+ sendGroupMessage(bot: Bot, channelId: string, options: {
7
+ text?: string;
8
+ image?: Buffer;
9
+ mimeType?: string;
10
+ markdown?: boolean;
11
+ combineImageAndText?: boolean;
12
+ }): Promise<void>;
13
+ }
14
+ export declare function getQqBridge(ctx: Context): OptionalQqBridge | undefined;
15
+ export declare function isPlainNumericId(value: string): boolean;
16
+ export declare function formatUrlForPlatform(ctx: Context, platform: string | undefined, url: string, mode?: QqUrlMode, label?: string): string;
17
+ export declare function extractPlainPromptText(input: Session): string;
18
+ export declare function sendSessionReply(session: Session, text: string, image: Buffer | undefined, options: {
19
+ combineImageAndText: boolean;
20
+ markdown?: boolean;
21
+ }): Promise<void>;
22
+ export declare function sendScheduledMessage(ctx: Context, logger: Logger, bot: Bot, channelId: string, text: string, image: Buffer | undefined, options: {
23
+ combineImageAndText: boolean;
24
+ markdown?: boolean;
25
+ }): Promise<void>;
@@ -7,18 +7,13 @@ export declare class Scheduler {
7
7
  private service;
8
8
  private config;
9
9
  private running;
10
- private remindersRunning;
11
10
  constructor(ctx: Context, logger: Logger, service: LlEventService, config: Config);
12
11
  start(): void;
13
- private tick;
14
- private runReminders;
15
12
  private run;
16
13
  private activeTargets;
17
14
  private targetKey;
18
15
  private send;
19
16
  private sendOnce;
20
- private recordDelivery;
21
- private setlistDelivery;
22
17
  private maps;
23
18
  private sendReminders;
24
19
  private pollSetlists;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-rina-llevents",
3
3
  "description": "LoveLive活动信息订阅",
4
- "version": "0.0.2",
4
+ "version": "0.1.0",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [
@@ -14,11 +14,6 @@
14
14
  "koishi",
15
15
  "plugin"
16
16
  ],
17
- "homepage": "https://github.com/738NGX/rinachanbot",
18
- "repository": {
19
- "type": "git",
20
- "url": "git+https://github.com/738NGX/rinachanbot.git"
21
- },
22
17
  "peerDependencies": {
23
18
  "koishi": "^4.18.7"
24
19
  },
@@ -26,4 +21,4 @@
26
21
  "koishi-plugin-cron": "^3.1.0",
27
22
  "koishi-plugin-puppeteer": "^3.9.0"
28
23
  }
29
- }
24
+ }
package/readme.md CHANGED
@@ -18,10 +18,8 @@ https://ll-fans.jp/data/event/288?concert=427&performance=731
18
18
 
19
19
  - 定时轮询活动列表,发现新增、名称或日期变动,及近期一年内的活动详情变动。
20
20
  - 仅缓存未来一年内的详情;越接近开演检查越频繁。
21
- - 在 `performance.date + startTime`(日本时区)前 10 分钟发送一次提醒;提醒检查独立于列表同步与歌单截图,延迟时会在开演前补发并显示实际剩余分钟数。
22
- - 从预计结束时刻开始等待该场次歌单;首次收录时,每个推送目标只发送一次“演出歌单”,后续歌单变化不再自动推送。所有目标均已处理后,停止该场次的歌单轮询与截图。
23
- - 按场次和推送目标去重,兼容旧版首次推送及更新记录;已推送过的场次在升级或重启后不会再次发送。普通图片发送异常时仅重试图片,不重复发送已成功的文字。
24
- - OneBot 图片发送请求报错或超时时,结果可能是“实际送达但回执失败”。插件会单独记为“发送结果未确认”,保留已发送的文字链接并停止此场次图片自动重试,避免重复刷屏;如图片确实未到达或需要最新歌单,可用 `ll歌单` 手动查询。
21
+ - 在 `performance.date + startTime`(日本时区)前 10 分钟发送一次提醒。
22
+ - 从预计结束时刻开始轮询该场次歌单;首次出现时推送,随后变化时发送更新。
25
23
  - 歌单正文不入库;推送和 `ll歌单` 都使用 Puppeteer 截取 LL-Fans 原页面。
26
24
  - `performance.canceled` 会阻止提醒和歌单轮询;未来活动从列表消失只标为“待确认”,不会误判为取消。
27
25