koishi-plugin-node-async-bot-all 2.9.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/commands.d.ts CHANGED
@@ -6,3 +6,4 @@ export declare function getInfo(ctx: Context, session: Session): Promise<Object>
6
6
  export declare function getRW(ctx: Context, session: Session): Promise<Object>;
7
7
  export declare function getBA(ctx: Context, session: Session): Promise<Number>;
8
8
  export declare function serverTest(ctx: Context, session: Session): Promise<Object>;
9
+ export declare function getSteam(ctx: Context, session: Session, id: number): Promise<Object>;
package/lib/fun.d.ts CHANGED
@@ -1,11 +1,10 @@
1
- import { Context, FlatPick } from "koishi";
2
- import Analytics from "@koishijs/plugin-analytics";
1
+ import { Context } from "koishi";
3
2
  export declare function getSystemUsage(): Promise<Object>;
4
3
  export declare function getHongKongTime(): string;
5
4
  export declare function fetchWithTimeout(url: string, options: {} | undefined, timeout: number | undefined, log: any): Promise<Response>;
6
5
  export declare function readInfoFile(ctx: Context): Promise<string>;
7
6
  export declare function formatTimestampDiff(start: number, end: number): string;
8
- export declare function getMsgCount(array: FlatPick<Analytics.Message, "type" | "count">[]): Object;
7
+ export declare function getMsgCount(ctx: Context): Promise<Object>;
9
8
  export declare function hostPing(host: string): Promise<{
10
9
  success: boolean;
11
10
  data?: any;
@@ -13,3 +12,4 @@ export declare function hostPing(host: string): Promise<{
13
12
  alive?: boolean;
14
13
  packetLoss?: string;
15
14
  }>;
15
+ export declare function random(type: number | undefined, data: any, data2?: any): number;
package/lib/index.d.ts CHANGED
@@ -15,12 +15,14 @@ export interface ConfigCxV2 {
15
15
  id: string;
16
16
  api: Array<string>;
17
17
  note: Array<string>;
18
+ type: Array<string>;
18
19
  }
19
20
  export interface Config {
20
21
  cxV2: Array<ConfigCxV2>;
21
22
  rwAPI: string;
22
23
  timeout: number;
23
24
  baAPI: string[];
25
+ steamAPI: string;
24
26
  }
25
27
  export declare const Config: Schema<Config>;
26
28
  export declare function apply(ctx: Context): void;
package/lib/index.js CHANGED
@@ -34,7 +34,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
34
34
  // src/locales/zh-CN.yml
35
35
  var require_zh_CN = __commonJS({
36
36
  "src/locales/zh-CN.yml"(exports2, module2) {
37
- module2.exports = { commands: { cx: { description: "查询服务器当前人数。", messages: { msg: "{time}{list}\n进服指南请在群公告中查看。", list: "【MC 服务器 {count}】\n➣ {version}:{players}\n➣ 玩家列表:{list}\n➣ 备注:{note}", listNoPlayer: "【MC 服务器 {count}】\n➣ {version}:{players}\n➣ 备注:{note}", listFailed: "【MC 服务器 {count}】\n➣ 查询失败:{data}\n➣ 请稍后重试。", forbidden: "{time}\n此指令不允许在本群使用。", failed: "{time}\n查询失败:{data}", timeout: "请求超时。", timeout2: "响应超时。", fewData: "服务端返回的数据过少。", close: "服务器已关闭。", error: "执行错误。", unknown: "未知错误。", host: "没有到主机的路由。" } }, status: { description: "查询机器人状态。", messages: { msg: "{time}\n--- 系统状态 ---\n系统名称:{name}\nCPU使用率:{cpu}\n内存使用率:{memory}\n--- 机器人状态 ---\n昨日收/发消息数量:{msgCount}\n机器人版本:{version}\n运行时间:{online}", failed: "{time}\n状态获取失败。" } }, random: { description: "随机数生成器。", usage: "缺少参数时默认生成 0-10000 的随机数。\n使用示例:", examples: "random 1 128 生成1到128范围的随机数", messages: { msg: "{time}\n生成的随机数:{data}" } }, info: { description: "查询机器人信息。", messages: { msg: "{data}", failed: "{time}\n读取信息失败。" } }, rw: { description: "随机名言名句。", messages: { msg: "{time}\n{data}", failed1: "{time}\n获取失败(1)。", failed2: "{time}\n获取失败(2)。" } }, randomba: { description: "随机BA图。", messages: { wait: "{time}\n请等待图片上传(可能较慢)。" } }, servertest: { description: "Ping服务器。", messages: { msg: "{time}\n== Ping {host} ==\n状态:{alive}\n丢包率:{packetLoss}\n返回IP:{ip}", forbidden: "{time}\n此指令不允许在本群使用。", failed: "{time}\nPing 失败:{data}" } } } };
37
+ module2.exports = { commands: { cxgame: { description: "查询服务器当前人数。", messages: { msg: "{time}{list}\n进服指南请在群公告中查看。", list: "【{type} 服务器 {count}】\n➣ {version}:{players}\n➣ 玩家列表:{list}\n➣ 备注:{note}", listNoPlayer: "【{type} 服务器 {count}】\n➣ {version}:{players}\n➣ 备注:{note}", listFailed: "【{type} 服务器 {count}】\n➣ 查询失败:{data}\n➣ 请稍后重试。", forbidden: "{time}\n此指令不允许在本群使用。", failed: "{time}\n查询失败:{data}", timeout: "请求超时。", timeout2: "响应超时。", fewData: "服务端返回的数据过少。", close: "服务器已关闭。", error: "执行错误。", unknown: "未知错误。", host: "没有到主机的路由。" } }, status: { description: "查询机器人状态。", messages: { msg: "{time}\n--- 系统状态 ---\n系统名称:{name}\nCPU使用率:{cpu}\n内存使用率:{memory}\n--- 机器人状态 ---\n昨日收/发消息数量:{msgCount}\n机器人版本:{version}\n运行时间:{online}", failed: "{time}\n状态获取失败。" } }, random: { description: "随机数生成器。", usage: "缺少参数时默认生成 0-10000 的随机数。\n使用示例:", examples: "random 1 128 生成1到128范围的随机数", messages: { msg: "{time}\n生成的随机数:{data}" } }, info: { description: "查询机器人信息。", messages: { msg: "{data}", failed: "{time}\n读取信息失败。" } }, rw: { description: "随机名言名句。", messages: { msg: "{time}\n{data}", error: "执行错误。", failed1: "{time}\n获取失败(1)。", failed2: "{time}\n获取失败({data})。" } }, randomba: { description: "随机BA图。", messages: { wait: "{time}\n请等待图片上传(可能较慢)。" } }, servertest: { description: "Ping服务器。", messages: { msg: "{time}\n== Ping {host} ==\n状态:{alive}\n丢包率:{packetLoss}\n返回IP:{ip}", forbidden: "{time}\n此指令不允许在本群使用。", failed: "{time}\nPing 失败:{data}" } }, steamid: { description: "将 Steam 好友码(SteamID 3)转为 SteamID 64。", messages: { msg: "{time}\n转换结果:{data}", failed: "{time}\n转换失败:{data}", null: "参数 Steam 好友码(SteamID 3) 不得为空。" } } } };
38
38
  }
39
39
  });
40
40
 
@@ -48,16 +48,17 @@ __export(src_exports, {
48
48
  usage: () => usage
49
49
  });
50
50
  module.exports = __toCommonJS(src_exports);
51
- var import_koishi2 = require("koishi");
51
+ var import_koishi3 = require("koishi");
52
52
 
53
53
  // src/commands.ts
54
- var import_koishi = require("koishi");
54
+ var import_koishi2 = require("koishi");
55
55
 
56
56
  // src/fun.ts
57
57
  var import_os = __toESM(require("os"));
58
58
  var import_fs = __toESM(require("fs"));
59
59
  var import_ping = __toESM(require("ping"));
60
60
  var import_path = __toESM(require("path"));
61
+ var import_koishi = require("koishi");
61
62
  function getSystemName() {
62
63
  return import_os.default.type() + " " + import_os.default.release();
63
64
  }
@@ -66,19 +67,29 @@ function getMemoryUsage() {
66
67
  const totalMemory = import_os.default.totalmem();
67
68
  const freeMemory = import_os.default.freemem();
68
69
  const usedMemory = totalMemory - freeMemory;
69
- return Math.round(usedMemory / totalMemory * 100);
70
+ return Math.round(usedMemory / totalMemory * 1e4) / 100;
70
71
  }
71
72
  __name(getMemoryUsage, "getMemoryUsage");
72
73
  async function getCpuUsage() {
73
- const startUsage = process.cpuUsage();
74
- return new Promise((resolve) => {
75
- setTimeout(() => {
76
- const endUsage = process.cpuUsage(startUsage);
77
- const totalUsage = endUsage.user + endUsage.system;
78
- const percentage = totalUsage / (1e3 * 1e3);
79
- resolve(Math.round(percentage * 100));
80
- }, 1e3);
81
- });
74
+ const cpus1 = import_os.default.cpus();
75
+ await new Promise((resolve) => setTimeout(resolve, 100));
76
+ const cpus2 = import_os.default.cpus();
77
+ let totalIdle = 0;
78
+ let totalTick = 0;
79
+ for (let i = 0; i < cpus1.length; i++) {
80
+ const cpu1 = cpus1[i];
81
+ const cpu2 = cpus2[i];
82
+ const idle1 = cpu1.times.idle;
83
+ const total1 = Object.values(cpu1.times).reduce((acc, time) => acc + time, 0);
84
+ const idle2 = cpu2.times.idle;
85
+ const total2 = Object.values(cpu2.times).reduce((acc, time) => acc + time, 0);
86
+ const idleDiff = idle2 - idle1;
87
+ const totalDiff = total2 - total1;
88
+ totalIdle += idleDiff;
89
+ totalTick += totalDiff;
90
+ }
91
+ const usage2 = 100 - 100 * totalIdle / totalTick;
92
+ return Math.round(usage2 * 100) / 100;
82
93
  }
83
94
  __name(getCpuUsage, "getCpuUsage");
84
95
  async function getSystemUsage() {
@@ -101,30 +112,38 @@ async function getSystemUsage() {
101
112
  __name(getSystemUsage, "getSystemUsage");
102
113
  function getHongKongTime() {
103
114
  const now = /* @__PURE__ */ new Date();
104
- const hkOffset = 8 * 60;
105
- const hkTime = new Date(now.getTime() + (hkOffset + now.getTimezoneOffset()) * 6e4);
106
- return [
107
- hkTime.getFullYear(),
108
- (hkTime.getMonth() + 1).toString().padStart(2, "0"),
109
- hkTime.getDate().toString().padStart(2, "0")
110
- ].join("-") + " " + [
111
- hkTime.getHours().toString().padStart(2, "0"),
112
- hkTime.getMinutes().toString().padStart(2, "0"),
113
- hkTime.getSeconds().toString().padStart(2, "0")
114
- ].join(":");
115
+ const formatter = new Intl.DateTimeFormat("zh-CN", {
116
+ timeZone: "Asia/Hong_Kong",
117
+ year: "numeric",
118
+ month: "2-digit",
119
+ day: "2-digit",
120
+ hour: "2-digit",
121
+ minute: "2-digit",
122
+ second: "2-digit",
123
+ hour12: false
124
+ });
125
+ const parts = formatter.formatToParts(now);
126
+ const dateObj = {};
127
+ parts.forEach((part) => {
128
+ if (part.type !== "literal") {
129
+ dateObj[part.type] = part.value;
130
+ }
131
+ });
132
+ return `${dateObj.year}-${dateObj.month}-${dateObj.day} ${dateObj.hour}:${dateObj.minute}:${dateObj.second}`;
115
133
  }
116
134
  __name(getHongKongTime, "getHongKongTime");
117
135
  async function fetchWithTimeout(url, options = {}, timeout = 5e3, log) {
118
136
  const controller = new AbortController();
137
+ const { signal } = controller;
138
+ const fetchOptions = {
139
+ ...options,
140
+ signal
141
+ };
119
142
  const timeoutId = setTimeout(() => {
120
143
  controller.abort();
121
144
  }, timeout);
122
145
  try {
123
- const response = await fetch(url, {
124
- ...options,
125
- signal: controller.signal
126
- // 绑定终止信号
127
- });
146
+ const response = await fetch(url, fetchOptions);
128
147
  clearTimeout(timeoutId);
129
148
  log.info(`Fetch code: ${response.status}`);
130
149
  return response;
@@ -133,7 +152,7 @@ async function fetchWithTimeout(url, options = {}, timeout = 5e3, log) {
133
152
  log.error(error);
134
153
  log.error(`${error.name}: ${error.message}`);
135
154
  if (error.name === "AbortError") {
136
- throw new Error("请求超时");
155
+ throw new Error(`请求超时。(${timeout}ms)`);
137
156
  } else {
138
157
  throw error;
139
158
  }
@@ -163,7 +182,9 @@ function formatTimestampDiff(start, end) {
163
182
  return `${hours} 时 ${minutes} 分 ${seconds} 秒`;
164
183
  }
165
184
  __name(formatTimestampDiff, "formatTimestampDiff");
166
- function getMsgCount(array) {
185
+ async function getMsgCount(ctx) {
186
+ const array = await ctx.database.get("analytics.message", { date: import_koishi.Time.getDateNumber() - 1 }, ["type", "count"]);
187
+ ctx.logger.info(import_koishi.Time.getDateNumber() - 1);
167
188
  let receive = 0;
168
189
  let send = 0;
169
190
  array.forEach((item) => {
@@ -195,6 +216,20 @@ async function hostPing(host) {
195
216
  }
196
217
  }
197
218
  __name(hostPing, "hostPing");
219
+ function random(type = 0, data, data2) {
220
+ const random2 = new import_koishi.Random(() => Math.random());
221
+ switch (type) {
222
+ case 0:
223
+ return random2.int(data, data2);
224
+ case 1:
225
+ return random2.real(data, data2);
226
+ case 2:
227
+ return random2.pick(data);
228
+ default:
229
+ return 0;
230
+ }
231
+ }
232
+ __name(random, "random");
198
233
 
199
234
  // src/commands.ts
200
235
  async function getServer(ctx, session) {
@@ -284,10 +319,10 @@ async function getServer(ctx, session) {
284
319
  list = list + "\n" + session.text(".listFailed", temp);
285
320
  }
286
321
  } catch (err) {
287
- log.error(`Request error: ${err.message}`);
322
+ log.error(`Request error: ${err.message}`);
288
323
  const temp = {
289
324
  "count": count,
290
- "data": session.text(".error")
325
+ "data": err.name === "AbortError" ? session.text(".error") : err.message
291
326
  };
292
327
  log.info(`Server ${count}:`);
293
328
  log.info(temp);
@@ -324,7 +359,7 @@ async function getStatus(ctx, session) {
324
359
  "success": 1
325
360
  };
326
361
  } else {
327
- const msgCount = getMsgCount(await ctx.database.get("analytics.message", { date: import_koishi.Time.getDateNumber() - 1 }, ["type", "count"]));
362
+ const msgCount = await getMsgCount(ctx);
328
363
  msg = {
329
364
  "time": time,
330
365
  "name": vMsg["name"],
@@ -425,6 +460,7 @@ async function getRW(ctx, session) {
425
460
  log.error(`Request error: ${err.message}`);
426
461
  msg = {
427
462
  "time": time,
463
+ "data": err.name === "AbortError" ? session.text(".error") : err.message,
428
464
  "success": 2
429
465
  };
430
466
  log.info("Sent:");
@@ -436,14 +472,13 @@ __name(getRW, "getRW");
436
472
  async function getBA(ctx, session) {
437
473
  const log = ctx.logger("ba");
438
474
  log.info(`Got: {"form":"${session.event.guild?.id}","user":"${session.event.user?.id}","timestamp":${session.event.timestamp},"messageId":"${session.event.message?.id}"}`);
439
- const random = new import_koishi.Random(() => Math.random());
440
475
  const time = getHongKongTime();
441
476
  const vid = await session.send(session.text(".wait", { "time": time }));
442
- const ms = random.int(0, 1500);
443
- const link = random.pick(ctx.config.baAPI) + `?cacheBuster=${random.real(1, 2147483647)}`;
477
+ const ms = random(0, 0, 1500);
478
+ const link = random(2, ctx.config.baAPI) + `?cacheBuster=${random(1, 1, 2147483647)}`;
444
479
  log.info(`Link: ${link}`);
445
- await (0, import_koishi.sleep)(ms);
446
- await session.send(import_koishi.h.image(link));
480
+ await (0, import_koishi2.sleep)(ms);
481
+ await session.send(import_koishi2.h.image(link));
447
482
  await session.bot.deleteMessage(session.event.guild?.id, vid[0]);
448
483
  return 0;
449
484
  }
@@ -485,36 +520,84 @@ async function serverTest(ctx, session) {
485
520
  };
486
521
  }
487
522
  __name(serverTest, "serverTest");
523
+ async function getSteam(ctx, session, id) {
524
+ const log = ctx.logger("steamId");
525
+ log.info(`Got: {"form":"${session.event.guild?.id}","user":"${session.event.user?.id}","timestamp":${session.event.timestamp},"messageId":"${session.event.message?.id}"}`);
526
+ let msg;
527
+ let data;
528
+ const time = getHongKongTime();
529
+ try {
530
+ const response = await fetchWithTimeout(ctx.config.steamAPI + `?format=json&id=${id}`, {}, ctx.config.timeout, log);
531
+ if (response.ok) {
532
+ data = await response.text();
533
+ log.info("Server data: " + data);
534
+ data = JSON.parse(data);
535
+ msg = {
536
+ "time": time,
537
+ "data": data["data"],
538
+ "success": 0
539
+ };
540
+ log.info("Sent:");
541
+ log.info(msg);
542
+ } else {
543
+ data = await response.text();
544
+ log.error(`Error fetching data: ${data}`);
545
+ data = JSON.parse(data);
546
+ msg = {
547
+ "time": time,
548
+ "data": data["data"],
549
+ "success": 1
550
+ };
551
+ log.info("Sent:");
552
+ log.info(msg);
553
+ }
554
+ } catch (err) {
555
+ log.error(`Request error: ${err.message}`);
556
+ msg = {
557
+ "time": time,
558
+ "data": err.name === "AbortError" ? session.text(".error") : err.message,
559
+ "success": 2
560
+ };
561
+ log.info("Sent:");
562
+ log.info(msg);
563
+ }
564
+ return msg;
565
+ }
566
+ __name(getSteam, "getSteam");
488
567
 
489
568
  // package.json
490
- var version = "2.9.0";
569
+ var version = "2.11.0";
491
570
 
492
571
  // src/index.ts
493
572
  var inject = ["database"];
494
573
  var name = "node-async-bot-all";
495
574
  var usage = "这是一个私有插件。";
496
- var Config = import_koishi2.Schema.intersect([
497
- import_koishi2.Schema.object({
498
- timeout: import_koishi2.Schema.number().default(8e3).description("超时时间(毫秒)")
575
+ var Config = import_koishi3.Schema.intersect([
576
+ import_koishi3.Schema.object({
577
+ timeout: import_koishi3.Schema.number().default(8e3).description("超时时间(毫秒)")
499
578
  }).description("基础"),
500
- import_koishi2.Schema.object({
501
- cxV2: import_koishi2.Schema.array(
502
- import_koishi2.Schema.object({
503
- id: import_koishi2.Schema.string().required().description("查询 群"),
504
- api: import_koishi2.Schema.array(String).description("查询 API"),
505
- note: import_koishi2.Schema.array(String).description("查询 备注")
579
+ import_koishi3.Schema.object({
580
+ cxV2: import_koishi3.Schema.array(
581
+ import_koishi3.Schema.object({
582
+ id: import_koishi3.Schema.string().required().description("查询 群"),
583
+ api: import_koishi3.Schema.array(String).description("查询 API"),
584
+ note: import_koishi3.Schema.array(String).description("查询 备注"),
585
+ type: import_koishi3.Schema.array(String).description("查询 类型")
506
586
  })
507
587
  ).default([]).description("查询的 API 和 群")
508
588
  }).description("查询"),
509
- import_koishi2.Schema.object({
510
- rwAPI: import_koishi2.Schema.string().default("https://api.tasaed.top/rw/").description("随机文本 API")
589
+ import_koishi3.Schema.object({
590
+ rwAPI: import_koishi3.Schema.string().default("https://api.tasaed.top/rw/").description("随机文本 API")
511
591
  }).description("随机文本"),
512
- import_koishi2.Schema.object({
513
- baAPI: import_koishi2.Schema.array(String).default(["https://rba.kanostar.top/portrait"]).description("随机BA图 API")
592
+ import_koishi3.Schema.object({
593
+ baAPI: import_koishi3.Schema.array(String).default(["https://rba.kanostar.top/portrait"]).description("随机BA图 API")
514
594
  }).description("随机BA图"),
515
- import_koishi2.Schema.object({
516
- serverPing: import_koishi2.Schema.dict(String).role("table").description("键:群号;值:Host")
517
- }).description("服之测测(Ping)")
595
+ import_koishi3.Schema.object({
596
+ serverPing: import_koishi3.Schema.dict(String).role("table").description("键:群号;值:Host")
597
+ }).description("服之测测(Ping)"),
598
+ import_koishi3.Schema.object({
599
+ steamAPI: import_koishi3.Schema.string().default("https://api.tasaed.top/get/steamid/").description("转换 Steam ID API")
600
+ }).description("转换 Steam ID")
518
601
  ]).description("基础设置");
519
602
  function apply(ctx) {
520
603
  ctx.i18n.define("zh-CN", require_zh_CN());
@@ -530,7 +613,7 @@ function apply(ctx) {
530
613
  { id: "version", data: version }
531
614
  ]);
532
615
  });
533
- ctx.command("cx").action(async ({ session }) => {
616
+ ctx.command("cxGame").action(async ({ session }) => {
534
617
  const cx = await getServer(ctx, session);
535
618
  if (cx["success"] == 0) {
536
619
  return session?.text(".msg", cx);
@@ -549,8 +632,8 @@ function apply(ctx) {
549
632
  }
550
633
  });
551
634
  ctx.command("random [最小数:number] [最大数:number]").alias("随机数").action(async ({ session }, min, max) => {
552
- const random = await getRandom(ctx, session, min, max);
553
- return session?.text(".msg", random);
635
+ const random2 = await getRandom(ctx, session, min, max);
636
+ return session?.text(".msg", random2);
554
637
  });
555
638
  ctx.command("info").action(async ({ session }) => {
556
639
  const info = await getInfo(ctx, session);
@@ -570,7 +653,7 @@ function apply(ctx) {
570
653
  return session?.text(".failed2", rw);
571
654
  }
572
655
  });
573
- ctx.command("randomBA").alias("随机BA图").action(async ({ session }) => {
656
+ ctx.command("randomBA").alias("随机ba图").action(async ({ session }) => {
574
657
  await getBA(ctx, session);
575
658
  });
576
659
  ctx.command("serverTest").alias("服之测测").action(async ({ session }) => {
@@ -583,6 +666,17 @@ function apply(ctx) {
583
666
  return session?.text(".failed", server);
584
667
  }
585
668
  });
669
+ ctx.command("steamId <Steam 好友码(SteamID 3):posint>").alias("steam").action(async ({ session }, id) => {
670
+ if (id == null) {
671
+ return session?.text(".null");
672
+ }
673
+ const steam = await getSteam(ctx, session, id);
674
+ if (steam["success"] == 0) {
675
+ return session?.text(".msg", steam);
676
+ } else {
677
+ return session?.text(".failed", steam);
678
+ }
679
+ });
586
680
  }
587
681
  __name(apply, "apply");
588
682
  // Annotate the CommonJS export names for ESM import in node:
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-node-async-bot-all",
3
3
  "description": "NodeAsync Bot插件(自用)",
4
- "version": "2.9.0",
4
+ "version": "2.11.0",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "contributors": [