koishi-plugin-kkk 3.7.1 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # 更新日志
2
2
 
3
+ ## 3.7.2
4
+
5
+ > 群里发的图片**统一改走 markdown** 了 —— 普通图片消息会被 QQ 压得发糊,markdown 图片不会;
6
+ > 顺手把互动视频那张**剧情图的字放大**了。
7
+
8
+ ### 图片不再被压糊
9
+
10
+ - 卡片、评论图、图集、推送里的图……以前都是当「普通图片」发出去的,QQ 会二次压缩,
11
+ 卡片上的小字糊成一团。现在**图片一律按 markdown 图片发**:先传到机器人自己的图床,
12
+ 再用带尺寸的图片写法发出去,字是清楚的。
13
+ - markdown 图片**必须写死尺寸**(`![#宽px #高px](地址)`)—— 不写尺寸的话手机端根本不显示这张图,
14
+ 所以每一张都会先把真实的宽高读出来(JPEG / PNG / GIF / WebP 都认)。
15
+ - **平台不一样,处理不一样**(客户端能力决定的,不是选择):
16
+ - QQ 官方机器人:走 markdown 图片;
17
+ - OneBot 系(NapCat、Lagrange、go-cqhttp、Chronocat 等):客户端不认 markdown,
18
+ 收到只会显示成一串网址、图片全丢,所以这条链路**照旧发普通图片**;
19
+ - QQ 频道(qqguild)同理,也不改写。
20
+ - 一条消息里**同时有视频 / 语音 / 文件**时不改写:那种消息会按媒体发出去,markdown 内容会被丢掉。
21
+ - 转发里的图、合并转发收集中的图也不改写,保持原样。
22
+ - 传图床失败(或者宿主没装 assets 服务)时**照旧发普通图片**,不会因为改写不了就把图弄丢。
23
+ - 同一张图反复发(推送封面、面板卡片)不会再反复上传。
24
+
25
+ ### 互动视频:剧情图的字大了
26
+
27
+ - 剧情图里每个选项 / 结局的**字号调大**了(大约 1/3),手机上看得清多了。
28
+ - 长文字不再按「14 个字」硬切,改成**按这一列还能放多少像素**来截断,
29
+ 字大了也不会压到下一列的圆圈上;最后一列右边本来空着,会多显示几个字。
30
+ - 「已选」「图例」「提示」这些说明文字也跟着放大了一点。
31
+
3
32
  ## 3.7.1
4
33
 
5
34
  > 修一个 3.7.0 改过头的地方:**视频直接发到群里的那种互动视频,照旧要在群里发带按钮的选择面板**;
@@ -1,10 +1,10 @@
1
1
  {
2
- "version": "3.7.1",
3
- "buildTime": "2026-09-25T18:27:55.201Z",
4
- "buildTimestamp": 1790360875202,
2
+ "version": "3.7.2",
3
+ "buildTime": "2026-09-26T02:01:03.950Z",
4
+ "buildTimestamp": 1790388063951,
5
5
  "name": "koishi-plugin-kkk",
6
6
  "description": "抖音 / B站 / 快手 / 小红书 视频解析与动态推送,带 QQ 交互面板与弹幕烧录(karin-plugin-kkk 的 Koishi 移植版)",
7
7
  "homepage": "https://github.com/maimai993/koishi-plugin-kkk#readme",
8
- "commitHash": "80c363bd36af99ed42afc894ead313a883b8b44a",
9
- "shortCommitHash": "80c363b"
8
+ "commitHash": "41e817b5ec90f1b56475866f553b33c15a0b4e94",
9
+ "shortCommitHash": "41e817b"
10
10
  }
@@ -0,0 +1,280 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.imagesToMarkdown = exports.clearMarkdownImageCache = exports.markdownImageOf = void 0;
7
+ /**
8
+ * 图片段 → markdown 图片(`![#宽px #高px](url)`)。
9
+ *
10
+ * 用户反馈两条,这里一起解决:
11
+ * 1. **「所有的图片发送都要走 md,不然太模糊了」** —— QQ 的普通图片消息(image 段 → 适配器按
12
+ * MEDIA 上传)会被客户端二次压缩,卡片上的小字糊成一团;markdown 里的图片不会被压,字是清楚的。
13
+ * 2. **「![#px大小#px大小]() 必须要 #px,不然手机不会显示」** —— md 图片必须写死尺寸,
14
+ * 不写尺寸手机端干脆不显示这张图。
15
+ *
16
+ * 所以这里在**发送出口**统一改写:compat/node-karin 的 reply / sendMsg / sendMaster 四条路径都过一遍,
17
+ * 业务代码照旧 e.reply(segment.image(...)),不用一处处改。
18
+ *
19
+ * 只在「认 markdown 的平台」上生效(官方 QQ:`qq`):
20
+ * - OneBot 系(NapCat / Lagrange / go-cqhttp / Chronocat…)收到 markdown 只显示成一串文字、
21
+ * 图片全丢(用户实测),所以那条链路继续发图片段;
22
+ * - QQ 频道(`qqguild`)的适配器没有 markdown 分支,md 元素会被当纯文本渲染 → 也排除。
23
+ *
24
+ * 另外三种情况**不动**(动了只会更糟):
25
+ * - 消息里还有视频 / 语音 / 文件:适配器遇到附件会把整条消息转成 MEDIA,markdown 内容会被丢掉;
26
+ * - 合并转发收集中的消息:转发节点里塞 markdown 客户端不认;
27
+ * - 上传拿不到公网地址(没装 assets 服务等)、或者**读不出图片尺寸**:保持原来的图片段。
28
+ * 读不出尺寸是可以退回普通图片的,但**绝不能发一张不带尺寸的 markdown 图片** ——
29
+ * 用户实测「必须要 #px,不然手机不会显示」,那种图上手机就是一片空白。
30
+ */
31
+ const node_crypto_1 = __importDefault(require("node:crypto"));
32
+ const node_fs_1 = __importDefault(require("node:fs"));
33
+ const node_url_1 = require("node:url");
34
+ const logger_1 = require("./logger");
35
+ const runtime_1 = require("./runtime");
36
+ const segment_1 = require("./segment");
37
+ /** OneBot 系:不渲染 markdown(见文件头) */
38
+ const ONEBOT_LIKE = /onebot|napcat|lagrange|go-?cqhttp|chronocat|mirai/i;
39
+ /**
40
+ * 会渲染 markdown 图片的平台。
41
+ *
42
+ * 只认 `qq` 这一个平台名 —— QQ 的 markdown 是**官方机器人**能力,
43
+ * `qqguild`(频道)走的是另一套编码器,md 元素在那里会被当成纯文本原样发出去。
44
+ */
45
+ const canUseMarkdownImage = (platform) => {
46
+ const name = String(platform || '').toLowerCase();
47
+ if (!name)
48
+ return false;
49
+ if (ONEBOT_LIKE.test(name))
50
+ return false;
51
+ if (name.startsWith('qqguild'))
52
+ return false;
53
+ return name === 'qq' || name.startsWith('qq-') || name.startsWith('qqbot');
54
+ };
55
+ /** 媒体段:md 和附件不能塞进同一条消息(会被适配器吃掉),所以要跳过整条改写 */
56
+ const ATTACHMENT_TYPES = new Set(['video', 'audio', 'record', 'file']);
57
+ const isImageElement = (element) => !!element && typeof element === 'object' && (element.type === 'img' || element.type === 'image');
58
+ const srcOf = (element) => {
59
+ const attrs = element?.attrs ?? {};
60
+ const src = attrs.src ?? attrs.url ?? element?.data?.file ?? element?.data?.url;
61
+ return typeof src === 'string' ? src : '';
62
+ };
63
+ /** 按二进制头认 mime(发给 assets 用;标错会让适配器按错格式处理) */
64
+ const mimeOfBuffer = (buffer) => {
65
+ if (buffer.length >= 8 && buffer[0] === 0x89 && buffer.toString('latin1', 1, 4) === 'PNG')
66
+ return 'image/png';
67
+ if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8)
68
+ return 'image/jpeg';
69
+ if (buffer.length >= 6 && buffer.toString('latin1', 0, 3) === 'GIF')
70
+ return 'image/gif';
71
+ if (buffer.length >= 12 && buffer.toString('latin1', 0, 4) === 'RIFF' && buffer.toString('latin1', 8, 12) === 'WEBP')
72
+ return 'image/webp';
73
+ return 'image/jpeg';
74
+ };
75
+ /**
76
+ * 读出图片的**真实像素尺寸** —— md 里的 `#宽px #高px` 就靠它。
77
+ *
78
+ * 不引第三方库:卡片是 JPEG、图集是 JPEG、二维码是 PNG、实况图封面是 WebP,四种头都自己认,
79
+ * 免得又出现「取不到尺寸 → 正方形拉伸」或「没写尺寸 → 手机不显示」。
80
+ */
81
+ const readImageSize = (buffer) => {
82
+ // PNG:IHDR 就在固定偏移
83
+ if (buffer.length >= 24 && buffer[0] === 0x89 && buffer.toString('latin1', 1, 4) === 'PNG') {
84
+ return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
85
+ }
86
+ // GIF:逻辑屏幕描述符,小端
87
+ if (buffer.length >= 10 && buffer.toString('latin1', 0, 3) === 'GIF') {
88
+ return { width: buffer.readUInt16LE(6), height: buffer.readUInt16LE(8) };
89
+ }
90
+ // JPEG:扫到 SOF 段(SOF0..SOF15,跳过 DHT/DAC 这些非 SOF 标记)
91
+ if (buffer.length > 4 && buffer[0] === 0xff && buffer[1] === 0xd8) {
92
+ let offset = 2;
93
+ while (offset + 9 < buffer.length) {
94
+ if (buffer[offset] !== 0xff) {
95
+ offset++;
96
+ continue;
97
+ }
98
+ const marker = buffer[offset + 1];
99
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
100
+ return { height: buffer.readUInt16BE(offset + 5), width: buffer.readUInt16BE(offset + 7) };
101
+ }
102
+ const length = buffer.readUInt16BE(offset + 2);
103
+ if (length <= 0)
104
+ break;
105
+ offset += 2 + length;
106
+ }
107
+ }
108
+ // WebP:VP8X(扩展)/ VP8L(无损)/ VP8(有损)三种头的写法都不一样
109
+ if (buffer.length >= 30 && buffer.toString('latin1', 0, 4) === 'RIFF' && buffer.toString('latin1', 8, 12) === 'WEBP') {
110
+ const format = buffer.toString('latin1', 12, 16);
111
+ if (format === 'VP8X') {
112
+ return { width: 1 + buffer.readUIntLE(24, 3), height: 1 + buffer.readUIntLE(27, 3) };
113
+ }
114
+ if (format === 'VP8L') {
115
+ const bits = buffer.readUInt32LE(21);
116
+ return { width: 1 + (bits & 0x3fff), height: 1 + ((bits >> 14) & 0x3fff) };
117
+ }
118
+ if (format === 'VP8 ') {
119
+ return { width: buffer.readUInt16LE(26) & 0x3fff, height: buffer.readUInt16LE(28) & 0x3fff };
120
+ }
121
+ }
122
+ return { width: 0, height: 0 };
123
+ };
124
+ /** 把各种写法读成 Buffer:data URI / base64:// / file:// / 本地路径 / http(s) */
125
+ const loadImageBuffer = async (src) => {
126
+ try {
127
+ if (src.startsWith('base64://'))
128
+ return Buffer.from(src.slice('base64://'.length), 'base64');
129
+ if (src.startsWith('data:')) {
130
+ const comma = src.indexOf(',');
131
+ if (comma < 0)
132
+ return null;
133
+ return Buffer.from(src.slice(comma + 1), 'base64');
134
+ }
135
+ const localPath = src.startsWith('file://') ? (0, node_url_1.fileURLToPath)(src) : src;
136
+ if (!/^https?:\/\//i.test(src)) {
137
+ if (node_fs_1.default.existsSync(localPath))
138
+ return node_fs_1.default.readFileSync(localPath);
139
+ return null;
140
+ }
141
+ const response = await fetch(src);
142
+ if (!response.ok) {
143
+ logger_1.logger.mark('[图片md] 下载失败 HTTP ' + response.status + ': ' + src.slice(0, 80));
144
+ return null;
145
+ }
146
+ return Buffer.from(await response.arrayBuffer());
147
+ }
148
+ catch (error) {
149
+ logger_1.logger.mark('[图片md] 读取图片失败: ' + String(error?.message ?? error).slice(0, 120));
150
+ return null;
151
+ }
152
+ };
153
+ /**
154
+ * 上传到宿主的 assets,拿到 QQ 能直接取的 https 地址。
155
+ *
156
+ * md 里的图片地址**必须是公网 http(s)**:适配器只对 data: 图片做特殊处理
157
+ * (见 qq-crack 的 renderMarkdownDataImages —— data 图片会被它转回 MEDIA 上传,等于白改),
158
+ * 相对路径/本地路径手机端也取不到。
159
+ */
160
+ let warnedNoAssets = false;
161
+ const uploadImage = async (buffer) => {
162
+ const assets = (0, runtime_1.tryGetRuntime)()?.ctx?.assets;
163
+ if (!assets?.upload) {
164
+ /** 没装 assets 服务就整条链路都用不了,提示一次就够,别每张图刷一遍日志 */
165
+ if (!warnedNoAssets) {
166
+ warnedNoAssets = true;
167
+ logger_1.logger.mark('[图片md] 宿主没有 assets 服务(拿不到公网图片地址),图片继续按普通图片段发送');
168
+ }
169
+ return null;
170
+ }
171
+ const mime = mimeOfBuffer(buffer);
172
+ const ext = mime === 'image/png' ? '.png' : mime === 'image/gif' ? '.gif' : mime === 'image/webp' ? '.webp' : '.jpg';
173
+ try {
174
+ const uploaded = await assets.upload('data:' + mime + ';base64,' + buffer.toString('base64'), 'kkk-md' + ext);
175
+ const url = typeof uploaded === 'string' ? uploaded : uploaded?.url;
176
+ return url && /^https?:\/\//i.test(String(url)) ? String(url) : null;
177
+ }
178
+ catch (error) {
179
+ logger_1.logger.mark('[图片md] 上传失败: ' + String(error?.message ?? error).slice(0, 120));
180
+ return null;
181
+ }
182
+ };
183
+ /**
184
+ * 同一张图反复发(推送里的封面、面板卡片…)不用反复上传:
185
+ * 按图片内容摘要缓存结果,顺带省掉重复的下载与解码。
186
+ */
187
+ const imageCache = new Map();
188
+ const IMAGE_CACHE_MAX = 200;
189
+ /** 图片段 → md 图片字符串;拿不到尺寸/地址就返回 null(调用方保持原样,别把图弄丢) */
190
+ const markdownImageOf = async (src) => {
191
+ if (!src)
192
+ return null;
193
+ const key = node_crypto_1.default.createHash('md5').update(src).digest('hex');
194
+ const cached = imageCache.get(key);
195
+ if (cached)
196
+ return cached;
197
+ const buffer = await loadImageBuffer(src);
198
+ let result = null;
199
+ if (buffer && buffer.length) {
200
+ const { width, height } = readImageSize(buffer);
201
+ /**
202
+ * **读不出尺寸就不换成 markdown**(退回普通图片段)。
203
+ *
204
+ * 用户实测:「必须要 #px,不然手机不会显示」—— 不带尺寸的 md 图片在手机端干脆是空白,
205
+ * 比糊更糟。所以这里宁可发一张(会被压糊但看得见的)普通图片,
206
+ * 也不发一张手机上什么都不显示的 markdown 图片。
207
+ */
208
+ if (width > 0 && height > 0) {
209
+ const url = await uploadImage(buffer);
210
+ if (url)
211
+ result = '![#' + width + 'px #' + height + 'px](' + url + ')';
212
+ }
213
+ }
214
+ /**
215
+ * **只缓存成功的结果**:网络 / 图床抖动导致的失败要是也缓存下来,
216
+ * 这张图之后就一直按普通图片发(糊),得等重启才能恢复。
217
+ */
218
+ if (result) {
219
+ if (imageCache.size >= IMAGE_CACHE_MAX)
220
+ imageCache.delete(imageCache.keys().next().value);
221
+ imageCache.set(key, result);
222
+ }
223
+ else {
224
+ logger_1.logger.debug('[图片md] 这张图这次没转成 markdown,按普通图片发送: ' + src.slice(0, 60));
225
+ }
226
+ return result;
227
+ };
228
+ exports.markdownImageOf = markdownImageOf;
229
+ /** 清空缓存(测试用) */
230
+ const clearMarkdownImageCache = () => { imageCache.clear(); };
231
+ exports.clearMarkdownImageCache = clearMarkdownImageCache;
232
+ /**
233
+ * 把一条消息里的图片段改写成 markdown 图片(其它段原样保留、顺序不变)。
234
+ *
235
+ * 连续的图片合成**一个** markdown 元素(换行分隔)—— 和官方 QQ 的渲染习惯一致:
236
+ * 连续图片紧贴显示,视觉上仍是一整张卡片,而不是一张一张孤立的图。
237
+ *
238
+ * @param elements 已归一化的消息元素数组
239
+ * @param platform 适配器平台名(kompat 层从 bot.platform / session.platform 取)
240
+ * @returns 改写后的数组;不该改或改不动时**原样返回**,绝不让消息发不出去
241
+ */
242
+ const imagesToMarkdown = async (elements, platform) => {
243
+ const list = Array.isArray(elements) ? elements : [];
244
+ if (!list.length)
245
+ return list;
246
+ if (!canUseMarkdownImage(platform))
247
+ return list;
248
+ if (!list.some(isImageElement))
249
+ return list;
250
+ if (list.some((element) => ATTACHMENT_TYPES.has(String(element?.type ?? ''))))
251
+ return list;
252
+ const out = [];
253
+ /** 攒着的连续图片(遇到非图片段就冲出去) */
254
+ let run = [];
255
+ const flushRun = () => {
256
+ // 有图转不动(上传失败等)时 run 里会是空串占位,这里只冲有内容的
257
+ if (run.length)
258
+ out.push(segment_1.segment.markdown(run.join(String.fromCharCode(10))));
259
+ run = [];
260
+ };
261
+ for (const element of list) {
262
+ if (!isImageElement(element)) {
263
+ flushRun();
264
+ out.push(element);
265
+ continue;
266
+ }
267
+ const markdown = await (0, exports.markdownImageOf)(srcOf(element));
268
+ if (markdown) {
269
+ run.push(markdown);
270
+ }
271
+ else {
272
+ // 转不了就把它自己按图片段发出去,别丢
273
+ flushRun();
274
+ out.push(element);
275
+ }
276
+ }
277
+ flushRun();
278
+ return out;
279
+ };
280
+ exports.imagesToMarkdown = imagesToMarkdown;
@@ -34,6 +34,7 @@ const adapter_info_1 = require("./adapter-info");
34
34
  const logger_1 = require("./logger");
35
35
  Object.defineProperty(exports, "logger", { enumerable: true, get: function () { return logger_1.logger; } });
36
36
  const forward_collect_1 = require("./forward-collect");
37
+ const imageMarkdown_1 = require("./imageMarkdown");
37
38
  const sendError_1 = require("./sendError");
38
39
  const runtime_1 = require("./runtime");
39
40
  const segment_1 = require("./segment");
@@ -240,14 +241,16 @@ class KkkBot {
240
241
  logger_1.logger.debug('当前适配器(' + this.bot.platform + ')不支持合并转发,改为直接发送内容');
241
242
  }
242
243
  // 退化路径:整条发一次;失败再逐个元素发,尽量把内容送出去
244
+ /** 退化发送 = 直接发消息,所以图片同样要改走 markdown(见 compat/imageMarkdown) */
245
+ const fallback = await (0, imageMarkdown_1.imagesToMarkdown)(payload.elements, platformOfBot(this.bot));
243
246
  try {
244
- const ids = await this.bot.sendMessage(channelId, payload.elements);
247
+ const ids = await this.bot.sendMessage(channelId, fallback);
245
248
  return { messageId: ids[ids.length - 1] ?? '' };
246
249
  }
247
250
  catch (error) {
248
251
  logger_1.logger.warn('整条发送失败,改为逐个元素发送: ' + String(error?.message ?? error));
249
252
  let lastId = '';
250
- for (const item of payload.elements) {
253
+ for (const item of fallback) {
251
254
  const ids = await this.bot.sendMessage(channelId, [item]);
252
255
  lastId = ids[ids.length - 1] ?? lastId;
253
256
  }
@@ -346,11 +349,14 @@ class KkkBot {
346
349
  }
347
350
  /** 发送消息(karin 的 bot.sendMsg) */
348
351
  async sendMsg(contact, content, _options) {
352
+ const elements = normalizeContent(content);
349
353
  /** 解析结果合并转发:正在收集就攒起来(见 compat/forward-collect) */
350
- if ((0, forward_collect_1.collectForward)(peerOf(contact), content))
354
+ if ((0, forward_collect_1.collectForward)(peerOf(contact), elements))
351
355
  return { messageId: forward_collect_1.COLLECTED_MESSAGE_ID };
352
356
  const channelId = typeof contact === 'string' ? contact : contact.peer;
353
- const ids = await this.bot.sendMessage(channelId, normalizeContent(content));
357
+ /** 图片统一改走 markdown(见 compat/imageMarkdown) */
358
+ const outgoing = await (0, imageMarkdown_1.imagesToMarkdown)(elements, platformOfBot(this.bot));
359
+ const ids = await this.bot.sendMessage(channelId, outgoing);
354
360
  // 同 reply/uploadFile:**没拿到消息 ID 就是没发出去**,别当成功返回
355
361
  const id = ids?.[ids.length - 1] ?? '';
356
362
  if (!id) {
@@ -471,13 +477,21 @@ class Message {
471
477
  * 这时自动改用**主动消息**(不带引用,直接往频道里发),失败才把原错误抛出去。
472
478
  */
473
479
  async reply(content, _options) {
474
- const elements = normalizeContent(content);
480
+ const raw = normalizeContent(content);
475
481
  /**
476
482
  * 解析结果合并转发:正在收集就攒起来,等解析结束发一条转发(见 compat/forward-collect)。
477
483
  * 回一个假的消息 ID:调用方普遍只看「有没有拿到 ID」(例如 uploadFile 判断发送成没成功)。
478
484
  */
479
- if ((0, forward_collect_1.collectForward)(this.contact?.peer ?? '', elements))
485
+ if ((0, forward_collect_1.collectForward)(this.contact?.peer ?? '', raw))
480
486
  return { messageId: forward_collect_1.COLLECTED_MESSAGE_ID };
487
+ /**
488
+ * **图片统一改走 markdown**(上传拿公网地址 + 写死 `#宽px #高px`),见 compat/imageMarkdown。
489
+ *
490
+ * 放在这里是因为它是**所有回复的唯一出口** —— 业务代码一律 `e.reply(...)`,
491
+ * 不用一处处改业务代码。转换不成功会退回原来的图片段(绝不把图弄丢)。
492
+ * 上面的合并转发分支已经返回了,所以转发节点里仍然是普通图片段。
493
+ */
494
+ const elements = await (0, imageMarkdown_1.imagesToMarkdown)(raw, platformOfMessage(this));
481
495
  /**
482
496
  * 没拿到消息 ID 就是**没发出去**(对齐 qq-chat 的判法)。
483
497
  *
@@ -570,6 +584,19 @@ function normalizeContent(content) {
570
584
  function peerOf(contact) {
571
585
  return typeof contact === 'string' ? contact : String(contact?.peer ?? '');
572
586
  }
587
+ /**
588
+ * 适配器平台名。
589
+ *
590
+ * 发送出口要用它判断「这个平台认不认 markdown 图片」(见 compat/imageMarkdown):
591
+ * KkkBot 包装上直接转发真实 Bot 的 platform,传 KkkBot 或裸 Bot 都能取到。
592
+ */
593
+ function platformOfBot(bot) {
594
+ return String(bot?.platform ?? bot?.bot?.platform ?? '');
595
+ }
596
+ /** 同上,从消息事件取(会话上就带 platform,拿不到再问 bot) */
597
+ function platformOfMessage(message) {
598
+ return String(message.session?.platform ?? platformOfBot(message.bot));
599
+ }
573
600
  /**
574
601
  * 合并转发的载荷。
575
602
  *
@@ -707,18 +734,22 @@ async function sendMsg(selfId, contact, content, _options) {
707
734
  + '),这条消息发不出去。等它重新上线后下次推送会正常发出;如果是长期不在线,检查一下适配器连接');
708
735
  }
709
736
  const channelId = peerOf(contact);
737
+ const elements = normalizeContent(content);
710
738
  /** 解析结果合并转发:这条也走漏斗(karin.sendMsg 是业务代码另一条常用出口) */
711
- if ((0, forward_collect_1.collectForward)(channelId, normalizeContent(content))) {
739
+ if ((0, forward_collect_1.collectForward)(channelId, elements)) {
712
740
  return { messageId: forward_collect_1.COLLECTED_MESSAGE_ID, rawData: [] };
713
741
  }
714
- const ids = await bot.bot.sendMessage(channelId, normalizeContent(content));
742
+ /** 图片统一改走 markdown(见 compat/imageMarkdown) */
743
+ const outgoing = await (0, imageMarkdown_1.imagesToMarkdown)(elements, platformOfBot(bot.bot));
744
+ const ids = await bot.bot.sendMessage(channelId, outgoing);
715
745
  return { messageId: ids[ids.length - 1] ?? '', rawData: ids };
716
746
  }
717
747
  async function sendMaster(botId, master, content, _options) {
718
748
  const bot = resolveBot(botId);
719
749
  if (!bot)
720
750
  throw new Error('[kkk] 没有可用的机器人实例,无法发送消息');
721
- const elements = normalizeContent(content);
751
+ // 图片统一改走 markdown(见 compat/imageMarkdown):私聊和群里一样,md 图片才不会被压糊
752
+ const elements = await (0, imageMarkdown_1.imagesToMarkdown)(normalizeContent(content), platformOfBot(bot.bot));
722
753
  const target = bot.bot;
723
754
  // Satori 的 Bot 有 sendPrivateMessage;个别适配器没有,退化成私聊频道 id
724
755
  const ids = typeof target.sendPrivateMessage === 'function'
@@ -19,10 +19,98 @@ const DefaultLayout_1 = require("../../../components/DefaultLayout");
19
19
  const BILI_BLUE = '#00aeec';
20
20
  /** 顶层分支配色,和思维导图常见做法一致:一条主枝一个颜色 */
21
21
  const BRANCH_COLORS = ['#ff7a45', '#3fbf6f', '#22a6b3', '#a259ff', '#f0b429', '#5a8dee', '#e8608d', '#7f8c8d'];
22
+ /**
23
+ * 版面尺寸。
24
+ *
25
+ * **字要大**(用户要求):这张卡片是 1440px 宽的画布,到了手机聊天框里会被等比缩到
26
+ * 几百像素宽,图上文字的实际大小 = 字号 / 画布总宽 —— 所以「把字弄大」只能靠
27
+ * **字号占宽度的比例变大**:
28
+ * - 列宽不再跟着字号涨(涨了等于没变),只把字号提上去;
29
+ * - 每列能显示几个字 = 列宽 / 字号,字号大了就得少显示几个字,
30
+ * 标签改成**按像素宽度裁剪**(中文按 1 个字宽算),不让它压到下一列上去。
31
+ */
22
32
  const COL_WIDTH = 260;
23
- const ROW_HEIGHT = 62;
33
+ const ROW_HEIGHT = 88;
24
34
  const PAD_LEFT = 8;
25
- const PAD_TOP = 20;
35
+ const PAD_TOP = 24;
36
+ /** 节点文字的字号(选项 / 剧情节点) */
37
+ const CHOICE_FONT = 33;
38
+ const NODE_FONT = 34;
39
+ /** 一列文字最多能用到哪里:到下一列的圆圈之前就为止(别压到人家的圆上) */
40
+ const LABEL_WIDTH = COL_WIDTH - 45;
41
+ /**
42
+ * 一个字符大概占多少个字号宽:中文 / 全角算 1 个,空格 0.3,其余 0.5。
43
+ * (不用真的去量字体,够用就行 —— 目的是别让文字压到下一列的圆圈上。)
44
+ */
45
+ const charWidth = (char) => {
46
+ if (/[\u2e80-\ufffd\ufe30-\ufe4f]/.test(char))
47
+ return 1;
48
+ if (char === ' ')
49
+ return 0.3;
50
+ return 0.5;
51
+ };
52
+ /** 一段文字排出来大概多宽(像素) */
53
+ const lineWidth = (text, fontSize) => {
54
+ let total = 0;
55
+ for (const char of text)
56
+ total += charWidth(char) * fontSize;
57
+ return total;
58
+ };
59
+ /**
60
+ * 把标签排成**最多两行**,两行都装不下才截断加省略号。
61
+ *
62
+ * 以前是按「14 个字」裁的:中文一个字差不多一个字号宽,14 个字在 34px 字号下要 470 多个像素,
63
+ * 而列宽只有 260px —— 标签会直接压到下一列的圆圈上,字挤在一起更看不清。
64
+ *
65
+ * 为什么要折行而不是直接截断:字号调大以后一列只能放下六七个字,
66
+ * 直接砍会把「当前 · 第二题」这种关键信息切掉;折成两行既保住了字大,也保住了内容
67
+ * (行高已经在 ROW_HEIGHT 里留出来了)。
68
+ *
69
+ * @param label 原始文字
70
+ * @param fontSize 字号(越大能放的字越少)
71
+ * @param extra 额外可用宽度(最后一列右边没有东西,用它多占一点)
72
+ * @param suffix 后缀(「(默认)」这种)——**整块跟着最后一行,绝不从中间断开**
73
+ */
74
+ const wrapLabel = (label, fontSize, extra = 0, suffix = '') => {
75
+ const budget = LABEL_WIDTH + extra;
76
+ const lines = [];
77
+ let current = '';
78
+ let used = 0;
79
+ for (const char of label) {
80
+ const cost = charWidth(char) * fontSize;
81
+ if (current && used + cost > budget) {
82
+ lines.push(current);
83
+ current = '';
84
+ used = 0;
85
+ // 两行都满了:把第二行截断加省略号
86
+ if (lines.length >= 2) {
87
+ lines[1] = lines[1] + '…';
88
+ break;
89
+ }
90
+ }
91
+ current += char;
92
+ used += cost;
93
+ }
94
+ if (current) {
95
+ if (lines.length >= 2)
96
+ lines[1] = lines[1] + '…';
97
+ else
98
+ lines.push(current);
99
+ }
100
+ if (!lines.length)
101
+ lines.push('');
102
+ /** 后缀单独占一行也行(它很短),实在没地方了就跟在最后一行后面 */
103
+ if (suffix) {
104
+ const last = lines[lines.length - 1];
105
+ if (lineWidth(last + suffix, fontSize) <= budget)
106
+ lines[lines.length - 1] = last + suffix;
107
+ else if (lines.length < 2)
108
+ lines.push(suffix);
109
+ else
110
+ lines[lines.length - 1] = last + suffix;
111
+ }
112
+ return lines;
113
+ };
26
114
  /** 把剧情图摊平成「一行一项」的列表,并算好每个叶子占用的行号 */
27
115
  const flatten = (root, path, rootLabel) => {
28
116
  const items = [];
@@ -116,7 +204,7 @@ exports.BilibiliInteractive = react_1.default.memo((props) => {
116
204
  byId.set(item.id, item);
117
205
  const rowY = (row) => PAD_TOP + row * ROW_HEIGHT + ROW_HEIGHT / 2;
118
206
  const colX = (item) => PAD_LEFT + item.depth * COL_WIDTH;
119
- return ((0, jsx_runtime_1.jsx)(DefaultLayout_1.DefaultLayout, { ...props, children: (0, jsx_runtime_1.jsxs)("div", { style: { position: 'relative', zIndex: 10, padding: '64px 56px 48px' }, children: [(0, jsx_runtime_1.jsxs)("div", { style: { display: 'flex', alignItems: 'center', gap: 24 }, children: [(0, jsx_runtime_1.jsx)("span", { style: { borderRadius: 999, padding: '12px 28px', fontSize: 26, fontWeight: 900, letterSpacing: '0.18em', background: 'rgba(0,174,236,0.14)', color: BILI_BLUE }, children: "\u4E92\u52A8\u89C6\u9891" }), (0, jsx_runtime_1.jsxs)("span", { style: { fontSize: 26, fontWeight: 700, opacity: 0.42 }, children: ["\u7B2C ", data.step, " \u6BB5 \u00B7 \u5168\u90E8\u5267\u60C5\u6D41\u7A0B"] })] }), (0, jsx_runtime_1.jsx)("h1", { style: { margin: '28px 0 0', fontSize: 48, fontWeight: 900, lineHeight: 1.3, wordBreak: 'break-word' }, children: data.title }), path.length > 0 && ((0, jsx_runtime_1.jsxs)("div", { style: { marginTop: 18, fontSize: 27, fontWeight: 600, opacity: 0.5, wordBreak: 'break-word' }, children: ["\u5DF2\u9009\uFF1A", path.join(' → ')] })), flat && ((0, jsx_runtime_1.jsxs)("svg", { viewBox: '0 0 ' + width + ' ' + height, width: '100%', style: { marginTop: 26, display: 'block', overflow: 'visible' }, role: 'img', children: [flat.items.map((item) => {
207
+ return ((0, jsx_runtime_1.jsx)(DefaultLayout_1.DefaultLayout, { ...props, children: (0, jsx_runtime_1.jsxs)("div", { style: { position: 'relative', zIndex: 10, padding: '64px 56px 48px' }, children: [(0, jsx_runtime_1.jsxs)("div", { style: { display: 'flex', alignItems: 'center', gap: 24 }, children: [(0, jsx_runtime_1.jsx)("span", { style: { borderRadius: 999, padding: '12px 28px', fontSize: 26, fontWeight: 900, letterSpacing: '0.18em', background: 'rgba(0,174,236,0.14)', color: BILI_BLUE }, children: "\u4E92\u52A8\u89C6\u9891" }), (0, jsx_runtime_1.jsxs)("span", { style: { fontSize: 26, fontWeight: 700, opacity: 0.42 }, children: ["\u7B2C ", data.step, " \u6BB5 \u00B7 \u5168\u90E8\u5267\u60C5\u6D41\u7A0B"] })] }), (0, jsx_runtime_1.jsx)("h1", { style: { margin: '28px 0 0', fontSize: 48, fontWeight: 900, lineHeight: 1.3, wordBreak: 'break-word' }, children: data.title }), path.length > 0 && ((0, jsx_runtime_1.jsxs)("div", { style: { marginTop: 18, fontSize: 32, fontWeight: 600, opacity: 0.5, wordBreak: 'break-word' }, children: ["\u5DF2\u9009\uFF1A", path.join(' → ')] })), flat && ((0, jsx_runtime_1.jsxs)("svg", { viewBox: '0 0 ' + width + ' ' + height, width: '100%', style: { marginTop: 26, display: 'block', overflow: 'visible' }, role: 'img', children: [flat.items.map((item) => {
120
208
  if (!item.parent)
121
209
  return null;
122
210
  const parent = byId.get(item.parent);
@@ -131,7 +219,13 @@ exports.BilibiliInteractive = react_1.default.memo((props) => {
131
219
  const x = colX(item);
132
220
  const y = rowY(item.row);
133
221
  const isChoice = item.kind === 'choice';
134
- return ((0, jsx_runtime_1.jsxs)("g", { children: [(0, jsx_runtime_1.jsx)("circle", { cx: x, cy: y, r: isChoice ? 9 : 13, fill: item.walked || item.kind === 'root' ? item.color : '#ffffff', stroke: item.color, strokeWidth: 4 }), (0, jsx_runtime_1.jsxs)("text", { x: x + (isChoice ? 22 : 26), y: y + 9, fontSize: isChoice ? 27 : 29, fontWeight: item.walked || item.kind === 'root' ? 900 : 600, fill: item.walked ? item.color : 'currentColor', opacity: item.walked || item.kind === 'root' ? 1 : 0.82, children: [item.label.length > 14 ? item.label.slice(0, 14) + '…' : item.label, item.isDefault ? '(默认)' : ''] })] }, 'node-' + item.id));
135
- })] })), !flat && (data.choices ?? []).map((choice, index) => ((0, jsx_runtime_1.jsxs)("div", { style: { marginTop: index === 0 ? 30 : 18, fontSize: 36, fontWeight: 800 }, children: [choice.label, " ", choice.text, choice.isDefault ? '(默认)' : ''] }, choice.label + index))), (data.truncated || graph?.truncated) && ((0, jsx_runtime_1.jsx)("div", { style: { marginTop: 26, fontSize: 25, fontWeight: 600, opacity: 0.55 }, children: "\u5267\u60C5\u592A\u957F\uFF0C\u56FE\u4E0A\u53EA\u753B\u4E86\u524D\u534A\u90E8\u5206\u5206\u652F" })), (0, jsx_runtime_1.jsxs)("div", { style: { marginTop: 22, display: 'flex', alignItems: 'center', gap: 14, fontSize: 25, fontWeight: 600, opacity: 0.52 }, children: [(0, jsx_runtime_1.jsx)("span", { style: { display: 'inline-block', width: 26, height: 5, borderRadius: 999, background: BILI_BLUE } }), "\u9AD8\u4EAE\u7684\u662F\u4F60\u5DF2\u7ECF\u8D70\u8FC7\u7684\u8DEF"] }), data.notice && ((0, jsx_runtime_1.jsx)("div", { style: { marginTop: 18, borderRadius: 20, padding: '16px 28px', fontSize: 25, fontWeight: 600, opacity: 0.62, background: 'rgba(127,127,127,0.12)' }, children: data.notice }))] }) }));
222
+ const font = isChoice ? CHOICE_FONT : NODE_FONT;
223
+ const textX = x + (isChoice ? 22 : 26);
224
+ /** 「(默认)」也算进这一列的可视宽度里,免得它把第二行挤出去 */
225
+ const lines = wrapLabel(item.label, font, item.depth >= depth ? 56 : 0, item.isDefault ? '(默认)' : '');
226
+ /** 一行时基线和以前一样;两行时整块往上挪一点,让两行都贴着圆圈居中 */
227
+ const baseline = lines.length > 1 ? y - font * 0.15 : y + font * 0.35;
228
+ return ((0, jsx_runtime_1.jsxs)("g", { children: [(0, jsx_runtime_1.jsx)("circle", { cx: x, cy: y, r: isChoice ? 9 : 13, fill: item.walked || item.kind === 'root' ? item.color : '#ffffff', stroke: item.color, strokeWidth: 4 }), (0, jsx_runtime_1.jsx)("text", { x: textX, y: baseline, fontSize: font, fontWeight: item.walked || item.kind === 'root' ? 900 : 600, fill: item.walked ? item.color : 'currentColor', opacity: item.walked || item.kind === 'root' ? 1 : 0.82, children: lines.map((line, index) => ((0, jsx_runtime_1.jsx)("tspan", { x: textX, dy: index === 0 ? 0 : Math.round(font * 1.05), children: line }, 'line-' + index))) })] }, 'node-' + item.id));
229
+ })] })), !flat && (data.choices ?? []).map((choice, index) => ((0, jsx_runtime_1.jsxs)("div", { style: { marginTop: index === 0 ? 30 : 18, fontSize: 36, fontWeight: 800 }, children: [choice.label, " ", choice.text, choice.isDefault ? '(默认)' : ''] }, choice.label + index))), (data.truncated || graph?.truncated) && ((0, jsx_runtime_1.jsx)("div", { style: { marginTop: 26, fontSize: 30, fontWeight: 600, opacity: 0.55 }, children: "\u5267\u60C5\u592A\u957F\uFF0C\u56FE\u4E0A\u53EA\u753B\u4E86\u524D\u534A\u90E8\u5206\u5206\u652F" })), (0, jsx_runtime_1.jsxs)("div", { style: { marginTop: 22, display: 'flex', alignItems: 'center', gap: 14, fontSize: 30, fontWeight: 600, opacity: 0.52 }, children: [(0, jsx_runtime_1.jsx)("span", { style: { display: 'inline-block', width: 30, height: 6, borderRadius: 999, background: BILI_BLUE } }), "\u9AD8\u4EAE\u7684\u662F\u4F60\u5DF2\u7ECF\u8D70\u8FC7\u7684\u8DEF"] }), data.notice && ((0, jsx_runtime_1.jsx)("div", { style: { marginTop: 18, borderRadius: 20, padding: '16px 28px', fontSize: 30, fontWeight: 600, opacity: 0.62, background: 'rgba(127,127,127,0.12)' }, children: data.notice }))] }) }));
136
230
  });
137
231
  exports.BilibiliInteractive.displayName = 'BilibiliInteractive';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koishi-plugin-kkk",
3
- "version": "3.7.1",
3
+ "version": "3.7.2",
4
4
  "description": "抖音 / B站 / 快手 / 小红书 视频解析与动态推送,带 QQ 交互面板与弹幕烧录(karin-plugin-kkk 的 Koishi 移植版)",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
@@ -0,0 +1,33 @@
1
+ /**
2
+ * 临时探针:把剧情图用一个**很长的题目**渲染一遍,确认标签会折成两行、内容不丢。
3
+ */
4
+ const path = require('node:path')
5
+ const React = require('react')
6
+ const { renderToStaticMarkup } = require('react-dom/server')
7
+ const pluginRoot = path.resolve(__dirname, '..')
8
+ const runtime = require(path.join(pluginRoot, 'lib/compat/runtime.js'))
9
+ const noop = () => {}
10
+ runtime.bindRuntime({ ctx: { get: () => undefined, logger: () => ({ info: noop, warn: noop, error: noop, debug: noop, mark: noop }), config: {}, pluginRoot, dataRoot: require('node:os').tmpdir() } })
11
+ const template = require(path.join(pluginRoot, 'lib/ktr/template/bilibili/interactive/index.js'))
12
+ const Root = require(path.join(pluginRoot, 'lib/karin/root.js')).Root
13
+ const data = {
14
+ title: '测试:很长的题目',
15
+ step: 1,
16
+ path: ['向左走'],
17
+ graph: {
18
+ question: '开场',
19
+ choices: [
20
+ { label: 'A', text: '向左走', isDefault: true, children: [{ question: '你要不要现在就跟着她一起上楼去看看那个房间', isLeaf: false, choices: [] }] },
21
+ { label: 'B', text: '向右挖', children: [{ question: '结局二', isLeaf: true, choices: [] }] }
22
+ ]
23
+ }
24
+ }
25
+ const ctx = { theme: 'light', scale: 1, version: { plugin: 'koishi-plugin', pluginName: 'kkk', pluginVersion: Root.pluginVersion, releaseType: 'Stable', poweredBy: 'Koishi', frameworkVersion: Root.karinVersion } }
26
+ const def = template.default ?? template
27
+ const html = renderToStaticMarkup(React.createElement(def.component, { data, ctx }))
28
+ const tspans = html.match(/<tspan[^>]*>[^<]*<\/tspan>/g) || []
29
+ console.log('tspan 数量:', tspans.length)
30
+ console.log('折行的标签:')
31
+ for (const item of tspans.slice(0, 12)) console.log(' ', item.replace(/<[^>]+>/g, ' | '))
32
+ console.log('(默认)完整出现:', html.includes('(默认)'))
33
+ console.log('长题目开头出现:', html.includes('你要不要现在就'))