@atri-bot/core 1.1.21 → 1.1.23
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.ts +22 -1
- package/dist/index.js +7 -5
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -237,8 +237,16 @@ declare class Bot extends InjectLogger {
|
|
|
237
237
|
}): Promise<string>;
|
|
238
238
|
}
|
|
239
239
|
|
|
240
|
+
type LogRecorderConfig = {
|
|
241
|
+
enable?: boolean;
|
|
242
|
+
maxFiles?: number;
|
|
243
|
+
logLevel?: LogLevel;
|
|
244
|
+
logDir?: string;
|
|
245
|
+
};
|
|
246
|
+
|
|
240
247
|
type ATRIConfig = {
|
|
241
248
|
bot: BotConfig;
|
|
249
|
+
logRecorder?: LogRecorderConfig;
|
|
242
250
|
debug?: boolean;
|
|
243
251
|
baseDir: string;
|
|
244
252
|
configDir?: string;
|
|
@@ -263,10 +271,23 @@ interface LoadPluginOptions {
|
|
|
263
271
|
baseDir?: string;
|
|
264
272
|
}
|
|
265
273
|
|
|
274
|
+
declare class LogRecorder extends InjectLogger {
|
|
275
|
+
config: LogRecorderConfig;
|
|
276
|
+
atriConfig: ATRIConfig;
|
|
277
|
+
originConsoleLog: (message?: any, ...optionalParams: any[]) => void;
|
|
278
|
+
constructor(atriConfig: ATRIConfig, config: LogRecorderConfig);
|
|
279
|
+
rewriteConsole(): void;
|
|
280
|
+
handleException(): void;
|
|
281
|
+
stripAnsi(str: string): string;
|
|
282
|
+
saveLog(args: string[]): void;
|
|
283
|
+
removeUselessLogs(): void;
|
|
284
|
+
}
|
|
285
|
+
|
|
266
286
|
declare class ATRI extends InjectLogger {
|
|
267
287
|
config: ATRIConfig;
|
|
268
288
|
configDir: string;
|
|
269
289
|
bot: Bot;
|
|
290
|
+
logRecorder: LogRecorder;
|
|
270
291
|
import: NodeJS.Require;
|
|
271
292
|
loadedPlugins: Record<string, BasePlugin>;
|
|
272
293
|
loadPluginHooks: Record<string, LoadPluginHook>;
|
|
@@ -309,4 +330,4 @@ declare function performanceCounter(): () => string;
|
|
|
309
330
|
*/
|
|
310
331
|
declare function sortObjectArray<T extends object>(arr: T[], property: keyof T, sortType?: 'up' | 'down'): T[];
|
|
311
332
|
|
|
312
|
-
export { ATRI, type ATRIConfig, type AutoInferCommandEndPoint, type AutoInferMessageEndPoint, type AutoInferNoticeEndPoint, type AutoInferRequestEndPoint, BasePlugin, Bot, type BotConfig, type BotEvents, type CallbackReturn, type CallbackReturnType, type CommandCallback, type CommandContext, type CommandData, type CommandEvent, CommanderUtils, type LoadPluginHook, type LoadPluginHookContext, type LoadPluginOptions, type MessageCallback, type MessageEvent, type NonEmptyArray, type NoticeCallback, type NoticeEvent, type OptionArgs, type OptionParams, type PackageJson, type PluginModule, type RegEventOptions, type RemoveField, type RequestCallback, type RequestEvent, type UnRegHandler, performanceCounter, sortObjectArray };
|
|
333
|
+
export { ATRI, type ATRIConfig, type AutoInferCommandEndPoint, type AutoInferMessageEndPoint, type AutoInferNoticeEndPoint, type AutoInferRequestEndPoint, BasePlugin, Bot, type BotConfig, type BotEvents, type CallbackReturn, type CallbackReturnType, type CommandCallback, type CommandContext, type CommandData, type CommandEvent, CommanderUtils, type LoadPluginHook, type LoadPluginHookContext, type LoadPluginOptions, type LogRecorderConfig, type MessageCallback, type MessageEvent, type NonEmptyArray, type NoticeCallback, type NoticeEvent, type OptionArgs, type OptionParams, type PackageJson, type PluginModule, type RegEventOptions, type RemoveField, type RequestCallback, type RequestEvent, type UnRegHandler, performanceCounter, sortObjectArray };
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
var
|
|
2
|
-
(\u4F7F\u7528 -h \u83B7\u53D6\u5E2E\u52A9\u4FE1\u606F)`)]}else return this.logger.ERROR("\u547D\u4EE4\u5904\u7406\u51FA\u9519:",a),[2,a instanceof Error?a.message:"\u672A\u77E5\u9519\u8BEF"]}return[0,{prefix:s,commandName:r,params:{},args:[]}]}getCommandInfo(e,t,n="name"){let o=e[n]().replace("/","");return o===""||o==="program"?t:o}getCommandHelpInformation(e){let t=this.events.command.find(i=>i.commandName==="*"?!1:typeof i.commandName=="string"?i.commandName===e:i.commandName instanceof RegExp?i.commandName.test(e):!1);if(!t||!t.commander)return;let n=this.getCommandInfo(t.commander,t.commandName.toString()),o=this.config.prefix[0];return t.commander.name(n.includes(o)?n:`${o}${n}`).helpOption("-h, --help","\u5C55\u793A\u5E2E\u52A9\u4FE1\u606F").helpInformation().replaceAll("default:","\u9ED8\u8BA4\u503C:").replace("Arguments:","\u53C2\u6570:").replace("Options:","\u9009\u9879:").replace("Usage:","\u7528\u6CD5:")}async sendMsg(e,t,{reply:n=!0,at:o=!0}={}){try{if(e.message_type==="private")return await this.ws.send_private_msg({user_id:e.user_id,message:t});{let s=[];return n&&e.message_id&&s.push(
|
|
3
|
-
`)),t=[...s,...t],await this.ws.send_group_msg({group_id:e.group_id,message:t})}}catch{return null}}async sendForwardMsg(e,t){try{return e.message_type==="private"?await this.ws.send_private_forward_msg({user_id:e.user_id,message:t}):await this.ws.send_group_forward_msg({group_id:e.group_id,message:t})}catch{return null}}async isFriend(e){return this.ws.get_friend_list().then(t=>t.find(n=>n.user_id===e.user_id))}async getUsername(e){return"group_id"in e?this.ws.get_group_member_info({group_id:e.group_id,user_id:e.user_id}).then(t=>t.nickname):this.ws.get_stranger_info({user_id:e.user_id}).then(t=>t.nickname)}};var
|
|
1
|
+
var A=Object.defineProperty;var g=(m,e)=>A(m,"name",{value:e,configurable:!0});import{InjectLogger as S,Logger as B,LogLevel as O}from"@huan_kong/logger";import{createRequire as T}from"module";import l from"fs";import p from"path";import F from"process";import{InjectLogger as q,Logger as I,LogLevel as P}from"@huan_kong/logger";import{CommanderError as D}from"commander";import{NCWebsocket as H,Structs as h}from"node-napcat-ts";function b(){let m=performance.now();return()=>(performance.now()-m).toFixed(2)}g(b,"performanceCounter");function u(m,e,t="up"){return m.sort((n,o)=>n[e]>o[e]?t==="up"?1:-1:n[e]<o[e]?t==="up"?-1:1:0)}g(u,"sortObjectArray");var y=class m extends q{static{g(this,"Bot")}ws;config;events={command:[],message:[],notice:[],request:[]};constructor(e,t){super({level:e.logLevel??(e.debug?P.DEBUG:void 0)}),this.ws=t,this.config=e,e.debug&&(t.on("api.preSend",n=>this.logger.DEBUG("\u53D1\u9001API\u8BF7\u6C42",n)),t.on("api.response.success",n=>this.logger.DEBUG("\u6536\u5230API\u6210\u529F\u54CD\u5E94",n)),t.on("api.response.failure",n=>this.logger.DEBUG("\u6536\u5230API\u5931\u8D25\u54CD\u5E94",n)),t.on("message",n=>{if(n.message.length===0){this.logger.DEBUG("\u6536\u5230\u7A7A\u6D88\u606F, \u5DF2\u8DF3\u8FC7\u5904\u7406\u6D41\u7A0B:",n);return}this.logger.DEBUG("\u6536\u5230\u6D88\u606F:",n)}),t.on("request",n=>this.logger.DEBUG("\u6536\u5230\u8BF7\u6C42:",n)),t.on("notice",n=>this.logger.DEBUG("\u6536\u5230\u901A\u77E5:",n))),t.on("message",async n=>{if(n.message.length===0||this.config.debug&&!this.config.adminId.includes(n.user_id))return;let o=`message.${n.message_type}.${n.sub_type}`,s=this.config.adminId.includes(n.user_id),i=n.message[0].type==="reply";for(let r of this.events.message)if(o.includes(r.endPoint??"message")&&(!r.needReply||i)&&(!r.needAdmin||s)&&(!r.regexp||r.regexp.test(n.raw_message)))try{if(await r.callback({context:n})==="quit"){this.logger.DEBUG(`\u63D2\u4EF6 ${r.packageName} \u8BF7\u6C42\u63D0\u524D\u7EC8\u6B62`);break}}catch(d){this.logger.ERROR(`\u63D2\u4EF6 ${r.packageName} \u4E8B\u4EF6\u5904\u7406\u5931\u8D25:`,d)}for(let r of this.events.command)if(o.includes(r.endPoint??"message")&&(!r.needAdmin||s)&&(!r.needReply||i)){let[d,a]=this.parseCommand(n.raw_message,r.commandName,r.commander);if(d===1)continue;if(d===2){await this.sendMsg(n,[h.text(a)]);continue}let{prefix:E,commandName:C,params:f,args:k}=a;try{if(await r.callback({context:n,prefix:E,commandName:C,params:f,args:k})==="quit"){this.logger.DEBUG(`\u63D2\u4EF6 ${r.packageName} \u8BF7\u6C42\u63D0\u524D\u7EC8\u6B62`);break}}catch(x){this.logger.ERROR(`\u63D2\u4EF6 ${r.packageName} \u4E8B\u4EF6\u5904\u7406\u5931\u8D25:`,x)}}}),t.on("request",async n=>{let o=`request.${n.request_type}.${"sub_type"in n?n.sub_type:""}`;for(let s of this.events.request)if(o.includes(s.endPoint??"request"))try{if(await s.callback({context:n})==="quit"){this.logger.DEBUG(`\u63D2\u4EF6 ${s.packageName} \u8BF7\u6C42\u63D0\u524D\u7EC8\u6B62`);break}}catch(i){this.logger.ERROR(`\u63D2\u4EF6 ${s.packageName} \u4E8B\u4EF6\u5904\u7406\u5931\u8D25:`,i)}}),t.on("notice",async n=>{let o=`notice.${n.notice_type}.${"sub_type"in n?n.sub_type:""}`;n.notice_type==="notify"&&(n.sub_type==="input_status"?o+=`.${n.group_id!==0?"group":"friend"}`:n.sub_type==="poke"&&(o+=`.${"group_id"in n?"group":"friend"}`));for(let s of this.events.notice)if(o.includes(s.endPoint??"notice"))try{if(await s.callback({context:n})==="quit"){this.logger.DEBUG(`\u63D2\u4EF6 ${s.packageName} \u8BF7\u6C42\u63D0\u524D\u7EC8\u6B62`);break}}catch(i){this.logger.ERROR(`\u63D2\u4EF6 ${s.packageName} \u4E8B\u4EF6\u5904\u7406\u5931\u8D25:`,i)}}),this.logger.INFO("Bot \u521D\u59CB\u5316\u5B8C\u6210")}static async init(e){return new Promise((t,n)=>{let o=new I({title:"Bot",level:e.logLevel??(e.debug?P.DEBUG:void 0)}),s=new H({...e.connection,reconnection:e.reconnection}),i=b();s.on("socket.connecting",r=>{i=b(),o.INFO(`\u8FDE\u63A5\u4E2D [#${r.reconnection.nowAttempts}/${r.reconnection.attempts}]`)}),s.on("socket.error",r=>{if(o.ERROR(`\u8FDE\u63A5\u5931\u8D25 [#${r.reconnection.nowAttempts}/${r.reconnection.attempts}]`),o.ERROR("\u9519\u8BEF\u4FE1\u606F:",r),r.error_type==="response_error"&&(o.ERROR("NapCat \u670D\u52A1\u7AEF\u8FD4\u56DE\u9519\u8BEF, \u53EF\u80FD\u662F AccessToken \u9519\u8BEF"),process.exit(1)),r.reconnection.nowAttempts>=r.reconnection.attempts)throw n(`\u91CD\u8BD5\u6B21\u6570\u8D85\u8FC7\u8BBE\u7F6E\u7684${r.reconnection.attempts}\u6B21!`),new Error(`\u91CD\u8BD5\u6B21\u6570\u8D85\u8FC7\u8BBE\u7F6E\u7684${r.reconnection.attempts}\u6B21!`)}),s.on("socket.open",async r=>{o.INFO(`\u8FDE\u63A5\u6210\u529F [#${r.reconnection.nowAttempts}/${r.reconnection.attempts}]`),o.INFO(`\u8FDE\u63A5 NapCat \u8017\u65F6: ${i()}ms`),t(new m(e,s))}),s.connect()})}regEvent(e){let t={...e,priority:e.priority??1};switch(t.type){case"command":return this.events.command=u([...this.events.command,t],"priority","down"),()=>{let n=this.events.command.indexOf(t);n!==-1&&this.events.command.splice(n,1)};case"message":return this.events.message=u([...this.events.message,t],"priority","down"),()=>{let n=this.events.message.indexOf(t);n!==-1&&this.events.message.splice(n,1)};case"notice":return this.events.notice=u([...this.events.notice,t],"priority","down"),()=>{let n=this.events.notice.indexOf(t);n!==-1&&this.events.notice.splice(n,1)};case"request":return this.events.request=u([...this.events.request,t],"priority","down"),()=>{let n=this.events.request.indexOf(t);n!==-1&&this.events.request.splice(n,1)}}}parseCommand(e,t,n){let o=e.charAt(0),s=this.config.prefix.find(a=>a===o);if(!s)return[1,"\u672A\u5339\u914D\u5230\u524D\u7F00"];let i=e.split(" ");if(i.length===0)return[1,"\u547D\u4EE4\u4FE1\u606F\u672A\u7A7A"];let r=i[0].slice(s.length),d=i.slice(1).filter(a=>a!=="");if(t!=="*"&&(typeof t=="string"&&t!==r||t instanceof RegExp&&r.match(t)===null))return[1,"\u547D\u4EE4\u540D\u4E0D\u5339\u914D"];if(n)try{let a=n.configureOutput({writeErr:g(()=>{},"writeErr"),writeOut:g(()=>{},"writeOut")}).exitOverride().parse(d,{from:"user"});return[0,{prefix:s,commandName:r,params:a.opts(),args:a.processedArgs}]}catch(a){if(a instanceof D||"code"in a&&"message"in a){let{code:E,message:C}=a;if(E==="commander.helpDisplayed")return[2,this.getCommandHelpInformation(t.toString())??""];let f=C.replace("error:","\u9519\u8BEF:").replace("unknown option","\u672A\u77E5\u9009\u9879").replace("missing required argument","\u7F3A\u5C11\u5FC5\u8981\u53C2\u6570").replace("too many arguments","\u53C2\u6570\u8FC7\u591A").replace("invalid argument","\u65E0\u6548\u53C2\u6570").replace("option '","\u9009\u9879 '").replace("argument missing","\u7F3A\u5C11\u53C2\u6570").replace("Did you mean","\u4F60\u662F\u60F3\u8981").replace(/Expected (\d+) arguments? but got (\d+)\./,"\u671F\u671B $1 \u4E2A\u53C2\u6570\uFF0C\u4F46\u5F97\u5230\u4E86 $2 \u4E2A\u53C2\u6570\u3002");return[2,f+(f.includes("\u4F60\u662F\u60F3\u8981")?"":`
|
|
2
|
+
(\u4F7F\u7528 -h \u83B7\u53D6\u5E2E\u52A9\u4FE1\u606F)`)]}else return this.logger.ERROR("\u547D\u4EE4\u5904\u7406\u51FA\u9519:",a),[2,a instanceof Error?a.message:"\u672A\u77E5\u9519\u8BEF"]}return[0,{prefix:s,commandName:r,params:{},args:[]}]}getCommandInfo(e,t,n="name"){let o=e[n]().replace("/","");return o===""||o==="program"?t:o}getCommandHelpInformation(e){let t=this.events.command.find(i=>i.commandName==="*"?!1:typeof i.commandName=="string"?i.commandName===e:i.commandName instanceof RegExp?i.commandName.test(e):!1);if(!t||!t.commander)return;let n=this.getCommandInfo(t.commander,t.commandName.toString()),o=this.config.prefix[0];return t.commander.name(n.includes(o)?n:`${o}${n}`).helpOption("-h, --help","\u5C55\u793A\u5E2E\u52A9\u4FE1\u606F").helpInformation().replaceAll("default:","\u9ED8\u8BA4\u503C:").replace("Arguments:","\u53C2\u6570:").replace("Options:","\u9009\u9879:").replace("Usage:","\u7528\u6CD5:")}async sendMsg(e,t,{reply:n=!0,at:o=!0}={}){try{if(e.message_type==="private")return await this.ws.send_private_msg({user_id:e.user_id,message:t});{let s=[];return n&&e.message_id&&s.push(h.reply(e.message_id)),o&&e.user_id&&s.push(h.at(e.user_id),h.text(`
|
|
3
|
+
`)),t=[...s,...t],await this.ws.send_group_msg({group_id:e.group_id,message:t})}}catch{return null}}async sendForwardMsg(e,t){try{return e.message_type==="private"?await this.ws.send_private_forward_msg({user_id:e.user_id,message:t}):await this.ws.send_group_forward_msg({group_id:e.group_id,message:t})}catch{return null}}async isFriend(e){return this.ws.get_friend_list().then(t=>t.find(n=>n.user_id===e.user_id))}async getUsername(e){return"group_id"in e?this.ws.get_group_member_info({group_id:e.group_id,user_id:e.user_id}).then(t=>t.nickname):this.ws.get_stranger_info({user_id:e.user_id}).then(t=>t.nickname)}};import{InjectLogger as L,LogLevel as _}from"@huan_kong/logger";import c from"fs";import R from"path";var v=class extends L{static{g(this,"LogRecorder")}config;atriConfig;originConsoleLog=console.log;constructor(e,t){if(super({level:e.logLevel??(e.debug?_.DEBUG:void 0)}),this.atriConfig=e,this.config=t,e.debug&&!t.enable){this.logger.WARN("\u5F53\u524D\u5904\u4E8E\u5F00\u53D1\u6A21\u5F0F, \u5982\u9700\u8BB0\u5F55\u65E5\u5FD7, \u8BF7\u5C06 logRecorder.enable \u8BBE\u4E3A true");return}this.config={maxFiles:31,maxSize:100*1024*1024,logLevel:e.debug?_.DEBUG:_.INFO,logDir:R.join(e.baseDir,"logs"),...this.config},this.rewriteConsole(),this.handleException(),this.logger.INFO("\u65E5\u5FD7\u8BB0\u5F55\u5668\u5DF2\u542F\u7528")}rewriteConsole(){console.log=(e=>(...t)=>{this.saveLog(t),e(...t)})(console.log)}handleException(){process.on("uncaughtException",e=>{this.logger.ERROR(`\u6355\u83B7\u5230\u672A\u5904\u7406\u7684\u5F02\u5E38, \u9519\u8BEF\u4FE1\u606F:
|
|
4
|
+
`,e)})}stripAnsi(e){return e.replace(/\u001B\[[0-9;]*m/g,"")}saveLog(e){let t=e.map(o=>this.stripAnsi(o)).join(" ");c.existsSync(this.config.logDir)||c.mkdirSync(this.config.logDir,{recursive:!0});let n=R.join(this.config.logDir,`${new Date().toISOString().split("T")[0]}.log`);c.existsSync(n)||this.removeUselessLogs(),c.appendFileSync(n,t+`
|
|
5
|
+
`,{encoding:"utf-8"})}removeUselessLogs(){let e=c.readdirSync(this.config.logDir).filter(n=>/^\d{4}-\d{2}-\d{2}/.test(n)&&c.statSync(R.join(this.config.logDir,n)).isFile());if(e.length<=this.config.maxFiles)return;let t=e.length-this.config.maxFiles+1;e.sort().slice(0,t).map(n=>c.rmSync(R.join(this.config.logDir,n)))}};var w=class m extends S{static{g(this,"ATRI")}config;configDir;bot;logRecorder;import;loadedPlugins={};loadPluginHooks={};constructor(e,t,n){super({level:e.logLevel??(e.debug?O.DEBUG:void 0)}),this.config=e,this.bot=t,this.logRecorder=n,this.configDir=e.configDir??p.join(e.baseDir,"config"),this.import=T(e.baseDir)}static async init(e){let t=new B({title:"ATRI",level:e.logLevel??(e.debug?O.DEBUG:void 0)});e.disableClearTerminal||console.log("\x1Bc"),e.disableStartupMessage||console.log(`%c __ .__
|
|
4
6
|
_____ _/ |_ _______ |__|
|
|
5
7
|
\\__ \\ \\ __\\ \\_ __ \\ | |
|
|
6
8
|
/ __ \\_ | | | | \\/ | |
|
|
7
9
|
(____ / |__| |__| |__|
|
|
8
|
-
\\/`,"font-family: Consolas;"),t.INFO("\u30A2\u30C8\u30EA\u306F\u3001\u9AD8\u6027\u80FD\u3067\u3059\u304B\u3089\uFF01")
|
|
10
|
+
\\/`,"font-family: Consolas;");let n=new v(e,e.logRecorder??{});e.disableStartupMessage||t.INFO("\u30A2\u30C8\u30EA\u306F\u3001\u9AD8\u6027\u80FD\u3067\u3059\u304B\u3089\uFF01"),"debug"in e.bot||(e.bot.debug=e.debug),"logLevel"in e.bot||(e.bot.logLevel=e.logLevel),"timezone"in e||(e.timezone="Asia/Shanghai");let o=await y.init(e.bot),s=new m(e,o,n);for(let i of e.plugins??[]){let[r]=await s.loadPlugin(i);r!==0&&(t.ERROR("\u521D\u59CB\u63D2\u4EF6\u52A0\u8F7D\u5931\u8D25\uFF0C\u7A0B\u5E8F\u7EC8\u6B62"),F.exit(1))}return t.INFO("ATRI \u521D\u59CB\u5316\u5B8C\u6210"),s}async loadPlugin(e,t){if(t={initPlugin:!0,quiet:!1,import:this.import,...t},t.baseDir&&(t.import=T(t.baseDir)),t.quiet||this.logger.INFO(`\u52A0\u8F7D\u63D2\u4EF6: ${e}`),this.loadedPlugins[e])return t.quiet||this.logger.WARN(`\u63D2\u4EF6 ${e} \u5DF2\u52A0\u8F7D\uFF0C\u8DF3\u8FC7\u52A0\u8F7D`),[0,this.loadedPlugins[e]];let n=[e,p.join(e,"src/index.ts")];this.config.debug&&(n=n.reverse());let o;try{o=await t.import(n[0])}catch{try{o=await t.import(n[1])}catch(r){return t.quiet||this.logger.ERROR(`\u63D2\u4EF6 ${e} \u5BFC\u5165\u5931\u8D25:`,r),[1,r instanceof Error?r.message:String(r)]}}if(!o.Plugin)return t.quiet||this.logger.ERROR(`\u63D2\u4EF6 ${e} \u52A0\u8F7D\u5931\u8D25: \u672A\u627E\u5230 Plugin \u7C7B`),[1,"\u672A\u627E\u5230 Plugin \u7C7B"];let s;try{let r=t.import.resolve(p.join(e,"package.json"));s=JSON.parse(l.readFileSync(r,"utf-8"))}catch(r){t.quiet||(this.logger.WARN(`\u63D2\u4EF6 ${e} \u672A\u627E\u5230 package.json, \u5C06\u4F7F\u7528\u672A\u77E5\u4EE3\u66FF`),this.logger.DEBUG(r)),s={name:"\u672A\u77E5",version:"\u672A\u77E5"}}let i;try{i=new o.Plugin(this,s)}catch(r){return t.quiet||this.logger.ERROR(`\u63D2\u4EF6 ${e} \u5B9E\u4F8B\u5316\u5931\u8D25:`,r),[1,r instanceof Error?r.message:String(r)]}if(!t.initPlugin)return[0,i];try{for(let r in this.loadPluginHooks){let d=this.loadPluginHooks[r];if(!await d({plugin:i,packageName:e}))return t.quiet||this.logger.ERROR(`\u63D2\u4EF6 ${e} \u52A0\u8F7D\u5931\u8D25: \u52A0\u8F7D\u94A9\u5B50 ${r} \u8FD4\u56DE false`),[2,r]}return i.disableAutoLoadConfig||(i.config=await this.loadConfig(i.configName??e,i.defaultConfig??{})),await i.load(),this.loadedPlugins[e]=i,t.quiet||this.logger.INFO(`\u63D2\u4EF6 ${e} \u52A0\u8F7D\u6210\u529F`),[0,i]}catch(r){return t.quiet||this.logger.ERROR(`\u63D2\u4EF6 ${e} \u52A0\u8F7D\u5931\u8D25:`,r),[1,r instanceof Error?r.message:String(r)]}}async unloadPlugin(e){let t=this.loadedPlugins[e];if(!t)return this.logger.WARN(`\u63D2\u4EF6 ${e} \u672A\u52A0\u8F7D`),[1,"\u63D2\u4EF6\u672A\u52A0\u8F7D"];try{return t.unregHandlers.forEach(n=>n()),await t.unload(),delete this.loadedPlugins[e],this.logger.INFO(`\u63D2\u4EF6 ${e} \u5378\u8F7D\u6210\u529F`),[0]}catch(n){return this.logger.ERROR(`\u63D2\u4EF6 ${e} \u5378\u8F7D\u5931\u8D25:`,n),[1,n instanceof Error?n.message:String(n)]}}async loadConfig(e,t){e=e.replaceAll("/","__"),l.existsSync(this.configDir)||l.mkdirSync(this.configDir,{recursive:!0});let n=p.join(this.configDir,`${e}.json`);if(!l.existsSync(n))return l.writeFileSync(n,JSON.stringify(t,null,2)),t;try{let o=JSON.parse(l.readFileSync(n,"utf-8"));return{...t,...o}}catch(o){return this.logger.ERROR(`\u63D2\u4EF6 ${e} \u914D\u7F6E\u52A0\u8F7D\u5931\u8D25:`,o),{}}}async saveConfig(e,t){e=e.replaceAll("/","__"),l.existsSync(this.configDir)||l.mkdirSync(this.configDir,{recursive:!0});let n=p.join(this.configDir,`${e}.json`);l.writeFileSync(n,JSON.stringify(t,null,2))}addPluginLoadHook(e,t){this.loadPluginHooks[e]=t}removePluginLoadHook(e){delete this.loadPluginHooks[e]}};var N=class{static{g(this,"CommanderUtils")}static enum(e){return function(t){if(!e.includes(t))throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u662F\u6709\u6548\u53C2\u6570, \u6709\u6548\u53C2\u6570:
|
|
9
11
|
${e.map(n=>` - ${n}`).join(`
|
|
10
|
-
`)}`);return t}}static int(e={}){return function(t){let n=parseInt(t);if(isNaN(n))throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u662F\u6709\u6548\u7684\u6574\u6570`);if(e.min!==void 0&&n<e.min)throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u80FD\u5C0F\u4E8E ${e.min}`);if(e.max!==void 0&&n>e.max)throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u80FD\u5927\u4E8E ${e.max}`);return n}}static float(e={}){return function(t){let n=parseFloat(t);if(isNaN(n))throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u662F\u6709\u6548\u7684\u6D6E\u70B9\u6570`);if(e.min!==void 0&&n<e.min)throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u80FD\u5C0F\u4E8E ${e.min}`);if(e.max!==void 0&&n>e.max)throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u80FD\u5927\u4E8E ${e.max}`);return n}}};import{Logger as
|
|
12
|
+
`)}`);return t}}static int(e={}){return function(t){let n=parseInt(t);if(isNaN(n))throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u662F\u6709\u6548\u7684\u6574\u6570`);if(e.min!==void 0&&n<e.min)throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u80FD\u5C0F\u4E8E ${e.min}`);if(e.max!==void 0&&n>e.max)throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u80FD\u5927\u4E8E ${e.max}`);return n}}static float(e={}){return function(t){let n=parseFloat(t);if(isNaN(n))throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u662F\u6709\u6548\u7684\u6D6E\u70B9\u6570`);if(e.min!==void 0&&n<e.min)throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u80FD\u5C0F\u4E8E ${e.min}`);if(e.max!==void 0&&n>e.max)throw new Error(`\u53C2\u6570 "${t}" \u4E0D\u80FD\u5927\u4E8E ${e.max}`);return n}}};import{Logger as j,LogLevel as M}from"@huan_kong/logger";var $=class{static{g(this,"BasePlugin")}packageJson;disableAutoLoadConfig;configName;defaultConfig;config;atri;bot;ws;unregHandlers=[];logger;constructor(e,t){this.atri=e,this.bot=e.bot,this.ws=e.bot.ws,this.config={},this.packageJson=t,this.logger=new j({title:this.packageJson.name,level:e.config.logLevel??(e.config.debug?M.DEBUG:void 0)})}saveConfig(e){this.atri.saveConfig(this.configName??this.packageJson.name,e??this.config)}regCommandEvent(e){let t=this.bot.regEvent({...e,type:"command",packageName:this.packageJson.name});return this.unregHandlers.push(t),t}regMessageEvent(e){let t=this.bot.regEvent({...e,type:"message",packageName:this.packageJson.name});return this.unregHandlers.push(t),t}regRequestEvent(e){let t=this.bot.regEvent({...e,type:"request",packageName:this.packageJson.name});return this.unregHandlers.push(t),t}regNoticeEvent(e){let t=this.bot.regEvent({...e,type:"notice",packageName:this.packageJson.name});return this.unregHandlers.push(t),t}};export{w as ATRI,$ as BasePlugin,y as Bot,N as CommanderUtils,b as performanceCounter,u as sortObjectArray};
|