@atri-bot/core 1.1.4 → 1.1.6
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 +5 -5
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -245,25 +245,26 @@ type ATRIConfig = {
|
|
|
245
245
|
baseDir: string;
|
|
246
246
|
configDir?: string;
|
|
247
247
|
logLevel?: LogLevel;
|
|
248
|
+
plugins?: string[];
|
|
248
249
|
disableClearTerminal?: boolean;
|
|
249
250
|
disableStartupMessage?: boolean;
|
|
250
|
-
disableAutoLoadPlugins?: boolean;
|
|
251
251
|
};
|
|
252
252
|
interface PluginModule {
|
|
253
253
|
Plugin?: new (...args: ConstructorParameters<typeof BasePlugin>) => BasePlugin;
|
|
254
254
|
}
|
|
255
255
|
type LoadPluginHook = (plugin: BasePlugin) => Promise<boolean> | boolean;
|
|
256
|
-
type ImportFunction = () => Promise<PluginModule>;
|
|
257
256
|
|
|
258
257
|
declare class ATRI extends InjectLogger {
|
|
259
258
|
config: ATRIConfig;
|
|
260
259
|
configDir: string;
|
|
261
260
|
bot: Bot;
|
|
261
|
+
import: NodeJS.Require;
|
|
262
262
|
loadedPlugins: Record<string, BasePlugin>;
|
|
263
263
|
loadPluginHooks: Record<string, LoadPluginHook>;
|
|
264
264
|
private constructor();
|
|
265
265
|
static init(config: ATRIConfig): Promise<ATRI>;
|
|
266
|
-
loadPlugin(
|
|
266
|
+
loadPlugin(pluginName: string): Promise<boolean>;
|
|
267
|
+
loadPlugins(pluginNames: string[]): Promise<boolean>;
|
|
267
268
|
unloadPlugin(pluginName: string): Promise<boolean>;
|
|
268
269
|
loadConfig<TConfig extends object>(pluginName: string, defaultConfig: TConfig): Promise<{}>;
|
|
269
270
|
saveConfig<TConfig extends object>(pluginName: string, config: TConfig): Promise<void>;
|
|
@@ -283,6 +284,5 @@ declare function performanceCounter(): () => string;
|
|
|
283
284
|
* @param sortType up=>升序 down=>降序
|
|
284
285
|
*/
|
|
285
286
|
declare function sortObjectArray<T extends object>(arr: T[], property: keyof T, sortType?: 'up' | 'down'): T[];
|
|
286
|
-
declare function getImportItemName(importFunction: () => Promise<any>): string;
|
|
287
287
|
|
|
288
|
-
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, type
|
|
288
|
+
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, type LoadPluginHook, type MessageCallback, type MessageEvent, type NonEmptyArray, type NoticeCallback, type NoticeEvent, type OptionArgs, type OptionParams, type PluginModule, type RegEventOptions, type RemoveField, type RequestCallback, type RequestEvent, type UnRegHandler, performanceCounter, sortObjectArray };
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{InjectLogger as
|
|
2
|
-
(\u4F7F\u7528 -h \u83B7\u53D6\u5E2E\u52A9\u4FE1\u606F)`)]):(this.logger.ERROR(
|
|
3
|
-
`)),
|
|
1
|
+
import{InjectLogger as x,Logger as w,LogLevel as f}from"@huan_kong/logger";import{createRequire as H}from"module";import m from"fs";import h from"path";import q from"process";import{InjectLogger as k,Logger as O,LogLevel as C}from"@huan_kong/logger";import{CommanderError as T}from"commander";import{NCWebsocket as P,Structs as d}from"node-napcat-ts";function c(){let g=performance.now();return()=>(performance.now()-g).toFixed(2)}function u(g,e,n="up"){return g.sort((t,o)=>t[e]>o[e]?n==="up"?1:-1:t[e]<o[e]?n==="up"?-1:1:0)}var p=class g extends k{ws;config;events={command:[],message:[],notice:[],request:[]};constructor(e,n){super({level:e.debug?C.DEBUG:e.logLevel}),this.ws=n,this.config=e,e.debug&&(n.on("api.preSend",t=>this.logger.DEBUG("\u53D1\u9001API\u8BF7\u6C42",t)),n.on("api.response.success",t=>this.logger.DEBUG("\u6536\u5230API\u6210\u529F\u54CD\u5E94",t)),n.on("api.response.failure",t=>this.logger.DEBUG("\u6536\u5230API\u5931\u8D25\u54CD\u5E94",t)),n.on("message",t=>{if(t.message.length===0){this.logger.DEBUG("\u6536\u5230\u7A7A\u6D88\u606F, \u5DF2\u8DF3\u8FC7\u5904\u7406\u6D41\u7A0B:",t);return}this.logger.DEBUG("\u6536\u5230\u6D88\u606F:",t)}),n.on("request",t=>this.logger.DEBUG("\u6536\u5230\u8BF7\u6C42:",t)),n.on("notice",t=>this.logger.DEBUG("\u6536\u5230\u901A\u77E5:",t))),n.on("message",async t=>{if(t.message.length===0)return;let o=`message.${t.message_type}.${t.sub_type}`,s=this.config.adminId.includes(t.user_id),a=t.message[0].type==="reply";for(let r of this.events.message)if(o.includes(r.endPoint??"message")&&(!r.needReply||a)&&(!r.needAdmin||s)&&(!r.regexp||r.regexp.test(t.raw_message)))try{if(await r.callback({context:t})==="quit"){this.logger.DEBUG(`\u63D2\u4EF6 ${r.pluginName} \u8BF7\u6C42\u63D0\u524D\u7EC8\u6B62`);break}}catch(l){this.logger.ERROR(`\u63D2\u4EF6 ${r.pluginName} \u4E8B\u4EF6\u5904\u7406\u5931\u8D25:`,l)}for(let r of this.events.command)if(o.includes(r.endPoint??"message")&&(!r.needAdmin||s)&&(!r.needReply||a)){let[l,i]=this.parseCommand(t.raw_message,r.commandName,r.commander);if(l===1)continue;if(l===2){await this.sendMsg(t,[d.text(i)]);continue}let{prefix:y,commandName:b,params:E,args:N}=i;try{if(await r.callback({context:t,prefix:y,commandName:b,params:E,args:N})==="quit"){this.logger.DEBUG(`\u63D2\u4EF6 ${r.pluginName} \u8BF7\u6C42\u63D0\u524D\u7EC8\u6B62`);break}}catch(v){this.logger.ERROR(`\u63D2\u4EF6 ${r.pluginName} \u4E8B\u4EF6\u5904\u7406\u5931\u8D25:`,v)}}}),n.on("request",async t=>{let o=`request.${t.request_type}.${"sub_type"in t?t.sub_type:""}`;for(let s of this.events.request)if(o.includes(s.endPoint??"request"))try{if(await s.callback({context:t})==="quit"){this.logger.DEBUG(`\u63D2\u4EF6 ${s.pluginName} \u8BF7\u6C42\u63D0\u524D\u7EC8\u6B62`);break}}catch(a){this.logger.ERROR(`\u63D2\u4EF6 ${s.pluginName} \u4E8B\u4EF6\u5904\u7406\u5931\u8D25:`,a)}}),n.on("notice",async t=>{let o=`notice.${t.notice_type}.${"sub_type"in t?t.sub_type:""}`;t.notice_type==="notify"&&(t.sub_type==="input_status"?o+=`.${t.group_id!==0?"group":"friend"}`:t.sub_type==="poke"&&(o+=`.${"group_id"in t?"group":"friend"}`));for(let s of this.events.notice)if(o.includes(s.endPoint??"notice"))try{if(await s.callback({context:t})==="quit"){this.logger.DEBUG(`\u63D2\u4EF6 ${s.pluginName} \u8BF7\u6C42\u63D0\u524D\u7EC8\u6B62`);break}}catch(a){this.logger.ERROR(`\u63D2\u4EF6 ${s.pluginName} \u4E8B\u4EF6\u5904\u7406\u5931\u8D25:`,a)}}),this.logger.INFO("Bot \u521D\u59CB\u5316\u5B8C\u6210")}static async init(e){return new Promise((n,t)=>{let o=new O({title:"Bot",level:e.debug?C.DEBUG:e.logLevel}),s=new P({...e.connection,reconnection:e.reconnection}),a=c();s.on("socket.connecting",r=>{a=c(),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 t(`\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: ${a()}ms`),n(new g(e,s))}),s.connect()})}regEvent(e){let n={...e,priority:e.priority??1};switch(n.type){case"command":return this.events.command=u([...this.events.command,n],"priority","down"),()=>{let t=this.events.command.indexOf(n);t!==-1&&this.events.command.splice(t,1)};case"message":return this.events.message=u([...this.events.message,n],"priority","down"),()=>{let t=this.events.message.indexOf(n);t!==-1&&this.events.message.splice(t,1)};case"notice":return this.events.notice=u([...this.events.notice,n],"priority","down"),()=>{let t=this.events.notice.indexOf(n);t!==-1&&this.events.notice.splice(t,1)};case"request":return this.events.request=u([...this.events.request,n],"priority","down"),()=>{let t=this.events.request.indexOf(n);t!==-1&&this.events.request.splice(t,1)}}}parseCommand(e,n,t){let o=e.charAt(0),s=this.config.prefix.find(i=>i===o);if(!s)return[1,"\u672A\u5339\u914D\u5230\u524D\u7F00"];let a=e.split(" ");if(a.length===0)return[1,"\u547D\u4EE4\u4FE1\u606F\u672A\u7A7A"];let r=a[0].slice(s.length),l=a.slice(1).filter(i=>i!=="");if(n!=="*"&&(typeof n=="string"&&n!==r||n instanceof RegExp&&r.match(n)===null))return[1,"\u547D\u4EE4\u540D\u4E0D\u5339\u914D"];if(t)try{let i=t.configureOutput({writeErr:()=>{},writeOut:()=>{}}).exitOverride().parse(l,{from:"user"});return[0,{prefix:s,commandName:r,params:i.opts(),args:i.processedArgs}]}catch(i){return i instanceof T?i.code==="commander.helpDisplayed"?[2,this.getCommandHelpInformation(n.toString())??""]:(i.message=i.message.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"),[2,i.message+(i.message.includes("\u4F60\u662F\u60F3\u8981")?"":`
|
|
2
|
+
(\u4F7F\u7528 -h \u83B7\u53D6\u5E2E\u52A9\u4FE1\u606F)`)]):(this.logger.ERROR(i),[2,i instanceof Error?i.message:"\u672A\u77E5\u9519\u8BEF"])}return[0,{prefix:s,commandName:r,params:{},args:[]}]}getCommandInfo(e,n,t="name"){let o=e[t]().replace("/","");return o===""||o==="program"?n:o}getCommandHelpInformation(e){let n=this.events.command.find(a=>a.commandName.toString()===e);if(!n||!n.commander)return;let t=this.getCommandInfo(n.commander,n.commandName.toString()),o=this.config.prefix[0];return n.commander.name(t.includes(o)?t:`${o}${t}`).helpOption("-h, --help","\u5C55\u793A\u5E2E\u52A9\u4FE1\u606F").helpInformation().replace("default:","\u9ED8\u8BA4\u503C:").replace("Arguments:","\u53C2\u6570:").replace("Options:","\u9009\u9879:").replace("Usage:","\u7528\u6CD5:")}async sendMsg(e,n,{reply:t=!0,at:o=!0}={}){try{if(e.message_type==="private")return await this.ws.send_private_msg({user_id:e.user_id,message:n});{let s=[];return t&&e.message_id&&s.push(d.reply(e.message_id)),o&&e.user_id&&s.push(d.at(e.user_id),d.text(`
|
|
3
|
+
`)),n=[...s,...n],await this.ws.send_group_msg({group_id:e.group_id,message:n})}}catch{return null}}async sendForwardMsg(e,n){try{return e.message_type==="private"?await this.ws.send_private_forward_msg({user_id:e.user_id,message:n}):await this.ws.send_group_forward_msg({group_id:e.group_id,message:n})}catch{return null}}async isFriend(e){return this.ws.get_friend_list().then(n=>n.find(t=>t.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(n=>n.nickname):this.ws.get_stranger_info({user_id:e.user_id}).then(n=>n.nickname)}};var R=class g extends x{config;configDir;bot;import;loadedPlugins={};loadPluginHooks={};constructor(e,n){super({level:e.debug?f.DEBUG:e.logLevel}),this.config=e,this.bot=n,this.configDir=e.configDir??h.join(e.baseDir,"config"),this.import=H(e.baseDir)}static async init(e){e.debug&&(e.logLevel=f.DEBUG);let n=new w({title:"ATRI",level:e.debug?f.DEBUG:e.logLevel});e.disableClearTerminal||console.log("\x1Bc"),e.disableStartupMessage||(console.log(`%c __ .__
|
|
4
4
|
_____ _/ |_ _______ |__|
|
|
5
5
|
\\__ \\ \\ __\\ \\_ __ \\ | |
|
|
6
6
|
/ __ \\_ | | | | \\/ | |
|
|
7
7
|
(____ / |__| |__| |__|
|
|
8
|
-
\\/`,"font-family: Consolas;"),
|
|
8
|
+
\\/`,"font-family: Consolas;"),n.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);let t=await p.init(e.bot),o=new g(e,t);return e.plugins&&(await o.loadPlugins(e.plugins)||(n.ERROR("\u63D2\u4EF6\u52A0\u8F7D\u5931\u8D25\uFF0C\u7A0B\u5E8F\u7EC8\u6B62"),q.exit(1))),n.INFO("ATRI \u521D\u59CB\u5316\u5B8C\u6210"),o}async loadPlugin(e){this.logger.INFO(`\u52A0\u8F7D\u63D2\u4EF6: ${e}`);let n;try{n=await this.import(e)}catch(t){return this.logger.ERROR(`\u63D2\u4EF6 ${e} \u52A0\u8F7D\u5931\u8D25:`,t),!1}if(!n.Plugin)return this.logger.ERROR(`\u63D2\u4EF6 ${e} \u52A0\u8F7D\u5931\u8D25: \u672A\u627E\u5230 Plugin \u7C7B`),!1;try{let t=new n.Plugin(this);if(!t.pluginName)return this.logger.ERROR(`\u63D2\u4EF6 ${e} \u52A0\u8F7D\u5931\u8D25: \u7F3A\u5C11\u5FC5\u8981\u53C2\u6570: pluginName`),!1;for(let o in this.loadPluginHooks){let s=this.loadPluginHooks[o];if(!await s(t))return this.logger.ERROR(`\u63D2\u4EF6 ${t.pluginName} \u52A0\u8F7D\u5931\u8D25: \u52A0\u8F7D\u94A9\u5B50 ${o} \u8FD4\u56DE false`),!1}if(!t.getDisableAutoLoadConfig()){let o=await this.loadConfig(t.getConfigName(),t.getDefaultConfig());t.setConfig(o)}await t.load(),this.loadedPlugins[t.pluginName]=t,this.logger.INFO(`\u63D2\u4EF6 ${t.pluginName} \u52A0\u8F7D\u6210\u529F`)}catch(t){return this.logger.ERROR(`\u63D2\u4EF6 ${e} \u52A0\u8F7D\u5931\u8D25:`,t),!1}return!0}async loadPlugins(e){for(let n of e)if(!await this.loadPlugin(n))return!1;return!0}async unloadPlugin(e){if(!this.loadedPlugins[e])return this.logger.WARN(`\u63D2\u4EF6 ${e} \u672A\u52A0\u8F7D`),!0;let n=this.loadedPlugins[e];try{n.getUnregHandlers().forEach(t=>t()),await n.unload(),delete this.loadedPlugins[e],this.logger.INFO(`\u63D2\u4EF6 ${e} \u5378\u8F7D\u6210\u529F`)}catch(t){return this.logger.ERROR(`\u63D2\u4EF6 ${e} \u5378\u8F7D\u5931\u8D25:`,t),!1}return!0}async loadConfig(e,n){m.existsSync(this.configDir)||m.mkdirSync(this.configDir,{recursive:!0});let t=h.join(this.configDir,`${e}.json`);if(!m.existsSync(t))return m.writeFileSync(t,JSON.stringify(n,null,2)),n;try{let o=JSON.parse(m.readFileSync(t,"utf-8"));return{...n,...o}}catch(o){return this.logger.ERROR(`\u63D2\u4EF6 ${e} \u914D\u7F6E\u52A0\u8F7D\u5931\u8D25:`,o),{}}}async saveConfig(e,n){m.existsSync(this.configDir)||m.mkdirSync(this.configDir,{recursive:!0});let t=h.join(this.configDir,`${e}.json`);m.writeFileSync(t,JSON.stringify(n,null,2))}addPluginLoadHook(e,n){this.loadPluginHooks[e]=n}removePluginLoadHook(e){delete this.loadPluginHooks[e]}};import{Logger as A,LogLevel as I}from"@huan_kong/logger";var _=class{disableAutoLoadConfig;configName;defaultConfig;config;atri;bot;ws;unregHandlers=[];logger;constructor(e){this.atri=e,this.bot=e.bot,this.ws=e.bot.ws,this.config={}}initLogger(){let e=this.atri.config;this.logger=new A({title:this.pluginName,level:e.debug?I.DEBUG:e.logLevel})}setConfig(e){this.config=e}saveConfig(e){this.atri.saveConfig(this.configName??this.pluginName,e??this.config)}getDisableAutoLoadConfig(){return this.disableAutoLoadConfig}getConfigName(){return this.configName??this.pluginName}getDefaultConfig(){return this.defaultConfig??{}}getUnregHandlers(){return this.unregHandlers}getPluginName(){return this.pluginName}regCommandEvent(e){let n=this.bot.regEvent({...e,type:"command",pluginName:this.pluginName});return this.unregHandlers.push(n),n}regMessageEvent(e){let n=this.bot.regEvent({...e,type:"message",pluginName:this.pluginName});return this.unregHandlers.push(n),n}regRequestEvent(e){let n=this.bot.regEvent({...e,type:"request",pluginName:this.pluginName});return this.unregHandlers.push(n),n}regNoticeEvent(e){let n=this.bot.regEvent({...e,type:"notice",pluginName:this.pluginName});return this.unregHandlers.push(n),n}};export{R as ATRI,_ as BasePlugin,p as Bot,c as performanceCounter,u as sortObjectArray};
|