koishi-plugin-node-async-bot-all 2.8.0 → 2.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/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
@@ -14,6 +14,7 @@ export declare const usage = "\u8FD9\u662F\u4E00\u4E2A\u79C1\u6709\u63D2\u4EF6\u
14
14
  export interface ConfigCxV2 {
15
15
  id: string;
16
16
  api: Array<string>;
17
+ note: Array<string>;
17
18
  }
18
19
  export interface Config {
19
20
  cxV2: Array<ConfigCxV2>;
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➣ 协议版本:{protocol}", listNoPlayer: "【MC 服务器 {count}】\n➣ {version}:{players}\n➣ 协议版本:{protocol}", 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: { cxmc: { 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}", 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}" } } } };
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) {
@@ -221,6 +256,7 @@ async function getServer(ctx, session) {
221
256
  let count = 0;
222
257
  let list = "";
223
258
  for (const item of api) {
259
+ const note = ctx.config.cxV2[index]["note"][count];
224
260
  count++;
225
261
  try {
226
262
  const response = await fetchWithTimeout(item, {}, ctx.config.timeout, log);
@@ -233,7 +269,7 @@ async function getServer(ctx, session) {
233
269
  "count": count,
234
270
  "players": data["players"],
235
271
  "version": data["version"],
236
- "protocol": data["protocol"]
272
+ "note": note ?? ""
237
273
  };
238
274
  log.info(`Server ${count}:`);
239
275
  log.info(temp);
@@ -244,7 +280,7 @@ async function getServer(ctx, session) {
244
280
  "players": data["players"],
245
281
  "version": data["version"],
246
282
  "list": data["list"].join(", "),
247
- "protocol": data["protocol"]
283
+ "note": note ?? ""
248
284
  };
249
285
  log.info(`Server ${count}:`);
250
286
  log.info(temp);
@@ -283,10 +319,10 @@ async function getServer(ctx, session) {
283
319
  list = list + "\n" + session.text(".listFailed", temp);
284
320
  }
285
321
  } catch (err) {
286
- log.error(`Request error: ${err.message}`);
322
+ log.error(`Request error: ${err.message}`);
287
323
  const temp = {
288
324
  "count": count,
289
- "data": session.text(".error")
325
+ "data": err.name === "AbortError" ? session.text(".error") : err.message
290
326
  };
291
327
  log.info(`Server ${count}:`);
292
328
  log.info(temp);
@@ -323,7 +359,7 @@ async function getStatus(ctx, session) {
323
359
  "success": 1
324
360
  };
325
361
  } else {
326
- const msgCount = getMsgCount(await ctx.database.get("analytics.message", { date: import_koishi.Time.getDateNumber() - 1 }, ["type", "count"]));
362
+ const msgCount = await getMsgCount(ctx);
327
363
  msg = {
328
364
  "time": time,
329
365
  "name": vMsg["name"],
@@ -424,6 +460,7 @@ async function getRW(ctx, session) {
424
460
  log.error(`Request error: ${err.message}`);
425
461
  msg = {
426
462
  "time": time,
463
+ "data": err.name === "AbortError" ? session.text(".error") : err.message,
427
464
  "success": 2
428
465
  };
429
466
  log.info("Sent:");
@@ -435,14 +472,13 @@ __name(getRW, "getRW");
435
472
  async function getBA(ctx, session) {
436
473
  const log = ctx.logger("ba");
437
474
  log.info(`Got: {"form":"${session.event.guild?.id}","user":"${session.event.user?.id}","timestamp":${session.event.timestamp},"messageId":"${session.event.message?.id}"}`);
438
- const random = new import_koishi.Random(() => Math.random());
439
475
  const time = getHongKongTime();
440
476
  const vid = await session.send(session.text(".wait", { "time": time }));
441
- const ms = random.int(0, 1500);
442
- 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)}`;
443
479
  log.info(`Link: ${link}`);
444
- await (0, import_koishi.sleep)(ms);
445
- await session.send(import_koishi.h.image(link));
480
+ await (0, import_koishi2.sleep)(ms);
481
+ await session.send(import_koishi2.h.image(link));
446
482
  await session.bot.deleteMessage(session.event.guild?.id, vid[0]);
447
483
  return 0;
448
484
  }
@@ -486,32 +522,33 @@ async function serverTest(ctx, session) {
486
522
  __name(serverTest, "serverTest");
487
523
 
488
524
  // package.json
489
- var version = "2.8.0";
525
+ var version = "2.10.0";
490
526
 
491
527
  // src/index.ts
492
528
  var inject = ["database"];
493
529
  var name = "node-async-bot-all";
494
530
  var usage = "这是一个私有插件。";
495
- var Config = import_koishi2.Schema.intersect([
496
- import_koishi2.Schema.object({
497
- timeout: import_koishi2.Schema.number().default(8e3).description("超时时间(毫秒)")
531
+ var Config = import_koishi3.Schema.intersect([
532
+ import_koishi3.Schema.object({
533
+ timeout: import_koishi3.Schema.number().default(8e3).description("超时时间(毫秒)")
498
534
  }).description("基础"),
499
- import_koishi2.Schema.object({
500
- cxV2: import_koishi2.Schema.array(
501
- import_koishi2.Schema.object({
502
- id: import_koishi2.Schema.string().required().description("查询 群"),
503
- api: import_koishi2.Schema.array(String).description("查询 API")
535
+ import_koishi3.Schema.object({
536
+ cxV2: import_koishi3.Schema.array(
537
+ import_koishi3.Schema.object({
538
+ id: import_koishi3.Schema.string().required().description("查询 群"),
539
+ api: import_koishi3.Schema.array(String).description("查询 API"),
540
+ note: import_koishi3.Schema.array(String).description("查询 备注")
504
541
  })
505
542
  ).default([]).description("查询的 API 和 群")
506
543
  }).description("查询"),
507
- import_koishi2.Schema.object({
508
- rwAPI: import_koishi2.Schema.string().default("https://api.tasaed.top/rw/").description("随机文本 API")
544
+ import_koishi3.Schema.object({
545
+ rwAPI: import_koishi3.Schema.string().default("https://api.tasaed.top/rw/").description("随机文本 API")
509
546
  }).description("随机文本"),
510
- import_koishi2.Schema.object({
511
- baAPI: import_koishi2.Schema.array(String).default(["https://rba.kanostar.top/portrait"]).description("随机BA图 API")
547
+ import_koishi3.Schema.object({
548
+ baAPI: import_koishi3.Schema.array(String).default(["https://rba.kanostar.top/portrait"]).description("随机BA图 API")
512
549
  }).description("随机BA图"),
513
- import_koishi2.Schema.object({
514
- serverPing: import_koishi2.Schema.dict(String).role("table").description("键:群号;值:Host")
550
+ import_koishi3.Schema.object({
551
+ serverPing: import_koishi3.Schema.dict(String).role("table").description("键:群号;值:Host")
515
552
  }).description("服之测测(Ping)")
516
553
  ]).description("基础设置");
517
554
  function apply(ctx) {
@@ -528,7 +565,7 @@ function apply(ctx) {
528
565
  { id: "version", data: version }
529
566
  ]);
530
567
  });
531
- ctx.command("cx").action(async ({ session }) => {
568
+ ctx.command("cxMc").action(async ({ session }) => {
532
569
  const cx = await getServer(ctx, session);
533
570
  if (cx["success"] == 0) {
534
571
  return session?.text(".msg", cx);
@@ -547,8 +584,8 @@ function apply(ctx) {
547
584
  }
548
585
  });
549
586
  ctx.command("random [最小数:number] [最大数:number]").alias("随机数").action(async ({ session }, min, max) => {
550
- const random = await getRandom(ctx, session, min, max);
551
- return session?.text(".msg", random);
587
+ const random2 = await getRandom(ctx, session, min, max);
588
+ return session?.text(".msg", random2);
552
589
  });
553
590
  ctx.command("info").action(async ({ session }) => {
554
591
  const info = await getInfo(ctx, session);
@@ -568,7 +605,7 @@ function apply(ctx) {
568
605
  return session?.text(".failed2", rw);
569
606
  }
570
607
  });
571
- ctx.command("randomBA").alias("随机BA图").action(async ({ session }) => {
608
+ ctx.command("randomBA").alias("随机ba图").action(async ({ session }) => {
572
609
  await getBA(ctx, session);
573
610
  });
574
611
  ctx.command("serverTest").alias("服之测测").action(async ({ session }) => {
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.8.0",
4
+ "version": "2.10.0",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "contributors": [