@azimiao/koishi-plugin-cafe-bot-exp 0.0.9 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ declare const CafeTimeTools: {
2
+ getRemainingSecondsToBeijingMidnight: () => number;
3
+ };
4
+ export default CafeTimeTools;
@@ -0,0 +1,3 @@
1
+ import { HTTP } from "koishi";
2
+ declare function downloadFileIfNotExist(http: HTTP, downloadUrl: string, savePath: string, forceUpdate: boolean): Promise<boolean>;
3
+ export default downloadFileIfNotExist;
@@ -4,6 +4,7 @@
4
4
  import { Schema } from "koishi";
5
5
  export interface CafeBotDrawConfig {
6
6
  baseDataUrl: string;
7
+ forceUpdateDataWhenLoad: boolean;
7
8
  ImageServer: string;
8
9
  ImageServerAuth: string;
9
10
  MinCount: number;
package/lib/index.d.ts CHANGED
@@ -5,4 +5,5 @@ import { Context } from 'koishi';
5
5
  import { Config } from './config';
6
6
  export declare const name = "cafe-bot-exp";
7
7
  export * from "./config";
8
+ export declare const inject: string[];
8
9
  export declare function apply(ctx: Context, config: Config): Promise<void>;
package/lib/index.js CHANGED
@@ -32,6 +32,7 @@ var src_exports = {};
32
32
  __export(src_exports, {
33
33
  Config: () => Config4,
34
34
  apply: () => apply4,
35
+ inject: () => inject3,
35
36
  name: () => name4
36
37
  });
37
38
  module.exports = __toCommonJS(src_exports);
@@ -44,9 +45,8 @@ __export(draw_exports, {
44
45
  inject: () => inject,
45
46
  name: () => name
46
47
  });
47
- var fs = __toESM(require("fs/promises"));
48
+ var fs2 = __toESM(require("fs/promises"));
48
49
  var path = __toESM(require("path"));
49
- var import_fs_promises = __toESM(require("fs.promises.exists"));
50
50
 
51
51
  // src/common/DailySeededName.ts
52
52
  function DailySeededName(uid) {
@@ -89,12 +89,12 @@ var PseudoRandom = class {
89
89
  "seed": this.seed
90
90
  });
91
91
  }
92
- next = /* @__PURE__ */ __name(() => {
92
+ next = () => {
93
93
  return this.randFunc();
94
- }, "next");
95
- nextInt = /* @__PURE__ */ __name((min, max) => {
94
+ };
95
+ nextInt = (min, max) => {
96
96
  return Math.floor(this.next() * (max - min + 1)) + min;
97
- }, "nextInt");
97
+ };
98
98
  };
99
99
  var PseudoRandom_default = PseudoRandom;
100
100
 
@@ -257,6 +257,7 @@ var html_default = HtmlCreator;
257
257
  var import_koishi = require("koishi");
258
258
  var CafeBotDrawConfig = import_koishi.Schema.object({
259
259
  baseDataUrl: import_koishi.Schema.string().description("数据链接").default("https://www.azimiao.com/kiseki.json"),
260
+ forceUpdateDataWhenLoad: import_koishi.Schema.boolean().description("插件加载时强制刷新数据").default(false),
260
261
  ImageServer: import_koishi.Schema.string().description("图像生成服务器").default("http://127.0.0.1:3000/screenshot"),
261
262
  ImageServerAuth: import_koishi.Schema.string().description("图像生成服务器密码").default(""),
262
263
  MinCount: import_koishi.Schema.number().description("最小抽取次数").default(0),
@@ -281,6 +282,29 @@ function At(argv, newLine = true) {
281
282
  }
282
283
  __name(At, "At");
283
284
 
285
+ // src/common/downloadTool.ts
286
+ var fs = __toESM(require("fs/promises"));
287
+ var import_fs_promises = __toESM(require("fs.promises.exists"));
288
+ async function downloadFileIfNotExist(http, downloadUrl, savePath, forceUpdate) {
289
+ var result = true;
290
+ var exist = await (0, import_fs_promises.default)(savePath);
291
+ console.log(savePath);
292
+ var needDownload = !exist || forceUpdate;
293
+ if (needDownload) {
294
+ console.log(`Data ${savePath} not exist or forceUpdate,try download from ${downloadUrl}`);
295
+ result = await http.get(downloadUrl).then(async (res) => {
296
+ await fs.writeFile(savePath, JSON.stringify(res));
297
+ console.log(`Data ${downloadUrl} download ok,save path ${savePath}`);
298
+ return true;
299
+ }).catch((e) => {
300
+ return false;
301
+ });
302
+ }
303
+ return result;
304
+ }
305
+ __name(downloadFileIfNotExist, "downloadFileIfNotExist");
306
+ var downloadTool_default = downloadFileIfNotExist;
307
+
284
308
  // src/draw/index.ts
285
309
  var name = "cafe-bot-exp.draw";
286
310
  var inject = ["http"];
@@ -298,21 +322,15 @@ function shuffleWithCustomRandom(array, rand) {
298
322
  }
299
323
  __name(shuffleWithCustomRandom, "shuffleWithCustomRandom");
300
324
  var star2Name = null;
301
- async function downloadCardDataIfNotExist(ctx, config) {
302
- if (cafebotCardData != null && cafebotCardData.length > 0) {
325
+ async function downloadCardDataIfNotExist(ctx, config, forceUpdate) {
326
+ if (!forceUpdate && cafebotCardData != null && cafebotCardData.length > 0) {
303
327
  return;
304
328
  }
305
329
  const root = path.join(ctx.baseDir, "data", `${name}-data`);
306
- await fs.mkdir(root, { recursive: true });
330
+ await fs2.mkdir(root, { recursive: true });
307
331
  const cardFilePath = path.join(root, "card.json");
308
- var a = await (0, import_fs_promises.default)(cardFilePath);
309
- if (!a) {
310
- console.log(`card data ${cardFilePath} not exist,try download from ${config.baseDataUrl}`);
311
- await ctx.http.get(config.baseDataUrl).then(async (res) => {
312
- await fs.writeFile(cardFilePath, JSON.stringify(res));
313
- });
314
- }
315
- var fileContent = await fs.readFile(cardFilePath, "utf-8");
332
+ await downloadTool_default(ctx.http, config.baseDataUrl, cardFilePath, forceUpdate);
333
+ var fileContent = await fs2.readFile(cardFilePath, "utf-8");
316
334
  try {
317
335
  cafebotCardData = JSON.parse(fileContent);
318
336
  } catch (error) {
@@ -322,7 +340,7 @@ async function downloadCardDataIfNotExist(ctx, config) {
322
340
  }
323
341
  __name(downloadCardDataIfNotExist, "downloadCardDataIfNotExist");
324
342
  async function getCards(seed, ctx, config) {
325
- await downloadCardDataIfNotExist(ctx, config);
343
+ await downloadCardDataIfNotExist(ctx, config, false);
326
344
  let minCount = config.MinCount;
327
345
  let maxCount = config.MaxCount;
328
346
  let randomer = new PseudoRandom_default(seed);
@@ -377,6 +395,7 @@ async function getCards(seed, ctx, config) {
377
395
  }
378
396
  __name(getCards, "getCards");
379
397
  async function apply(ctx, config) {
398
+ await downloadCardDataIfNotExist(ctx, config, config.forceUpdateDataWhenLoad);
380
399
  ctx.command("轨迹抽卡/给我抽", "进行每日抽卡").action(async (argv, _) => {
381
400
  let seed = DailySeededName(argv.session.userId);
382
401
  console.log(`getcard for ${seed}`);
@@ -448,6 +467,7 @@ async function apply(ctx, config) {
448
467
  await argv.session?.cancelQueued();
449
468
  console.log(`getcard img for ${seed} send ok~`);
450
469
  }).catch(async (e) => {
470
+ console.log(e);
451
471
  delete requestWebCache[seed];
452
472
  await argv.session?.sendQueued(`${At(argv)}图片生成失败`);
453
473
  await argv.session?.cancelQueued();
@@ -536,20 +556,42 @@ __export(quiz_exports, {
536
556
  inject: () => inject2,
537
557
  name: () => name3
538
558
  });
559
+ var import_koishi6 = require("koishi");
560
+ var fs3 = __toESM(require("fs/promises"));
561
+ var path2 = __toESM(require("path"));
539
562
 
540
563
  // src/quiz/config.ts
541
564
  var import_koishi5 = require("koishi");
542
565
  var CafeBotQuizConfig = import_koishi5.Schema.object({
543
- baseQuizUrl: import_koishi5.Schema.string().description("答题数据 Url").default("https://www.azimiao.com/quiz.json"),
566
+ baseQuizUrl: import_koishi5.Schema.string().description("答题列表 Url").default("https://www.azimiao.com/quiz.json"),
567
+ forceUpdateWhenLoad: import_koishi5.Schema.boolean().description("插件加载时强制更新题目列表").default(false),
568
+ answerTimeout: import_koishi5.Schema.number().description("回答超时时间(秒)").default(300),
544
569
  maxQuizPerDay: import_koishi5.Schema.number().description("每日单人最大答题数").default(5),
545
570
  redisServer: import_koishi5.Schema.string().description("redis服务器地址"),
546
571
  // TODO: 计划: 分数存储使用 sqlite, 临时数据(如当前题目)用内存就行了?
547
572
  redisAuth: import_koishi5.Schema.string().description("redis服务器密码")
548
573
  }).description("答题配置");
549
574
 
575
+ // src/common/CafeTimeTools.ts
576
+ var CafeTimeTools = {
577
+ getRemainingSecondsToBeijingMidnight: function() {
578
+ const now = /* @__PURE__ */ new Date();
579
+ const utcNow = now.getTime();
580
+ const target = new Date(now);
581
+ target.setUTCHours(16, 0, 0, 0);
582
+ if (utcNow >= target.getTime()) {
583
+ target.setUTCDate(target.getUTCDate() + 1);
584
+ }
585
+ const diff = target.getTime() - utcNow;
586
+ const seconds = Math.ceil(diff / 1e3);
587
+ return seconds;
588
+ }
589
+ };
590
+ var CafeTimeTools_default = CafeTimeTools;
591
+
550
592
  // src/quiz/index.ts
551
593
  var name3 = "cafe-bot-exp.quiz";
552
- var inject2 = ["http"];
594
+ var inject2 = ["http", "cache"];
553
595
  var Config3 = CafeBotQuizConfig;
554
596
  var validOptions = {
555
597
  "A": 0,
@@ -565,31 +607,135 @@ var validOptions = {
565
607
  "3": 2,
566
608
  "4": 3
567
609
  };
610
+ var quizDataIds = [];
611
+ var quizDataSet = {};
612
+ async function downloadQuitDataIfNotExist(ctx, config, forceUpdate) {
613
+ if (!forceUpdate && quizDataIds != null && quizDataIds.length > 0) {
614
+ return;
615
+ }
616
+ const root = path2.join(ctx.baseDir, "data", `${name3}-data`);
617
+ await fs3.mkdir(root, { recursive: true });
618
+ const quizFilePath = path2.join(root, "quiz.json");
619
+ await downloadTool_default(ctx.http, config.baseQuizUrl, quizFilePath, forceUpdate);
620
+ var fileContent = await fs3.readFile(quizFilePath, "utf-8");
621
+ try {
622
+ var a = JSON.parse(fileContent);
623
+ var quizData = a.filter((item) => item.question.t === "MCWithTextOnly");
624
+ quizData.forEach((element) => {
625
+ quizDataIds.push(element.question.id);
626
+ quizDataSet[element.question.id] = element;
627
+ });
628
+ } catch (error) {
629
+ throw new Error("quiz read error");
630
+ }
631
+ return;
632
+ }
633
+ __name(downloadQuitDataIfNotExist, "downloadQuitDataIfNotExist");
634
+ async function answerHandler(ctx, config, argv, answer) {
635
+ await downloadQuitDataIfNotExist(ctx, config, false);
636
+ var lastQuestion = await ctx.cache.get("question", argv.session.userId);
637
+ if (!lastQuestion) {
638
+ await argv.session?.send("你还未开始答题或已超时哦~");
639
+ return;
640
+ }
641
+ let selectNumber = -1;
642
+ if (answer in validOptions) {
643
+ selectNumber = validOptions[answer];
644
+ } else {
645
+ await argv.session?.send(`${At(argv)}选项无效,请重新输入~`);
646
+ return;
647
+ }
648
+ await ctx.cache.delete("question", argv.session.userId);
649
+ if (quizDataIds == null || quizDataIds.length <= 0) {
650
+ await argv.session?.send(`${At(argv)}超级计算机『卡佩尔』发生核心故障😵`);
651
+ return;
652
+ }
653
+ var qItem = quizDataSet[lastQuestion.question];
654
+ console.log(`${argv.session.userId} try answer quiz(id:${lastQuestion.question}), input answer:${selectNumber}`);
655
+ if (qItem && lastQuestion.answer == selectNumber) {
656
+ await argv.session?.send(`${At(argv)}回答正确😊${qItem.explain.length > 0 ? "," + qItem.explain : ""}`);
657
+ return;
658
+ } else {
659
+ await argv.session?.send(`${At(argv)}回答错误😟${qItem.explain2.length > 0 ? "," + qItem.explain2 : ""}`);
660
+ return;
661
+ }
662
+ }
663
+ __name(answerHandler, "answerHandler");
568
664
  async function apply3(ctx, config) {
665
+ await downloadQuitDataIfNotExist(ctx, config, config.forceUpdateWhenLoad);
569
666
  ctx.command("轨迹答题/出题").action(async (argv, _) => {
570
- await argv.session?.send("开发中");
571
- return;
572
- });
573
- ctx.command("轨迹答题/回答 <answer:text>", `使用"回答+选项"回答问题,如"回答 A"`).action(async (argv, answer) => {
574
- let selectNumber = -1;
575
- if (answer in validOptions) {
576
- selectNumber = validOptions[answer];
577
- } else {
578
- await argv.session?.send(`${At(argv)}回答错误~`);
667
+ await downloadQuitDataIfNotExist(ctx, config, false);
668
+ var lastQuestion = await ctx.cache.get("question", argv.session.userId);
669
+ if (lastQuestion) {
670
+ await argv.session?.send("上一题还没有回答哦~");
671
+ return;
672
+ }
673
+ var dailyNameKey = DailySeededName(argv.session.userId);
674
+ if (quizDataIds == null || quizDataIds.length <= 0) {
675
+ await argv.session?.send(`${At(argv)}超级计算机『卡佩尔』发生核心故障😵`);
676
+ return;
677
+ }
678
+ var todayCount = await ctx.cache.get("todayCache", dailyNameKey);
679
+ if (!todayCount) {
680
+ todayCount = 0;
579
681
  }
580
- if (selectNumber == 3) {
581
- await argv.session?.send(`<audio src="https://trails-game.com/wp-content/uploads/2021/07/renne.wav"/>`);
682
+ if (todayCount >= config.maxQuizPerDay) {
683
+ await argv.session?.send(`${At(argv)}今日答题已到上限哦~明天再来看看吧❤`);
582
684
  return;
583
- } else {
584
- await argv.session?.send(`${At(argv)}开发中`);
585
685
  }
686
+ todayCount++;
687
+ var cacheTimeoutTime = CafeTimeTools_default.getRemainingSecondsToBeijingMidnight();
688
+ await ctx.cache.set("todayCache", dailyNameKey, todayCount, cacheTimeoutTime * 1e3);
689
+ var randomId = import_koishi6.Random.pick(quizDataIds);
690
+ var qItem = quizDataSet[randomId];
691
+ var qOptions = import_koishi6.Random.shuffle(qItem.options);
692
+ var answerIndex = -1;
693
+ console.log(`${argv.session.userId} get a new quiz(id:${randomId})`);
694
+ for (var i = 0; i < qOptions.length; i++) {
695
+ if (qOptions[i].oid === qItem.a) {
696
+ answerIndex = i;
697
+ break;
698
+ }
699
+ }
700
+ await ctx.cache.set("question", argv.session.userId, { question: randomId, answer: answerIndex }, config.answerTimeout * 1e3);
701
+ var messageQuestion = `${qItem.question.img.length > 0 ? `<img src="${qItem.question.img}"/>` : ``}${At(argv)}${qItem.question.s}
702
+ A. ${qOptions[0].s}
703
+ B. ${qOptions[1].s}
704
+ C. ${qOptions[2].s}
705
+ D. ${qOptions[3].s}`;
706
+ await argv.session?.send(messageQuestion);
707
+ return;
708
+ });
709
+ ctx.command("轨迹答题/回答 <answer:text>", `回复"回答+空格+选项"回答问题哦,如"回答 A"`).action(async (argv, answer) => {
710
+ await answerHandler(ctx, config, argv, answer);
711
+ return;
712
+ });
713
+ ctx.command("轨迹答题/A", "选择 A 选项").action(async (argv, _) => {
714
+ await answerHandler(ctx, config, argv, "A");
715
+ return;
716
+ });
717
+ ctx.command("轨迹答题/B", "选择 B 选项").action(async (argv, _) => {
718
+ await answerHandler(ctx, config, argv, "B");
719
+ return;
720
+ });
721
+ ctx.command("轨迹答题/C", "选择 C 选项").action(async (argv, _) => {
722
+ await answerHandler(ctx, config, argv, "C");
723
+ return;
724
+ });
725
+ ctx.command("轨迹答题/D", "选择 D 选项").action(async (argv, _) => {
726
+ await answerHandler(ctx, config, argv, "D");
727
+ return;
728
+ });
729
+ ctx.command("轨迹答题/答题分数").action(async (argv, _) => {
730
+ await argv.session?.send(`${At(argv)}正在开发中哦~`);
731
+ return;
586
732
  });
587
733
  }
588
734
  __name(apply3, "apply");
589
735
 
590
736
  // src/config.ts
591
- var import_koishi6 = require("koishi");
592
- var Config4 = import_koishi6.Schema.intersect([
737
+ var import_koishi7 = require("koishi");
738
+ var Config4 = import_koishi7.Schema.intersect([
593
739
  CafeBotDrawConfig.collapse(),
594
740
  CafeBotQuizConfig.collapse(),
595
741
  CafeBotCatConfig.collapse()
@@ -597,6 +743,7 @@ var Config4 = import_koishi6.Schema.intersect([
597
743
 
598
744
  // src/index.ts
599
745
  var name4 = "cafe-bot-exp";
746
+ var inject3 = ["http", "cache"];
600
747
  async function apply4(ctx, config) {
601
748
  ctx.plugin(draw_exports, config);
602
749
  ctx.plugin(quiz_exports, config);
@@ -610,5 +757,6 @@ __name(apply4, "apply");
610
757
  0 && (module.exports = {
611
758
  Config,
612
759
  apply,
760
+ inject,
613
761
  name
614
762
  });
@@ -4,6 +4,8 @@
4
4
  import { Schema } from "koishi";
5
5
  export interface CafeBotQuizConfig {
6
6
  baseQuizUrl: string;
7
+ forceUpdateWhenLoad: boolean;
8
+ answerTimeout: number;
7
9
  maxQuizPerDay: number;
8
10
  redisServer: string;
9
11
  redisAuth: string;
@@ -8,4 +8,15 @@ export declare const inject: string[];
8
8
  export interface Config extends CafeBotQuizConfig {
9
9
  }
10
10
  export declare const Config: Schema<Config>;
11
+ interface QuestionCache {
12
+ question: number;
13
+ answer: number;
14
+ }
15
+ declare module '@koishijs/cache' {
16
+ interface Tables {
17
+ question: QuestionCache;
18
+ todayCache: number;
19
+ }
20
+ }
11
21
  export declare function apply(ctx: Context, config: Config): Promise<void>;
22
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@azimiao/koishi-plugin-cafe-bot-exp",
3
3
  "description": "cafe bot experiment",
4
- "version": "0.0.9",
4
+ "version": "0.0.11",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "repository": {
@@ -32,7 +32,8 @@
32
32
  },
33
33
  "service": {
34
34
  "required": [
35
- "http"
35
+ "http",
36
+ "cache"
36
37
  ]
37
38
  },
38
39
  "locales": [
@@ -44,4 +45,4 @@
44
45
  "@stdlib/random-base-uniform": "^0.2.1",
45
46
  "fs.promises.exists": "^1.1.4"
46
47
  }
47
- }
48
+ }
@@ -1 +0,0 @@
1
- export declare function DailySeededName(uid: any): string;
@@ -1,2 +0,0 @@
1
- export declare function DailySeededName(uid: any): string;
2
- export declare function DailySeededRandom(uid: any): () => number;
@@ -1,11 +0,0 @@
1
- /**
2
- * PseudoRandom 伪随机数类
3
- */
4
- declare class PseudoRandom {
5
- private seed;
6
- private randFunc;
7
- constructor(seedStr: string);
8
- next: () => number;
9
- nextInt: (min: number, max: number) => number;
10
- }
11
- export default PseudoRandom;
@@ -1,2 +0,0 @@
1
- declare function HtmlCreator(cardList: any): string;
2
- export default HtmlCreator;
File without changes