koishi-plugin-kkk 3.7.0 → 3.7.2

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.
@@ -0,0 +1,263 @@
1
+ /**
2
+ * 图片段 → markdown 图片(`![#宽px #高px](url)`)。
3
+ *
4
+ * 用户反馈两条,这里一起解决:
5
+ * 1. **「所有的图片发送都要走 md,不然太模糊了」** —— QQ 的普通图片消息(image 段 → 适配器按
6
+ * MEDIA 上传)会被客户端二次压缩,卡片上的小字糊成一团;markdown 里的图片不会被压,字是清楚的。
7
+ * 2. **「![#px大小#px大小]() 必须要 #px,不然手机不会显示」** —— md 图片必须写死尺寸,
8
+ * 不写尺寸手机端干脆不显示这张图。
9
+ *
10
+ * 所以这里在**发送出口**统一改写:compat/node-karin 的 reply / sendMsg / sendMaster 四条路径都过一遍,
11
+ * 业务代码照旧 e.reply(segment.image(...)),不用一处处改。
12
+ *
13
+ * 只在「认 markdown 的平台」上生效(官方 QQ:`qq`):
14
+ * - OneBot 系(NapCat / Lagrange / go-cqhttp / Chronocat…)收到 markdown 只显示成一串文字、
15
+ * 图片全丢(用户实测),所以那条链路继续发图片段;
16
+ * - QQ 频道(`qqguild`)的适配器没有 markdown 分支,md 元素会被当纯文本渲染 → 也排除。
17
+ *
18
+ * 另外三种情况**不动**(动了只会更糟):
19
+ * - 消息里还有视频 / 语音 / 文件:适配器遇到附件会把整条消息转成 MEDIA,markdown 内容会被丢掉;
20
+ * - 合并转发收集中的消息:转发节点里塞 markdown 客户端不认;
21
+ * - 上传拿不到公网地址(没装 assets 服务等)、或者**读不出图片尺寸**:保持原来的图片段。
22
+ * 读不出尺寸是可以退回普通图片的,但**绝不能发一张不带尺寸的 markdown 图片** ——
23
+ * 用户实测「必须要 #px,不然手机不会显示」,那种图上手机就是一片空白。
24
+ */
25
+ import crypto from 'node:crypto'
26
+ import fs from 'node:fs'
27
+ import path from 'node:path'
28
+ import { fileURLToPath } from 'node:url'
29
+
30
+ import { logger } from './logger'
31
+ import { tryGetRuntime } from './runtime'
32
+ import { segment } from './segment'
33
+
34
+ /** OneBot 系:不渲染 markdown(见文件头) */
35
+ const ONEBOT_LIKE = /onebot|napcat|lagrange|go-?cqhttp|chronocat|mirai/i
36
+
37
+ /**
38
+ * 会渲染 markdown 图片的平台。
39
+ *
40
+ * 只认 `qq` 这一个平台名 —— QQ 的 markdown 是**官方机器人**能力,
41
+ * `qqguild`(频道)走的是另一套编码器,md 元素在那里会被当成纯文本原样发出去。
42
+ */
43
+ const canUseMarkdownImage = (platform: string): boolean => {
44
+ const name = String(platform || '').toLowerCase()
45
+ if (!name) return false
46
+ if (ONEBOT_LIKE.test(name)) return false
47
+ if (name.startsWith('qqguild')) return false
48
+ return name === 'qq' || name.startsWith('qq-') || name.startsWith('qqbot')
49
+ }
50
+
51
+ /** 媒体段:md 和附件不能塞进同一条消息(会被适配器吃掉),所以要跳过整条改写 */
52
+ const ATTACHMENT_TYPES = new Set(['video', 'audio', 'record', 'file'])
53
+
54
+ const isImageElement = (element: any): boolean =>
55
+ !!element && typeof element === 'object' && (element.type === 'img' || element.type === 'image')
56
+
57
+ const srcOf = (element: any): string => {
58
+ const attrs = element?.attrs ?? {}
59
+ const src = attrs.src ?? attrs.url ?? element?.data?.file ?? element?.data?.url
60
+ return typeof src === 'string' ? src : ''
61
+ }
62
+
63
+ /** 按二进制头认 mime(发给 assets 用;标错会让适配器按错格式处理) */
64
+ const mimeOfBuffer = (buffer: Buffer): string => {
65
+ if (buffer.length >= 8 && buffer[0] === 0x89 && buffer.toString('latin1', 1, 4) === 'PNG') return 'image/png'
66
+ if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8) return 'image/jpeg'
67
+ if (buffer.length >= 6 && buffer.toString('latin1', 0, 3) === 'GIF') return 'image/gif'
68
+ if (buffer.length >= 12 && buffer.toString('latin1', 0, 4) === 'RIFF' && buffer.toString('latin1', 8, 12) === 'WEBP') return 'image/webp'
69
+ return 'image/jpeg'
70
+ }
71
+
72
+ /**
73
+ * 读出图片的**真实像素尺寸** —— md 里的 `#宽px #高px` 就靠它。
74
+ *
75
+ * 不引第三方库:卡片是 JPEG、图集是 JPEG、二维码是 PNG、实况图封面是 WebP,四种头都自己认,
76
+ * 免得又出现「取不到尺寸 → 正方形拉伸」或「没写尺寸 → 手机不显示」。
77
+ */
78
+ const readImageSize = (buffer: Buffer): { width: number; height: number } => {
79
+ // PNG:IHDR 就在固定偏移
80
+ if (buffer.length >= 24 && buffer[0] === 0x89 && buffer.toString('latin1', 1, 4) === 'PNG') {
81
+ return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) }
82
+ }
83
+ // GIF:逻辑屏幕描述符,小端
84
+ if (buffer.length >= 10 && buffer.toString('latin1', 0, 3) === 'GIF') {
85
+ return { width: buffer.readUInt16LE(6), height: buffer.readUInt16LE(8) }
86
+ }
87
+ // JPEG:扫到 SOF 段(SOF0..SOF15,跳过 DHT/DAC 这些非 SOF 标记)
88
+ if (buffer.length > 4 && buffer[0] === 0xff && buffer[1] === 0xd8) {
89
+ let offset = 2
90
+ while (offset + 9 < buffer.length) {
91
+ if (buffer[offset] !== 0xff) { offset++; continue }
92
+ const marker = buffer[offset + 1]
93
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
94
+ return { height: buffer.readUInt16BE(offset + 5), width: buffer.readUInt16BE(offset + 7) }
95
+ }
96
+ const length = buffer.readUInt16BE(offset + 2)
97
+ if (length <= 0) break
98
+ offset += 2 + length
99
+ }
100
+ }
101
+ // WebP:VP8X(扩展)/ VP8L(无损)/ VP8(有损)三种头的写法都不一样
102
+ if (buffer.length >= 30 && buffer.toString('latin1', 0, 4) === 'RIFF' && buffer.toString('latin1', 8, 12) === 'WEBP') {
103
+ const format = buffer.toString('latin1', 12, 16)
104
+ if (format === 'VP8X') {
105
+ return { width: 1 + buffer.readUIntLE(24, 3), height: 1 + buffer.readUIntLE(27, 3) }
106
+ }
107
+ if (format === 'VP8L') {
108
+ const bits = buffer.readUInt32LE(21)
109
+ return { width: 1 + (bits & 0x3fff), height: 1 + ((bits >> 14) & 0x3fff) }
110
+ }
111
+ if (format === 'VP8 ') {
112
+ return { width: buffer.readUInt16LE(26) & 0x3fff, height: buffer.readUInt16LE(28) & 0x3fff }
113
+ }
114
+ }
115
+ return { width: 0, height: 0 }
116
+ }
117
+
118
+ /** 把各种写法读成 Buffer:data URI / base64:// / file:// / 本地路径 / http(s) */
119
+ const loadImageBuffer = async (src: string): Promise<Buffer | null> => {
120
+ try {
121
+ if (src.startsWith('base64://')) return Buffer.from(src.slice('base64://'.length), 'base64')
122
+ if (src.startsWith('data:')) {
123
+ const comma = src.indexOf(',')
124
+ if (comma < 0) return null
125
+ return Buffer.from(src.slice(comma + 1), 'base64')
126
+ }
127
+ const localPath = src.startsWith('file://') ? fileURLToPath(src) : src
128
+ if (!/^https?:\/\//i.test(src)) {
129
+ if (fs.existsSync(localPath)) return fs.readFileSync(localPath)
130
+ return null
131
+ }
132
+ const response = await fetch(src)
133
+ if (!response.ok) {
134
+ logger.mark('[图片md] 下载失败 HTTP ' + response.status + ': ' + src.slice(0, 80))
135
+ return null
136
+ }
137
+ return Buffer.from(await response.arrayBuffer())
138
+ } catch (error: any) {
139
+ logger.mark('[图片md] 读取图片失败: ' + String(error?.message ?? error).slice(0, 120))
140
+ return null
141
+ }
142
+ }
143
+
144
+ /**
145
+ * 上传到宿主的 assets,拿到 QQ 能直接取的 https 地址。
146
+ *
147
+ * md 里的图片地址**必须是公网 http(s)**:适配器只对 data: 图片做特殊处理
148
+ * (见 qq-crack 的 renderMarkdownDataImages —— data 图片会被它转回 MEDIA 上传,等于白改),
149
+ * 相对路径/本地路径手机端也取不到。
150
+ */
151
+ let warnedNoAssets = false
152
+
153
+ const uploadImage = async (buffer: Buffer): Promise<string | null> => {
154
+ const assets: any = (tryGetRuntime() as any)?.ctx?.assets
155
+ if (!assets?.upload) {
156
+ /** 没装 assets 服务就整条链路都用不了,提示一次就够,别每张图刷一遍日志 */
157
+ if (!warnedNoAssets) {
158
+ warnedNoAssets = true
159
+ logger.mark('[图片md] 宿主没有 assets 服务(拿不到公网图片地址),图片继续按普通图片段发送')
160
+ }
161
+ return null
162
+ }
163
+ const mime = mimeOfBuffer(buffer)
164
+ const ext = mime === 'image/png' ? '.png' : mime === 'image/gif' ? '.gif' : mime === 'image/webp' ? '.webp' : '.jpg'
165
+ try {
166
+ const uploaded: any = await assets.upload('data:' + mime + ';base64,' + buffer.toString('base64'), 'kkk-md' + ext)
167
+ const url = typeof uploaded === 'string' ? uploaded : uploaded?.url
168
+ return url && /^https?:\/\//i.test(String(url)) ? String(url) : null
169
+ } catch (error: any) {
170
+ logger.mark('[图片md] 上传失败: ' + String(error?.message ?? error).slice(0, 120))
171
+ return null
172
+ }
173
+ }
174
+
175
+ /**
176
+ * 同一张图反复发(推送里的封面、面板卡片…)不用反复上传:
177
+ * 按图片内容摘要缓存结果,顺带省掉重复的下载与解码。
178
+ */
179
+ const imageCache = new Map<string, string | null>()
180
+ const IMAGE_CACHE_MAX = 200
181
+
182
+ /** 图片段 → md 图片字符串;拿不到尺寸/地址就返回 null(调用方保持原样,别把图弄丢) */
183
+ export const markdownImageOf = async (src: string): Promise<string | null> => {
184
+ if (!src) return null
185
+ const key = crypto.createHash('md5').update(src).digest('hex')
186
+ const cached = imageCache.get(key)
187
+ if (cached) return cached
188
+ const buffer = await loadImageBuffer(src)
189
+ let result: string | null = null
190
+ if (buffer && buffer.length) {
191
+ const { width, height } = readImageSize(buffer)
192
+ /**
193
+ * **读不出尺寸就不换成 markdown**(退回普通图片段)。
194
+ *
195
+ * 用户实测:「必须要 #px,不然手机不会显示」—— 不带尺寸的 md 图片在手机端干脆是空白,
196
+ * 比糊更糟。所以这里宁可发一张(会被压糊但看得见的)普通图片,
197
+ * 也不发一张手机上什么都不显示的 markdown 图片。
198
+ */
199
+ if (width > 0 && height > 0) {
200
+ const url = await uploadImage(buffer)
201
+ if (url) result = '![#' + width + 'px #' + height + 'px](' + url + ')'
202
+ }
203
+ }
204
+ /**
205
+ * **只缓存成功的结果**:网络 / 图床抖动导致的失败要是也缓存下来,
206
+ * 这张图之后就一直按普通图片发(糊),得等重启才能恢复。
207
+ */
208
+ if (result) {
209
+ if (imageCache.size >= IMAGE_CACHE_MAX) imageCache.delete(imageCache.keys().next().value as string)
210
+ imageCache.set(key, result)
211
+ } else {
212
+ logger.debug('[图片md] 这张图这次没转成 markdown,按普通图片发送: ' + src.slice(0, 60))
213
+ }
214
+ return result
215
+ }
216
+
217
+ /** 清空缓存(测试用) */
218
+ export const clearMarkdownImageCache = (): void => { imageCache.clear() }
219
+
220
+ /**
221
+ * 把一条消息里的图片段改写成 markdown 图片(其它段原样保留、顺序不变)。
222
+ *
223
+ * 连续的图片合成**一个** markdown 元素(换行分隔)—— 和官方 QQ 的渲染习惯一致:
224
+ * 连续图片紧贴显示,视觉上仍是一整张卡片,而不是一张一张孤立的图。
225
+ *
226
+ * @param elements 已归一化的消息元素数组
227
+ * @param platform 适配器平台名(kompat 层从 bot.platform / session.platform 取)
228
+ * @returns 改写后的数组;不该改或改不动时**原样返回**,绝不让消息发不出去
229
+ */
230
+ export const imagesToMarkdown = async (elements: any[], platform: string): Promise<any[]> => {
231
+ const list = Array.isArray(elements) ? elements : []
232
+ if (!list.length) return list
233
+ if (!canUseMarkdownImage(platform)) return list
234
+ if (!list.some(isImageElement)) return list
235
+ if (list.some((element) => ATTACHMENT_TYPES.has(String(element?.type ?? '')))) return list
236
+
237
+ const out: any[] = []
238
+ /** 攒着的连续图片(遇到非图片段就冲出去) */
239
+ let run: string[] = []
240
+ const flushRun = () => {
241
+ // 有图转不动(上传失败等)时 run 里会是空串占位,这里只冲有内容的
242
+ if (run.length) out.push(segment.markdown(run.join(String.fromCharCode(10))))
243
+ run = []
244
+ }
245
+
246
+ for (const element of list) {
247
+ if (!isImageElement(element)) {
248
+ flushRun()
249
+ out.push(element)
250
+ continue
251
+ }
252
+ const markdown = await markdownImageOf(srcOf(element))
253
+ if (markdown) {
254
+ run.push(markdown)
255
+ } else {
256
+ // 转不了就把它自己按图片段发出去,别丢
257
+ flushRun()
258
+ out.push(element)
259
+ }
260
+ }
261
+ flushRun()
262
+ return out
263
+ }
@@ -20,6 +20,7 @@ import { isSemverGreater } from '../karin/module/utils/semver'
20
20
  import { resolveAdapterInfo } from './adapter-info'
21
21
  import { logger } from './logger'
22
22
  import { COLLECTED_MESSAGE_ID, collectForward } from './forward-collect'
23
+ import { imagesToMarkdown } from './imageMarkdown'
23
24
  import { UnconfirmedSendError, classifySendFailure, decorateSendError, describeSendFailure, isPassiveLimitFailure } from './sendError'
24
25
  import { commandQueue, eventQueue, getRuntime, karinPathBase, taskQueue, tryGetRuntime } from './runtime'
25
26
  import { segment } from './segment'
@@ -250,13 +251,15 @@ export class KkkBot {
250
251
  }
251
252
 
252
253
  // 退化路径:整条发一次;失败再逐个元素发,尽量把内容送出去
254
+ /** 退化发送 = 直接发消息,所以图片同样要改走 markdown(见 compat/imageMarkdown) */
255
+ const fallback = await imagesToMarkdown(payload.elements, platformOfBot(this.bot))
253
256
  try {
254
- const ids = await this.bot.sendMessage(channelId, payload.elements as any)
257
+ const ids = await this.bot.sendMessage(channelId, fallback as any)
255
258
  return { messageId: ids[ids.length - 1] ?? '' }
256
259
  } catch (error) {
257
260
  logger.warn('整条发送失败,改为逐个元素发送: ' + String((error as any)?.message ?? error))
258
261
  let lastId = ''
259
- for (const item of payload.elements) {
262
+ for (const item of fallback) {
260
263
  const ids = await this.bot.sendMessage(channelId, [item] as any)
261
264
  lastId = ids[ids.length - 1] ?? lastId
262
265
  }
@@ -351,10 +354,13 @@ export class KkkBot {
351
354
 
352
355
  /** 发送消息(karin 的 bot.sendMsg) */
353
356
  async sendMsg (contact: Contact | string, content: any, _options?: any): Promise<{ messageId: string }> {
357
+ const elements = normalizeContent(content)
354
358
  /** 解析结果合并转发:正在收集就攒起来(见 compat/forward-collect) */
355
- if (collectForward(peerOf(contact), content)) return { messageId: COLLECTED_MESSAGE_ID }
359
+ if (collectForward(peerOf(contact), elements)) return { messageId: COLLECTED_MESSAGE_ID }
356
360
  const channelId = typeof contact === 'string' ? contact : contact.peer
357
- const ids = await this.bot.sendMessage(channelId, normalizeContent(content) as any)
361
+ /** 图片统一改走 markdown(见 compat/imageMarkdown) */
362
+ const outgoing = await imagesToMarkdown(elements, platformOfBot(this.bot))
363
+ const ids = await this.bot.sendMessage(channelId, outgoing as any)
358
364
  // 同 reply/uploadFile:**没拿到消息 ID 就是没发出去**,别当成功返回
359
365
  const id = ids?.[ids.length - 1] ?? ''
360
366
  if (!id) {
@@ -480,13 +486,22 @@ export class Message {
480
486
  * 这时自动改用**主动消息**(不带引用,直接往频道里发),失败才把原错误抛出去。
481
487
  */
482
488
  async reply (content: any, _options?: any): Promise<{ messageId: string; rawData?: any }> {
483
- const elements = normalizeContent(content)
489
+ const raw = normalizeContent(content)
484
490
 
485
491
  /**
486
492
  * 解析结果合并转发:正在收集就攒起来,等解析结束发一条转发(见 compat/forward-collect)。
487
493
  * 回一个假的消息 ID:调用方普遍只看「有没有拿到 ID」(例如 uploadFile 判断发送成没成功)。
488
494
  */
489
- if (collectForward(this.contact?.peer ?? '', elements)) return { messageId: COLLECTED_MESSAGE_ID }
495
+ if (collectForward(this.contact?.peer ?? '', raw)) return { messageId: COLLECTED_MESSAGE_ID }
496
+
497
+ /**
498
+ * **图片统一改走 markdown**(上传拿公网地址 + 写死 `#宽px #高px`),见 compat/imageMarkdown。
499
+ *
500
+ * 放在这里是因为它是**所有回复的唯一出口** —— 业务代码一律 `e.reply(...)`,
501
+ * 不用一处处改业务代码。转换不成功会退回原来的图片段(绝不把图弄丢)。
502
+ * 上面的合并转发分支已经返回了,所以转发节点里仍然是普通图片段。
503
+ */
504
+ const elements = await imagesToMarkdown(raw, platformOfMessage(this))
490
505
 
491
506
  /**
492
507
  * 没拿到消息 ID 就是**没发出去**(对齐 qq-chat 的判法)。
@@ -585,6 +600,21 @@ function peerOf (contact: Contact | string): string {
585
600
  return typeof contact === 'string' ? contact : String((contact as Contact)?.peer ?? '')
586
601
  }
587
602
 
603
+ /**
604
+ * 适配器平台名。
605
+ *
606
+ * 发送出口要用它判断「这个平台认不认 markdown 图片」(见 compat/imageMarkdown):
607
+ * KkkBot 包装上直接转发真实 Bot 的 platform,传 KkkBot 或裸 Bot 都能取到。
608
+ */
609
+ function platformOfBot (bot: any): string {
610
+ return String(bot?.platform ?? bot?.bot?.platform ?? '')
611
+ }
612
+
613
+ /** 同上,从消息事件取(会话上就带 platform,拿不到再问 bot) */
614
+ function platformOfMessage (message: Message): string {
615
+ return String(message.session?.platform ?? platformOfBot(message.bot))
616
+ }
617
+
588
618
  /**
589
619
  * 合并转发的载荷。
590
620
  *
@@ -718,18 +748,22 @@ async function sendMsg (selfId: string, contact: Contact | string, content: any,
718
748
  + '),这条消息发不出去。等它重新上线后下次推送会正常发出;如果是长期不在线,检查一下适配器连接')
719
749
  }
720
750
  const channelId = peerOf(contact)
751
+ const elements = normalizeContent(content)
721
752
  /** 解析结果合并转发:这条也走漏斗(karin.sendMsg 是业务代码另一条常用出口) */
722
- if (collectForward(channelId, normalizeContent(content))) {
753
+ if (collectForward(channelId, elements)) {
723
754
  return { messageId: COLLECTED_MESSAGE_ID, rawData: [] }
724
755
  }
725
- const ids = await bot.bot.sendMessage(channelId, normalizeContent(content) as any)
756
+ /** 图片统一改走 markdown(见 compat/imageMarkdown) */
757
+ const outgoing = await imagesToMarkdown(elements, platformOfBot(bot.bot))
758
+ const ids = await bot.bot.sendMessage(channelId, outgoing as any)
726
759
  return { messageId: ids[ids.length - 1] ?? '', rawData: ids }
727
760
  }
728
761
 
729
762
  async function sendMaster (botId: string, master: string, content: any, _options?: any) {
730
763
  const bot = resolveBot(botId)
731
764
  if (!bot) throw new Error('[kkk] 没有可用的机器人实例,无法发送消息')
732
- const elements = normalizeContent(content)
765
+ // 图片统一改走 markdown(见 compat/imageMarkdown):私聊和群里一样,md 图片才不会被压糊
766
+ const elements = await imagesToMarkdown(normalizeContent(content), platformOfBot(bot.bot))
733
767
  const target = bot.bot as any
734
768
  // Satori 的 Bot 有 sendPrivateMessage;个别适配器没有,退化成私聊频道 id
735
769
  const ids = typeof target.sendPrivateMessage === 'function'
@@ -24,11 +24,29 @@ import {
24
24
  // 解析阶段(「下载进度」指令读的就是这里登记的状态)
25
25
  import { DOWNLOAD_STAGES, clearParseStage, updateDownloadStage } from './Network/Downloader'
26
26
 
27
+ /** 发送结果里把消息 ID 抠出来(不同适配器返回的形状不一样:对象带 messageId、或者就是字符串数组) */
28
+ const reportSent = (options: uploadFileOptions | undefined, sent: any): void => {
29
+ if (!options?.onSent) return
30
+ try {
31
+ const id = typeof sent === 'string'
32
+ ? sent
33
+ : (sent?.messageId ?? (Array.isArray(sent) ? sent[0] : ''))
34
+ if (id) options.onSent(String(id))
35
+ } catch { /* 拿不到 ID 不影响发送本身 */ }
36
+ }
37
+
27
38
  type uploadFileOptions = {
28
39
  /** 是否使用群文件上传 */
29
40
  useGroupFile?: boolean
30
41
  /** 消息ID,如果有,则将使用该消息ID制作回复元素 */
31
42
  message_id?: string
43
+ /**
44
+ * 发出去了把消息 ID 交回来(可选)。
45
+ *
46
+ * 互动视频用它:下一段播出来之后要**撤回上一段那条视频**,群里只留当前这一段
47
+ * (不然点几次剧情,群里就躺着一串视频)。
48
+ */
49
+ onSent?: (messageId: string) => void
32
50
  /** 是否为主动消息 */
33
51
  active?: boolean
34
52
  /** 主动消息参数 */
@@ -351,12 +369,14 @@ export const uploadFile = async (event: Message, file: fileInfo, videoUrl: strin
351
369
  // 是群文件
352
370
  const bot = karin.getBot(String(options.activeOption?.uin))!
353
371
  logger.mark(`${logger.blue('主动消息:')} 视频大小: ${newFileSize.toFixed(1)}MB 正在通过${logger.yellow('bot.uploadFile')}回复...`)
354
- await bot.uploadFile(contact, File, file.originTitle ? `${file.originTitle}.mp4` : `${File.split('/').pop()}`)
372
+ const sent: any = await bot.uploadFile(contact, File, file.originTitle ? `${file.originTitle}.mp4` : `${File.split('/').pop()}`)
373
+ reportSent(options, sent)
355
374
  } else {
356
375
  // 不是群文件
357
376
  logger.mark(`${logger.blue('主动消息:')} 视频大小: ${newFileSize.toFixed(1)}MB 正在通过${logger.yellow('karin.sendMsg')}回复...`)
358
377
  // 兼容层已经把「没拿到消息 ID」当成失败抛出(见 compat/sendError),所以这里没有异常就是发出去了
359
- await karin.sendMsg(selfId, contact, [segment.video(File)], { retryCount: 0 })
378
+ const sent: any = await karin.sendMsg(selfId, contact, [segment.video(File)], { retryCount: 0 })
379
+ reportSent(options, sent)
360
380
  sendStatus = true
361
381
  }
362
382
  } else {
@@ -364,12 +384,14 @@ export const uploadFile = async (event: Message, file: fileInfo, videoUrl: strin
364
384
  if (useGroupFile) {
365
385
  // 是文件
366
386
  logger.mark(`${logger.blue('被动消息:')} 视频大小: ${newFileSize.toFixed(1)}MB 正在通过${logger.yellow('e.bot.uploadFile')}回复...`)
367
- await event.bot.uploadFile(event.contact, File, file.originTitle ? `${file.originTitle}.mp4` : `${File.split('/').pop()}`)
387
+ const sent: any = await event.bot.uploadFile(event.contact, File, file.originTitle ? `${file.originTitle}.mp4` : `${File.split('/').pop()}`)
388
+ reportSent(options, sent)
368
389
  } else {
369
390
  // 不是文件
370
391
  logger.mark(`${logger.blue('被动消息:')} 视频大小: ${newFileSize.toFixed(1)}MB 正在通过${logger.yellow('e.reply')}回复...`)
371
392
  // 同上:异常才是失败(没拿到消息 ID 已经由兼容层抛出来了)
372
- await event.reply(segment.video(File) || videoUrl)
393
+ const sent: any = await event.reply(segment.video(File) || videoUrl)
394
+ reportSent(options, sent)
373
395
  sendStatus = true
374
396
  }
375
397
  }
@@ -85,7 +85,11 @@ import {
85
85
  buildBilibiliVideoDescRichText,
86
86
  getUsernameMetadata
87
87
  } from '@/platform/bilibili/dynamic-text'
88
- import { runInteractiveStory, renderInteractiveChart as renderChart } from '@/platform/bilibili/interactive-story'
88
+ import {
89
+ rememberStoryVideo,
90
+ renderInteractiveChart as renderChart,
91
+ runInteractiveStory
92
+ } from '@/platform/bilibili/interactive-story'
89
93
  import { BilibiliDataTypes } from '@/types'
90
94
 
91
95
  let img: ElementTypes[]
@@ -664,14 +668,13 @@ export class Bilibili extends Base {
664
668
  await downloadTask
665
669
  await this.sendPreparedVideo()
666
670
  /**
667
- * 互动视频:**群里不再发「选择按钮」了**(用户要求)。
668
- *
669
- * 剧情选择整个搬到播放页上(选项贴在视频上、点完显示加载进度);
670
- * 群里如果还同步问一遍,用户会被两处剧情各问一次。
671
- * 只有「视频直接发到群里、没走播放页」时,顺手补一张**剧情图**(图片,不是按钮)——
672
- * 用户至少能看到这张图里有几条分支。
671
+ * 互动视频的剧情怎么走,看这次的视频发到哪儿:
672
+ * · **走在线播放**(视频没发进群里,用户在看播放页)→ 选项在播放页上贴出来,
673
+ * 群里不再问一遍,免得两处各问一次(见 sendPreparedVideo 里的 story);
674
+ * · **直接发到群里**(没有播放页)→ 照旧在群里发**带按钮的选择面板**,
675
+ * 用户点一下播下一段,并撤回上一段视频(用户要求)。
673
676
  */
674
- if (this.interactive && !this.publishedStory) void this.sendInteractiveChartOnly()
677
+ if (this.interactive && !this.publishedStory) void this.startInteractiveStory()
675
678
  })
676
679
  }
677
680
  }
@@ -1935,35 +1938,6 @@ export class Bilibili extends Base {
1935
1938
  return this.preparedVideo !== null
1936
1939
  }
1937
1940
 
1938
- /**
1939
- * 互动视频发到群里时:只补一张**剧情图**,不问选项(用户要求:群里不要选择按钮)。
1940
- *
1941
- * 选项流程在播放页里(见 sendPreparedVideo 的 story);这里只把「有几条分支」画出来。
1942
- * 失败只记日志 —— 出不了图不影响视频已经发出去这件事。
1943
- */
1944
- private async sendInteractiveChartOnly (): Promise<void> {
1945
- const interactive = this.interactive
1946
- if (!interactive) return
1947
- /** 没勾「流程图」就什么都不做(配置说了算) */
1948
- if (!Config.bilibili.sendContent.some((item) => item === 'chart')) return
1949
- try {
1950
- const info = await fetchInteractiveInfo({ bvid: interactive.bvid, cid: interactive.cid, headers: this.headers })
1951
- if (!info) return
1952
- await renderChart({
1953
- e: this.e,
1954
- bvid: interactive.bvid,
1955
- graphVersion: info.graphVersion,
1956
- cid: interactive.cid,
1957
- title: this.workInfo?.title ?? '互动视频',
1958
- notice: info.notice,
1959
- headers: this.headers,
1960
- full: true
1961
- })
1962
- } catch (error: any) {
1963
- logger.debug('[互动视频] 群里补剧情图失败(不影响视频): ' + String(error?.message ?? error))
1964
- }
1965
- }
1966
-
1967
1941
  /**
1968
1942
  * 起一次互动剧情(后台长跑,不阻塞解析主流程)。
1969
1943
  *
@@ -2136,10 +2110,17 @@ export class Bilibili extends Base {
2136
2110
  }
2137
2111
  logger.warn('[在线播放] 播放会话登记失败,退回直接发送视频文件')
2138
2112
  }
2113
+ /**
2114
+ * 互动视频(发到群里的那种):把这条视频的消息 ID 记下来 ——
2115
+ * 用户点了下一个选项之后,这条要撤回,群里只留当前这一段。
2116
+ */
2117
+ const sentOptions = this.interactive
2118
+ ? { onSent: (messageId: string) => rememberStoryVideo(this.e, messageId) }
2119
+ : undefined
2139
2120
  if (totalBytes > Config.app.groupfilevalue) {
2140
- await uploadFile(this.e, { filepath, totalBytes, originTitle }, videoUrl ?? '', { useGroupFile: true })
2121
+ await uploadFile(this.e, { filepath, totalBytes, originTitle }, videoUrl ?? '', { useGroupFile: true, ...sentOptions })
2141
2122
  } else {
2142
- await uploadFile(this.e, { filepath, totalBytes, originTitle }, videoUrl ?? '')
2123
+ await uploadFile(this.e, { filepath, totalBytes, originTitle }, videoUrl ?? '', sentOptions)
2143
2124
  }
2144
2125
  return true
2145
2126
  }
@@ -41,6 +41,42 @@ export const RENDER_CHART_COMMAND = '渲染流程图'
41
41
  /** 每个频道最近一条「选项消息」,用于发下一条之前撤回 */
42
42
  const lastChoiceMessages = new Map<string, string>()
43
43
 
44
+ /**
45
+ * 每个频道最近一条「剧情视频」的消息 ID。
46
+ *
47
+ * 用户要求:点一下选项,**上一段视频也要撤回** —— 不然玩几段之后群里躺着一串视频。
48
+ * 视频是解析链路发的(不是这里发的),所以由那边把它发出去的消息 ID 记进来。
49
+ */
50
+ const lastStoryVideos = new Map<string, string>()
51
+
52
+ /** 记下刚发出去的剧情视频(由解析链路在上传成功时调用) */
53
+ export const rememberStoryVideo = (e: Message, messageId: string | undefined): void => {
54
+ if (!messageId) return
55
+ lastStoryVideos.set(sessionKeyOf(e), String(messageId))
56
+ }
57
+
58
+ /**
59
+ * 取出并清掉「上一条剧情视频」的消息 ID。
60
+ *
61
+ * 取出来就删:这条只该被撤回一次,撤回失败也不能反复去点。
62
+ */
63
+ const takeStoryVideo = (e: Message): string | undefined => {
64
+ const key = sessionKeyOf(e)
65
+ const messageId = lastStoryVideos.get(key)
66
+ if (messageId) lastStoryVideos.delete(key)
67
+ return messageId
68
+ }
69
+
70
+ /** 撤回某条消息(失败只记日志,绝不影响剧情) */
71
+ const recallMessage = async (e: Message, messageId: string | undefined): Promise<void> => {
72
+ if (!messageId) return
73
+ try {
74
+ await (e.bot as any)?.recallMsg?.(messageId, channelOf(e))
75
+ } catch (error: any) {
76
+ logger.debug('[互动视频] 撤回消息失败: ' + String(error?.message ?? error))
77
+ }
78
+ }
79
+
44
80
  const platformOf = (e: any): string =>
45
81
  String(e?.bot?.bot?.platform ?? e?.bot?.platform ?? e?.platform ?? '')
46
82
 
@@ -358,11 +394,19 @@ export const runInteractiveStory = async (options: StoryOptions): Promise<StoryR
358
394
  currentCid = choice.cid
359
395
 
360
396
  if (play) {
397
+ /**
398
+ * 用户要求:点一下选项,**上一段视频也要撤回**(群里只留当前这一段)。
399
+ *
400
+ * 顺序是「发新的 → 撤旧的」:先取走旧 ID(新的那条发出去时会被重新记上),
401
+ * 新的发完再撤旧的 —— 中间不会出现「一段视频都没有」的空档。
402
+ */
403
+ const previousVideo = takeStoryVideo(target)
361
404
  try {
362
405
  await play(currentCid, target)
363
406
  } catch (error: any) {
364
407
  logger.warn('[互动视频] 播放下一段失败(cid=' + currentCid + '): ' + String(error?.message ?? error))
365
408
  }
409
+ await recallMessage(target, previousVideo)
366
410
  }
367
411
  node = { ...next, cid: currentCid }
368
412
  }