mioki 0.4.2 → 0.5.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/dist/index.d.cts CHANGED
@@ -11,13 +11,19 @@ import mri from "mri";
11
11
  import path from "node:path";
12
12
  import dayjs from "dayjs";
13
13
  import dedent from "dedent";
14
+ import { box, colorize, colors, stripAnsi } from "consola/utils";
14
15
  import systemInfo from "systeminformation";
15
16
  import { ScheduledTask, TaskContext } from "node-cron";
16
17
 
17
18
  //#region rolldown:runtime
18
19
  //#endregion
19
20
  //#region src/logger.d.ts
20
- declare const getMiokiLogger: (level: LogLevel) => ConsolaInstance;
21
+ declare const logger: ConsolaInstance;
22
+ /**
23
+ * 获取日志文件名
24
+ */
25
+ declare function getLogFilePath(type?: string): string;
26
+ declare function getMiokiLogger(level: LogLevel): ConsolaInstance;
21
27
  //#endregion
22
28
  //#region src/start.d.ts
23
29
  interface StartOptions {
@@ -25,7 +31,7 @@ interface StartOptions {
25
31
  }
26
32
  declare function start(options?: StartOptions): Promise<void>;
27
33
  declare namespace utils_d_exports {
28
- export { AnyFunc, Arrayable, ChromeUA, CreateCmdOptions, Gettable, HasMessage, Noop, PureObject, START_TIME, base64Decode, base64Encode, clamp, createCmd, createDB, createStore, dayjs, dedent, ensureBuffer, filesize, filter, find, formatDuration, formatQQLevel, fs, getAuthCodeViaTicket, getBfaceUrl, getGroupAvatarLink, getImage, getImageUrl, getMentionedImage, getMentionedImageUrl, getMentionedUserId, getMinicoTokenViaAuthCode, getQQAvatarLink, getQuoteImage, getQuoteImageUrl, getQuoteMessage, getQuoteText, getTerminalInput, isBoolean, isDefined, isFunction, isGroupMsg, isNumber, isObject, isPrivateMsg, isString, jiti, localNum, localeDate, localeTime, match, md5, mri, noNullish, path, prettyMs, qs, queryDevToolsLoginStatus, randomId, randomInt, randomItem, randomItems, requestLoginViaDevTools, runWithReaction, string2argv, stringifyError, systemInfo, text, toArray, toMsgId, unique, uuid, wait };
34
+ export { AnyFunc, Arrayable, ChromeUA, CreateCmdOptions, Gettable, HasMessage, Noop, PureObject, START_TIME, base64Decode, base64Encode, box, clamp, colorize, colors, createCmd, createDB, createStore, dayjs, dedent, ensureBuffer, filesize, filter, find, formatDuration, formatQQLevel, fs, getAuthCodeViaTicket, getBfaceUrl, getGroupAvatarLink, getImage, getImageUrl, getMentionedImage, getMentionedImageUrl, getMentionedUserId, getMinicoTokenViaAuthCode, getQQAvatarLink, getQuoteImage, getQuoteImageUrl, getQuoteMessage, getQuoteText, getTerminalInput, isBoolean, isDefined, isFunction, isGroupMsg, isNumber, isObject, isPrivateMsg, isString, jiti, localNum, localeDate, localeTime, match, md5, mri, noNullish, path, prettyMs, qs, queryDevToolsLoginStatus, randomId, randomInt, randomItem, randomItems, requestLoginViaDevTools, runWithReaction, string2argv, stringifyError, stripAnsi, systemInfo, text, toArray, toMsgId, unique, uuid, wait };
29
35
  }
30
36
  declare const ChromeUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0.0.0";
31
37
  type Noop = () => void;
@@ -356,7 +362,7 @@ declare function getTerminalInput(inputTip?: string): Promise<string>;
356
362
  */
357
363
  declare const START_TIME: Date;
358
364
  declare namespace config_d_exports {
359
- export { BOT_CWD, MiokiConfig, botConfig, getLogFilePath, hasRight, isAdmin, isInPm2, isOwner, isOwnerOrAdmin, readMiokiConfig, readPackageJson, updateBotCWD, updateBotConfig, writePackageJson };
365
+ export { BOT_CWD, MiokiConfig, botConfig, hasRight, isAdmin, isInPm2, isOwner, isOwnerOrAdmin, readMiokiConfig, readPackageJson, updateBotCWD, updateBotConfig, writePackageJson };
360
366
  }
361
367
  /**
362
368
  * mioki 配置
@@ -441,10 +447,6 @@ declare const hasRight: (id: number | {
441
447
  * 是否在 PM2 中运行
442
448
  */
443
449
  declare const isInPm2: boolean;
444
- /**
445
- * 获取日志文件名
446
- */
447
- declare function getLogFilePath(uin: number, platformName: string): string;
448
450
  declare namespace actions_d_exports {
449
451
  export { createForwardMsg, getViolationRecords, noticeAdmins, noticeFriends, noticeGroups, noticeMainOwner, noticeOwners, runWithErrorHandler, signArk, uploadImageToCollection, uploadImageToGroupHomework, uploadImageToGroupNotice };
450
452
  }
@@ -656,5 +658,5 @@ declare function findLocalPlugins(): Promise<{
656
658
  absPath: string;
657
659
  }[]>;
658
660
  //#endregion
659
- export { AnyFunc, Arrayable, BOT_CWD, ChromeUA, CreateCmdOptions, Gettable, HasMessage, MiokiConfig, MiokiContext, MiokiPlugin, MiokiServices, Noop, OmitBotParamFromFunc, PureObject, START_TIME, StartOptions, addService, base64Decode, base64Encode, bindBot, botConfig, clamp, createCmd, createDB, createForwardMsg, createStore, dayjs, dedent, definePlugin, enablePlugin, ensureBuffer, ensurePluginDir, filesize, filter, find, findLocalPlugins, formatDuration, formatQQLevel, fs, getAbsPluginDir, getAuthCodeViaTicket, getBfaceUrl, getGroupAvatarLink, getImage, getImageUrl, getMentionedImage, getMentionedImageUrl, getMentionedUserId, getMinicoTokenViaAuthCode, getMiokiLogger, getQQAvatarLink, getQuoteImage, getQuoteImageUrl, getQuoteMessage, getQuoteText, getTerminalInput, getViolationRecords, hasRight, isAdmin, isBoolean, isDefined, isFunction, isGroupMsg, isInPm2, isNumber, isObject, isOwner, isOwnerOrAdmin, isPrivateMsg, isString, jiti, localNum, localeDate, localeTime, match, md5, mri, noNullish, noticeAdmins, noticeFriends, noticeGroups, noticeMainOwner, noticeOwners, path, prettyMs, qs, queryDevToolsLoginStatus, randomId, randomInt, randomItem, randomItems, readMiokiConfig, readPackageJson, requestLoginViaDevTools, runWithErrorHandler, runWithReaction, runtimePlugins, services, signArk, start, string2argv, stringifyError, systemInfo, text, toArray, toMsgId, unique, updateBotCWD, updateBotConfig, uploadImageToCollection, uploadImageToGroupHomework, uploadImageToGroupNotice, uuid, wait, writePackageJson };
661
+ export { AnyFunc, Arrayable, BOT_CWD, ChromeUA, CreateCmdOptions, Gettable, HasMessage, MiokiConfig, MiokiContext, MiokiPlugin, MiokiServices, Noop, OmitBotParamFromFunc, PureObject, START_TIME, StartOptions, addService, base64Decode, base64Encode, bindBot, botConfig, box, clamp, colorize, colors, createCmd, createDB, createForwardMsg, createStore, dayjs, dedent, definePlugin, enablePlugin, ensureBuffer, ensurePluginDir, filesize, filter, find, findLocalPlugins, formatDuration, formatQQLevel, fs, getAbsPluginDir, getAuthCodeViaTicket, getBfaceUrl, getGroupAvatarLink, getImage, getImageUrl, getLogFilePath, getMentionedImage, getMentionedImageUrl, getMentionedUserId, getMinicoTokenViaAuthCode, getMiokiLogger, getQQAvatarLink, getQuoteImage, getQuoteImageUrl, getQuoteMessage, getQuoteText, getTerminalInput, getViolationRecords, hasRight, isAdmin, isBoolean, isDefined, isFunction, isGroupMsg, isInPm2, isNumber, isObject, isOwner, isOwnerOrAdmin, isPrivateMsg, isString, jiti, localNum, localeDate, localeTime, logger, match, md5, mri, noNullish, noticeAdmins, noticeFriends, noticeGroups, noticeMainOwner, noticeOwners, path, prettyMs, qs, queryDevToolsLoginStatus, randomId, randomInt, randomItem, randomItems, readMiokiConfig, readPackageJson, requestLoginViaDevTools, runWithErrorHandler, runWithReaction, runtimePlugins, services, signArk, start, string2argv, stringifyError, stripAnsi, systemInfo, text, toArray, toMsgId, unique, updateBotCWD, updateBotConfig, uploadImageToCollection, uploadImageToGroupHomework, uploadImageToGroupNotice, uuid, wait, writePackageJson };
660
662
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.mts CHANGED
@@ -10,12 +10,18 @@ import prettyMs from "pretty-ms";
10
10
  import { filesize } from "filesize";
11
11
  import dayjs from "dayjs";
12
12
  import dedent from "dedent";
13
+ import { box, colorize, colors, stripAnsi } from "consola/utils";
13
14
  import systemInfo from "systeminformation";
14
15
  import { ConsolaInstance } from "consola/core";
15
16
  import { ScheduledTask, TaskContext } from "node-cron";
16
17
 
17
18
  //#region src/logger.d.ts
18
- declare const getMiokiLogger: (level: LogLevel) => ConsolaInstance;
19
+ declare const logger: ConsolaInstance;
20
+ /**
21
+ * 获取日志文件名
22
+ */
23
+ declare function getLogFilePath(type?: string): string;
24
+ declare function getMiokiLogger(level: LogLevel): ConsolaInstance;
19
25
  //#endregion
20
26
  //#region src/start.d.ts
21
27
  interface StartOptions {
@@ -23,7 +29,7 @@ interface StartOptions {
23
29
  }
24
30
  declare function start(options?: StartOptions): Promise<void>;
25
31
  declare namespace utils_d_exports {
26
- export { AnyFunc, Arrayable, ChromeUA, CreateCmdOptions, Gettable, HasMessage, Noop, PureObject, START_TIME, base64Decode, base64Encode, clamp, createCmd, createDB, createStore, dayjs, dedent, ensureBuffer, filesize, filter, find, formatDuration, formatQQLevel, fs, getAuthCodeViaTicket, getBfaceUrl, getGroupAvatarLink, getImage, getImageUrl, getMentionedImage, getMentionedImageUrl, getMentionedUserId, getMinicoTokenViaAuthCode, getQQAvatarLink, getQuoteImage, getQuoteImageUrl, getQuoteMessage, getQuoteText, getTerminalInput, isBoolean, isDefined, isFunction, isGroupMsg, isNumber, isObject, isPrivateMsg, isString, jiti, localNum, localeDate, localeTime, match, md5, mri, noNullish, path, prettyMs, qs, queryDevToolsLoginStatus, randomId, randomInt, randomItem, randomItems, requestLoginViaDevTools, runWithReaction, string2argv, stringifyError, systemInfo, text, toArray, toMsgId, unique, uuid, wait };
32
+ export { AnyFunc, Arrayable, ChromeUA, CreateCmdOptions, Gettable, HasMessage, Noop, PureObject, START_TIME, base64Decode, base64Encode, box, clamp, colorize, colors, createCmd, createDB, createStore, dayjs, dedent, ensureBuffer, filesize, filter, find, formatDuration, formatQQLevel, fs, getAuthCodeViaTicket, getBfaceUrl, getGroupAvatarLink, getImage, getImageUrl, getMentionedImage, getMentionedImageUrl, getMentionedUserId, getMinicoTokenViaAuthCode, getQQAvatarLink, getQuoteImage, getQuoteImageUrl, getQuoteMessage, getQuoteText, getTerminalInput, isBoolean, isDefined, isFunction, isGroupMsg, isNumber, isObject, isPrivateMsg, isString, jiti, localNum, localeDate, localeTime, match, md5, mri, noNullish, path, prettyMs, qs, queryDevToolsLoginStatus, randomId, randomInt, randomItem, randomItems, requestLoginViaDevTools, runWithReaction, string2argv, stringifyError, stripAnsi, systemInfo, text, toArray, toMsgId, unique, uuid, wait };
27
33
  }
28
34
  declare const ChromeUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0.0.0";
29
35
  type Noop = () => void;
@@ -354,7 +360,7 @@ declare function getTerminalInput(inputTip?: string): Promise<string>;
354
360
  */
355
361
  declare const START_TIME: Date;
356
362
  declare namespace config_d_exports {
357
- export { BOT_CWD, MiokiConfig, botConfig, getLogFilePath, hasRight, isAdmin, isInPm2, isOwner, isOwnerOrAdmin, readMiokiConfig, readPackageJson, updateBotCWD, updateBotConfig, writePackageJson };
363
+ export { BOT_CWD, MiokiConfig, botConfig, hasRight, isAdmin, isInPm2, isOwner, isOwnerOrAdmin, readMiokiConfig, readPackageJson, updateBotCWD, updateBotConfig, writePackageJson };
358
364
  }
359
365
  /**
360
366
  * mioki 配置
@@ -439,10 +445,6 @@ declare const hasRight: (id: number | {
439
445
  * 是否在 PM2 中运行
440
446
  */
441
447
  declare const isInPm2: boolean;
442
- /**
443
- * 获取日志文件名
444
- */
445
- declare function getLogFilePath(uin: number, platformName: string): string;
446
448
  declare namespace actions_d_exports {
447
449
  export { createForwardMsg, getViolationRecords, noticeAdmins, noticeFriends, noticeGroups, noticeMainOwner, noticeOwners, runWithErrorHandler, signArk, uploadImageToCollection, uploadImageToGroupHomework, uploadImageToGroupNotice };
448
450
  }
@@ -654,5 +656,5 @@ declare function findLocalPlugins(): Promise<{
654
656
  absPath: string;
655
657
  }[]>;
656
658
  //#endregion
657
- export { AnyFunc, Arrayable, BOT_CWD, ChromeUA, CreateCmdOptions, Gettable, HasMessage, MiokiConfig, MiokiContext, MiokiPlugin, MiokiServices, Noop, OmitBotParamFromFunc, PureObject, START_TIME, StartOptions, addService, base64Decode, base64Encode, bindBot, botConfig, clamp, createCmd, createDB, createForwardMsg, createStore, dayjs, dedent, definePlugin, enablePlugin, ensureBuffer, ensurePluginDir, filesize, filter, find, findLocalPlugins, formatDuration, formatQQLevel, fs, getAbsPluginDir, getAuthCodeViaTicket, getBfaceUrl, getGroupAvatarLink, getImage, getImageUrl, getMentionedImage, getMentionedImageUrl, getMentionedUserId, getMinicoTokenViaAuthCode, getMiokiLogger, getQQAvatarLink, getQuoteImage, getQuoteImageUrl, getQuoteMessage, getQuoteText, getTerminalInput, getViolationRecords, hasRight, isAdmin, isBoolean, isDefined, isFunction, isGroupMsg, isInPm2, isNumber, isObject, isOwner, isOwnerOrAdmin, isPrivateMsg, isString, jiti, localNum, localeDate, localeTime, match, md5, mri, noNullish, noticeAdmins, noticeFriends, noticeGroups, noticeMainOwner, noticeOwners, path, prettyMs, qs, queryDevToolsLoginStatus, randomId, randomInt, randomItem, randomItems, readMiokiConfig, readPackageJson, requestLoginViaDevTools, runWithErrorHandler, runWithReaction, runtimePlugins, services, signArk, start, string2argv, stringifyError, systemInfo, text, toArray, toMsgId, unique, updateBotCWD, updateBotConfig, uploadImageToCollection, uploadImageToGroupHomework, uploadImageToGroupNotice, uuid, wait, writePackageJson };
659
+ export { AnyFunc, Arrayable, BOT_CWD, ChromeUA, CreateCmdOptions, Gettable, HasMessage, MiokiConfig, MiokiContext, MiokiPlugin, MiokiServices, Noop, OmitBotParamFromFunc, PureObject, START_TIME, StartOptions, addService, base64Decode, base64Encode, bindBot, botConfig, box, clamp, colorize, colors, createCmd, createDB, createForwardMsg, createStore, dayjs, dedent, definePlugin, enablePlugin, ensureBuffer, ensurePluginDir, filesize, filter, find, findLocalPlugins, formatDuration, formatQQLevel, fs, getAbsPluginDir, getAuthCodeViaTicket, getBfaceUrl, getGroupAvatarLink, getImage, getImageUrl, getLogFilePath, getMentionedImage, getMentionedImageUrl, getMentionedUserId, getMinicoTokenViaAuthCode, getMiokiLogger, getQQAvatarLink, getQuoteImage, getQuoteImageUrl, getQuoteMessage, getQuoteText, getTerminalInput, getViolationRecords, hasRight, isAdmin, isBoolean, isDefined, isFunction, isGroupMsg, isInPm2, isNumber, isObject, isOwner, isOwnerOrAdmin, isPrivateMsg, isString, jiti, localNum, localeDate, localeTime, logger, match, md5, mri, noNullish, noticeAdmins, noticeFriends, noticeGroups, noticeMainOwner, noticeOwners, path, prettyMs, qs, queryDevToolsLoginStatus, randomId, randomInt, randomItem, randomItems, readMiokiConfig, readPackageJson, requestLoginViaDevTools, runWithErrorHandler, runWithReaction, runtimePlugins, services, signArk, start, string2argv, stringifyError, stripAnsi, systemInfo, text, toArray, toMsgId, unique, updateBotCWD, updateBotConfig, uploadImageToCollection, uploadImageToGroupHomework, uploadImageToGroupNotice, uuid, wait, writePackageJson };
658
660
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -13,8 +13,8 @@ import pm, { default as prettyMs } from "pretty-ms";
13
13
  import { filesize } from "filesize";
14
14
  import dayjs from "dayjs";
15
15
  import dedent, { default as dedent$1 } from "dedent";
16
+ import { box, colorize, colors, colors as colors$1, stripAnsi, stripAnsi as stripAnsi$1 } from "consola/utils";
16
17
  import systemInfo from "systeminformation";
17
- import { colors, stripAnsi } from "consola/utils";
18
18
  import { LogLevels, createConsola } from "consola/core";
19
19
  import { hrtime } from "node:process";
20
20
  import os from "node:os";
@@ -27,7 +27,10 @@ var utils_exports = /* @__PURE__ */ __export({
27
27
  START_TIME: () => START_TIME,
28
28
  base64Decode: () => base64Decode,
29
29
  base64Encode: () => base64Encode,
30
+ box: () => box,
30
31
  clamp: () => clamp,
32
+ colorize: () => colorize,
33
+ colors: () => colors,
31
34
  createCmd: () => createCmd,
32
35
  createDB: () => createDB,
33
36
  createStore: () => createStore,
@@ -83,6 +86,7 @@ var utils_exports = /* @__PURE__ */ __export({
83
86
  runWithReaction: () => runWithReaction,
84
87
  string2argv: () => string2argv,
85
88
  stringifyError: () => stringifyError,
89
+ stripAnsi: () => stripAnsi,
86
90
  systemInfo: () => systemInfo,
87
91
  text: () => text,
88
92
  toArray: () => toArray,
@@ -453,7 +457,7 @@ async function getQuoteMessage(event, timeout = 3e3) {
453
457
  resolve(cacheMsg$1);
454
458
  } else if (Date.now() - start$1 > timeout) {
455
459
  clearInterval(timer);
456
- throw new Error(`>>> 获取引用消息超时 ${timeout}, Key: ${key}`);
460
+ throw new Error(`获取引用消息超时 ${timeout}, Key: ${key}`);
457
461
  }
458
462
  }, 100);
459
463
  });
@@ -728,7 +732,6 @@ const START_TIME = /* @__PURE__ */ new Date();
728
732
  var config_exports = /* @__PURE__ */ __export({
729
733
  BOT_CWD: () => BOT_CWD,
730
734
  botConfig: () => botConfig,
731
- getLogFilePath: () => getLogFilePath$1,
732
735
  hasRight: () => hasRight,
733
736
  isAdmin: () => isAdmin,
734
737
  isInPm2: () => isInPm2,
@@ -771,14 +774,14 @@ const updateBotConfig = async (draftFn) => {
771
774
  const pkg = readPackageJson();
772
775
  pkg.mioki = structuredClone(botConfig);
773
776
  writePackageJson(pkg);
774
- console.log(`>>> 检测到配置变动,已同步至 package.json 文件`);
777
+ logger.info(`检测到配置变动,已同步至 package.json 文件`);
775
778
  };
776
779
  /**
777
780
  * 更新机器人根目录
778
781
  */
779
782
  const updateBotCWD = (root) => {
780
783
  BOT_CWD.value = root;
781
- console.log(`>>> 机器人根目录已设置为 ${root}`);
784
+ logger.info(`机器人根目录已设置为 ${root}`);
782
785
  };
783
786
  /**
784
787
  * 是否是主人
@@ -810,13 +813,6 @@ const hasRight = (id) => {
810
813
  * 是否在 PM2 中运行
811
814
  */
812
815
  const isInPm2 = Boolean("pm_id" in process.env || "PM2_USAGE" in process.env);
813
- /**
814
- * 获取日志文件名
815
- */
816
- function getLogFilePath$1(uin, platformName) {
817
- const startTime = dayjs().format("YYYY-MM-DD_HH-mm-ss");
818
- return path$1.join(BOT_CWD.value, `logs/${uin}_${platformName}_${startTime}.log`);
819
- }
820
816
 
821
817
  //#endregion
822
818
  //#region src/logger.ts
@@ -846,6 +842,7 @@ const LEVEL_MAP = {
846
842
  color: "gray"
847
843
  }
848
844
  };
845
+ const logger = getMiokiLogger(botConfig.log_level || "info");
849
846
  /**
850
847
  * 获取日志文件名
851
848
  */
@@ -853,7 +850,7 @@ function getLogFilePath(type = "") {
853
850
  const startTime = dayjs().format("YYYY-MM-DD_HH-mm-ss");
854
851
  return path$1.join(BOT_CWD.value, `logs/${startTime}${type ? "." + type : ""}.log`);
855
852
  }
856
- const getMiokiLogger = (level) => {
853
+ function getMiokiLogger(level) {
857
854
  const logDir = path$1.join(BOT_CWD.value, "logs");
858
855
  if (!fs$1.existsSync(logDir)) fs$1.mkdirSync(logDir, { recursive: true });
859
856
  const logFile = getLogFilePath();
@@ -861,12 +858,12 @@ const getMiokiLogger = (level) => {
861
858
  level: LogLevels[level],
862
859
  defaults: { tag: "mioki" },
863
860
  reporters: [{ log: (logObj) => {
864
- const message = stripAnsi(logObj.message || logObj.args?.join(" ") || "");
861
+ const message = stripAnsi$1(logObj.message || logObj.args?.join(" ") || "");
865
862
  const line = `${`[${logObj.date.toISOString()}] [${LEVEL_MAP[logObj.level].name}] ${logObj.tag ? `[${logObj.tag}] ` : ""}`}${message}`;
866
863
  fs$1.appendFileSync(logFile, line + "\n");
867
864
  } }, { log: (logObj) => {
868
865
  const message = logObj.message || logObj.args?.join(" ") || "";
869
- const line = `${colors.gray(`[${logObj.date.toLocaleTimeString("zh-CN")}]`) + " " + colors.bold(colors[LEVEL_MAP[logObj.level].color](LEVEL_MAP[logObj.level].name)) + " " + (logObj.tag ? colors.dim(`[${logObj.tag}] `) : "")}${message}`;
866
+ const line = `${colors$1.gray(`[${logObj.date.toLocaleTimeString("zh-CN")}]`) + " " + colors$1.bold(colors$1[LEVEL_MAP[logObj.level].color](LEVEL_MAP[logObj.level].name)) + " " + (logObj.tag ? colors$1.dim(`[${logObj.tag}] `) : "")}${message}`;
870
867
  if (logObj.level <= LogLevels["info"]) console.log(line);
871
868
  else if (logObj.level === LogLevels["warn"]) console.warn(line);
872
869
  else console.debug(line);
@@ -877,11 +874,11 @@ const getMiokiLogger = (level) => {
877
874
  date: true
878
875
  }
879
876
  });
880
- };
877
+ }
881
878
 
882
879
  //#endregion
883
880
  //#region package.json
884
- var version = "0.4.2";
881
+ var version = "0.5.0";
885
882
 
886
883
  //#endregion
887
884
  //#region src/actions.ts
@@ -904,11 +901,11 @@ var actions_exports = /* @__PURE__ */ __export({
904
901
  */
905
902
  async function noticeGroups(bot, groupIdList, message, delay = 1e3) {
906
903
  if (!bot.isOnline()) {
907
- bot.logger.error("发送失败,Bot 不在线");
904
+ logger.error("发送失败,Bot 不在线");
908
905
  return;
909
906
  }
910
907
  if (!message) {
911
- bot.logger.warn("消息内容为空");
908
+ logger.warn("消息内容为空");
912
909
  return;
913
910
  }
914
911
  for (const groupId of groupIdList) {
@@ -923,11 +920,11 @@ async function noticeGroups(bot, groupIdList, message, delay = 1e3) {
923
920
  */
924
921
  async function noticeFriends(bot, friendIdList, message, delay = 1e3) {
925
922
  if (!bot.isOnline) {
926
- bot.logger.error("发送失败,Bot 不在线");
923
+ logger.error("发送失败,Bot 不在线");
927
924
  return;
928
925
  }
929
926
  if (!message) {
930
- bot.logger.warn("消息内容为空");
927
+ logger.warn("消息内容为空");
931
928
  return;
932
929
  }
933
930
  for (const friendId of friendIdList) {
@@ -954,11 +951,11 @@ async function noticeOwners(bot, message, delay = 1e3) {
954
951
  */
955
952
  async function noticeMainOwner(bot, message) {
956
953
  if (!bot.isOnline()) {
957
- bot.logger.error("发送失败,Bot 不在线");
954
+ logger.error("发送失败,Bot 不在线");
958
955
  return;
959
956
  }
960
957
  if (!message) {
961
- bot.logger.warn("消息内容为空");
958
+ logger.warn("消息内容为空");
962
959
  return;
963
960
  }
964
961
  const mainOwner = botConfig.owners[0];
@@ -1009,7 +1006,7 @@ async function runWithErrorHandler(bot, fn, event, message = (err) => `报...报
1009
1006
  else try {
1010
1007
  await noticeMainOwner(bot, "发送失败,可能被风控,请检查签名状态。");
1011
1008
  } catch {
1012
- bot.logger.error("发送失败,可能被风控,请检查签名状态。");
1009
+ logger.error("发送失败,可能被风控,请检查签名状态。");
1013
1010
  }
1014
1011
  }
1015
1012
  }
@@ -1189,7 +1186,7 @@ async function enablePlugin(bot, plugin, type = "external") {
1189
1186
  const start$1 = hrtime.bigint();
1190
1187
  const clears = /* @__PURE__ */ new Set();
1191
1188
  const userClears = /* @__PURE__ */ new Set();
1192
- const logger = bot.logger.withDefaults({
1189
+ const logger$1 = bot.logger.withDefaults({
1193
1190
  tag: `plugin:${name}`,
1194
1191
  args: [name]
1195
1192
  });
@@ -1200,33 +1197,33 @@ async function enablePlugin(bot, plugin, type = "external") {
1200
1197
  ...utils_exports,
1201
1198
  ...config_exports,
1202
1199
  ...buildRemovedActions(bot),
1203
- logger,
1200
+ logger: logger$1,
1204
1201
  services,
1205
1202
  clears: userClears,
1206
1203
  addService: (name$1, service, cover) => {
1207
- logger.debug(`Adding service: ${name$1} (cover: ${cover ? "yes" : "no"})`);
1204
+ logger$1.debug(`Adding service: ${name$1} (cover: ${cover ? "yes" : "no"})`);
1208
1205
  const removeService = () => {
1209
- logger.debug(`Removing service: ${name$1}`);
1206
+ logger$1.debug(`Removing service: ${name$1}`);
1210
1207
  addService(name$1, service, cover);
1211
1208
  };
1212
1209
  clears.add(removeService);
1213
1210
  return removeService;
1214
1211
  },
1215
1212
  handle: (eventName, handler) => {
1216
- logger.debug(`Registering event handler for event: ${String(eventName)}`);
1213
+ logger$1.debug(`Registering event handler for event: ${String(eventName)}`);
1217
1214
  bot.on(eventName, handler);
1218
1215
  const unsubscribe = () => {
1219
- logger.debug(`Unregistering event handler for event: ${String(eventName)}`);
1216
+ logger$1.debug(`Unregistering event handler for event: ${String(eventName)}`);
1220
1217
  bot.off(eventName, handler);
1221
1218
  };
1222
1219
  clears.add(unsubscribe);
1223
1220
  return unsubscribe;
1224
1221
  },
1225
1222
  cron: (cronExpression, handler) => {
1226
- logger.debug(`Scheduling cron job: ${cronExpression}`);
1223
+ logger$1.debug(`Scheduling cron job: ${cronExpression}`);
1227
1224
  const job = nodeCron.schedule(cronExpression, (now) => handler(context, now));
1228
1225
  const clear = () => {
1229
- logger.debug(`Stopping cron job: ${cronExpression}`);
1226
+ logger$1.debug(`Stopping cron job: ${cronExpression}`);
1230
1227
  job.stop();
1231
1228
  };
1232
1229
  clears.add(clear);
@@ -1242,19 +1239,19 @@ async function enablePlugin(bot, plugin, type = "external") {
1242
1239
  plugin,
1243
1240
  disable: async () => {
1244
1241
  try {
1245
- logger.debug(`Disabling plugin [${typeDesc}]${name}@${version$1}`);
1242
+ logger$1.debug(`Disabling plugin [${typeDesc}]${name}@${version$1}`);
1246
1243
  await Promise.all([...clears, ...userClears].map((fn) => fn?.()));
1247
1244
  runtimePlugins.delete(name);
1248
1245
  } catch (err) {
1249
- throw new Error(`>>> 禁用插件 [${colors.bold(colors.yellow(typeDesc))}]${colors.bold(colors.yellow(name))}@${colors.bold(colors.yellow(version$1))} 失败: ${err?.message}`);
1246
+ throw new Error(`禁用插件 [${colors$1.yellow(typeDesc)}]${colors$1.yellow(`${name}@${version$1}`)} 失败: ${err?.message}`);
1250
1247
  }
1251
1248
  }
1252
1249
  });
1253
1250
  const end = hrtime.bigint();
1254
1251
  const time = Math.round(Number(end - start$1)) / 1e6;
1255
- bot.logger.info(`>>> 启用插件 ${colors.bold(colors.yellow(`[${typeDesc}]`))}${colors.bold(colors.yellow(`${name}@${version$1}`))} => 耗时 ${colors.bold(colors.green(time.toFixed(2)))} ms`);
1252
+ bot.logger.info(`启用插件 ${colors$1.yellow(`[${typeDesc}]`)}${colors$1.yellow(`${name}@${version$1}`)} => 耗时 ${colors$1.green(time.toFixed(2))} ms`);
1256
1253
  } catch (e) {
1257
- throw new Error(`>>> 启用插件 ${colors.bold(colors.yellow(`[${typeDesc}]`))}${colors.bold(colors.yellow(`${name}@${version$1}`))} 失败: ${e?.message}`);
1254
+ throw new Error(`启用插件 ${colors$1.yellow(`[${typeDesc}]`)}${colors$1.yellow(`${name}@${version$1}`)} 失败: ${e?.message}`);
1258
1255
  }
1259
1256
  return plugin;
1260
1257
  }
@@ -1687,40 +1684,52 @@ async function start(options = {}) {
1687
1684
  const { cwd = process.cwd() } = options;
1688
1685
  if (cwd !== BOT_CWD.value) updateBotCWD(cwd);
1689
1686
  process.title = `mioki v${version}`;
1690
- const logger = getMiokiLogger(botConfig.log_level || "info");
1691
1687
  const plugin_dir = getAbsPluginDir();
1692
- logger.info(`>>> -> ${colors.bold(colors.cyan("mioki"))} ${colors.bold(colors.green(`v${version}`))} <-`);
1693
- logger.info(`>>> ${colors.yellow(colors.underline(`基于 NapCat 的 TypeScript 🤖️ 机器人框架。`))}`);
1694
- logger.info(`>>> ${colors.italic(`作者: Viki <hi@viki.moe> (https://github.com/vikiboss)`)}`);
1695
- logger.info(`>>> ${colors.italic(`协议: Licensed under MIT License.`)}`);
1696
- logger.info(`>>> ${colors.cyan(`GitHub: https://github.com/vikiboss/mioki`)}`);
1697
- logger.info(">>> ----------------------------------------");
1698
- logger.info(`>>> 工作目录: ${colors.bold(colors.blue(BOT_CWD.value))}`);
1699
- logger.info(`>>> 插件目录: ${colors.bold(colors.blue(plugin_dir))}`);
1688
+ logger.info(colors$1.dim("=".repeat(40)));
1689
+ logger.info(`欢迎使用 ${colors$1.bold(colors$1.cyan("mioki"))} ${colors$1.bold(colors$1.green(`v${version}`))}`);
1690
+ logger.info(colors$1.yellow(colors$1.underline(`一个基于 NapCat TypeScript 的QQ 机器人框架`)));
1691
+ logger.info(colors$1.cyan(`轻量 * 跨平台 * 体验 * 热重载 * 继承 KiviBot`));
1692
+ logger.info(colors$1.dim("=".repeat(40)));
1693
+ logger.info(colors$1.dim(colors$1.italic(`作者: Viki <hi@viki.moe> (https://github.com/vikiboss)`)));
1694
+ logger.info(colors$1.dim(colors$1.italic(`仓库: https://github.com/vikiboss/mioki`)));
1695
+ logger.info(colors$1.dim(colors$1.italic(`文档: https://mioki.viki.moe/docs`)));
1696
+ logger.info(colors$1.dim("=".repeat(40)));
1697
+ logger.info(`${colors$1.dim("工作目录: ")}${colors$1.blue(BOT_CWD.value)}`);
1698
+ logger.info(`${colors$1.dim("插件目录: ")}${colors$1.blue(plugin_dir)}`);
1699
+ logger.info(`${colors$1.dim("配置文件: ")}${colors$1.blue(`${BOT_CWD.value}/package.json`)}`);
1700
+ logger.info(colors$1.dim("=".repeat(40)));
1701
+ const { protocol = "ws", port = 6700, host = "localhost", token } = botConfig.napcat || {};
1702
+ logger.info(`开始连接 NapCat 实例: ${colors$1.green(`${protocol}://${host}:${port}`)}`);
1700
1703
  const napcat = new NapCat({
1701
- ...botConfig.napcat,
1704
+ token,
1705
+ protocol,
1706
+ host,
1707
+ port,
1702
1708
  logger
1703
1709
  });
1704
- napcat.on("napcat.connected", async ({ user_id, nickname }) => {
1705
- logger.info(`>>> 已连接到 NapCat: ${colors.bold(colors.green(nickname))}(${colors.bold(colors.green(user_id))})`);
1710
+ napcat.on("ws.close", () => {
1711
+ logger.error("连接已关闭,请确保 NapCat 实例正常运行及 token 配置正确");
1712
+ });
1713
+ napcat.on("napcat.connected", async ({ user_id, nickname, app_name, app_version }) => {
1714
+ logger.info(`已连接到 NapCat 实例: ${colors$1.green(`${app_name}-v${app_version}-${nickname}(${user_id})`)}`);
1706
1715
  let lastNoticeTime = 0;
1707
1716
  process.on("uncaughtException", async (err) => {
1708
1717
  const msg = stringifyError(err);
1709
- napcat.logger.error(`>>> uncaughtException, 出错了: ${msg}`);
1718
+ napcat.logger.error(`uncaughtException, 出错了: ${msg}`);
1710
1719
  if (Date.now() - lastNoticeTime < 1e3) return;
1711
1720
  lastNoticeTime = Date.now();
1712
1721
  await noticeMainOwner(napcat, `mioki 发生未捕获异常:\n\n${msg}`).catch(() => {
1713
- napcat.logger.error(">>> 发送未捕获异常通知失败");
1722
+ napcat.logger.error("发送未捕获异常通知失败");
1714
1723
  });
1715
1724
  });
1716
1725
  process.on("unhandledRejection", async (err) => {
1717
1726
  const msg = stringifyError(err);
1718
- napcat.logger.error(`>>> unhandledRejection, 出错了: ${msg}`);
1727
+ napcat.logger.error(`unhandledRejection, 出错了: ${msg}`);
1719
1728
  if (Date.now() - lastNoticeTime < 1e3) return;
1720
1729
  lastNoticeTime = Date.now();
1721
1730
  const date = (/* @__PURE__ */ new Date()).toLocaleString();
1722
1731
  await noticeMainOwner(napcat, `【${date}】\n\nmioki 发生未处理异常:\n\n${msg}`).catch(() => {
1723
- napcat.logger.error(">>> 发送未处理异常通知失败");
1732
+ napcat.logger.error("发送未处理异常通知失败");
1724
1733
  });
1725
1734
  });
1726
1735
  ensurePluginDir();
@@ -1729,7 +1738,7 @@ async function start(options = {}) {
1729
1738
  absPath: path$1.resolve(plugin_dir, p)
1730
1739
  })).filter((p) => {
1731
1740
  if (!fs$1.existsSync(p.absPath)) {
1732
- napcat.logger.warn(`>>> 插件 ${colors.bold(colors.red(p.dirName))} 不存在,已忽略`);
1741
+ napcat.logger.warn(`插件 ${colors$1.red(p.dirName)} 不存在,已忽略`);
1733
1742
  return false;
1734
1743
  }
1735
1744
  return true;
@@ -1739,7 +1748,7 @@ async function start(options = {}) {
1739
1748
  try {
1740
1749
  const plugin = await jiti.import(absPath, { default: true });
1741
1750
  if (plugin.name !== dirName) {
1742
- const tip = `>>> 插件目录名 [${colors.bold(colors.yellow(dirName))}] 和插件声明的 name [${colors.bold(colors.yellow(plugin.name))}] 不一致,可能导致重载异常,请修改一致后重启。`;
1751
+ const tip = `插件目录名 [${colors$1.yellow(dirName)}] 和插件声明的 name [${colors$1.yellow(plugin.name)}] 不一致,可能导致重载异常,请修改一致后重启。`;
1743
1752
  napcat.logger.warn(tip);
1744
1753
  noticeMainOwner(napcat, tip);
1745
1754
  }
@@ -1753,7 +1762,7 @@ async function start(options = {}) {
1753
1762
  const start$1 = hrtime.bigint();
1754
1763
  const sortedUserPlugins = (await Promise.all(promises)).filter(Boolean).toSorted((prev, next) => (prev.priority ?? 100) - (next.priority ?? 100));
1755
1764
  if (failedImportPlugins.length) {
1756
- const tip = `>>> ${colors.bold(colors.red(failedImportPlugins.length))} 个插件加载失败: \n\n${failedImportPlugins.map(([dirName, err]) => `${dirName}: ${err}`).join("\n\n")}`;
1765
+ const tip = `${colors$1.red(failedImportPlugins.length)} 个插件加载失败: \n\n${failedImportPlugins.map(([dirName, err]) => `${dirName}: ${err}`).join("\n\n")}`;
1757
1766
  napcat.logger.warn(tip);
1758
1767
  noticeMainOwner(napcat, tip);
1759
1768
  }
@@ -1766,7 +1775,7 @@ async function start(options = {}) {
1766
1775
  const sortedGroups = Array.from(pluginGroups.entries()).toSorted(([a], [b]) => a - b);
1767
1776
  const failedEnablePlugins = [];
1768
1777
  try {
1769
- napcat.logger.info(`>>> 加载内置插件: ${BUILTIN_PLUGINS.map((p) => colors.bold(colors.cyan(p.name))).join(", ")}`);
1778
+ napcat.logger.info(`加载内置插件: ${BUILTIN_PLUGINS.map((p) => colors$1.cyan(p.name)).join(", ")}`);
1770
1779
  await Promise.all(BUILTIN_PLUGINS.map((p) => enablePlugin(napcat, p, "builtin")));
1771
1780
  for (const [_, plugins$1] of sortedGroups) await Promise.all(plugins$1.map(async (p) => {
1772
1781
  try {
@@ -1778,22 +1787,22 @@ async function start(options = {}) {
1778
1787
  } catch (e) {
1779
1788
  napcat.logger.error(e?.message);
1780
1789
  await noticeMainOwner(napcat, e?.message).catch(() => {
1781
- napcat.logger.error(">>> 发送插件启用失败通知失败");
1790
+ napcat.logger.error("发送插件启用失败通知失败");
1782
1791
  });
1783
1792
  }
1784
1793
  const end = hrtime.bigint();
1785
1794
  const costTime = Math.round(Number(end - start$1)) / 1e6;
1786
1795
  const failedCount = failedImportPlugins.length + failedEnablePlugins.length;
1787
- const failedInfo = failedCount > 0 ? `${colors.bold(colors.red(failedCount))} 个失败 (导入 ${colors.bold(colors.red(failedImportPlugins.length))},启用 ${colors.bold(colors.red(failedEnablePlugins.length))})。` : "";
1788
- napcat.logger.info(`>>> 成功加载了 ${colors.bold(colors.green(runtimePlugins.size))} 个插件。${failedInfo ? failedInfo : ""}总耗时 ${colors.bold(colors.green(costTime.toFixed(2)))} ms`);
1789
- napcat.logger.info(colors.bold(colors.green(`>>> mioki v${version} 启动完成!祝您使用愉快!🎉️`)));
1796
+ const failedInfo = failedCount > 0 ? `${colors$1.red(failedCount)} 个失败 (导入 ${colors$1.red(failedImportPlugins.length)},启用 ${colors$1.red(failedEnablePlugins.length)})` : "";
1797
+ napcat.logger.info(`成功加载了 ${colors$1.green(runtimePlugins.size)} 个插件,${failedInfo ? failedInfo : ""}总耗时 ${colors$1.green(costTime.toFixed(2))} 毫秒`);
1798
+ napcat.logger.info(colors$1.green(`mioki v${version} 启动完成,祝您使用愉快 🎉️`));
1790
1799
  if (botConfig.online_push) await noticeMainOwner(napcat, `✅ mioki v${version} 已就绪`).catch((err) => {
1791
- napcat.logger.error(`>>> 发送就绪通知失败: ${stringifyError(err)}`);
1800
+ napcat.logger.error(`发送就绪通知失败: ${stringifyError(err)}`);
1792
1801
  });
1793
1802
  });
1794
1803
  await napcat.run();
1795
1804
  }
1796
1805
 
1797
1806
  //#endregion
1798
- export { BOT_CWD, ChromeUA, START_TIME, addService, base64Decode, base64Encode, bindBot, botConfig, clamp, createCmd, createDB, createForwardMsg, createStore, dayjs, dedent, definePlugin, enablePlugin, ensureBuffer, ensurePluginDir, filesize, filter, find, findLocalPlugins, formatDuration, formatQQLevel, fs, getAbsPluginDir, getAuthCodeViaTicket, getBfaceUrl, getGroupAvatarLink, getImage, getImageUrl, getMentionedImage, getMentionedImageUrl, getMentionedUserId, getMinicoTokenViaAuthCode, getMiokiLogger, getQQAvatarLink, getQuoteImage, getQuoteImageUrl, getQuoteMessage, getQuoteText, getTerminalInput, getViolationRecords, hasRight, isAdmin, isBoolean, isDefined, isFunction, isGroupMsg, isInPm2, isNumber, isObject, isOwner, isOwnerOrAdmin, isPrivateMsg, isString, jiti, localNum, localeDate, localeTime, match, md5, mri, noNullish, noticeAdmins, noticeFriends, noticeGroups, noticeMainOwner, noticeOwners, path, prettyMs, qs, queryDevToolsLoginStatus, randomId, randomInt, randomItem, randomItems, readMiokiConfig, readPackageJson, requestLoginViaDevTools, runWithErrorHandler, runWithReaction, runtimePlugins, services, signArk, start, string2argv, stringifyError, systemInfo, text, toArray, toMsgId, unique, updateBotCWD, updateBotConfig, uploadImageToCollection, uploadImageToGroupHomework, uploadImageToGroupNotice, uuid, wait, writePackageJson };
1807
+ export { BOT_CWD, ChromeUA, START_TIME, addService, base64Decode, base64Encode, bindBot, botConfig, box, clamp, colorize, colors, createCmd, createDB, createForwardMsg, createStore, dayjs, dedent, definePlugin, enablePlugin, ensureBuffer, ensurePluginDir, filesize, filter, find, findLocalPlugins, formatDuration, formatQQLevel, fs, getAbsPluginDir, getAuthCodeViaTicket, getBfaceUrl, getGroupAvatarLink, getImage, getImageUrl, getLogFilePath, getMentionedImage, getMentionedImageUrl, getMentionedUserId, getMinicoTokenViaAuthCode, getMiokiLogger, getQQAvatarLink, getQuoteImage, getQuoteImageUrl, getQuoteMessage, getQuoteText, getTerminalInput, getViolationRecords, hasRight, isAdmin, isBoolean, isDefined, isFunction, isGroupMsg, isInPm2, isNumber, isObject, isOwner, isOwnerOrAdmin, isPrivateMsg, isString, jiti, localNum, localeDate, localeTime, logger, match, md5, mri, noNullish, noticeAdmins, noticeFriends, noticeGroups, noticeMainOwner, noticeOwners, path, prettyMs, qs, queryDevToolsLoginStatus, randomId, randomInt, randomItem, randomItems, readMiokiConfig, readPackageJson, requestLoginViaDevTools, runWithErrorHandler, runWithReaction, runtimePlugins, services, signArk, start, string2argv, stringifyError, stripAnsi, systemInfo, text, toArray, toMsgId, unique, updateBotCWD, updateBotConfig, uploadImageToCollection, uploadImageToGroupHomework, uploadImageToGroupNotice, uuid, wait, writePackageJson };
1799
1808
  //# sourceMappingURL=index.mjs.map