koishi-plugin-oni-sync-bot 0.9.3 → 0.10.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/index.js CHANGED
@@ -35,20 +35,49 @@ __export(src_exports, {
35
35
  name: () => name
36
36
  });
37
37
  module.exports = __toCommonJS(src_exports);
38
- var import_koishi11 = require("koishi");
39
38
  var import_path = require("path");
40
39
 
40
+ // src/config.ts
41
+ var import_koishi = require("koishi");
42
+ var SiteConfig = import_koishi.Schema.object({
43
+ domain: import_koishi.Schema.string().description("你的短链域名(必填,如:klei.vip)").default("klei.vip"),
44
+ main_site: import_koishi.Schema.string().description("主站域名(必填,如:oxygennotincluded.wiki.gg)").default("oxygennotincluded.wiki.gg/zh"),
45
+ bwiki_site: import_koishi.Schema.string().description("镜像站域名(必填,如:wiki.biligame.com)").default("wiki.biligame.com/oni")
46
+ });
47
+ var AccountConfig = import_koishi.Schema.object({
48
+ ggUsername: import_koishi.Schema.string().description("WIKIGG 用户名").default("1"),
49
+ ggPassword: import_koishi.Schema.string().description("WIKIGG 密码").default("1"),
50
+ bwikiusername: import_koishi.Schema.string().description("bwiki用户名").default("1"),
51
+ bwikipassword: import_koishi.Schema.string().description("bwiki密码").default("1")
52
+ });
53
+ var NotifyConfig = import_koishi.Schema.object({
54
+ logsUrl: import_koishi.Schema.string().description("日志查看地址").default("https://klei.vip/onilogs"),
55
+ notifyGroupIds: import_koishi.Schema.array(import_koishi.Schema.string()).description(
56
+ '增量更新同步成功时通知的群频道ID列表,如 ["group:123456"],留空则不发送通知'
57
+ ).default([]),
58
+ notifyBotPlatform: import_koishi.Schema.string().description("通知 bot 的平台标识,默认 qq").default("qq")
59
+ });
60
+ var ScheduleConfig = import_koishi.Schema.object({
61
+ updateCron: import_koishi.Schema.string().description("页面缓存自动更新 cron 表达式(默认每天凌晨 2 点)").default("0 2 * * *")
62
+ });
63
+ var Config = import_koishi.Schema.intersect([
64
+ AccountConfig,
65
+ SiteConfig,
66
+ NotifyConfig,
67
+ ScheduleConfig
68
+ ]);
69
+
41
70
  // src/services/wikiBotService.ts
42
- var import_koishi2 = require("koishi");
71
+ var import_koishi4 = require("koishi");
43
72
  var import_mwn = require("mwn");
44
73
 
45
74
  // src/utils/tools.ts
46
- var import_koishi = require("koishi");
75
+ var import_koishi2 = require("koishi");
47
76
  var import_pinyin_pro = require("pinyin-pro");
48
77
  var CROSS_SITE_LINK_REGEX = /\[\[(en|ru|pt-br):[^\]]*\]\]/g;
49
78
  var DEV_TEXT_REGEX = /(?<!\w)Dev:/g;
50
79
  var MODULE_NAMESPACE_PREFIX = "Module:Dev/";
51
- var logger = new import_koishi.Logger("oni-sync");
80
+ var logger = new import_koishi2.Logger("oni-sync");
52
81
  function clean_page_text(text) {
53
82
  const textWithoutCrossLink = text.replace(CROSS_SITE_LINK_REGEX, "");
54
83
  const textWithReplacedDev = textWithoutCrossLink.replace(
@@ -95,9 +124,10 @@ async function getAndProcessPageContent(site, pageTitle) {
95
124
  rvlimit: 1
96
125
  });
97
126
  if (queryRes && queryRes.query && queryRes.query.pages) {
98
- const pageIds = Object.keys(queryRes.query.pages);
127
+ const pages = queryRes.query.pages;
128
+ const pageIds = Object.keys(pages);
99
129
  if (pageIds.length > 0) {
100
- const page = queryRes.query.pages[pageIds[0]];
130
+ const page = pages[pageIds[0]];
101
131
  if (page.revisions && page.revisions.length > 0) {
102
132
  rawText = page.revisions[0].content || "";
103
133
  }
@@ -146,19 +176,17 @@ function getErrorMessage(error) {
146
176
  }
147
177
  __name(getErrorMessage, "getErrorMessage");
148
178
  function formatWikiTime(isoString) {
149
- try {
150
- const date = new Date(isoString);
151
- if (Number.isNaN(date.getTime())) return isoString;
152
- const pad = /* @__PURE__ */ __name((n) => String(n).padStart(2, "0"), "pad");
153
- const y = date.getFullYear();
154
- const m = pad(date.getMonth() + 1);
155
- const d = pad(date.getDate());
156
- const hh = pad((date.getUTCHours() + 8) % 24);
157
- const mm = pad(date.getUTCMinutes());
158
- return `${y}-${m}-${d} ${hh}:${mm}`;
159
- } catch {
160
- return isoString;
161
- }
179
+ const date = new Date(isoString);
180
+ if (Number.isNaN(date.getTime())) return isoString;
181
+ const BEIJING_OFFSET_MS = 8 * 60 * 60 * 1e3;
182
+ const beijing = new Date(date.getTime() + BEIJING_OFFSET_MS);
183
+ const pad = /* @__PURE__ */ __name((n) => String(n).padStart(2, "0"), "pad");
184
+ const y = beijing.getUTCFullYear();
185
+ const m = pad(beijing.getUTCMonth() + 1);
186
+ const d = pad(beijing.getUTCDate());
187
+ const hh = pad(beijing.getUTCHours());
188
+ const mm = pad(beijing.getUTCMinutes());
189
+ return `${y}-${m}-${d} ${hh}:${mm}`;
162
190
  }
163
191
  __name(formatWikiTime, "formatWikiTime");
164
192
  function normalizeChannelId(rawId) {
@@ -200,15 +228,41 @@ function stripImagePrefix(fileName) {
200
228
  }
201
229
  __name(stripImagePrefix, "stripImagePrefix");
202
230
 
231
+ // src/utils/async.ts
232
+ var import_koishi3 = require("koishi");
233
+ async function withRetry(fn, options = {}) {
234
+ const { attempts = 3, delayMs = 1e3, onRetry } = options;
235
+ if (!Number.isInteger(attempts) || attempts < 1) {
236
+ throw new RangeError(`attempts 必须是 >= 1 的整数,收到 ${attempts}`);
237
+ }
238
+ let lastError;
239
+ for (let attempt = 1; attempt <= attempts; attempt++) {
240
+ try {
241
+ return await fn();
242
+ } catch (error) {
243
+ lastError = error;
244
+ if (attempt >= attempts) break;
245
+ onRetry?.(error, attempt, attempts);
246
+ if (delayMs > 0) await (0, import_koishi3.sleep)(delayMs);
247
+ }
248
+ }
249
+ throw lastError;
250
+ }
251
+ __name(withRetry, "withRetry");
252
+
203
253
  // src/services/wikiBotService.ts
204
- var WikiBotService = class _WikiBotService extends import_koishi2.Service {
254
+ function isAssertUserFailed(error) {
255
+ return typeof error === "object" && error !== null && error.code === "assertuserfailed";
256
+ }
257
+ __name(isAssertUserFailed, "isAssertUserFailed");
258
+ var WikiBotService = class _WikiBotService extends import_koishi4.Service {
205
259
  static {
206
260
  __name(this, "WikiBotService");
207
261
  }
208
262
  static inject = [];
209
263
  ggbot = null;
210
264
  bwikibot = null;
211
- isReady = false;
265
+ botProxies = { gg: null, bwiki: null };
212
266
  botConfig;
213
267
  static USER_AGENT = `OniSyncBot/1.0 (https://klei.vip; Charles@klei.vip)`;
214
268
  static MAX_RETRIES = 3;
@@ -217,6 +271,24 @@ var WikiBotService = class _WikiBotService extends import_koishi2.Service {
217
271
  super(ctx, "wikiBot", true);
218
272
  this.botConfig = config;
219
273
  }
274
+ /** 站点显示名,避免到处写 `site === "gg" ? "WIKIGG" : "bwiki"` */
275
+ static siteLabel(site) {
276
+ return site === "gg" ? "WIKIGG" : "bwiki";
277
+ }
278
+ botOf(site) {
279
+ return site === "gg" ? this.ggbot : this.bwikibot;
280
+ }
281
+ setBot(site, bot) {
282
+ if (site === "gg") {
283
+ this.ggbot = bot;
284
+ } else {
285
+ this.bwikibot = bot;
286
+ }
287
+ }
288
+ siteConfigOf(site) {
289
+ const sites = this.getSitesConfig();
290
+ return site === "gg" ? sites.gg : sites.bwiki;
291
+ }
220
292
  getSitesConfig() {
221
293
  return {
222
294
  gg: {
@@ -235,20 +307,17 @@ var WikiBotService = class _WikiBotService extends import_koishi2.Service {
235
307
  }
236
308
  };
237
309
  }
238
- delay(ms) {
239
- return new Promise((resolve2) => setTimeout(resolve2, ms));
240
- }
241
- async loginWithRetry(siteConfig, attempt = 1) {
310
+ async loginWithRetry(siteConfig) {
242
311
  try {
243
- const bot = await this.login(siteConfig);
244
- return bot;
312
+ return await withRetry(() => this.login(siteConfig), {
313
+ attempts: _WikiBotService.MAX_RETRIES,
314
+ delayMs: _WikiBotService.RETRY_DELAY,
315
+ onRetry: /* @__PURE__ */ __name((error, attempt, attempts) => logger.debug(
316
+ `${siteConfig.name} 登录失败,重试中 (${attempt}/${attempts}): ${getErrorMessage(error)}`
317
+ ), "onRetry")
318
+ });
245
319
  } catch (error) {
246
- const errorMsg = getErrorMessage(error);
247
- if (attempt < _WikiBotService.MAX_RETRIES) {
248
- await this.delay(_WikiBotService.RETRY_DELAY);
249
- return this.loginWithRetry(siteConfig, attempt + 1);
250
- }
251
- logger.error(`❌ ${siteConfig.name} 登录失败`, errorMsg);
320
+ logger.error(`❌ ${siteConfig.name} 登录失败`, getErrorMessage(error));
252
321
  throw error;
253
322
  }
254
323
  }
@@ -283,21 +352,9 @@ var WikiBotService = class _WikiBotService extends import_koishi2.Service {
283
352
  }
284
353
  async start() {
285
354
  try {
286
- const sitesConfig = this.getSitesConfig();
287
- try {
288
- this.ggbot = await this.loginWithRetry(sitesConfig.gg);
289
- logger.info("✅ WIKIGG 登录成功");
290
- } catch (error) {
291
- this.ggbot = null;
292
- }
293
- try {
294
- this.bwikibot = await this.loginWithRetry(sitesConfig.bwiki);
295
- logger.info("✅ bwiki 登录成功");
296
- } catch (error) {
297
- this.bwikibot = null;
298
- }
299
- this.isReady = this.ggbot !== null || this.bwikibot !== null;
300
- if (!this.isReady) {
355
+ const ggOk = await this.loginSite("gg");
356
+ const bwikiOk = await this.loginSite("bwiki");
357
+ if (!ggOk && !bwikiOk) {
301
358
  logger.error("❌ WikiBotService 初始化失败,两个 Wiki 均无法登录");
302
359
  }
303
360
  } catch (error) {
@@ -306,181 +363,174 @@ var WikiBotService = class _WikiBotService extends import_koishi2.Service {
306
363
  }
307
364
  }
308
365
  stop() {
309
- this.isReady = false;
310
366
  this.ggbot = null;
311
367
  this.bwikibot = null;
312
- this.ggbotProxy = null;
313
- this.bwikibotProxy = null;
368
+ this.botProxies = { gg: null, bwiki: null };
314
369
  }
315
370
  async relogin() {
316
- const sitesConfig = this.getSitesConfig();
317
- let ggSuccess = false;
318
- let bwikiSuccess = false;
319
- try {
320
- this.ggbot = await this.loginWithRetry(sitesConfig.gg);
321
- ggSuccess = true;
322
- logger.info("✅ WIKIGG 重新登录成功");
323
- } catch (error) {
324
- this.ggbot = null;
371
+ const gg = await this.loginSite("gg", true);
372
+ const bwiki = await this.loginSite("bwiki", true);
373
+ return { gg, bwiki };
374
+ }
375
+ /**
376
+ * 确保两个站点都已登录:任一未就绪时先尝试重新登录。
377
+ * 就绪状态属于本服务的职责,调用方只消费结果。
378
+ */
379
+ async ensureReady() {
380
+ if (!this.isGGBotReady() || !this.isBWikiBotReady()) {
381
+ logger.warn("检测到部分机器人未就绪,尝试重新登录...");
382
+ try {
383
+ await this.relogin();
384
+ } catch (error) {
385
+ logger.error("重新登录失败:", getErrorMessage(error));
386
+ }
325
387
  }
388
+ return { gg: this.isGGBotReady(), bwiki: this.isBWikiBotReady() };
389
+ }
390
+ /** 登录单个站点;失败不抛错、只返回是否成功(顺序调用以保持原有时序) */
391
+ async loginSite(site, isRelogin = false) {
392
+ const label = _WikiBotService.siteLabel(site);
326
393
  try {
327
- this.bwikibot = await this.loginWithRetry(sitesConfig.bwiki);
328
- bwikiSuccess = true;
329
- logger.info("✅ bwiki 重新登录成功");
394
+ this.setBot(site, await this.loginWithRetry(this.siteConfigOf(site)));
395
+ logger.info(`✅ ${label} ${isRelogin ? "重新" : ""}登录成功`);
396
+ return true;
330
397
  } catch (error) {
331
- this.bwikibot = null;
398
+ this.setBot(site, null);
399
+ return false;
332
400
  }
333
- this.isReady = this.ggbot !== null || this.bwikibot !== null;
334
- return { gg: ggSuccess, bwiki: bwikiSuccess };
335
401
  }
336
402
  async reloginSite(site) {
337
- const siteName = site === "gg" ? "WIKIGG" : "bwiki";
338
- const sitesConfig = this.getSitesConfig();
339
- const siteConfig = site === "gg" ? sitesConfig.gg : sitesConfig.bwiki;
403
+ const label = _WikiBotService.siteLabel(site);
340
404
  try {
341
- const bot = await this.loginWithRetry(siteConfig);
342
- if (site === "gg") {
343
- this.ggbot = bot;
344
- } else {
345
- this.bwikibot = bot;
346
- }
347
- logger.info(`✅ ${siteName} 自动重新登录成功`);
405
+ this.setBot(site, await this.loginWithRetry(this.siteConfigOf(site)));
406
+ logger.info(`✅ ${label} 自动重新登录成功`);
348
407
  } catch (error) {
349
- if (site === "gg") {
350
- this.ggbot = null;
351
- } else {
352
- this.bwikibot = null;
353
- }
408
+ this.setBot(site, null);
354
409
  throw error;
355
410
  }
356
411
  }
412
+ /** 两个站点是否至少有一个可用(派生状态,不需要手工同步) */
413
+ get isReady() {
414
+ return this.ggbot !== null || this.bwikibot !== null;
415
+ }
357
416
  isGGBotReady() {
358
- return this.ggbot !== null;
417
+ return this.botOf("gg") !== null;
359
418
  }
360
419
  isBWikiBotReady() {
361
- return this.bwikibot !== null;
420
+ return this.botOf("bwiki") !== null;
362
421
  }
422
+ /**
423
+ * 生成一个"登录态永远有效"的客户端代理。
424
+ *
425
+ * 设计说明(为什么必须是代理而不是普通对象):
426
+ * Mwn 的方法很多,且调用方需要 `continuedQueryGen` 这类**异步生成器**以及
427
+ * `options` 这类**非函数属性**。用代理可以完整转发任意成员,同时把
428
+ * "assert=user 失败 → 重新登录 → 重放调用" 这件事对调用方完全隐藏。
429
+ */
363
430
  createBotProxy(site) {
364
- const self = this;
431
+ const label = _WikiBotService.siteLabel(site);
365
432
  const METHODS_TO_SKIP = /* @__PURE__ */ new Set(["cookieJar", "setRequestOptions"]);
366
433
  const getCurrentBot = /* @__PURE__ */ __name(() => {
367
- const bot = site === "gg" ? self.ggbot : self.bwikibot;
434
+ const bot = this.botOf(site);
368
435
  if (!bot) {
369
- throw new Error(
370
- `${site === "gg" ? "WIKIGG" : "bwiki"} bot 尚未就绪,请检查登录配置或查看日志`
371
- );
436
+ throw new Error(`${label} bot 尚未就绪,请检查登录配置或查看日志`);
372
437
  }
373
438
  return bot;
374
439
  }, "getCurrentBot");
440
+ const memberOf = /* @__PURE__ */ __name((bot, prop) => bot[prop], "memberOf");
441
+ const invokeWithRelogin = /* @__PURE__ */ __name(async (invoke) => {
442
+ try {
443
+ return await invoke(getCurrentBot());
444
+ } catch (error) {
445
+ if (!isAssertUserFailed(error)) throw error;
446
+ await this.reloginSite(site);
447
+ return await invoke(getCurrentBot());
448
+ }
449
+ }, "invokeWithRelogin");
375
450
  return new Proxy({}, {
376
- get(_target, prop) {
377
- const propKey = prop;
378
- const currentBot = getCurrentBot();
379
- const value = currentBot[propKey];
380
- if (typeof value !== "function") {
381
- return value;
382
- }
383
- if (METHODS_TO_SKIP.has(prop)) {
384
- return value.bind(currentBot);
451
+ get: /* @__PURE__ */ __name((_target, prop) => {
452
+ const value = memberOf(getCurrentBot(), prop);
453
+ if (typeof value !== "function") return value;
454
+ if (typeof prop === "string" && METHODS_TO_SKIP.has(prop)) {
455
+ return value.bind(this.botOf(site));
385
456
  }
386
457
  if (prop === "continuedQueryGen") {
387
- return function(...args) {
388
- let activeBot = getCurrentBot();
389
- let activeMethod = activeBot.continuedQueryGen;
390
- let activeIterator = activeMethod.apply(activeBot, args)[Symbol.asyncIterator]();
458
+ return (...args) => {
459
+ const relogin = /* @__PURE__ */ __name(() => this.reloginSite(site), "relogin");
460
+ const createIterator = /* @__PURE__ */ __name((callArgs) => {
461
+ const generate = memberOf(
462
+ getCurrentBot(),
463
+ "continuedQueryGen"
464
+ );
465
+ return generate(...callArgs)[Symbol.asyncIterator]();
466
+ }, "createIterator");
467
+ let iterator = createIterator(args);
391
468
  return {
392
469
  [Symbol.asyncIterator]() {
393
470
  return this;
394
471
  },
395
472
  async next() {
396
473
  try {
397
- return await activeIterator.next();
474
+ return await iterator.next();
398
475
  } catch (error) {
399
- if (error.code === "assertuserfailed") {
400
- await self.reloginSite(site);
401
- activeBot = getCurrentBot();
402
- activeMethod = activeBot.continuedQueryGen;
403
- const newGen = activeMethod.apply(activeBot, args);
404
- activeIterator = newGen[Symbol.asyncIterator]();
405
- return await activeIterator.next();
406
- }
407
- throw error;
476
+ if (!isAssertUserFailed(error)) throw error;
477
+ await relogin();
478
+ iterator = createIterator(args);
479
+ return await iterator.next();
408
480
  }
409
481
  }
410
482
  };
411
483
  };
412
484
  }
413
- return async function(...args) {
414
- let executeBot = getCurrentBot();
415
- let method = executeBot[propKey];
485
+ return (...args) => invokeWithRelogin((bot) => {
486
+ const method = memberOf(bot, prop);
416
487
  if (typeof method !== "function") {
417
- throw new Error(
418
- `${site === "gg" ? "WIKIGG" : "bwiki"} bot 缺少方法 ${String(prop)}`
419
- );
420
- }
421
- try {
422
- return await method.apply(executeBot, args);
423
- } catch (error) {
424
- if (error.code === "assertuserfailed") {
425
- await self.reloginSite(site);
426
- executeBot = getCurrentBot();
427
- method = executeBot[propKey];
428
- if (typeof method !== "function") {
429
- throw new Error(
430
- `${site === "gg" ? "WIKIGG" : "bwiki"} 新 bot 缺少方法 ${String(prop)}`
431
- );
432
- }
433
- return await method.apply(executeBot, args);
434
- }
435
- throw error;
488
+ throw new Error(`${label} bot 缺少方法 ${String(prop)}`);
436
489
  }
437
- };
438
- }
490
+ const call = method;
491
+ return call.apply(bot, args);
492
+ });
493
+ }, "get")
439
494
  });
440
495
  }
441
- ggbotProxy = null;
442
- bwikibotProxy = null;
496
+ /** WIKIGG 客户端(透明处理登录过期) */
443
497
  getGGBot() {
444
- if (!this.ggbot) {
445
- throw new Error("WIKIGG bot 尚未就绪,请检查登录配置或查看日志");
446
- }
447
- if (!this.ggbotProxy) {
448
- this.ggbotProxy = this.createBotProxy("gg");
449
- }
450
- return this.ggbotProxy;
498
+ return this.getBot("gg");
451
499
  }
500
+ /** bwiki 客户端(透明处理登录过期) */
452
501
  getBWikiBot() {
453
- if (!this.bwikibot) {
454
- throw new Error("bwiki bot 尚未就绪,请检查登录配置或查看日志");
502
+ return this.getBot("bwiki");
503
+ }
504
+ getBot(site) {
505
+ if (!this.botOf(site)) {
506
+ throw new Error(
507
+ `${_WikiBotService.siteLabel(site)} bot 尚未就绪,请检查登录配置或查看日志`
508
+ );
455
509
  }
456
- if (!this.bwikibotProxy) {
457
- this.bwikibotProxy = this.createBotProxy("bwiki");
510
+ let proxy = this.botProxies[site];
511
+ if (!proxy) {
512
+ proxy = this.createBotProxy(site);
513
+ this.botProxies[site] = proxy;
458
514
  }
459
- return this.bwikibotProxy;
515
+ return proxy;
460
516
  }
461
517
  };
462
- ((WikiBotService2) => {
463
- WikiBotService2.Config = import_koishi2.Schema.object({
464
- ggUsername: import_koishi2.Schema.string().description("WIKIGG 用户名").default("1"),
465
- ggPassword: import_koishi2.Schema.string().description("WIKIGG 密码").default("1"),
466
- bwikiusername: import_koishi2.Schema.string().description("bwiki用户名").default("1"),
467
- bwikipassword: import_koishi2.Schema.string().description("bwiki密码").default("1")
468
- });
469
- })(WikiBotService || (WikiBotService = {}));
470
518
 
471
519
  // src/services/consoleLogProvider.ts
472
- var import_koishi3 = require("koishi");
520
+ var import_koishi5 = require("koishi");
473
521
  var import_plugin_console = require("@koishijs/plugin-console");
474
- var logBuffer = [];
475
- var PublicLogProvider = class extends import_plugin_console.DataService {
476
- static {
477
- __name(this, "PublicLogProvider");
478
- }
479
- constructor(ctx) {
522
+ var MAX_RECORDS = 1e3;
523
+ var LOG_SCOPE = "oni-sync";
524
+ var ConsoleLogData = class extends import_plugin_console.DataService {
525
+ constructor(ctx, buffer) {
480
526
  super(ctx, "onilogs", { authority: 0 });
527
+ this.buffer = buffer;
528
+ }
529
+ static {
530
+ __name(this, "ConsoleLogData");
481
531
  }
482
532
  async get() {
483
- return logBuffer;
533
+ return this.buffer;
484
534
  }
485
535
  };
486
536
  var ConsoleLogProvider = class {
@@ -488,23 +538,28 @@ var ConsoleLogProvider = class {
488
538
  __name(this, "ConsoleLogProvider");
489
539
  }
490
540
  static inject = ["console"];
541
+ /**
542
+ * 日志缓冲。刻意做成实例状态而非模块级变量:
543
+ * 模块级可变数组是全进程共享的单例,多实例或热重载时会互相串数据。
544
+ */
545
+ buffer = [];
491
546
  constructor(ctx) {
492
- ctx.plugin(PublicLogProvider);
547
+ ctx.plugin(ConsoleLogData, this.buffer);
493
548
  const target = {
494
549
  colors: 0,
495
550
  record: /* @__PURE__ */ __name((record) => {
496
- if (record.name !== "oni-sync") return;
497
- logBuffer.push(record);
498
- if (logBuffer.length > 1e3) {
499
- logBuffer = logBuffer.slice(-1e3);
551
+ if (record.name !== LOG_SCOPE) return;
552
+ this.buffer.push(record);
553
+ if (this.buffer.length > MAX_RECORDS) {
554
+ this.buffer.splice(0, this.buffer.length - MAX_RECORDS);
500
555
  }
501
- ctx.get("console")?.patch("onilogs", logBuffer);
556
+ ctx.get("console")?.patch("onilogs", this.buffer);
502
557
  }, "record")
503
558
  };
504
- import_koishi3.Logger.targets.push(target);
559
+ import_koishi5.Logger.targets.push(target);
505
560
  ctx.on("dispose", () => {
506
- const index = import_koishi3.Logger.targets.indexOf(target);
507
- if (index > -1) import_koishi3.Logger.targets.splice(index, 1);
561
+ const index = import_koishi5.Logger.targets.indexOf(target);
562
+ if (index > -1) import_koishi5.Logger.targets.splice(index, 1);
508
563
  });
509
564
  }
510
565
  };
@@ -528,7 +583,6 @@ var DatabaseExtension = class {
528
583
  };
529
584
 
530
585
  // src/plugins/routeRedirect.ts
531
- var import_koishi4 = require("koishi");
532
586
  var RouteRedirect = class {
533
587
  static {
534
588
  __name(this, "RouteRedirect");
@@ -575,810 +629,872 @@ var RouteRedirect = class {
575
629
  });
576
630
  }
577
631
  };
578
- ((RouteRedirect2) => {
579
- RouteRedirect2.Config = import_koishi4.Schema.object({
580
- domain: import_koishi4.Schema.string().description("你的短链域名(必填,如:klei.vip)").default("klei.vip"),
581
- main_site: import_koishi4.Schema.string().description("主站域名(必填,如:oxygennotincluded.wiki.gg)").default("oxygennotincluded.wiki.gg/zh"),
582
- bwiki_site: import_koishi4.Schema.string().description("镜像站域名(必填,如:wiki.biligame.com)").default("wiki.biligame.com/oni")
583
- });
584
- })(RouteRedirect || (RouteRedirect = {}));
585
-
586
- // src/plugins/syncCommands.ts
587
- var import_koishi8 = require("koishi");
588
-
589
- // src/sync/pageSync.ts
590
- var import_koishi6 = require("koishi");
591
632
 
592
633
  // src/sync/imgSync.ts
593
- var import_koishi5 = require("koishi");
594
634
  var import_node_fetch = __toESM(require("node-fetch"));
595
635
  var import_form_data = __toESM(require("form-data"));
596
- var CONFIG = {
597
- IGNORED_IMAGES: [],
598
- SYNC_INTERVAL_SUCCESS: 3e3,
599
- SYNC_INTERVAL_FAILED: 5e3,
600
- UPLOAD_COMMENT: "从 WikiGG 自动同步转存",
601
- UPLOAD_TEXT: "== 授权说明 ==\n本文件从 WikiGG 转存,遵循原站点授权协议。"
636
+ var DEFAULT_OPTIONS = {
637
+ ignoredImages: [],
638
+ intervalSuccess: 3e3,
639
+ intervalFailed: 5e3,
640
+ uploadComment: "从 WikiGG 自动同步转存",
641
+ uploadText: "== 授权说明 ==\n本文件从 WikiGG 转存,遵循原站点授权协议。"
602
642
  };
603
- async function getImageInfo(site, fileName) {
604
- try {
605
- const normalizedTitle = normalizeImageTitle(fileName);
606
- const response = await site.query({
607
- action: "query",
608
- titles: normalizedTitle,
609
- prop: "imageinfo",
610
- iiprop: "url|sha1|size|mime"
611
- });
612
- const pages = response.query?.pages || {};
613
- const page = Object.values(pages)[0];
614
- if (!page || page.missing || !page.imageinfo || page.imageinfo.length === 0) {
615
- return null;
616
- }
617
- const imageInfo = page.imageinfo[0];
618
- return {
619
- url: imageInfo.url,
620
- sha1: imageInfo.sha1,
621
- size: imageInfo.size
622
- };
623
- } catch (error) {
624
- const errorMsg = getErrorMessage(error);
625
- logger.error(`[GetImageInfo] 获取 ${fileName} 信息失败:`, errorMsg);
626
- return null;
643
+ var ImageSyncer = class {
644
+ constructor(source, target, deps = {}) {
645
+ this.source = source;
646
+ this.target = target;
647
+ this.options = { ...DEFAULT_OPTIONS, ...deps.options };
627
648
  }
628
- }
629
- __name(getImageInfo, "getImageInfo");
630
- async function deleteOldVersions(bot, fileName) {
631
- try {
632
- const normalizedTitle = normalizeImageTitle(fileName);
633
- const response = await bot.query({
634
- action: "query",
635
- titles: normalizedTitle,
636
- prop: "revisions",
637
- rvprop: "ids|timestamp",
638
- rvlimit: "max",
639
- rvdir: "newer"
640
- // 按时间正序排列,最新的在最后
641
- });
642
- const pages = response.query?.pages || {};
643
- const page = Object.values(pages)[0];
644
- if (!page || !page.revisions || page.revisions.length <= 1) {
645
- return;
646
- }
647
- const revisionIds = page.revisions.slice(0, -1).map((rev) => rev.revid);
648
- const token = await bot.getCsrfToken();
649
- for (const revid of revisionIds) {
650
- try {
651
- await bot.rawRequest({
652
- method: "POST",
653
- url: bot.options.apiUrl,
654
- data: {
655
- action: "delete",
656
- title: fileName,
657
- revid,
658
- token,
659
- reason: "自动清理旧版本,只保留最新同步版本",
660
- format: "json"
661
- }
662
- });
663
- logger.info(`[SyncImg] 🗑️ 删除旧版本 ${revid} 成功`);
664
- } catch (error) {
665
- const errorMsg = getErrorMessage(error);
666
- logger.error(`[SyncImg] ❌ 删除旧版本 ${revid} 失败:`, errorMsg);
649
+ static {
650
+ __name(this, "ImageSyncer");
651
+ }
652
+ options;
653
+ async getImageInfo(site, fileName) {
654
+ try {
655
+ const normalizedTitle = normalizeImageTitle(fileName);
656
+ const response = await site.query({
657
+ action: "query",
658
+ titles: normalizedTitle,
659
+ prop: "imageinfo",
660
+ iiprop: "url|sha1|size|mime"
661
+ });
662
+ const pages = response.query?.pages || {};
663
+ const page = Object.values(pages)[0];
664
+ if (!page || page.missing || !page.imageinfo || page.imageinfo.length === 0) {
665
+ return null;
667
666
  }
667
+ const imageInfo = page.imageinfo[0];
668
+ return {
669
+ url: imageInfo.url,
670
+ sha1: imageInfo.sha1,
671
+ size: imageInfo.size
672
+ };
673
+ } catch (error) {
674
+ const errorMsg = getErrorMessage(error);
675
+ logger.error(`[GetImageInfo] 获取 ${fileName} 信息失败:`, errorMsg);
676
+ return null;
668
677
  }
669
- } catch (error) {
670
- const errorMsg = getErrorMessage(error);
671
- logger.error(`[SyncImg] ❌ 获取版本信息失败:`, errorMsg);
672
678
  }
673
- }
674
- __name(deleteOldVersions, "deleteOldVersions");
675
- async function syncSingleImage(sourceBot, targetBot, fileName, config) {
676
- if (CONFIG.IGNORED_IMAGES.includes(fileName)) {
677
- logger.info(`[SyncImg] 🚫 图片 ${fileName} 在忽略列表,跳过`);
678
- return { success: true, reason: "ignored" };
679
- }
680
- const bareFileName = stripImagePrefix(fileName);
681
- try {
682
- logger.info(`[SyncImg] 🚀 开始处理: ${bareFileName}`);
683
- const sourceImageInfo = await getImageInfo(sourceBot, bareFileName);
684
- if (!sourceImageInfo) {
685
- logger.info(`[SyncImg] ❌ 源站未找到图片: ${fileName}`);
686
- return { success: false, reason: "source_missing" };
687
- }
688
- const targetImageInfo = await getImageInfo(targetBot, bareFileName);
689
- logger.info(`原图片sha1: ${sourceImageInfo.sha1}`);
690
- logger.info(`目标图片sha1: ${targetImageInfo?.sha1}`);
691
- if (targetImageInfo && targetImageInfo.sha1 === sourceImageInfo.sha1) {
692
- logger.info(`[SyncImg] 🟡 图片 ${fileName} 已存在且内容一致,跳过`);
693
- return { success: true, reason: "no_change" };
694
- }
695
- logger.info(`[SyncImg] 📥 下载图片: ${sourceImageInfo.url}`);
696
- const imageResponse = await (0, import_node_fetch.default)(sourceImageInfo.url, {
697
- headers: {
698
- "User-Agent": "OniSyncBot/1.0 (https://klei.vip; Charles@klei.vip)"
679
+ async deleteOldVersions(bot, fileName) {
680
+ try {
681
+ const normalizedTitle = normalizeImageTitle(fileName);
682
+ const response = await bot.query({
683
+ action: "query",
684
+ titles: normalizedTitle,
685
+ prop: "revisions",
686
+ rvprop: "ids|timestamp",
687
+ rvlimit: "max",
688
+ rvdir: "newer"
689
+ // 按时间正序排列,最新的在最后
690
+ });
691
+ const pages = response.query?.pages || {};
692
+ const page = Object.values(pages)[0];
693
+ if (!page || !page.revisions || page.revisions.length <= 1) {
694
+ return;
699
695
  }
700
- });
701
- if (!imageResponse.ok) {
702
- throw new Error(`图片下载失败,HTTP状态码: ${imageResponse.status}`);
703
- }
704
- const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
705
- logger.info(
706
- `[SyncImg] 📤 上传图片: ${bareFileName} (大小: ${(imageBuffer.length / 1024).toFixed(1)} KB)`
707
- );
708
- const token = await targetBot.getCsrfToken();
709
- const form = new import_form_data.default();
710
- form.append("action", "upload");
711
- form.append("filename", bareFileName);
712
- form.append("text", CONFIG.UPLOAD_TEXT);
713
- form.append("comment", CONFIG.UPLOAD_COMMENT);
714
- form.append("token", token);
715
- form.append("ignorewarnings", "0");
716
- form.append("format", "json");
717
- form.append("file", imageBuffer, {
718
- filename: bareFileName,
719
- contentType: imageResponse.headers.get("content-type") || "application/octet-stream"
720
- });
721
- const rawResponse = await targetBot.rawRequest({
722
- method: "POST",
723
- url: targetBot.options.apiUrl,
724
- data: form,
725
- headers: {
726
- ...form.getHeaders()
727
- // "X-authkey": `${getSitesConfig(config).huiji.uakey}`,
696
+ const revisionIds = page.revisions.slice(0, -1).map((rev) => rev.revid);
697
+ const token = await bot.getCsrfToken();
698
+ for (const revid of revisionIds) {
699
+ try {
700
+ await bot.rawRequest({
701
+ method: "POST",
702
+ url: bot.options.apiUrl,
703
+ data: {
704
+ action: "delete",
705
+ title: fileName,
706
+ revid,
707
+ token,
708
+ reason: "自动清理旧版本,只保留最新同步版本",
709
+ format: "json"
710
+ }
711
+ });
712
+ logger.info(`[SyncImg] 🗑️ 删除旧版本 ${revid} 成功`);
713
+ } catch (error) {
714
+ const errorMsg = getErrorMessage(error);
715
+ logger.error(`[SyncImg] ❌ 删除旧版本 ${revid} 失败:`, errorMsg);
716
+ }
728
717
  }
729
- });
730
- const responseData = rawResponse.data;
731
- if (responseData.upload && responseData.upload.result === "Success") {
732
- logger.info(`[SyncImg] ✅ 图片 ${fileName} 同步成功`);
733
- await deleteOldVersions(targetBot, fileName);
734
- return { success: true, reason: "synced" };
735
- } else if (responseData.error) {
736
- throw new Error(`${responseData.error.code}: ${responseData.error.info}`);
737
- } else {
738
- throw new Error(`未知响应: ${JSON.stringify(responseData)}`);
739
- }
740
- } catch (error) {
741
- if (error instanceof Error && error.message.includes("fileexists-no-change")) {
742
- logger.info(`[SyncImg] 🟡 图片 ${fileName} 已存在且内容相同,跳过`);
743
- return { success: true, reason: "no_change" };
718
+ } catch (error) {
719
+ const errorMsg = getErrorMessage(error);
720
+ logger.error(`[SyncImg] ❌ 获取版本信息失败:`, errorMsg);
744
721
  }
745
- const errMsg = error.message || String(error);
746
- logger.error(`[SyncImg] ❌ 图片 ${fileName} 同步失败:`, errMsg);
747
- return { success: false, reason: errMsg };
748
722
  }
749
- }
750
- __name(syncSingleImage, "syncSingleImage");
751
- async function getAllImages(site) {
752
- logger.info(`[SyncAllImg] 📥 开始获取WikiGG所有图片`);
753
- const allImages = [];
754
- const queryGen = site.continuedQueryGen({
755
- action: "query",
756
- list: "allimages",
757
- ailimit: "max",
758
- aidir: "ascending",
759
- ainamespace: 6
760
- });
761
- for await (const res of queryGen) {
762
- const imageItems = res.query?.allimages || [];
763
- const imageTitles = imageItems.map((img) => img.title);
764
- allImages.push(...imageTitles);
765
- logger.info(`[SyncAllImg] 📄 已获取 ${allImages.length} 个图片`);
766
- }
767
- logger.info(`[SyncAllImg] 📊 总计获取到 ${allImages.length} 个图片`);
768
- return allImages;
769
- }
770
- __name(getAllImages, "getAllImages");
771
- async function syncAllImages(sourceBot, targetBot, config) {
772
- try {
773
- const imageList = await getAllImages(sourceBot);
774
- if (imageList.length === 0) {
775
- logger.info(`[SyncAllImg] 📭 源站无图片可同步,结束`);
776
- return;
723
+ async syncOne(fileName) {
724
+ if (this.options.ignoredImages.includes(fileName)) {
725
+ logger.info(`[SyncImg] 🚫 图片 ${fileName} 在忽略列表,跳过`);
726
+ return { success: true, reason: "ignored" };
777
727
  }
778
- let successCount = 0;
779
- let failCount = 0;
780
- let skipCount = 0;
781
- const failedImages = [];
782
- logger.info(
783
- `[SyncAllImg] 🚦 开始批量同步,总计 ${imageList.length} 个图片`
784
- );
785
- for (let i = 0; i < imageList.length; i++) {
786
- const fileName = imageList[i];
787
- const progress = (i + 1) / imageList.length * 100;
728
+ const bareFileName = stripImagePrefix(fileName);
729
+ try {
730
+ logger.info(`[SyncImg] 🚀 开始处理: ${bareFileName}`);
731
+ const sourceImageInfo = await this.getImageInfo(this.source, bareFileName);
732
+ if (!sourceImageInfo) {
733
+ logger.info(`[SyncImg] ❌ 源站未找到图片: ${fileName}`);
734
+ return { success: false, reason: "source_missing" };
735
+ }
736
+ const targetImageInfo = await this.getImageInfo(this.target, bareFileName);
737
+ logger.info(`原图片sha1: ${sourceImageInfo.sha1}`);
738
+ logger.info(`目标图片sha1: ${targetImageInfo?.sha1}`);
739
+ if (targetImageInfo && targetImageInfo.sha1 === sourceImageInfo.sha1) {
740
+ logger.info(`[SyncImg] 🟡 图片 ${fileName} 已存在且内容一致,跳过`);
741
+ return { success: true, reason: "no_change" };
742
+ }
743
+ logger.info(`[SyncImg] 📥 下载图片: ${sourceImageInfo.url}`);
744
+ const imageResponse = await (0, import_node_fetch.default)(sourceImageInfo.url, {
745
+ headers: {
746
+ "User-Agent": "OniSyncBot/1.0 (https://klei.vip; Charles@klei.vip)"
747
+ }
748
+ });
749
+ if (!imageResponse.ok) {
750
+ throw new Error(`图片下载失败,HTTP状态码: ${imageResponse.status}`);
751
+ }
752
+ const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
788
753
  logger.info(
789
- `
790
- [SyncAllImg] 📈 进度 ${i + 1}/${imageList.length} (${progress.toFixed(1)}%)`
754
+ `[SyncImg] 📤 上传图片: ${bareFileName} (大小: ${(imageBuffer.length / 1024).toFixed(1)} KB)`
791
755
  );
792
- const result = await syncSingleImage(
793
- sourceBot,
794
- targetBot,
795
- fileName,
796
- config
797
- );
798
- if (!result.success) {
799
- failCount++;
800
- failedImages.push(fileName);
801
- await (0, import_koishi5.sleep)(CONFIG.SYNC_INTERVAL_FAILED);
802
- } else {
803
- successCount++;
804
- if (result.reason === "ignored" || result.reason === "no_change") {
805
- skipCount++;
756
+ const token = await this.target.getCsrfToken();
757
+ const form = new import_form_data.default();
758
+ form.append("action", "upload");
759
+ form.append("filename", bareFileName);
760
+ form.append("text", this.options.uploadText);
761
+ form.append("comment", this.options.uploadComment);
762
+ form.append("token", token);
763
+ form.append("ignorewarnings", "0");
764
+ form.append("format", "json");
765
+ form.append("file", imageBuffer, {
766
+ filename: bareFileName,
767
+ contentType: imageResponse.headers.get("content-type") || "application/octet-stream"
768
+ });
769
+ const rawResponse = await this.target.rawRequest({
770
+ method: "POST",
771
+ url: this.target.options.apiUrl,
772
+ data: form,
773
+ headers: {
774
+ ...form.getHeaders()
806
775
  }
807
- await (0, import_koishi5.sleep)(CONFIG.SYNC_INTERVAL_SUCCESS);
776
+ });
777
+ const responseData = rawResponse.data;
778
+ if (responseData.upload && responseData.upload.result === "Success") {
779
+ logger.info(`[SyncImg] ✅ 图片 ${fileName} 同步成功`);
780
+ await this.deleteOldVersions(this.target, fileName);
781
+ return { success: true, reason: "synced" };
782
+ } else if (responseData.error) {
783
+ throw new Error(`${responseData.error.code}: ${responseData.error.info}`);
784
+ } else {
785
+ throw new Error(`未知响应: ${JSON.stringify(responseData)}`);
808
786
  }
787
+ } catch (error) {
788
+ if (error instanceof Error && error.message.includes("fileexists-no-change")) {
789
+ logger.info(`[SyncImg] 🟡 图片 ${fileName} 已存在且内容相同,跳过`);
790
+ return { success: true, reason: "no_change" };
791
+ }
792
+ const errMsg = getErrorMessage(error);
793
+ logger.error(`[SyncImg] ❌ 图片 ${fileName} 同步失败:`, errMsg);
794
+ return { success: false, reason: errMsg };
795
+ }
796
+ }
797
+ async listAll() {
798
+ logger.info(`[SyncAllImg] 📥 开始获取WikiGG所有图片`);
799
+ const allImages = [];
800
+ const queryGen = this.source.continuedQueryGen({
801
+ action: "query",
802
+ list: "allimages",
803
+ ailimit: "max",
804
+ aidir: "ascending",
805
+ ainamespace: 6
806
+ });
807
+ for await (const res of queryGen) {
808
+ const imageItems = res.query?.allimages || [];
809
+ allImages.push(...imageItems.map((img) => img.title));
810
+ logger.info(`[SyncAllImg] 📄 已获取 ${allImages.length} 个图片`);
809
811
  }
810
- if (failedImages.length > 0) {
812
+ logger.info(`[SyncAllImg] 📊 总计获取到 ${allImages.length} 个图片`);
813
+ return allImages;
814
+ }
815
+ /** 批量同步所有图片:先串行同步一轮,再重试失败的 */
816
+ async syncAll() {
817
+ try {
818
+ const imageList = await this.listAll();
819
+ if (imageList.length === 0) {
820
+ logger.info(`[SyncAllImg] 📭 源站无图片可同步,结束`);
821
+ return;
822
+ }
823
+ let successCount = 0;
824
+ let failCount = 0;
825
+ let skipCount = 0;
826
+ const failedImages = [];
811
827
  logger.info(
812
- `
813
- [SyncAllImg] 🔄 开始重试 ${failedImages.length} 个失败图片`
828
+ `[SyncAllImg] 🚦 开始批量同步,总计 ${imageList.length} 个图片`
814
829
  );
815
- const stillFailed = [];
816
- for (const fileName of failedImages) {
817
- logger.info(`
818
- [SyncAllImg] 🔁 重试: ${fileName}`);
819
- const result = await syncSingleImage(
820
- sourceBot,
821
- targetBot,
822
- fileName,
823
- config
830
+ for (let i = 0; i < imageList.length; i++) {
831
+ const fileName = imageList[i];
832
+ const progress = (i + 1) / imageList.length * 100;
833
+ logger.info(
834
+ `
835
+ [SyncAllImg] 📈 进度 ${i + 1}/${imageList.length} (${progress.toFixed(1)}%)`
824
836
  );
825
- if (result.success) {
826
- successCount++;
827
- failCount--;
828
- logger.info(`[SyncAllImg] ✅ 重试成功: ${fileName}`);
837
+ const result = await this.syncOne(fileName);
838
+ if (!result.success) {
839
+ failCount++;
840
+ failedImages.push(fileName);
841
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
829
842
  } else {
830
- stillFailed.push(fileName);
831
- logger.info(`[SyncAllImg] ❌ 重试失败: ${fileName}`);
843
+ successCount++;
844
+ if (result.reason === "ignored" || result.reason === "no_change") {
845
+ skipCount++;
846
+ }
847
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
832
848
  }
833
- await (0, import_koishi5.sleep)(CONFIG.SYNC_INTERVAL_SUCCESS);
834
849
  }
835
- if (stillFailed.length > 0) {
836
- logger.info(`
837
- [SyncAllImg] ❌ 最终失败列表(需手动处理):`);
838
- stillFailed.forEach(
839
- (title, idx) => logger.info(` ${idx + 1}. ${title}`)
850
+ if (failedImages.length > 0) {
851
+ logger.info(
852
+ `
853
+ [SyncAllImg] 🔄 开始重试 ${failedImages.length} 个失败图片`
840
854
  );
841
- } else {
842
- logger.info(`
855
+ const stillFailed = [];
856
+ for (const fileName of failedImages) {
857
+ logger.info(`
858
+ [SyncAllImg] 🔁 重试: ${fileName}`);
859
+ const result = await this.syncOne(fileName);
860
+ if (result.success) {
861
+ successCount++;
862
+ failCount--;
863
+ logger.info(`[SyncAllImg] ✅ 重试成功: ${fileName}`);
864
+ } else {
865
+ stillFailed.push(fileName);
866
+ logger.info(`[SyncAllImg] ❌ 重试失败: ${fileName}`);
867
+ }
868
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
869
+ }
870
+ if (stillFailed.length > 0) {
871
+ logger.info(`
872
+ [SyncAllImg] ❌ 最终失败列表(需手动处理):`);
873
+ stillFailed.forEach(
874
+ (title, idx) => logger.info(` ${idx + 1}. ${title}`)
875
+ );
876
+ } else {
877
+ logger.info(`
843
878
  [SyncAllImg] 🎉 所有失败图片重试成功!`);
879
+ }
844
880
  }
845
- }
846
- logger.info(`
881
+ logger.info(`
847
882
  [SyncAllImg] 📊 同步完成!`);
848
- logger.info(`├─ 总计:${imageList.length} 个图片`);
849
- logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
850
- logger.info(`└─ 失败:${failCount} 个`);
851
- } catch (globalError) {
852
- logger.error(`[SyncAllImg] 💥 同步流程异常终止:`, globalError);
853
- throw globalError;
883
+ logger.info(`├─ 总计:${imageList.length} 个图片`);
884
+ logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
885
+ logger.info(`└─ 失败:${failCount} 个`);
886
+ } catch (globalError) {
887
+ logger.error(`[SyncAllImg] 💥 同步流程异常终止:`, globalError);
888
+ throw globalError;
889
+ }
854
890
  }
855
- }
856
- __name(syncAllImages, "syncAllImages");
891
+ };
857
892
 
858
893
  // src/sync/pageSync.ts
859
- var CONFIG2 = {
860
- IGNORED_PAGES: /* @__PURE__ */ new Set(["教程", "MediaWiki:Common.css", "首页", "Main Page"]),
861
- SYNC_INTERVAL_SUCCESS: 500,
862
- SYNC_INTERVAL_FAILED: 1e3,
863
- NAMESPACE: 0,
864
- BATCH_LIMIT: "max",
865
- FILE_NAMESPACE_PREFIX: "File:",
866
- DEFAULT_USER: "同步坤器人",
867
- INCREMENTAL_USER: "定时同步",
868
- DB_RETRY_MAX: 3,
869
- DB_RETRY_DELAY: 500
894
+ var DEFAULT_OPTIONS2 = {
895
+ ignoredPages: /* @__PURE__ */ new Set(["教程", "MediaWiki:Common.css", "首页", "Main Page"]),
896
+ intervalSuccess: 500,
897
+ intervalFailed: 1e3,
898
+ namespace: 0,
899
+ batchLimit: "max",
900
+ fileNamespacePrefix: "File:",
901
+ defaultUser: "同步坤器人",
902
+ dbRetryMax: 3,
903
+ dbRetryDelay: 500
870
904
  };
871
- async function withRetry(fn, maxRetries = CONFIG2.DB_RETRY_MAX, delay = CONFIG2.DB_RETRY_DELAY) {
872
- let lastError;
873
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
874
- try {
875
- return await fn();
876
- } catch (err) {
877
- lastError = err instanceof Error ? err : new Error(String(err));
878
- if (attempt < maxRetries) {
879
- logger.debug(
880
- `数据库操作失败,正在重试 (${attempt}/${maxRetries}): ${lastError.message}`
881
- );
882
- await (0, import_koishi6.sleep)(delay);
883
- }
884
- }
905
+ var PageSyncer = class {
906
+ constructor(source, target, deps = {}) {
907
+ this.source = source;
908
+ this.target = target;
909
+ this.options = { ...DEFAULT_OPTIONS2, ...deps.options };
910
+ this.database = deps.database;
911
+ this.notify = deps.notify;
912
+ this.images = new ImageSyncer(source, target);
885
913
  }
886
- throw lastError || new Error("数据库操作失败");
887
- }
888
- __name(withRetry, "withRetry");
889
- async function ensurePageInDatabase(database, pageId, title) {
890
- if (!database) return;
891
- try {
892
- await withRetry(async () => {
893
- const existing = await database.get("wikipages", { title });
894
- if (existing.length === 0) {
895
- const { pinyin_full, pinyin_first } = generatePinyinInfo(title);
896
- await database.create("wikipages", {
897
- id: pageId,
898
- title,
899
- pinyin_full,
900
- pinyin_first
901
- });
902
- logger.info(`[数据库初始化] ✅ 页面 ${title} 已添加到数据库`);
903
- }
914
+ static {
915
+ __name(this, "PageSyncer");
916
+ }
917
+ options;
918
+ database;
919
+ notify;
920
+ images;
921
+ // ---------------------------------------------------------------- 数据库
922
+ /** 带重试的数据库操作 */
923
+ retryDb(fn) {
924
+ return withRetry(fn, {
925
+ attempts: this.options.dbRetryMax,
926
+ delayMs: this.options.dbRetryDelay,
927
+ onRetry: /* @__PURE__ */ __name((error, attempt, attempts) => logger.debug(
928
+ `数据库操作失败,正在重试 (${attempt}/${attempts}): ${getErrorMessage(error)}`
929
+ ), "onRetry")
904
930
  });
905
- } catch (err) {
906
- const errMsg = err instanceof Error ? err.message : String(err);
907
- logger.warn(`[数据库初始化] ❌ 初始化页面 ${title} 失败: ${errMsg}`);
908
931
  }
909
- }
910
- __name(ensurePageInDatabase, "ensurePageInDatabase");
911
- async function updateContributorToDatabase(database, title, user, timestamp) {
912
- if (!database) return;
913
- try {
914
- await withRetry(async () => {
915
- await database.set(
916
- "wikipages",
917
- { title },
918
- {
919
- contributor: user,
920
- change_time: formatWikiTime(timestamp)
932
+ /** 若数据库中不存在该页面,先写入基本数据(含拼音索引) */
933
+ async ensurePageInDatabase(pageId, title) {
934
+ const database = this.database;
935
+ if (!database) return;
936
+ try {
937
+ await this.retryDb(async () => {
938
+ const existing = await database.get("wikipages", { title });
939
+ if (existing.length === 0) {
940
+ const { pinyin_full, pinyin_first } = generatePinyinInfo(title);
941
+ await database.create("wikipages", {
942
+ id: pageId,
943
+ title,
944
+ pinyin_full,
945
+ pinyin_first
946
+ });
947
+ logger.info(`[数据库初始化] ✅ 页面 ${title} 已添加到数据库`);
921
948
  }
949
+ });
950
+ } catch (err) {
951
+ logger.warn(
952
+ `[数据库初始化] ❌ 初始化页面 ${title} 失败: ${getErrorMessage(err)}`
922
953
  );
923
- logger.debug(`[数据库更新] ✅ 页面 ${title} 的贡献者信息已更新: ${user}`);
924
- });
925
- } catch (err) {
926
- const errMsg = err instanceof Error ? err.message : String(err);
927
- logger.warn(
928
- `[数据库更新] ❌ 更新页面 ${title} 的贡献者信息失败: ${errMsg}`
929
- );
930
- }
931
- }
932
- __name(updateContributorToDatabase, "updateContributorToDatabase");
933
- async function syncSinglePage(oldSite, newSite, pageTitle, user) {
934
- if (CONFIG2.IGNORED_PAGES.has(pageTitle)) {
935
- logger.info(`[syncSinglePage] 🚫 页面 ${pageTitle} 在忽略列表中,跳过`);
936
- return { success: true, reason: "ignored" };
937
- }
938
- try {
939
- logger.info(`[syncSinglePage] 🚀 开始同步页面: ${pageTitle}`);
940
- const [oldContent, newContent] = await Promise.all([
941
- getAndProcessPageContent(oldSite, pageTitle),
942
- getAndProcessPageContent(newSite, pageTitle)
943
- ]);
944
- if (oldContent === newContent) {
945
- logger.info(`[syncSinglePage] 🟡 页面 ${pageTitle} 内容未改变,跳过`);
946
- return { success: true, reason: "no_change" };
947
954
  }
948
- await newSite.save(pageTitle, oldContent, `由:${user} 触发更改,此时同步`);
949
- logger.info(`[syncSinglePage] ✅ 页面 ${pageTitle} 同步成功`);
950
- return { success: true, reason: "synced" };
951
- } catch (error) {
952
- const errMsg = error instanceof Error ? error.message : String(error);
953
- logger.error(`[syncSinglePage] ❌ 页面 ${pageTitle} 同步失败:`, errMsg);
954
- return { success: false, reason: errMsg };
955
955
  }
956
- }
957
- __name(syncSinglePage, "syncSinglePage");
958
- async function getAllPages(site) {
959
- logger.info(
960
- `[SyncAllPages] 📥 开始获取原站点所有页面(命名空间${CONFIG2.NAMESPACE})`
961
- );
962
- const allPages = [];
963
- const queryGen = site.continuedQueryGen({
964
- action: "query",
965
- list: "allpages",
966
- apnamespace: CONFIG2.NAMESPACE,
967
- aplimit: CONFIG2.BATCH_LIMIT,
968
- apdir: "ascending"
969
- });
970
- for await (const res of queryGen) {
971
- const pageTitles = res.query?.allpages?.map((page) => page.title) || [];
972
- allPages.push(...pageTitles);
973
- logger.info(`[SyncAllPages] 📄 已获取 ${allPages.length} 个页面`);
974
- }
975
- logger.info(`[SyncAllPages] 📊 原站点总计获取到 ${allPages.length} 个页面`);
976
- return allPages;
977
- }
978
- __name(getAllPages, "getAllPages");
979
- async function processPageWithStats(oldSite, newSite, pageTitle, user, stats, failedPages) {
980
- const syncResult = await syncSinglePage(oldSite, newSite, pageTitle, user);
981
- if (!syncResult.success) {
982
- stats.failCount++;
983
- failedPages.push(pageTitle);
984
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_FAILED);
985
- } else {
986
- stats.successCount++;
987
- if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
988
- stats.skipCount++;
956
+ /** 更新页面贡献者信息到数据库 */
957
+ async updateContributorToDatabase(title, user, timestamp) {
958
+ const database = this.database;
959
+ if (!database) return;
960
+ try {
961
+ await this.retryDb(async () => {
962
+ await database.set(
963
+ "wikipages",
964
+ { title },
965
+ {
966
+ contributor: user,
967
+ change_time: formatWikiTime(timestamp)
968
+ }
969
+ );
970
+ logger.debug(
971
+ `[数据库更新] ✅ 页面 ${title} 的贡献者信息已更新: ${user}`
972
+ );
973
+ });
974
+ } catch (err) {
975
+ logger.warn(
976
+ `[数据库更新] ❌ 更新页面 ${title} 的贡献者信息失败: ${getErrorMessage(err)}`
977
+ );
989
978
  }
990
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_SUCCESS);
991
979
  }
992
- }
993
- __name(processPageWithStats, "processPageWithStats");
994
- function printProgress(current, total, pageTitle) {
995
- const progress = (current / total * 100).toFixed(1);
996
- const remaining = total - current;
997
- logger.info(
998
- `
999
- [SyncAllPages] 📈 进度 [${current}/${total}] (${progress}%) - 处理 ${pageTitle} | 剩余 ${remaining} 个`
1000
- );
1001
- }
1002
- __name(printProgress, "printProgress");
1003
- function printFinalReport(total, successCount, failCount, skipCount, stillFailed) {
1004
- logger.info(`
1005
- [SyncAllPages] 📋 ===== 最终同步报告 =====`);
1006
- if (stillFailed.length > 0) {
1007
- logger.info(`❌ 以下页面经过重试仍然失败,请手动检查:`);
1008
- stillFailed.forEach((title, idx) => {
1009
- logger.info(` ${idx + 1}. ${title}`);
1010
- });
1011
- } else {
1012
- logger.info(`🎉 所有页面同步成功(含重试)!`);
1013
- }
1014
- logger.info(`
1015
- [SyncAllPages] 🎯 同步流程结束!`);
1016
- logger.info(`├─ 总计:${total} 个页面`);
1017
- logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
1018
- logger.info(`└─ 失败:${failCount} 个`);
1019
- }
1020
- __name(printFinalReport, "printFinalReport");
1021
- async function syncPages(oldSite, newSite) {
1022
- try {
1023
- const oldPageList = await getAllPages(oldSite);
1024
- const total = oldPageList.length;
1025
- if (total === 0) {
1026
- logger.info(`[SyncAllPages] 📭 原站点无页面可同步,结束`);
1027
- return;
980
+ // ------------------------------------------------------------ 单页 / 全量
981
+ async syncOne(pageTitle, user) {
982
+ if (this.options.ignoredPages.has(pageTitle)) {
983
+ logger.info(`[syncSinglePage] 🚫 页面 ${pageTitle} 在忽略列表中,跳过`);
984
+ return { success: true, reason: "ignored" };
1028
985
  }
1029
- const stats = { successCount: 0, failCount: 0, skipCount: 0 };
1030
- const failedPages = [];
1031
- logger.info(`[SyncAllPages] 🚦 开始批量同步,总计 ${total} 个页面`);
1032
- for (let index = 0; index < total; index++) {
1033
- const pageTitle = oldPageList[index];
1034
- printProgress(index + 1, total, pageTitle);
1035
- await processPageWithStats(
1036
- oldSite,
1037
- newSite,
986
+ try {
987
+ logger.info(`[syncSinglePage] 🚀 开始同步页面: ${pageTitle}`);
988
+ const [oldContent, newContent] = await Promise.all([
989
+ getAndProcessPageContent(this.source, pageTitle),
990
+ getAndProcessPageContent(this.target, pageTitle)
991
+ ]);
992
+ if (oldContent === newContent) {
993
+ logger.info(`[syncSinglePage] 🟡 页面 ${pageTitle} 内容未改变,跳过`);
994
+ return { success: true, reason: "no_change" };
995
+ }
996
+ await this.target.save(
1038
997
  pageTitle,
1039
- CONFIG2.DEFAULT_USER,
1040
- stats,
1041
- failedPages
1042
- );
1043
- }
1044
- let stillFailed = [];
1045
- if (failedPages.length > 0) {
1046
- logger.info(
1047
- `
1048
- [SyncAllPages] 🔄 ===== 开始重试 ${failedPages.length} 个失败页面 =====`
998
+ oldContent,
999
+ `由:${user} 触发更改,此时同步`
1049
1000
  );
1050
- for (const pageTitle of failedPages) {
1051
- logger.info(`
1052
- [SyncAllPages] 🔁 重试中: ${pageTitle}`);
1053
- const syncResult = await syncSinglePage(
1054
- oldSite,
1055
- newSite,
1056
- pageTitle,
1057
- CONFIG2.DEFAULT_USER
1058
- );
1059
- if (syncResult.success) {
1060
- stats.successCount++;
1061
- stats.failCount--;
1062
- if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
1063
- stats.skipCount++;
1064
- }
1065
- logger.info(`[SyncAllPages] ✅ 页面 ${pageTitle} 重试成功`);
1066
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_SUCCESS);
1067
- } else {
1068
- stillFailed.push(pageTitle);
1069
- logger.info(`[SyncAllPages] ❌ 页面 ${pageTitle} 再次失败`);
1070
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_FAILED);
1071
- }
1072
- }
1001
+ logger.info(`[syncSinglePage] ✅ 页面 ${pageTitle} 同步成功`);
1002
+ return { success: true, reason: "synced" };
1003
+ } catch (error) {
1004
+ const errMsg = getErrorMessage(error);
1005
+ logger.error(`[syncSinglePage] ❌ 页面 ${pageTitle} 同步失败:`, errMsg);
1006
+ return { success: false, reason: errMsg };
1073
1007
  }
1074
- printFinalReport(
1075
- total,
1076
- stats.successCount,
1077
- stats.failCount,
1078
- stats.skipCount,
1079
- stillFailed
1080
- );
1081
- } catch (globalError) {
1082
- logger.error(`[SyncAllPages] 💥 批量同步流程异常终止:`, globalError);
1083
- throw globalError;
1084
1008
  }
1085
- }
1086
- __name(syncPages, "syncPages");
1087
- async function incrementalUpdate(oldSite, newSite, config, onSynced, database) {
1088
- const startTime = Date.now();
1089
- const processedTitles = /* @__PURE__ */ new Set();
1090
- const syncedItems = [];
1091
- let totalProcessed = 0;
1092
- let totalSkipped = 0;
1093
- let totalSynced = 0;
1094
- try {
1095
- const now = /* @__PURE__ */ new Date();
1096
- const threeHoursAgo = new Date(now.getTime() - 3 * 60 * 60 * 1e3);
1009
+ async listAll() {
1097
1010
  logger.info(
1098
- `[增量更新流程] ⏰ 开始处理 ${threeHoursAgo.toISOString()} 到 ${now.toISOString()} 的更新...`
1011
+ `[SyncAllPages] 📥 开始获取原站点所有页面(命名空间${this.options.namespace})`
1099
1012
  );
1100
- const queryGen = oldSite.continuedQueryGen({
1013
+ const allPages = [];
1014
+ const queryGen = this.source.continuedQueryGen({
1101
1015
  action: "query",
1102
- list: "recentchanges",
1103
- rcstart: now.toISOString(),
1104
- rcend: threeHoursAgo.toISOString(),
1105
- rcdir: "older",
1106
- rcprop: "user|comment|title|timestamp|ids"
1016
+ list: "allpages",
1017
+ apnamespace: this.options.namespace,
1018
+ aplimit: this.options.batchLimit,
1019
+ apdir: "ascending"
1107
1020
  });
1108
1021
  for await (const res of queryGen) {
1109
- const pages = res.query?.recentchanges || [];
1110
- for (const page of pages) {
1111
- const {
1112
- title,
1113
- user: rcUser,
1114
- timestamp: rcTimestamp,
1115
- comment: rcComment,
1116
- pageid
1117
- } = page;
1118
- if (processedTitles.has(title)) {
1119
- logger.debug(`[增量更新流程] ⏭️ 已处理过 ${title}, 跳过`);
1120
- totalSkipped++;
1121
- continue;
1122
- }
1123
- if (CONFIG2.IGNORED_PAGES.has(title)) {
1124
- logger.info(
1125
- `[增量更新流程] 🚫 ${title} 在无需处理的页面列表中, 跳过`
1022
+ const pageTitles = res.query?.allpages?.map((page) => page.title) || [];
1023
+ allPages.push(...pageTitles);
1024
+ logger.info(`[SyncAllPages] 📄 已获取 ${allPages.length} 个页面`);
1025
+ }
1026
+ logger.info(`[SyncAllPages] 📊 原站点总计获取到 ${allPages.length} 个页面`);
1027
+ return allPages;
1028
+ }
1029
+ async processPageWithStats(pageTitle, user, stats, failedPages) {
1030
+ const syncResult = await this.syncOne(pageTitle, user);
1031
+ if (!syncResult.success) {
1032
+ stats.failCount++;
1033
+ failedPages.push(pageTitle);
1034
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
1035
+ } else {
1036
+ stats.successCount++;
1037
+ if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
1038
+ stats.skipCount++;
1039
+ }
1040
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
1041
+ }
1042
+ }
1043
+ printProgress(current, total, pageTitle) {
1044
+ const progress = (current / total * 100).toFixed(1);
1045
+ const remaining = total - current;
1046
+ logger.info(
1047
+ `
1048
+ [SyncAllPages] 📈 进度 [${current}/${total}] (${progress}%) - 处理 ${pageTitle} | 剩余 ${remaining} 个`
1049
+ );
1050
+ }
1051
+ printFinalReport(total, successCount, failCount, skipCount, stillFailed) {
1052
+ logger.info(`
1053
+ [SyncAllPages] 📋 ===== 最终同步报告 =====`);
1054
+ if (stillFailed.length > 0) {
1055
+ logger.info(`❌ 以下页面经过重试仍然失败,请手动检查:`);
1056
+ stillFailed.forEach((title, idx) => {
1057
+ logger.info(` ${idx + 1}. ${title}`);
1058
+ });
1059
+ } else {
1060
+ logger.info(`🎉 所有页面同步成功(含重试)!`);
1061
+ }
1062
+ logger.info(`
1063
+ [SyncAllPages] 🎯 同步流程结束!`);
1064
+ logger.info(`├─ 总计:${total} 个页面`);
1065
+ logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
1066
+ logger.info(`└─ 失败:${failCount} 个`);
1067
+ }
1068
+ /** 全量同步所有页面:先串行同步一轮,再重试失败的 */
1069
+ async syncAll() {
1070
+ try {
1071
+ const oldPageList = await this.listAll();
1072
+ const total = oldPageList.length;
1073
+ if (total === 0) {
1074
+ logger.info(`[SyncAllPages] 📭 原站点无页面可同步,结束`);
1075
+ return;
1076
+ }
1077
+ const stats = {
1078
+ successCount: 0,
1079
+ failCount: 0,
1080
+ skipCount: 0
1081
+ };
1082
+ const failedPages = [];
1083
+ logger.info(`[SyncAllPages] 🚦 开始批量同步,总计 ${total} 个页面`);
1084
+ for (let index = 0; index < total; index++) {
1085
+ const pageTitle = oldPageList[index];
1086
+ this.printProgress(index + 1, total, pageTitle);
1087
+ await this.processPageWithStats(
1088
+ pageTitle,
1089
+ this.options.defaultUser,
1090
+ stats,
1091
+ failedPages
1092
+ );
1093
+ }
1094
+ const stillFailed = [];
1095
+ if (failedPages.length > 0) {
1096
+ logger.info(
1097
+ `
1098
+ [SyncAllPages] 🔄 ===== 开始重试 ${failedPages.length} 个失败页面 =====`
1099
+ );
1100
+ for (const pageTitle of failedPages) {
1101
+ logger.info(`
1102
+ [SyncAllPages] 🔁 重试中: ${pageTitle}`);
1103
+ const syncResult = await this.syncOne(
1104
+ pageTitle,
1105
+ this.options.defaultUser
1126
1106
  );
1127
- processedTitles.add(title);
1128
- totalSkipped++;
1129
- continue;
1130
- }
1131
- processedTitles.add(title);
1132
- totalProcessed++;
1133
- try {
1134
- const user = rcUser || "未知";
1135
- const timestamp = rcTimestamp || "";
1136
- const comment = rcComment || "";
1137
- if (title.startsWith(CONFIG2.FILE_NAMESPACE_PREFIX)) {
1138
- await handleImageSync(
1139
- oldSite,
1140
- newSite,
1141
- title,
1142
- user,
1143
- timestamp,
1144
- comment,
1145
- config,
1146
- syncedItems
1147
- );
1107
+ if (syncResult.success) {
1108
+ stats.successCount++;
1109
+ stats.failCount--;
1110
+ if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
1111
+ stats.skipCount++;
1112
+ }
1113
+ logger.info(`[SyncAllPages] ✅ 页面 ${pageTitle} 重试成功`);
1114
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
1148
1115
  } else {
1149
- await handlePageSync(
1150
- oldSite,
1151
- newSite,
1152
- title,
1153
- pageid || 0,
1154
- user,
1155
- timestamp,
1156
- comment,
1157
- database,
1158
- syncedItems
1159
- );
1160
- totalSynced++;
1116
+ stillFailed.push(pageTitle);
1117
+ logger.info(`[SyncAllPages] ❌ 页面 ${pageTitle} 再次失败`);
1118
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
1161
1119
  }
1162
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_SUCCESS);
1163
- } catch (error) {
1164
- const errMsg = error instanceof Error ? error.message : String(error);
1165
- logger.error(`[增量更新流程] ❌ 处理 ${title} 时出错:`, errMsg);
1166
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_FAILED);
1167
1120
  }
1168
1121
  }
1169
- }
1170
- } catch (globalError) {
1171
- logger.error(`[增量更新流程] 💥 增量更新流程异常终止:`, globalError);
1172
- throw globalError;
1173
- } finally {
1174
- const duration = (Date.now() - startTime) / 1e3;
1175
- logger.info(
1176
- `[增量更新流程] ✅ 增量更新完成!处理: ${totalProcessed}, 跳过: ${totalSkipped}, 同步: ${totalSynced}, 通知: ${syncedItems.length}, 耗时: ${duration.toFixed(2)}s`
1177
- );
1178
- if (syncedItems.length > 0) {
1179
- onSynced?.(syncedItems);
1122
+ this.printFinalReport(
1123
+ total,
1124
+ stats.successCount,
1125
+ stats.failCount,
1126
+ stats.skipCount,
1127
+ stillFailed
1128
+ );
1129
+ } catch (globalError) {
1130
+ logger.error(`[SyncAllPages] 💥 批量同步流程异常终止:`, globalError);
1131
+ throw globalError;
1180
1132
  }
1181
1133
  }
1182
- }
1183
- __name(incrementalUpdate, "incrementalUpdate");
1184
- async function handleImageSync(oldSite, newSite, title, user, timestamp, comment, config, syncedItems) {
1185
- const fileName = title.replace(CONFIG2.FILE_NAMESPACE_PREFIX, "");
1186
- logger.info(`[增量更新流程] 🖼️ 检查到图片: ${title},正在尝试转存`);
1187
- const result = await syncSingleImage(oldSite, newSite, fileName, config);
1188
- if (result.success && result.reason === "synced") {
1189
- syncedItems.push({
1190
- title,
1191
- type: "image",
1192
- user,
1193
- timestamp,
1194
- comment
1195
- });
1134
+ // ---------------------------------------------------------------- 增量更新
1135
+ /**
1136
+ * 增量更新:取最近 3 小时的 recentchanges 并逐条同步。
1137
+ *
1138
+ * 结束时通过构造时注入的 `notify` 一次性回调成功条目
1139
+ * (仅 reason==="synced" 的页面与图片)。
1140
+ */
1141
+ async incrementalUpdate() {
1142
+ const startTime = Date.now();
1143
+ const processedTitles = /* @__PURE__ */ new Set();
1144
+ const syncedItems = [];
1145
+ let totalProcessed = 0;
1146
+ let totalSkipped = 0;
1147
+ let totalSynced = 0;
1148
+ try {
1149
+ const now = /* @__PURE__ */ new Date();
1150
+ const threeHoursAgo = new Date(now.getTime() - 3 * 60 * 60 * 1e3);
1151
+ logger.info(
1152
+ `[增量更新流程] ⏰ 开始处理 ${threeHoursAgo.toISOString()} 到 ${now.toISOString()} 的更新...`
1153
+ );
1154
+ const queryGen = this.source.continuedQueryGen({
1155
+ action: "query",
1156
+ list: "recentchanges",
1157
+ rcstart: now.toISOString(),
1158
+ rcend: threeHoursAgo.toISOString(),
1159
+ rcdir: "older",
1160
+ rcprop: "user|comment|title|timestamp|ids"
1161
+ });
1162
+ for await (const res of queryGen) {
1163
+ const pages = res.query?.recentchanges || [];
1164
+ for (const page of pages) {
1165
+ const {
1166
+ title,
1167
+ user: rcUser,
1168
+ timestamp: rcTimestamp,
1169
+ comment: rcComment,
1170
+ pageid
1171
+ } = page;
1172
+ if (processedTitles.has(title)) {
1173
+ logger.debug(`[增量更新流程] ⏭️ 已处理过 ${title}, 跳过`);
1174
+ totalSkipped++;
1175
+ continue;
1176
+ }
1177
+ if (this.options.ignoredPages.has(title)) {
1178
+ logger.info(
1179
+ `[增量更新流程] 🚫 ${title} 在无需处理的页面列表中, 跳过`
1180
+ );
1181
+ processedTitles.add(title);
1182
+ totalSkipped++;
1183
+ continue;
1184
+ }
1185
+ processedTitles.add(title);
1186
+ totalProcessed++;
1187
+ try {
1188
+ const user = rcUser || "未知";
1189
+ const timestamp = rcTimestamp || "";
1190
+ const comment = rcComment || "";
1191
+ if (title.startsWith(this.options.fileNamespacePrefix)) {
1192
+ await this.handleImageSync(
1193
+ title,
1194
+ user,
1195
+ timestamp,
1196
+ comment,
1197
+ syncedItems
1198
+ );
1199
+ } else {
1200
+ await this.handlePageSync(
1201
+ title,
1202
+ pageid || 0,
1203
+ user,
1204
+ timestamp,
1205
+ comment,
1206
+ syncedItems
1207
+ );
1208
+ totalSynced++;
1209
+ }
1210
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
1211
+ } catch (error) {
1212
+ const errMsg = getErrorMessage(error);
1213
+ logger.error(`[增量更新流程] ❌ 处理 ${title} 时出错:`, errMsg);
1214
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
1215
+ }
1216
+ }
1217
+ }
1218
+ } catch (globalError) {
1219
+ logger.error(`[增量更新流程] 💥 增量更新流程异常终止:`, globalError);
1220
+ throw globalError;
1221
+ } finally {
1222
+ const duration = (Date.now() - startTime) / 1e3;
1223
+ logger.info(
1224
+ `[增量更新流程] ✅ 增量更新完成!处理: ${totalProcessed}, 跳过: ${totalSkipped}, 同步: ${totalSynced}, 通知: ${syncedItems.length}, 耗时: ${duration.toFixed(2)}s`
1225
+ );
1226
+ if (syncedItems.length > 0) {
1227
+ this.notify?.(syncedItems);
1228
+ }
1229
+ }
1196
1230
  }
1197
- }
1198
- __name(handleImageSync, "handleImageSync");
1199
- async function handlePageSync(oldSite, newSite, title, pageId, user, timestamp, comment, database, syncedItems) {
1200
- await ensurePageInDatabase(database, pageId, title);
1201
- const result = await syncSinglePage(oldSite, newSite, title, user);
1202
- if (result.success) {
1203
- if (result.reason === "synced") {
1231
+ /** 增量更新中遇到图片页面时的处理 */
1232
+ async handleImageSync(title, user, timestamp, comment, syncedItems) {
1233
+ const fileName = title.replace(this.options.fileNamespacePrefix, "");
1234
+ logger.info(`[增量更新流程] 🖼️ 检查到图片: ${title},正在尝试转存`);
1235
+ const result = await this.images.syncOne(fileName);
1236
+ if (result.success && result.reason === "synced") {
1204
1237
  syncedItems.push({
1205
1238
  title,
1206
- type: "page",
1239
+ type: "image",
1207
1240
  user,
1208
1241
  timestamp,
1209
1242
  comment
1210
1243
  });
1211
1244
  }
1212
- await updateContributorToDatabase(database, title, user, timestamp);
1213
1245
  }
1214
- }
1215
- __name(handlePageSync, "handlePageSync");
1246
+ /** 增量更新中遇到普通页面时的处理 */
1247
+ async handlePageSync(title, pageId, user, timestamp, comment, syncedItems) {
1248
+ await this.ensurePageInDatabase(pageId, title);
1249
+ const result = await this.syncOne(title, user);
1250
+ if (result.success) {
1251
+ if (result.reason === "synced") {
1252
+ syncedItems.push({
1253
+ title,
1254
+ type: "page",
1255
+ user,
1256
+ timestamp,
1257
+ comment
1258
+ });
1259
+ }
1260
+ await this.updateContributorToDatabase(title, user, timestamp);
1261
+ }
1262
+ }
1263
+ };
1216
1264
 
1217
1265
  // src/sync/moduleSync.ts
1218
- var import_koishi7 = require("koishi");
1219
- var CONFIG3 = {
1220
- MODULE_NAMESPACE: 828,
1221
- // 模块命名空间
1222
- IGNORED_MODULES: [],
1223
- // 忽略的模块列表
1224
- SYNC_INTERVAL_SUCCESS: 500,
1225
- // 同步成功后等待时间(毫秒)
1226
- SYNC_INTERVAL_FAILED: 1e3
1227
- // 同步失败后等待时间(毫秒)
1266
+ var DEFAULT_OPTIONS3 = {
1267
+ moduleNamespace: 828,
1268
+ ignoredModules: [],
1269
+ intervalSuccess: 500,
1270
+ intervalFailed: 1e3
1228
1271
  };
1229
- async function syncSingleModule(oldSite, newSite, moduleTitle, user) {
1230
- if (CONFIG3.IGNORED_MODULES.includes(moduleTitle)) {
1231
- logger.info(`[SyncModule] 🚫 模块 ${moduleTitle} 在忽略列表中,跳过`);
1232
- return { success: true, reason: "ignored" };
1272
+ var DEFAULT_USER = "同步坤器人";
1273
+ var ModuleSyncer = class {
1274
+ constructor(source, target, deps = {}) {
1275
+ this.source = source;
1276
+ this.target = target;
1277
+ this.options = { ...DEFAULT_OPTIONS3, ...deps.options };
1233
1278
  }
1234
- try {
1235
- logger.info(`[SyncModule] 🔍 开始获取模块 ${moduleTitle} 的内容`);
1236
- let targetTitle = moduleTitle;
1237
- if (/^Dev:/i.test(moduleTitle)) {
1238
- const subPageName = moduleTitle.replace(/^Dev:/i, "");
1239
- targetTitle = `Module:Dev/${subPageName}`;
1240
- logger.info(
1241
- `[SyncModule] 🔀 检测到 Dev 命名空间,路径映射: ${moduleTitle} -> ${targetTitle}`
1279
+ static {
1280
+ __name(this, "ModuleSyncer");
1281
+ }
1282
+ options;
1283
+ async syncOne(moduleTitle, user) {
1284
+ if (this.options.ignoredModules.includes(moduleTitle)) {
1285
+ logger.info(`[SyncModule] 🚫 模块 ${moduleTitle} 在忽略列表中,跳过`);
1286
+ return { success: true, reason: "ignored" };
1287
+ }
1288
+ try {
1289
+ logger.info(`[SyncModule] 🔍 开始获取模块 ${moduleTitle} 的内容`);
1290
+ let targetTitle = moduleTitle;
1291
+ if (/^Dev:/i.test(moduleTitle)) {
1292
+ const subPageName = moduleTitle.replace(/^Dev:/i, "");
1293
+ targetTitle = `Module:Dev/${subPageName}`;
1294
+ logger.info(
1295
+ `[SyncModule] 🔀 检测到 Dev 命名空间,路径映射: ${moduleTitle} -> ${targetTitle}`
1296
+ );
1297
+ }
1298
+ const [oldContent, newContent] = await Promise.all([
1299
+ getAndProcessPageContent(this.source, moduleTitle),
1300
+ getAndProcessPageContent(this.target, targetTitle)
1301
+ ]);
1302
+ if (oldContent === newContent) {
1303
+ logger.info(`[SyncModule] 🟡 模块 ${moduleTitle} 内容未改变,跳过`);
1304
+ return { success: true, reason: "no_change" };
1305
+ }
1306
+ await this.target.save(
1307
+ targetTitle,
1308
+ oldContent,
1309
+ `由:${user || "同步坤器人手动"} 触发更改,此时同步`
1242
1310
  );
1311
+ logger.info(`[SyncModule] ✅ 模块 ${moduleTitle} 同步成功`);
1312
+ return { success: true, reason: "synced" };
1313
+ } catch (error) {
1314
+ const errMsg = getErrorMessage(error);
1315
+ logger.error(`[SyncModule] ❌ 模块 ${moduleTitle} 同步失败:`, errMsg);
1316
+ return { success: false, reason: errMsg };
1243
1317
  }
1244
- const [oldContent, newContent] = await Promise.all([
1245
- getAndProcessPageContent(oldSite, moduleTitle),
1246
- getAndProcessPageContent(newSite, targetTitle)
1247
- ]);
1248
- if (oldContent === newContent) {
1249
- logger.info(`[SyncModule] 🟡 模块 ${moduleTitle} 内容未改变,跳过`);
1250
- return { success: true, reason: "no_change" };
1318
+ }
1319
+ async listAll() {
1320
+ logger.info(
1321
+ `[SyncAllModules] 📥 开始获取原站点所有模块(命名空间${this.options.moduleNamespace})`
1322
+ );
1323
+ const allModules = [];
1324
+ const queryGen = this.source.continuedQueryGen({
1325
+ action: "query",
1326
+ list: "allpages",
1327
+ apnamespace: this.options.moduleNamespace,
1328
+ aplimit: "max",
1329
+ apdir: "ascending"
1330
+ });
1331
+ for await (const res of queryGen) {
1332
+ const titles = res.query?.allpages?.map((page) => page.title) || [];
1333
+ allModules.push(...titles);
1334
+ logger.info(`[SyncAllModules] 📄 已获取 ${allModules.length} 个模块`);
1251
1335
  }
1252
- await newSite.save(
1253
- targetTitle,
1254
- oldContent,
1255
- `由:${user || "同步坤器人手动"} 触发更改,此时同步`
1336
+ logger.info(
1337
+ `[SyncAllModules] 📊 原站点总计获取到 ${allModules.length} 个模块`
1256
1338
  );
1257
- logger.info(`[SyncModule] ✅ 模块 ${moduleTitle} 同步成功`);
1258
- return { success: true, reason: "synced" };
1259
- } catch (error) {
1260
- const errMsg = error.message || String(error);
1261
- logger.error(`[SyncModule] ❌ 模块 ${moduleTitle} 同步失败:`, errMsg);
1262
- return { success: false, reason: errMsg };
1263
- }
1264
- }
1265
- __name(syncSingleModule, "syncSingleModule");
1266
- async function getAllModules(site) {
1267
- logger.info(
1268
- `[SyncAllModules] 📥 开始获取原站点所有模块(命名空间${CONFIG3.MODULE_NAMESPACE})`
1269
- );
1270
- const allModules = [];
1271
- const queryGen = site.continuedQueryGen({
1272
- action: "query",
1273
- list: "allpages",
1274
- apnamespace: CONFIG3.MODULE_NAMESPACE,
1275
- // 模块命名空间
1276
- aplimit: "max",
1277
- apdir: "ascending"
1278
- });
1279
- for await (const res of queryGen) {
1280
- const moduleTitles = res.query?.allpages?.map((page) => page.title) || [];
1281
- allModules.push(...moduleTitles);
1282
- logger.info(`[SyncAllModules] 📄 已获取 ${allModules.length} 个模块`);
1339
+ return allModules;
1283
1340
  }
1284
- logger.info(
1285
- `[SyncAllModules] 📊 原站点总计获取到 ${allModules.length} 个模块`
1286
- );
1287
- return allModules;
1288
- }
1289
- __name(getAllModules, "getAllModules");
1290
- async function syncModules(oldSite, newSite) {
1291
- try {
1292
- const oldModuleList = await getAllModules(oldSite);
1293
- const total = oldModuleList.length;
1294
- if (total === 0) {
1295
- logger.info(`[SyncAllModules] 📭 原站点无模块可同步,结束`);
1296
- return;
1297
- }
1298
- let successCount = 0;
1299
- let failCount = 0;
1300
- let skipCount = 0;
1301
- const failedModules = [];
1302
- logger.info(`[SyncAllModules] 🚦 开始批量同步,总计 ${total} 个模块`);
1303
- for (let index = 0; index < total; index++) {
1304
- const moduleTitle = oldModuleList[index];
1305
- const current = index + 1;
1306
- const remaining = total - current;
1307
- const progress = (current / total * 100).toFixed(1);
1308
- logger.info(
1309
- `
1341
+ /** 批量同步所有模块:先串行同步一轮,再重试失败的 */
1342
+ async syncAll() {
1343
+ try {
1344
+ const oldModuleList = await this.listAll();
1345
+ const total = oldModuleList.length;
1346
+ if (total === 0) {
1347
+ logger.info(`[SyncAllModules] 📭 原站点无模块可同步,结束`);
1348
+ return;
1349
+ }
1350
+ let successCount = 0;
1351
+ let failCount = 0;
1352
+ let skipCount = 0;
1353
+ const failedModules = [];
1354
+ logger.info(`[SyncAllModules] 🚦 开始批量同步,总计 ${total} 个模块`);
1355
+ for (let index = 0; index < total; index++) {
1356
+ const moduleTitle = oldModuleList[index];
1357
+ const current = index + 1;
1358
+ const remaining = total - current;
1359
+ const progress = (current / total * 100).toFixed(1);
1360
+ logger.info(
1361
+ `
1310
1362
  [SyncAllModules] 📈 进度 [${current}/${total}] (${progress}%) - 处理 ${moduleTitle} | 剩余 ${remaining} 个`
1311
- );
1312
- const syncResult = await syncSingleModule(
1313
- oldSite,
1314
- newSite,
1315
- moduleTitle,
1316
- "同步坤器人"
1317
- );
1318
- if (!syncResult.success) {
1319
- failCount++;
1320
- failedModules.push(moduleTitle);
1321
- await (0, import_koishi7.sleep)(CONFIG3.SYNC_INTERVAL_FAILED);
1322
- } else {
1323
- successCount++;
1324
- if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
1325
- skipCount++;
1363
+ );
1364
+ const result = await this.syncOne(moduleTitle, DEFAULT_USER);
1365
+ if (!result.success) {
1366
+ failCount++;
1367
+ failedModules.push(moduleTitle);
1368
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
1369
+ } else {
1370
+ successCount++;
1371
+ if (result.reason === "ignored" || result.reason === "no_change") {
1372
+ skipCount++;
1373
+ }
1374
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
1326
1375
  }
1327
- await (0, import_koishi7.sleep)(CONFIG3.SYNC_INTERVAL_SUCCESS);
1328
1376
  }
1329
- }
1330
- if (failedModules.length > 0) {
1331
- logger.info(
1332
- `
1377
+ if (failedModules.length > 0) {
1378
+ logger.info(
1379
+ `
1333
1380
  [SyncAllModules] 🔄 ===== 开始重试 ${failedModules.length} 个失败模块 =====`
1334
- );
1335
- const stillFailed = [];
1336
- for (const moduleTitle of failedModules) {
1337
- logger.info(`
1338
- [SyncAllModules] 🔁 重试中: ${moduleTitle}`);
1339
- const syncResult = await syncSingleModule(
1340
- oldSite,
1341
- newSite,
1342
- moduleTitle,
1343
- "同步坤器人"
1344
1381
  );
1345
- if (syncResult.success) {
1346
- successCount++;
1347
- failCount--;
1348
- if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
1349
- skipCount++;
1382
+ const stillFailed = [];
1383
+ for (const moduleTitle of failedModules) {
1384
+ logger.info(`
1385
+ [SyncAllModules] 🔁 重试中: ${moduleTitle}`);
1386
+ const result = await this.syncOne(moduleTitle, DEFAULT_USER);
1387
+ if (result.success) {
1388
+ successCount++;
1389
+ failCount--;
1390
+ if (result.reason === "ignored" || result.reason === "no_change") {
1391
+ skipCount++;
1392
+ }
1393
+ logger.info(`[SyncAllModules] ✅ 模块 ${moduleTitle} 重试成功`);
1394
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
1395
+ } else {
1396
+ stillFailed.push(moduleTitle);
1397
+ logger.info(`[SyncAllModules] ❌ 模块 ${moduleTitle} 再次失败`);
1398
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
1350
1399
  }
1351
- logger.info(`[SyncAllModules] ✅ 模块 ${moduleTitle} 重试成功`);
1352
- await (0, import_koishi7.sleep)(CONFIG3.SYNC_INTERVAL_SUCCESS);
1400
+ }
1401
+ logger.info(`
1402
+ [SyncAllModules] 📋 ===== 最终同步报告 =====`);
1403
+ if (stillFailed.length > 0) {
1404
+ logger.info(`❌ 以下模块经过重试仍然失败,请手动检查:`);
1405
+ stillFailed.forEach((title, idx) => {
1406
+ logger.info(` ${idx + 1}. ${title}`);
1407
+ });
1353
1408
  } else {
1354
- stillFailed.push(moduleTitle);
1355
- logger.info(`[SyncAllModules] ❌ 模块 ${moduleTitle} 再次失败`);
1356
- await (0, import_koishi7.sleep)(CONFIG3.SYNC_INTERVAL_FAILED);
1409
+ logger.info(`🎉 所有模块同步成功(含重试)!`);
1357
1410
  }
1358
1411
  }
1359
1412
  logger.info(`
1360
- [SyncAllModules] 📋 ===== 最终同步报告 =====`);
1361
- if (stillFailed.length > 0) {
1362
- logger.info(`❌ 以下模块经过重试仍然失败,请手动检查:`);
1363
- stillFailed.forEach((title, idx) => {
1364
- logger.info(` ${idx + 1}. ${title}`);
1365
- });
1366
- } else {
1367
- logger.info(`🎉 所有模块同步成功(含重试)!`);
1413
+ [SyncAllModules] 🎯 同步完成!`);
1414
+ logger.info(`├─ 总计:${total} 个模块`);
1415
+ logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
1416
+ logger.info(`└─ 失败:${failCount} 个`);
1417
+ } catch (error) {
1418
+ logger.error(
1419
+ `[SyncAllModules] 💥 批量同步流程异常终止:`,
1420
+ getErrorMessage(error)
1421
+ );
1422
+ throw error;
1423
+ }
1424
+ }
1425
+ };
1426
+
1427
+ // src/services/syncNotifier.ts
1428
+ var SyncNotifier = class {
1429
+ constructor(ctx, groupIds = [], platform = "qq") {
1430
+ this.ctx = ctx;
1431
+ this.groupIds = groupIds;
1432
+ this.platform = platform || "qq";
1433
+ }
1434
+ static {
1435
+ __name(this, "SyncNotifier");
1436
+ }
1437
+ groupIds;
1438
+ platform;
1439
+ get enabled() {
1440
+ return this.groupIds.length > 0;
1441
+ }
1442
+ async notify(items) {
1443
+ if (items.length === 0) return;
1444
+ try {
1445
+ const bots = this.activeBots();
1446
+ if (bots.length === 0) {
1447
+ logger.warn(
1448
+ `[通知] 未找到可用的 ${this.platform} 平台 bot,跳过群通知`
1449
+ );
1450
+ return;
1451
+ }
1452
+ const message = this.formatMessage(items);
1453
+ for (const bot of bots) {
1454
+ for (const rawChannelId of this.groupIds) {
1455
+ const channelId = normalizeChannelId(rawChannelId);
1456
+ if (!channelId) continue;
1457
+ try {
1458
+ await bot.sendMessage(channelId, message);
1459
+ logger.info(
1460
+ `[通知] 向 ${bot.platform}/${channelId} 推送成功 (${items.length} 条)`
1461
+ );
1462
+ } catch (error) {
1463
+ logger.error(
1464
+ `[通知] 向 ${bot.platform}/${channelId} 发送消息失败:`,
1465
+ getErrorMessage(error)
1466
+ );
1467
+ }
1468
+ }
1368
1469
  }
1470
+ } catch (error) {
1471
+ logger.error(`[通知] 处理通知过程出错:`, getErrorMessage(error));
1369
1472
  }
1370
- logger.info(`
1371
- [SyncAllModules] 🎯 同步完成!`);
1372
- logger.info(`├─ 总计:${total} 个模块`);
1373
- logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
1374
- logger.info(`└─ 失败:${failCount} 个`);
1375
- } catch (error) {
1376
- const errorMsg = getErrorMessage(error);
1377
- logger.error(`[SyncAllModules] 💥 批量同步流程异常终止:`, errorMsg);
1378
- throw error;
1379
1473
  }
1380
- }
1381
- __name(syncModules, "syncModules");
1474
+ activeBots() {
1475
+ const bots = [];
1476
+ for (const bot of this.ctx.bots) {
1477
+ if (bot.platform === this.platform && bot.isActive) {
1478
+ bots.push(bot);
1479
+ }
1480
+ }
1481
+ return bots;
1482
+ }
1483
+ formatMessage(items) {
1484
+ const lines = [`Wiki 同步更新(${items.length} 条)`, ""];
1485
+ items.forEach((item, index) => {
1486
+ const label = item.type === "image" ? "🖼️" : "📖";
1487
+ const time = item.timestamp ? formatWikiTime(item.timestamp) : "";
1488
+ const user = item.user || "未知";
1489
+ const summary = truncateComment(item.comment || "", 10);
1490
+ const commentPart = summary ? `|${summary}` : "";
1491
+ lines.push(
1492
+ `${label} ${index + 1}. ${item.title}|${user}|${time}${commentPart}`
1493
+ );
1494
+ });
1495
+ return lines.join("\n");
1496
+ }
1497
+ };
1382
1498
 
1383
1499
  // src/plugins/syncCommands.ts
1384
1500
  var SyncCommands = class {
@@ -1391,20 +1507,27 @@ var SyncCommands = class {
1391
1507
  constructor(ctx, config) {
1392
1508
  this.config = config;
1393
1509
  logger.info("WikiBot 服务已就绪,初始化定时任务和指令");
1394
- this.notifyFn = this.buildNotifyFn(ctx);
1510
+ const notifier = new SyncNotifier(
1511
+ ctx,
1512
+ config.notifyGroupIds,
1513
+ config.notifyBotPlatform
1514
+ );
1515
+ this.notifyFn = notifier.enabled ? (items) => void notifier.notify(items) : void 0;
1516
+ this.registerScheduledTasks(ctx);
1517
+ this.registerCommands(ctx);
1518
+ }
1519
+ /** 同步相关的定时任务;cron 表达式即调度策略,集中在一处便于对照 */
1520
+ registerScheduledTasks(ctx) {
1395
1521
  ctx.cron("15 * * * *", async () => {
1396
1522
  if (!await this.ensureBotsReady(ctx, "增量更新")) return;
1397
- await incrementalUpdate(
1398
- ctx.wikiBot.getGGBot(),
1399
- ctx.wikiBot.getBWikiBot(),
1400
- config,
1401
- this.notifyFn,
1402
- ctx.database
1403
- );
1523
+ await new PageSyncer(ctx.wikiBot.getGGBot(), ctx.wikiBot.getBWikiBot(), {
1524
+ database: ctx.database,
1525
+ notify: this.notifyFn
1526
+ }).incrementalUpdate();
1404
1527
  });
1405
1528
  ctx.cron("30 8 * * 4", async () => {
1406
1529
  if (!await this.ensureBotsReady(ctx, "同步所有页面")) return;
1407
- await syncPages(ctx.wikiBot.getGGBot(), ctx.wikiBot.getBWikiBot()).then(() => {
1530
+ await new PageSyncer(ctx.wikiBot.getGGBot(), ctx.wikiBot.getBWikiBot()).syncAll().then(() => {
1408
1531
  logger.info("自动任务:尝试同步所有页面,从 WIKIGG 到 bwiki");
1409
1532
  }).catch((err) => {
1410
1533
  logger.error(`同步所有页面失败,错误信息:${err}`);
@@ -1412,11 +1535,10 @@ var SyncCommands = class {
1412
1535
  });
1413
1536
  ctx.cron("30 8 * * 3", async () => {
1414
1537
  if (!await this.ensureBotsReady(ctx, "同步所有图片")) return;
1415
- await syncAllImages(
1538
+ await new ImageSyncer(
1416
1539
  ctx.wikiBot.getGGBot(),
1417
- ctx.wikiBot.getBWikiBot(),
1418
- config
1419
- ).then(() => {
1540
+ ctx.wikiBot.getBWikiBot()
1541
+ ).syncAll().then(() => {
1420
1542
  logger.info("自动任务:尝试同步所有图片,从 WIKIGG 到 bwiki");
1421
1543
  }).catch((err) => {
1422
1544
  logger.error(`同步所有图片失败,错误信息:${err}`);
@@ -1427,87 +1549,12 @@ var SyncCommands = class {
1427
1549
  await this.syncAllContributors(ctx, "定时任务");
1428
1550
  });
1429
1551
  logger.info("✅ 每周日贡献者定时同步任务已注册(每周日凌晨2点执行)");
1430
- this.registerCommands(ctx);
1431
1552
  }
1432
- /**
1433
- * 构建增量更新同步成功的通知回调
1434
- * 当配置了 notifyGroupIds 时,将同步成功的页面/图片合并成一条消息推送到指定 QQ 群
1435
- */
1436
- buildNotifyFn(ctx) {
1437
- const groupIds = this.config.notifyGroupIds;
1438
- if (!groupIds || groupIds.length === 0) return void 0;
1439
- const platform = this.config.notifyBotPlatform || "qq";
1440
- return async (items) => {
1441
- try {
1442
- if (!items || items.length === 0) return;
1443
- const bots = [];
1444
- for (const bot of ctx.bots) {
1445
- if (bot.platform === platform && bot.isActive) {
1446
- bots.push(bot);
1447
- }
1448
- }
1449
- if (bots.length === 0) {
1450
- logger.warn(`[通知] 未找到可用的 ${platform} 平台 bot,跳过群通知`);
1451
- return;
1452
- }
1453
- const lines = [];
1454
- lines.push(`Wiki 同步更新(${items.length} 条)`);
1455
- lines.push("");
1456
- for (let i = 0; i < items.length; i++) {
1457
- const item = items[i];
1458
- const label = item.type === "image" ? "🖼️" : "📖";
1459
- const zhTime = item.timestamp ? formatWikiTime(item.timestamp) : "";
1460
- const user = item.user || "未知";
1461
- const shortComment = truncateComment(item.comment || "", 10);
1462
- const commentLine = shortComment ? `|${shortComment}` : "";
1463
- lines.push(
1464
- `${label} ${i + 1}. ${item.title}|${user}|${zhTime}${commentLine}`
1465
- );
1466
- }
1467
- const message = lines.join("\n");
1468
- for (const bot of bots) {
1469
- for (const rawChannelId of groupIds) {
1470
- const channelId = normalizeChannelId(rawChannelId);
1471
- if (!channelId) continue;
1472
- try {
1473
- await bot.sendMessage(channelId, message);
1474
- logger.info(
1475
- `[通知] 向 ${bot.platform}/${channelId} 推送成功 (${items.length} 条)`
1476
- );
1477
- } catch (error) {
1478
- logger.error(
1479
- `[通知] 向 ${bot.platform}/${channelId} 发送消息失败:`,
1480
- getErrorMessage(error)
1481
- );
1482
- }
1483
- }
1484
- }
1485
- } catch (error) {
1486
- logger.error(`[通知] 处理通知过程出错:`, getErrorMessage(error));
1487
- }
1488
- };
1489
- }
1490
- /**
1491
- * 确保机器人就绪,如果未就绪则尝试重新登录
1492
- * @param ctx Koishi 上下文
1493
- * @param taskName 任务名称(用于日志)
1494
- * @returns 机器人是否已就绪
1495
- */
1496
1553
  async ensureBotsReady(ctx, taskName) {
1497
- if (!ctx.wikiBot.isGGBotReady() || !ctx.wikiBot.isBWikiBotReady()) {
1498
- logger.warn(`检测到部分机器人未就绪,尝试重新登录...`);
1499
- try {
1500
- await ctx.wikiBot.relogin();
1501
- } catch (error) {
1502
- logger.error(`重新登录失败: ${error}`);
1503
- return false;
1504
- }
1505
- }
1506
- const ggReady = ctx.wikiBot.isGGBotReady();
1507
- const bwikiReady = ctx.wikiBot.isBWikiBotReady();
1508
- if (!ggReady || !bwikiReady) {
1554
+ const { gg, bwiki } = await ctx.wikiBot.ensureReady();
1555
+ if (!gg || !bwiki) {
1509
1556
  logger.warn(
1510
- `${taskName} 跳过:Wiki 机器人仍未就绪 - WIKIGG: ${ggReady ? "✅" : "❌"}, bwiki: ${bwikiReady ? "✅" : "❌"}`
1557
+ `${taskName} 跳过:Wiki 机器人仍未就绪 - WIKIGG: ${gg ? "✅" : "❌"}, bwiki: ${bwiki ? "✅" : "❌"}`
1511
1558
  );
1512
1559
  return false;
1513
1560
  }
@@ -1519,12 +1566,10 @@ var SyncCommands = class {
1519
1566
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1520
1567
  }
1521
1568
  try {
1522
- await syncSinglePage(
1569
+ await new PageSyncer(
1523
1570
  ctx.wikiBot.getGGBot(),
1524
- ctx.wikiBot.getBWikiBot(),
1525
- pageTitle,
1526
- "sync-bot"
1527
- );
1571
+ ctx.wikiBot.getBWikiBot()
1572
+ ).syncOne(pageTitle, "sync-bot");
1528
1573
  return `✅ 已尝试同步页面:${pageTitle},请前往控制台查看:${this.config.logsUrl}`;
1529
1574
  } catch (err) {
1530
1575
  logger.error(`同步页面 ${pageTitle} 失败,错误信息:${err}`);
@@ -1538,12 +1583,11 @@ var SyncCommands = class {
1538
1583
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1539
1584
  }
1540
1585
  try {
1541
- await incrementalUpdate(
1586
+ await new PageSyncer(
1542
1587
  ctx.wikiBot.getGGBot(),
1543
1588
  ctx.wikiBot.getBWikiBot(),
1544
- this.config,
1545
- this.notifyFn
1546
- );
1589
+ { notify: this.notifyFn }
1590
+ ).incrementalUpdate();
1547
1591
  return `✅ 已尝试获取三小时前的编辑并同步,请前往控制台查看:${this.config.logsUrl}`;
1548
1592
  } catch (err) {
1549
1593
  logger.error(`增量更新失败,错误信息:${err}`);
@@ -1555,7 +1599,10 @@ var SyncCommands = class {
1555
1599
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1556
1600
  }
1557
1601
  try {
1558
- await syncPages(ctx.wikiBot.getGGBot(), ctx.wikiBot.getBWikiBot());
1602
+ await new PageSyncer(
1603
+ ctx.wikiBot.getGGBot(),
1604
+ ctx.wikiBot.getBWikiBot()
1605
+ ).syncAll();
1559
1606
  return `✅ 已尝试同步所有页面,请前往控制台查看:${this.config.logsUrl}`;
1560
1607
  } catch (err) {
1561
1608
  logger.error(`同步所有页面失败,错误信息:${err}`);
@@ -1569,12 +1616,10 @@ var SyncCommands = class {
1569
1616
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1570
1617
  }
1571
1618
  try {
1572
- await syncSingleModule(
1619
+ await new ModuleSyncer(
1573
1620
  ctx.wikiBot.getGGBot(),
1574
- ctx.wikiBot.getBWikiBot(),
1575
- moduleTitle,
1576
- "sync-bot"
1577
- );
1621
+ ctx.wikiBot.getBWikiBot()
1622
+ ).syncOne(moduleTitle, "sync-bot");
1578
1623
  return `✅ 已尝试同步模块:${moduleTitle},请前往控制台查看:${this.config.logsUrl}`;
1579
1624
  } catch (err) {
1580
1625
  logger.error(`同步模块 ${moduleTitle} 失败,错误信息:${err}`);
@@ -1586,7 +1631,10 @@ var SyncCommands = class {
1586
1631
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1587
1632
  }
1588
1633
  try {
1589
- await syncModules(ctx.wikiBot.getGGBot(), ctx.wikiBot.getBWikiBot());
1634
+ await new ModuleSyncer(
1635
+ ctx.wikiBot.getGGBot(),
1636
+ ctx.wikiBot.getBWikiBot()
1637
+ ).syncAll();
1590
1638
  return `✅ 已尝试同步所有模块,请前往控制台查看:${this.config.logsUrl}`;
1591
1639
  } catch (err) {
1592
1640
  logger.error(`同步所有模块失败,错误信息:${err}`);
@@ -1598,11 +1646,11 @@ var SyncCommands = class {
1598
1646
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1599
1647
  }
1600
1648
  try {
1601
- await syncSingleImage(
1649
+ await new ImageSyncer(
1602
1650
  ctx.wikiBot.getGGBot(),
1603
- ctx.wikiBot.getBWikiBot(),
1604
- `${imgTitle.startsWith("File:") ? "" : "File:"}${imgTitle}`,
1605
- this.config
1651
+ ctx.wikiBot.getBWikiBot()
1652
+ ).syncOne(
1653
+ `${imgTitle.startsWith("File:") ? "" : "File:"}${imgTitle}`
1606
1654
  );
1607
1655
  return `✅ 已尝试同步图片:${imgTitle}`;
1608
1656
  } catch (err) {
@@ -1615,11 +1663,10 @@ var SyncCommands = class {
1615
1663
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1616
1664
  }
1617
1665
  try {
1618
- await syncAllImages(
1666
+ await new ImageSyncer(
1619
1667
  ctx.wikiBot.getGGBot(),
1620
- ctx.wikiBot.getBWikiBot(),
1621
- this.config
1622
- );
1668
+ ctx.wikiBot.getBWikiBot()
1669
+ ).syncAll();
1623
1670
  return `✅ 已尝试同步所有图片,请前往控制台查看:${this.config.logsUrl}`;
1624
1671
  } catch (err) {
1625
1672
  logger.error(`同步所有图片失败,错误信息:${err}`);
@@ -1646,10 +1693,14 @@ var SyncCommands = class {
1646
1693
  formatversion: "2",
1647
1694
  rvprop: "timestamp|user"
1648
1695
  });
1649
- if (res.query.pages[0].missing === true) {
1696
+ const page = res.query?.pages?.[0];
1697
+ if (!page || page.missing === true) {
1698
+ return { contributor: "", change_time: "" };
1699
+ }
1700
+ const revisions = page.revisions?.[0];
1701
+ if (!revisions) {
1650
1702
  return { contributor: "", change_time: "" };
1651
1703
  }
1652
- const revisions = res.query.pages[0].revisions[0];
1653
1704
  return {
1654
1705
  contributor: revisions.user,
1655
1706
  change_time: formatWikiTime(revisions.timestamp)
@@ -1718,7 +1769,7 @@ var SyncCommands = class {
1718
1769
  let failCount = 0;
1719
1770
  const failedPages = [];
1720
1771
  for (const page of pages) {
1721
- await (0, import_koishi8.sleep)(800);
1772
+ await (0, import_koishi3.sleep)(800);
1722
1773
  try {
1723
1774
  const data = await this.getContributorsAndTimestamp(
1724
1775
  page.title,
@@ -1756,25 +1807,221 @@ var SyncCommands = class {
1756
1807
  }
1757
1808
  }
1758
1809
  };
1759
- ((SyncCommands2) => {
1760
- SyncCommands2.Config = import_koishi8.Schema.object({
1761
- ggUsername: import_koishi8.Schema.string().description("WIKIGG 用户名").default("1"),
1762
- ggPassword: import_koishi8.Schema.string().description("WIKIGG 密码").default("1"),
1763
- bwikiusername: import_koishi8.Schema.string().description("bwiki用户名").default("1"),
1764
- bwikipassword: import_koishi8.Schema.string().description("bwiki密码").default("1"),
1765
- domain: import_koishi8.Schema.string().description("你的短链域名(必填,如:klei.vip)").default("klei.vip"),
1766
- main_site: import_koishi8.Schema.string().description("主站域名(必填,如:oxygennotincluded.wiki.gg)").default("oxygennotincluded.wiki.gg/zh"),
1767
- bwiki_site: import_koishi8.Schema.string().description("镜像站域名(必填,如:wiki.biligame.com)").default("wiki.biligame.com/oni"),
1768
- logsUrl: import_koishi8.Schema.string().description("日志查看地址").default("https://klei.vip/onilogs"),
1769
- notifyGroupIds: import_koishi8.Schema.array(import_koishi8.Schema.string()).description(
1770
- '增量更新同步成功时通知的群频道ID列表,如 ["group:123456"],留空则不发送通知'
1771
- ).default([]),
1772
- notifyBotPlatform: import_koishi8.Schema.string().description("通知 bot 的平台标识,默认 qq").default("qq")
1773
- });
1774
- })(SyncCommands || (SyncCommands = {}));
1810
+
1811
+ // src/utils/matcher.ts
1812
+ function getCommonPrefixLength(a, b) {
1813
+ const minLen = Math.min(a.length, b.length);
1814
+ let i = 0;
1815
+ while (i < minLen && a[i] === b[i]) i++;
1816
+ return i;
1817
+ }
1818
+ __name(getCommonPrefixLength, "getCommonPrefixLength");
1819
+ function calculateScore(page, queryKey, queryPinyinFull, queryPinyinFirst) {
1820
+ let score = 0;
1821
+ const { title, pinyin_full, pinyin_first } = page;
1822
+ if (queryKey && title.includes(queryKey)) score += 10;
1823
+ if (queryPinyinFull) {
1824
+ if (pinyin_full.startsWith(queryPinyinFull)) score += 9;
1825
+ if (pinyin_full.includes(queryPinyinFull)) score += 8;
1826
+ }
1827
+ if (queryPinyinFirst && pinyin_first.includes(queryPinyinFirst)) score += 6;
1828
+ const titlePrefixLen = getCommonPrefixLength(title, queryKey);
1829
+ if (titlePrefixLen >= 2) {
1830
+ score += titlePrefixLen;
1831
+ }
1832
+ const pinyinPrefixLen = getCommonPrefixLength(pinyin_full, queryPinyinFull);
1833
+ if (pinyinPrefixLen >= 3) {
1834
+ score += Math.floor(pinyinPrefixLen / 2);
1835
+ }
1836
+ return score;
1837
+ }
1838
+ __name(calculateScore, "calculateScore");
1839
+ function findFuzzyMatches(allPages, queryKey, queryPinyinFull, queryPinyinFirst, limit = 5) {
1840
+ const matchResults = [];
1841
+ for (const page of allPages) {
1842
+ const score = calculateScore(
1843
+ page,
1844
+ queryKey,
1845
+ queryPinyinFull,
1846
+ queryPinyinFirst
1847
+ );
1848
+ if (score > 0) {
1849
+ matchResults.push({ id: page.id, title: page.title, score });
1850
+ }
1851
+ }
1852
+ return matchResults.sort((a, b) => b.score - a.score || a.title.length - b.title.length).filter(
1853
+ (item, index, array) => array.findIndex((t) => t.title === item.title) === index
1854
+ ).slice(0, limit);
1855
+ }
1856
+ __name(findFuzzyMatches, "findFuzzyMatches");
1857
+
1858
+ // src/services/messageRenderer.ts
1859
+ var QQ_STYLE_ROW_SEPARATOR = "---\n";
1860
+ var MessageRenderer = class {
1861
+ constructor(ctx, domain) {
1862
+ this.ctx = ctx;
1863
+ this.domain = domain;
1864
+ }
1865
+ static {
1866
+ __name(this, "MessageRenderer");
1867
+ }
1868
+ isQQ(session) {
1869
+ return session?.platform === "qq";
1870
+ }
1871
+ /**
1872
+ * 发送(或返回)回复内容。
1873
+ * @returns QQ 平台发送成功时返回 undefined;其它情况返回可直接发给用户的纯文本
1874
+ */
1875
+ async send(session, content, keyboard) {
1876
+ if (!this.isQQ(session)) return content;
1877
+ try {
1878
+ const qq = session;
1879
+ const payload = {
1880
+ msg_id: qq.messageId,
1881
+ msg_type: 2,
1882
+ markdown: { content }
1883
+ };
1884
+ if (keyboard) payload.keyboard = keyboard;
1885
+ await qq.bot.internal.sendMessage(qq.channelId, payload);
1886
+ return void 0;
1887
+ } catch (error) {
1888
+ this.ctx.logger("oni-sync-bot").warn("QQ Markdown 发送失败,降级为纯文本:", error);
1889
+ return content;
1890
+ }
1891
+ }
1892
+ async usageMessage(session) {
1893
+ if (this.isQQ(session)) {
1894
+ const markdown = `**以下是使用说明:**
1895
+ > GG原站点: [https://${this.domain}/gg/88888888](https://${this.domain}/gg/88888888)
1896
+
1897
+ > bwiki: [https://${this.domain}/bw/88888888](https://${this.domain}/bw/88888888)
1898
+ `;
1899
+ return this.send(session, markdown);
1900
+ }
1901
+ return `以下是使用说明:
1902
+ GG原站点: https://${this.domain}/gg/88888888
1903
+
1904
+ bwiki: https://${this.domain}/bw/88888888`;
1905
+ }
1906
+ async resultMessage(session, page, prefix) {
1907
+ const hasMeta = Boolean(page.contributor || page.change_time);
1908
+ if (this.isQQ(session)) {
1909
+ let markdown = "";
1910
+ if (prefix) markdown += `**${prefix}**
1911
+ `;
1912
+ markdown += `**📖 ${page.title}**
1913
+
1914
+ `;
1915
+ if (hasMeta) {
1916
+ markdown += QQ_STYLE_ROW_SEPARATOR;
1917
+ if (page.contributor) {
1918
+ markdown += `> **👤 最后贡献者:** ${page.contributor}
1919
+ `;
1920
+ }
1921
+ if (page.change_time) {
1922
+ markdown += `> **🕐 最后修改:** ${page.change_time}
1923
+ `;
1924
+ }
1925
+ markdown += `惟知是信 至诚若天
1926
+ ${QQ_STYLE_ROW_SEPARATOR}`;
1927
+ }
1928
+ return this.send(session, markdown, this.pageKeyboard(page));
1929
+ }
1930
+ let message = "";
1931
+ if (prefix) message += `${prefix}
1932
+ `;
1933
+ message += `📖 ${page.title}
1934
+ `;
1935
+ if (hasMeta) {
1936
+ message += "--------\n";
1937
+ if (page.contributor) {
1938
+ message += `👤 最后贡献者:${page.contributor}
1939
+ `;
1940
+ }
1941
+ if (page.change_time) {
1942
+ message += `🕐 最后修改:${page.change_time}
1943
+ `;
1944
+ }
1945
+ }
1946
+ message += "惟知是信 至诚若天\n";
1947
+ message += "--------\n";
1948
+ message += `🔗 GG原站点: \`https://${this.domain}/gg/${page.id}\`
1949
+ `;
1950
+ message += `📚 bwiki: \`https://${this.domain}/bw/${page.id}\``;
1951
+ return message;
1952
+ }
1953
+ /** 命中多个候选时的按钮键盘(每行 2 个,跳 bwiki 镜像) */
1954
+ matchListKeyboard(matches) {
1955
+ const rows = [];
1956
+ for (let i = 0; i < matches.length; i += 2) {
1957
+ const buttons = matches.slice(i, i + 2).map((item) => {
1958
+ const label = item.title.length > 10 ? item.title.slice(0, 10) : item.title;
1959
+ return this.linkButton(
1960
+ `${item.id}`,
1961
+ label,
1962
+ `https://${this.domain}/bw/${item.id}`
1963
+ );
1964
+ });
1965
+ rows.push({ buttons });
1966
+ }
1967
+ return { content: { rows } };
1968
+ }
1969
+ /** 单个页面结果的按钮键盘:原站 / 镜像 / 直链 */
1970
+ pageKeyboard(page) {
1971
+ return {
1972
+ content: {
1973
+ rows: [
1974
+ {
1975
+ buttons: [
1976
+ this.linkButton(
1977
+ `gg-${page.id}`,
1978
+ "GG 原站",
1979
+ `https://${this.domain}/gg/${page.id}`
1980
+ )
1981
+ ]
1982
+ },
1983
+ {
1984
+ buttons: [
1985
+ this.linkButton(
1986
+ `bw-${page.id}`,
1987
+ "Bwiki 镜像",
1988
+ `https://${this.domain}/bw/${page.id}`
1989
+ )
1990
+ ]
1991
+ },
1992
+ {
1993
+ buttons: [
1994
+ this.linkButton(
1995
+ `wiki-${page.id}`,
1996
+ "GG直链",
1997
+ `https://oxygennotincluded.wiki.gg/zh/${encodeURIComponent(page.title)}`
1998
+ )
1999
+ ]
2000
+ }
2001
+ ]
2002
+ }
2003
+ };
2004
+ }
2005
+ linkButton(idSuffix, label, url) {
2006
+ return {
2007
+ id: `btn-${idSuffix}`,
2008
+ render_data: {
2009
+ label,
2010
+ visited_label: "已打开",
2011
+ style: 1
2012
+ },
2013
+ action: {
2014
+ type: 0,
2015
+ permission: {
2016
+ type: 2
2017
+ },
2018
+ data: url
2019
+ }
2020
+ };
2021
+ }
2022
+ };
1775
2023
 
1776
2024
  // src/plugins/queryCommands.ts
1777
- var import_koishi9 = require("koishi");
1778
2025
  var SPECIAL_CASES = /* @__PURE__ */ new Map([
1779
2026
  [
1780
2027
  "火箭计算器",
@@ -1788,20 +2035,22 @@ var QueryCommands = class {
1788
2035
  static inject = ["database"];
1789
2036
  config;
1790
2037
  ctx;
2038
+ renderer;
1791
2039
  constructor(ctx, config) {
1792
2040
  this.ctx = ctx;
1793
2041
  this.config = config;
2042
+ this.renderer = new MessageRenderer(ctx, config.domain);
1794
2043
  this.registerCommands(ctx);
1795
2044
  }
1796
2045
  registerCommands(ctx) {
1797
2046
  ctx.command("x <itemName:text>", "查询缺氧中文wiki,精准匹配+拼音模糊匹配").alias("/查wiki").action(async ({ session }, itemName = "") => {
1798
2047
  const queryKey = itemName.trim().toLowerCase();
1799
2048
  if (!queryKey) {
1800
- return this.renderUsageMessage(session);
2049
+ return this.renderer.usageMessage(session);
1801
2050
  }
1802
- if (SPECIAL_CASES.has(queryKey)) {
1803
- const content = SPECIAL_CASES.get(queryKey);
1804
- return this.sendResponse(session, content);
2051
+ const specialCase = SPECIAL_CASES.get(queryKey);
2052
+ if (specialCase !== void 0) {
2053
+ return this.renderer.send(session, specialCase);
1805
2054
  }
1806
2055
  const { pinyin_full: queryPinyinFull, pinyin_first: queryPinyinFirst } = generatePinyinInfo(queryKey);
1807
2056
  const preciseMatch = await this.findPreciseMatch(
@@ -1811,7 +2060,7 @@ var QueryCommands = class {
1811
2060
  queryPinyinFirst
1812
2061
  );
1813
2062
  if (preciseMatch) {
1814
- return this.renderResultMessage(
2063
+ return this.renderer.resultMessage(
1815
2064
  session,
1816
2065
  preciseMatch,
1817
2066
  preciseMatch.prefix
@@ -1819,19 +2068,19 @@ var QueryCommands = class {
1819
2068
  }
1820
2069
  const allPages = await ctx.database.get("wikipages", {});
1821
2070
  if (allPages.length === 0) {
1822
- return this.sendResponse(
2071
+ return this.renderer.send(
1823
2072
  session,
1824
2073
  "❌ 本地缓存为空,请联系管理员执行【update】指令更新缓存!"
1825
2074
  );
1826
2075
  }
1827
- const fuzzyMatches = this.findFuzzyMatches(
2076
+ const fuzzyMatches = findFuzzyMatches(
1828
2077
  allPages,
1829
2078
  queryKey,
1830
2079
  queryPinyinFull,
1831
2080
  queryPinyinFirst
1832
2081
  );
1833
2082
  if (fuzzyMatches.length === 0) {
1834
- return this.sendResponse(
2083
+ return this.renderer.send(
1835
2084
  session,
1836
2085
  `❌ 未找到【${queryKey}】相关内容,请按游戏内标准名称重新查询!`
1837
2086
  );
@@ -1839,163 +2088,7 @@ var QueryCommands = class {
1839
2088
  return await this.handleSelection(session, fuzzyMatches);
1840
2089
  });
1841
2090
  }
1842
- isQQPlatform(session) {
1843
- return session?.platform === "qq";
1844
- }
1845
- buildLinkButton(idSuffix, label, url) {
1846
- return {
1847
- id: `btn-${idSuffix}`,
1848
- render_data: {
1849
- label,
1850
- visited_label: "已打开",
1851
- style: 1
1852
- },
1853
- action: {
1854
- type: 0,
1855
- permission: {
1856
- type: 2
1857
- },
1858
- data: url
1859
- }
1860
- };
1861
- }
1862
- buildQQKeyboard(matches) {
1863
- const rows = [];
1864
- for (let i = 0; i < matches.length; i += 2) {
1865
- const buttonsInRow = matches.slice(i, i + 2).map((item) => {
1866
- const label = item.title.length > 10 ? item.title.slice(0, 10) : item.title;
1867
- return this.buildLinkButton(
1868
- `${item.id}`,
1869
- label,
1870
- `https://${this.config.domain}/bw/${item.id}`
1871
- );
1872
- });
1873
- rows.push({ buttons: buttonsInRow });
1874
- }
1875
- return {
1876
- content: { rows }
1877
- };
1878
- }
1879
- async sendResponse(session, content, keyboard) {
1880
- if (this.isQQPlatform(session)) {
1881
- try {
1882
- const payload = {
1883
- msg_id: session.messageId,
1884
- msg_type: 2,
1885
- markdown: {
1886
- content
1887
- }
1888
- };
1889
- if (keyboard) {
1890
- payload.keyboard = keyboard;
1891
- }
1892
- await session.bot.internal.sendMessage(session.channelId, payload);
1893
- return;
1894
- } catch (e) {
1895
- this.ctx.logger("oni-sync-bot").warn("QQ Markdown 发送失败,降级为纯文本:", e);
1896
- return content;
1897
- }
1898
- }
1899
- return content;
1900
- }
1901
- renderUsageMessage(session) {
1902
- if (this.isQQPlatform(session)) {
1903
- const md = `**以下是使用说明:**
1904
- > GG原站点: [https://${this.config.domain}/gg/88888888](https://${this.config.domain}/gg/88888888)
1905
-
1906
- > bwiki: [https://${this.config.domain}/bw/88888888](https://${this.config.domain}/bw/88888888)
1907
- `;
1908
- return this.sendResponse(session, md);
1909
- }
1910
- return `以下是使用说明:
1911
- GG原站点: https://${this.config.domain}/gg/88888888
1912
-
1913
- bwiki: https://${this.config.domain}/bw/88888888`;
1914
- }
1915
- buildResultKeyboard(match) {
1916
- return {
1917
- content: {
1918
- rows: [
1919
- {
1920
- buttons: [
1921
- this.buildLinkButton(
1922
- `gg-${match.id}`,
1923
- "GG 原站",
1924
- `https://${this.config.domain}/gg/${match.id}`
1925
- )
1926
- ]
1927
- },
1928
- {
1929
- buttons: [
1930
- this.buildLinkButton(
1931
- `bw-${match.id}`,
1932
- "Bwiki 镜像",
1933
- `https://${this.config.domain}/bw/${match.id}`
1934
- )
1935
- ]
1936
- },
1937
- {
1938
- buttons: [
1939
- this.buildLinkButton(
1940
- `wiki-${match.id}`,
1941
- "GG直链",
1942
- `https://oxygennotincluded.wiki.gg/zh/${encodeURIComponent(match.title)}`
1943
- )
1944
- ]
1945
- }
1946
- ]
1947
- }
1948
- };
1949
- }
1950
- renderResultMessage(session, match, prefix) {
1951
- if (this.isQQPlatform(session)) {
1952
- let md = "";
1953
- if (prefix) {
1954
- md += `**${prefix}**
1955
- `;
1956
- }
1957
- md += `**📖 ${match.title}**
1958
-
1959
- `;
1960
- if (match.contributor || match.change_time) {
1961
- md += "---\n";
1962
- if (match.contributor) {
1963
- md += `> **👤 最后贡献者:** ${match.contributor}
1964
- `;
1965
- }
1966
- if (match.change_time) {
1967
- md += `> **🕐 最后修改:** ${match.change_time}
1968
- `;
1969
- }
1970
- md += "惟知是信 至诚若天\n---\n";
1971
- }
1972
- const keyboard = this.buildResultKeyboard(match);
1973
- return this.sendResponse(session, md, keyboard);
1974
- }
1975
- let message = "";
1976
- if (prefix) {
1977
- message += prefix + "\n";
1978
- }
1979
- message += `📖 ${match.title}
1980
- `;
1981
- if (match.contributor || match.change_time) {
1982
- message += "--------\n";
1983
- if (match.contributor) {
1984
- message += `👤 最后贡献者:${match.contributor}
1985
- `;
1986
- }
1987
- if (match.change_time) {
1988
- message += `🕐 最后修改:${match.change_time}
1989
- `;
1990
- }
1991
- }
1992
- message += "惟知是信 至诚若天\n";
1993
- message += "--------\n";
1994
- message += `🔗 GG原站点: \`https://${this.config.domain}/gg/${match.id}\`
1995
- `;
1996
- message += `📚 bwiki: \`https://${this.config.domain}/bw/${match.id}\``;
1997
- return message;
1998
- }
2091
+ /** 标题 / 全拼 / 首字母三种精准匹配,命中即返回(带用于展示的前缀文案) */
1999
2092
  async findPreciseMatch(ctx, queryKey, queryPinyinFull, queryPinyinFirst) {
2000
2093
  const checks = [
2001
2094
  { query: { title: queryKey }, prefix: "✅ 精准匹配成功" },
@@ -2022,65 +2115,28 @@ bwiki: https://${this.config.domain}/bw/88888888`;
2022
2115
  }
2023
2116
  return null;
2024
2117
  }
2025
- getCommonPrefixLength(a, b) {
2026
- const minLen = Math.min(a.length, b.length);
2027
- let i = 0;
2028
- while (i < minLen && a[i] === b[i]) i++;
2029
- return i;
2030
- }
2031
- calculateScore(page, queryKey, queryPinyinFull, queryPinyinFirst) {
2032
- let score = 0;
2033
- const { title, pinyin_full, pinyin_first } = page;
2034
- if (title.includes(queryKey)) score += 10;
2035
- if (pinyin_full.startsWith(queryPinyinFull)) score += 9;
2036
- if (pinyin_full.includes(queryPinyinFull)) score += 8;
2037
- if (pinyin_first.includes(queryPinyinFirst)) score += 6;
2038
- const titlePrefixLen = this.getCommonPrefixLength(title, queryKey);
2039
- if (titlePrefixLen >= 2) {
2040
- score += titlePrefixLen;
2041
- }
2042
- const pinyinPrefixLen = this.getCommonPrefixLength(
2043
- pinyin_full,
2044
- queryPinyinFull
2045
- );
2046
- if (pinyinPrefixLen >= 3) {
2047
- score += Math.floor(pinyinPrefixLen / 2);
2048
- }
2049
- return score;
2050
- }
2051
- findFuzzyMatches(allPages, queryKey, queryPinyinFull, queryPinyinFirst) {
2052
- const matchResults = [];
2053
- for (const page of allPages) {
2054
- const score = this.calculateScore(
2055
- page,
2056
- queryKey,
2057
- queryPinyinFull,
2058
- queryPinyinFirst
2059
- );
2060
- if (score > 0) {
2061
- matchResults.push({ id: page.id, title: page.title, score });
2062
- }
2063
- }
2064
- return matchResults.sort((a, b) => b.score - a.score || a.title.length - b.title.length).filter(
2065
- (item, index, array) => array.findIndex((t) => t.title === item.title) === index
2066
- ).slice(0, 5);
2067
- }
2118
+ /**
2119
+ * 处理多候选选择:
2120
+ * - QQ:直接回按钮列表,结束;
2121
+ * - 其它平台:提示输入序号并等待 15 秒。
2122
+ */
2068
2123
  async handleSelection(session, matches) {
2069
2124
  const resultCount = matches.length;
2070
- let replyMsg;
2071
- if (this.isQQPlatform(session)) {
2072
- let md = `**🔍 为你找到【 ${resultCount} 】个相似结果,请点击下方按钮查看详情:**
2125
+ if (this.renderer.isQQ(session)) {
2126
+ let markdown = `**🔍 为你找到【 ${resultCount} 】个相似结果,请点击下方按钮查看详情:**
2073
2127
  `;
2074
2128
  matches.forEach((item, index) => {
2075
- md += `
2129
+ markdown += `
2076
2130
  > \`${index + 1}\`. **${item.title}**
2077
2131
  `;
2078
2132
  });
2079
- const keyboard = this.buildQQKeyboard(matches);
2080
- await this.sendResponse(session, md, keyboard);
2081
- return;
2133
+ return this.renderer.send(
2134
+ session,
2135
+ markdown,
2136
+ this.renderer.matchListKeyboard(matches)
2137
+ );
2082
2138
  }
2083
- replyMsg = `🔍 未找到精准匹配,为你找到【 ${resultCount} 】个相似结果,请输入序号选择(10秒内有效):
2139
+ let replyMsg = `🔍 未找到精准匹配,为你找到【 ${resultCount} 】个相似结果,请输入序号选择(10秒内有效):
2084
2140
  `;
2085
2141
  matches.forEach((item, index) => {
2086
2142
  replyMsg += `${index + 1}. ${item.title}
@@ -2088,32 +2144,22 @@ bwiki: https://${this.config.domain}/bw/88888888`;
2088
2144
  });
2089
2145
  replyMsg += `
2090
2146
  ❗️ 提示:超时将静默结束,无任何回应`;
2091
- await this.sendResponse(session, replyMsg);
2092
- const userInput = await session.prompt(15e3);
2147
+ await this.renderer.send(session, replyMsg);
2148
+ const userInput = await session?.prompt(15e3);
2093
2149
  if (!userInput) return;
2094
2150
  const selectNum = parseInt(userInput.trim(), 10);
2095
2151
  if (isNaN(selectNum) || selectNum < 1 || selectNum > resultCount) {
2096
- return this.sendResponse(
2152
+ return this.renderer.send(
2097
2153
  session,
2098
2154
  `❌ 输入无效!请输入 1-${resultCount} 之间的数字序号`
2099
2155
  );
2100
2156
  }
2101
2157
  const selected = matches[selectNum - 1];
2102
- return this.renderResultMessage(
2103
- session,
2104
- selected,
2105
- "✅ 选择成功"
2106
- );
2158
+ return this.renderer.resultMessage(session, selected, "✅ 选择成功");
2107
2159
  }
2108
2160
  };
2109
- ((QueryCommands2) => {
2110
- QueryCommands2.Config = import_koishi9.Schema.object({
2111
- domain: import_koishi9.Schema.string().description("你的短链域名(必填,如:klei.vip)").default("klei.vip")
2112
- });
2113
- })(QueryCommands || (QueryCommands = {}));
2114
2161
 
2115
2162
  // src/plugins/updateCommands.ts
2116
- var import_koishi10 = require("koishi");
2117
2163
  var UpdateCommands = class {
2118
2164
  constructor(ctx, config) {
2119
2165
  this.ctx = ctx;
@@ -2152,7 +2198,7 @@ var UpdateCommands = class {
2152
2198
  aplimit: "max"
2153
2199
  });
2154
2200
  logger.info("主站页面查询成功");
2155
- const pages = res.query.allpages || [];
2201
+ const pages = res.query?.allpages || [];
2156
2202
  const pageData = pages.map((page) => {
2157
2203
  const { pinyin_full, pinyin_first } = generatePinyinInfo(page.title);
2158
2204
  return {
@@ -2170,33 +2216,33 @@ var UpdateCommands = class {
2170
2216
  }
2171
2217
  registerCommands(ctx) {
2172
2218
  ctx.command("update", "更新本地页面缓存(主站)", { authority: 2 }).action(async ({ session }) => {
2173
- await session.execute("update.status");
2219
+ await session?.execute("update.status");
2174
2220
  try {
2175
2221
  const result = await this.updatePageCache();
2176
- session.send(`✅ 检索到 ${result.count} 个页面,已更新至数据库`);
2222
+ session?.send(`✅ 检索到 ${result.count} 个页面,已更新至数据库`);
2177
2223
  } catch (err) {
2178
2224
  this.log.error("主站缓存更新失败", err);
2179
- session.send("❌ 主站缓存更新失败,请联系管理员查看日志");
2225
+ session?.send("❌ 主站缓存更新失败,请联系管理员查看日志");
2180
2226
  }
2181
2227
  });
2182
2228
  ctx.command("update.delete", "删除本地页面缓存", { authority: 4 }).action(async ({ session }) => {
2183
2229
  try {
2184
2230
  const count = await ctx.database.remove("wikipages", {});
2185
- session.send(`✅ 已删除 ${count.removed} 条本地缓存`);
2231
+ session?.send(`✅ 已删除 ${count.removed} 条本地缓存`);
2186
2232
  logger.info(`已删除 ${count.removed} 条本地缓存`);
2187
2233
  } catch (err) {
2188
2234
  this.log.error("删除缓存失败", err);
2189
- session.send("❌ 删除缓存失败,请联系管理员查看日志");
2235
+ session?.send("❌ 删除缓存失败,请联系管理员查看日志");
2190
2236
  }
2191
2237
  });
2192
2238
  ctx.command("update.status", "查询本地缓存数量", { authority: 1 }).action(async ({ session }) => {
2193
2239
  try {
2194
2240
  const pages = await ctx.database.get("wikipages", {});
2195
- session.send(`📊 数据库中缓存了 ${pages.length} 条页面`);
2241
+ session?.send(`📊 数据库中缓存了 ${pages.length} 条页面`);
2196
2242
  logger.info(`数据库中缓存了 ${pages.length} 条页面`);
2197
2243
  } catch (err) {
2198
2244
  this.log.error("查询缓存状态失败", err);
2199
- session.send("❌ 查询缓存状态失败,请联系管理员查看日志");
2245
+ session?.send("❌ 查询缓存状态失败,请联系管理员查看日志");
2200
2246
  }
2201
2247
  });
2202
2248
  ctx.command("redirect <pageName> <targetPageName>", "添加原站点重定向", {
@@ -2212,18 +2258,18 @@ var UpdateCommands = class {
2212
2258
  "来自qq机器人的添加重定向页面请求"
2213
2259
  );
2214
2260
  logger.info(`已为 ${pageName} 添加重定向至 ${targetPageName}`);
2215
- session.send(`✅ 已尝试添加重定向 ${pageName} -> ${targetPageName}`);
2216
- await session.execute(`update`);
2261
+ session?.send(`✅ 已尝试添加重定向 ${pageName} -> ${targetPageName}`);
2262
+ await session?.execute(`update`);
2217
2263
  } catch (err) {
2218
2264
  this.log.error(
2219
2265
  `添加重定向 ${pageName} -> ${targetPageName} 失败`,
2220
2266
  err
2221
2267
  );
2222
- session.send(`❌ 添加重定向失败,请联系管理员查看日志`);
2268
+ session?.send(`❌ 添加重定向失败,请联系管理员查看日志`);
2223
2269
  }
2224
2270
  });
2225
2271
  ctx.command("relogin", "手动重新登录 Wiki 机器人", { authority: 2 }).alias("重新登录").action(async ({ session }) => {
2226
- session.send("🚀 开始重新登录 Wiki 机器人...");
2272
+ session?.send("🚀 开始重新登录 Wiki 机器人...");
2227
2273
  try {
2228
2274
  const result = await ctx.wikiBot.relogin();
2229
2275
  let message = "📋 重新登录结果:\n";
@@ -2236,20 +2282,14 @@ var UpdateCommands = class {
2236
2282
  } else {
2237
2283
  message += "\n💥 所有 Wiki 机器人登录都失败了,请检查配置";
2238
2284
  }
2239
- session.send(message);
2285
+ session?.send(message);
2240
2286
  } catch (err) {
2241
2287
  this.log.error("重新登录失败", err);
2242
- session.send("❌ 重新登录过程中发生错误,请查看日志");
2288
+ session?.send("❌ 重新登录过程中发生错误,请查看日志");
2243
2289
  }
2244
2290
  });
2245
2291
  }
2246
2292
  };
2247
- ((UpdateCommands2) => {
2248
- UpdateCommands2.Config = import_koishi10.Schema.object({
2249
- logsUrl: import_koishi10.Schema.string().description("日志查看地址").default("https://klei.vip/onilogs"),
2250
- updateCron: import_koishi10.Schema.string().description("页面缓存自动更新 cron 表达式(默认每天凌晨 2 点)").default("0 2 * * *")
2251
- });
2252
- })(UpdateCommands || (UpdateCommands = {}));
2253
2293
 
2254
2294
  // src/plugins/todoList.ts
2255
2295
  var TodoList = class {
@@ -2329,7 +2369,7 @@ var TodoList = class {
2329
2369
  params.continue = "-||";
2330
2370
  }
2331
2371
  const res = await this.apiCallWithRetry(
2332
- () => this.ctx.wikiBot.ggbot.query(params)
2372
+ () => this.ctx.wikiBot.getGGBot().query(params)
2333
2373
  );
2334
2374
  if (res.query?.allpages) {
2335
2375
  modules.push(...res.query.allpages);
@@ -2343,28 +2383,24 @@ var TodoList = class {
2343
2383
  throw err;
2344
2384
  }
2345
2385
  }
2346
- sleep(ms) {
2347
- return new Promise((resolve2) => setTimeout(resolve2, ms));
2348
- }
2349
- async apiCallWithRetry(apiCall, maxRetries = 3) {
2350
- for (let i = 0; i < maxRetries; i++) {
2351
- try {
2352
- return await apiCall();
2353
- } catch (err) {
2354
- if (i === maxRetries - 1) {
2355
- throw err;
2356
- }
2357
- this.log.warn(`API 调用失败,正在重试 (${i + 1}/${maxRetries})...`);
2358
- await this.sleep(2e3);
2359
- }
2360
- }
2361
- throw new Error("Max retries exceeded");
2386
+ apiCallWithRetry(apiCall, maxRetries = 3) {
2387
+ return withRetry(apiCall, {
2388
+ attempts: maxRetries,
2389
+ delayMs: 2e3,
2390
+ onRetry: /* @__PURE__ */ __name((_error, attempt, attempts) => this.log.warn(`API 调用失败,正在重试 (${attempt}/${attempts})...`), "onRetry")
2391
+ });
2362
2392
  }
2363
- async getModuleRevisionFromGG(title) {
2393
+ /**
2394
+ * 读取指定站点上模块页面的最新修订信息。
2395
+ * 原先 gg / bwiki 各有一份逐行相同的实现,只有站点不同 —— 合并为按站点寻址。
2396
+ */
2397
+ async getModuleRevision(site, title) {
2398
+ const isGG = site === "gg";
2399
+ const bot = isGG ? this.ctx.wikiBot.getGGBot() : this.ctx.wikiBot.getBWikiBot();
2364
2400
  try {
2365
- await this.sleep(1e3);
2401
+ await (0, import_koishi3.sleep)(1e3);
2366
2402
  const res = await this.apiCallWithRetry(
2367
- () => this.ctx.wikiBot.ggbot.query({
2403
+ () => bot.query({
2368
2404
  action: "query",
2369
2405
  format: "json",
2370
2406
  prop: "revisions",
@@ -2374,47 +2410,15 @@ var TodoList = class {
2374
2410
  rvlimit: "1"
2375
2411
  })
2376
2412
  );
2377
- if (res.query?.pages && res.query.pages.length > 0) {
2378
- const page = res.query.pages[0];
2379
- if (page.revisions && page.revisions.length > 0) {
2380
- return {
2381
- ...page,
2382
- revision: page.revisions[0]
2383
- };
2384
- }
2385
- }
2386
- return null;
2413
+ const page = res.query?.pages?.[0];
2414
+ const revisions = page?.revisions;
2415
+ if (!revisions?.length) return null;
2416
+ return { title: page?.title, revisions, revision: revisions[0] };
2387
2417
  } catch (err) {
2388
- this.log.error(`从 wiki.gg 获取模块 ${title} 的修订信息失败`, err);
2389
- return null;
2390
- }
2391
- }
2392
- async getModuleRevisionFromBWiki(title) {
2393
- try {
2394
- await this.sleep(1e3);
2395
- const res = await this.apiCallWithRetry(
2396
- () => this.ctx.wikiBot.bwikibot.query({
2397
- action: "query",
2398
- format: "json",
2399
- prop: "revisions",
2400
- titles: title,
2401
- formatversion: "2",
2402
- rvprop: "timestamp|user|comment",
2403
- rvlimit: "1"
2404
- })
2418
+ this.log.error(
2419
+ `从 ${isGG ? "wiki.gg" : "bwiki"} 获取模块 ${title} 的修订信息失败`,
2420
+ err
2405
2421
  );
2406
- if (res.query?.pages && res.query.pages.length > 0) {
2407
- const page = res.query.pages[0];
2408
- if (page.revisions && page.revisions.length > 0) {
2409
- return {
2410
- ...page,
2411
- revision: page.revisions[0]
2412
- };
2413
- }
2414
- }
2415
- return null;
2416
- } catch (err) {
2417
- this.log.error(`从 bwikia 获取模块 ${title} 的修订信息失败`, err);
2418
2422
  return null;
2419
2423
  }
2420
2424
  }
@@ -2429,7 +2433,7 @@ var TodoList = class {
2429
2433
  let added = 0;
2430
2434
  let updated = 0;
2431
2435
  for (const module2 of modules) {
2432
- const moduleData = await this.getModuleRevisionFromGG(module2.title);
2436
+ const moduleData = await this.getModuleRevision("gg", module2.title);
2433
2437
  if (!moduleData || !moduleData.revision) {
2434
2438
  continue;
2435
2439
  }
@@ -2474,8 +2478,8 @@ var TodoList = class {
2474
2478
  let synced = 0;
2475
2479
  for (const todo of todos) {
2476
2480
  checked++;
2477
- const ggRevision = await this.getModuleRevisionFromGG(todo.title);
2478
- const bwikiRevision = await this.getModuleRevisionFromBWiki(todo.title);
2481
+ const ggRevision = await this.getModuleRevision("gg", todo.title);
2482
+ const bwikiRevision = await this.getModuleRevision("bwiki", todo.title);
2479
2483
  if (!ggRevision || !ggRevision.revision) {
2480
2484
  continue;
2481
2485
  }
@@ -2510,12 +2514,12 @@ var TodoList = class {
2510
2514
  }
2511
2515
  registerCommands(ctx) {
2512
2516
  ctx.command("todolist", "缺氧 TodoList").alias("todo").action(async ({ session }) => {
2513
- await session.execute("todo.list");
2517
+ await session?.execute("todo.list");
2514
2518
  });
2515
2519
  ctx.command("todo.list", "查看 TodoList").alias("todo.l").action(async ({ session }) => {
2516
2520
  return "📋 请访问 https://klei.vip/onitodos 进行 TodoList 管理";
2517
2521
  });
2518
- ctx.command("todo.add <title>", "添加待办事项").alias("todo.a").option("content", "-c <content>").option("createdBy", "-u <createdBy>").action(async ({ session, options }, title) => {
2522
+ ctx.command("todo.add <title>", "添加待办事项").alias("todo.a").option("content", "-c <content>").option("createdBy", "-u <createdBy>").action(async ({ session, options = {} }, title) => {
2519
2523
  if (!title) {
2520
2524
  return "❌ 请提供标题!用法:todo.add <标题> [-c <内容>] [-u <创建人>]";
2521
2525
  }
@@ -2535,7 +2539,7 @@ var TodoList = class {
2535
2539
  return "❌ 添加待办事项失败,请查看日志";
2536
2540
  }
2537
2541
  });
2538
- ctx.command("todo.edit <id>", "编辑待办事项").alias("todo.e").option("title", "-t <title>").option("content", "-c <content>").option("createdBy", "-u <createdBy>").action(async ({ session, options }, idStr) => {
2542
+ ctx.command("todo.edit <id>", "编辑待办事项").alias("todo.e").option("title", "-t <title>").option("content", "-c <content>").option("createdBy", "-u <createdBy>").action(async ({ session, options = {} }, idStr) => {
2539
2543
  const id = Number(idStr);
2540
2544
  if (!id || isNaN(id)) {
2541
2545
  return "❌ 请提供有效的 ID!";
@@ -2692,22 +2696,20 @@ var TodoList = class {
2692
2696
 
2693
2697
  // src/index.ts
2694
2698
  var name = "oni-sync-bot";
2695
- var Config = import_koishi11.Schema.intersect([
2696
- WikiBotService.Config,
2697
- RouteRedirect.Config,
2698
- SyncCommands.Config,
2699
- QueryCommands.Config,
2700
- UpdateCommands.Config
2701
- ]);
2699
+ var SUB_PLUGINS = [
2700
+ WikiBotService,
2701
+ ConsoleLogProvider,
2702
+ DatabaseExtension,
2703
+ RouteRedirect,
2704
+ SyncCommands,
2705
+ QueryCommands,
2706
+ UpdateCommands,
2707
+ TodoList
2708
+ ];
2702
2709
  function apply(ctx, config) {
2703
- ctx.plugin(WikiBotService, config);
2704
- ctx.plugin(ConsoleLogProvider);
2705
- ctx.plugin(DatabaseExtension);
2706
- ctx.plugin(RouteRedirect, config);
2707
- ctx.plugin(SyncCommands, config);
2708
- ctx.plugin(QueryCommands, config);
2709
- ctx.plugin(UpdateCommands, config);
2710
- ctx.plugin(TodoList);
2710
+ for (const plugin of SUB_PLUGINS) {
2711
+ ctx.plugin(plugin, config);
2712
+ }
2711
2713
  ctx.inject(["console"], (ctx2) => {
2712
2714
  ctx2.console.addEntry({
2713
2715
  dev: (0, import_path.resolve)(__dirname, "../client/index.ts"),