Browse Source

规范代码

枫林 3 months ago
parent
commit
2cb6737855
5 changed files with 142 additions and 150 deletions
  1. 72 0
      src/interface/plugin.ts
  2. 36 49
      src/lib/Plugins.ts
  3. 30 99
      src/lib/decorators.ts
  4. 2 1
      src/plugins/test.ts
  5. 2 1
      src/plugins/upload.ts

+ 72 - 0
src/interface/plugin.ts

@@ -0,0 +1,72 @@
+// 更新 Plugin 接口
+export interface Plugin {
+    id: string;
+    name: string;
+    commands: Command[];
+    class: any;
+    version?: string;
+    author?: string;
+    describe?: string;
+    config: PluginConfig
+}
+
+// 修改插件装饰器配置接口
+export interface PluginConfig {
+    id: string;// 插件ID
+    name: string;// 插件名称
+    version?: string;// 插件版本
+    describe?: string;// 插件描述
+    author?: string;// 插件作者
+    help?: {// 帮助命令配置,使用框架默认的帮助配置
+        enabled?: boolean;      // 是否启用帮助命令
+        command?: string[];     // 帮助命令
+        description?: string;   // 帮助命令描述
+    };
+    defaultCommandId?: string; // 默认函数
+}
+
+// 在 decorators.ts 中定义统一的接口
+export interface Command {
+    cmd: string;        // 命令名称
+    desc: string;       // 命令描述
+    fn: Function;       // 命令函数
+    aliases?: string[]; // 命令别名
+    cmdPrefix: string;  // 命令前缀
+    pluginId: string;   // 插件ID
+    class: new () => any;
+    template?: {
+        enabled: boolean;   // 是否启用模板
+        sendText: boolean;  // 是否发送文本
+        [key: string]: any; // 其他模板配置
+    };
+}
+// 参数元数据接口
+export interface ParamMetadata {
+    name: string; // 参数名称
+    type: ParamType; // 参数类型
+    index: number; // 参数索引
+    optional: boolean; // 是否可选
+}
+// 参数类型枚举
+export const ParamType = {
+    String: "string" as const,
+    Number: "number" as const,
+    Boolean: "boolean" as const,
+    Rest: "rest" as const
+} as const;
+// 从对象值中获取类型
+export type ParamType = typeof ParamType[keyof typeof ParamType];
+
+// 添加模板配置接口
+export interface TemplateConfig {
+    enabled: boolean;
+    sendText: boolean;
+    [key: string]: any;
+}
+
+// 修改命令装饰器配置
+export interface CommandConfig {
+    template?: TemplateConfig;
+    [key: string]: any;
+}
+

+ 36 - 49
src/lib/Plugins.ts

@@ -1,40 +1,33 @@
 
 import botlogger from "./logger.js";
-import {promises as fsPromises} from 'fs';
-import {HtmlImg} from "./Puppeteer.js";
+import { promises as fsPromises } from 'fs';
+import { HtmlImg } from "./Puppeteer.js";
 import type {
     GroupMessage,
-    EventHandleMap as MessageContext,
     PrivateFriendMessage,
     PrivateGroupMessage
 } from 'node-napcat-ts/dist/Interfaces.js';
 import * as cron from 'node-cron';
 import 'reflect-metadata';
-import {
-    ParamType,
-    commandList,
-    Command,
-    Plugin,
-} from './decorators.js';
+import { Command, Plugin, } from '../interface/plugin.js';
 import * as fs from 'fs'
 import * as path from 'path'
 // 获取指令前缀
-import {Botconfig as config, load, PermissionConfig, saveConfig} from './config.js'
-import {ImageSegment, ReplySegment, TextSegment} from "node-napcat-ts/dist/Structs.js";
-import {fileURLToPath} from 'node:url';
-import {qqBot} from "../app.js";
-import {count} from "node:console";
-import {IsPermission} from "./Permission.js";
-import {download} from "./download.js";
+import { Botconfig as config, load, PermissionConfig, saveConfig } from './config.js'
+import { ImageSegment, ReplySegment, TextSegment } from "node-napcat-ts/dist/Structs.js";
+import { fileURLToPath } from 'node:url';
+import { qqBot } from "../app.js";
+import { IsPermission } from "./Permission.js";
+import { download } from "./download.js";
+import { commandList } from "./decorators.js";
 
 //WSSendParam
-
 const CMD_PREFIX = config?.cmd?.prefix ?? '#';
-
+export const getCommands = () => commandList;
 // 导出装饰器
 // export { param, ParamType };
 // export const plugins = pluginsDecorator;
-export {config};  // 导出配置对象
+export { config };  // 导出配置对象
 // 创建消息工厂函数
 function createTextMessage(text: string): TextSegment {
     return {
@@ -85,12 +78,11 @@ function findCommand(plugin: Plugin, cmdName: string): Command | undefined {
     });
 }
 
-
-
 // 添加插件加载函数
 async function loadPlugins(): Promise<void> {
     try {
         const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
         const pluginsDir = path.join(__dirname, '..', 'plugins');
 
         // 删除require缓存相关代码
@@ -184,8 +176,6 @@ async function initializeScheduledTasks(instance: any): Promise<void> {
     }
 }
 
-
-
 // 修改 runplugins 函数
 export async function runplugins() {
     try {
@@ -217,7 +207,7 @@ export async function runplugins() {
                         if (!isAdmin) {
                             context.quick_action([{
                                 type: 'text',
-                                data: {text: `无权限,无法加载插件`}
+                                data: { text: `无权限,无法加载插件` }
                             }]);
                             return;
                         }
@@ -226,18 +216,18 @@ export async function runplugins() {
                         botlogger.info("下载完成:" + JSON.stringify(file));
                         context.quick_action([{
                             type: 'text',
-                            data: {text: `插件下载完成,开始重载`}
+                            data: { text: `插件下载完成,开始重载` }
                         }]);
                         let isload = load
-                            isload.isuplad=true;
-                            isload.name=file.file
-                            if((context.message_type === 'group')){
-                                isload.id = context.group_id
-                            }else{
-                                isload.id = context.sender.user_id
-                            }
-                            isload.isGroupMessage = (context.message_type === 'group');
-                            saveConfig("load", isload)
+                        isload.isuplad = true;
+                        isload.name = file.file
+                        if ((context.message_type === 'group')) {
+                            isload.id = context.group_id
+                        } else {
+                            isload.id = context.sender.user_id
+                        }
+                        isload.isGroupMessage = (context.message_type === 'group');
+                        saveConfig("load", isload)
                     }
                     return;
                 }
@@ -257,7 +247,7 @@ export async function runplugins() {
                             if (!isAdmin) {
                                 context.quick_action([{
                                     type: 'text',
-                                    data: {text: `无权限,无法加载插件`}
+                                    data: { text: `无权限,无法加载插件` }
                                 }]);
                                 return;
                             }
@@ -269,14 +259,14 @@ export async function runplugins() {
 
                             context.quick_action([{
                                 type: 'text',
-                                data: {text: `插件下载完成,开始重载`}
+                                data: { text: `插件下载完成,开始重载` }
                             }]);
                             let isload = load
-                            isload.isuplad=true;
-                            isload.name=pluginName
-                            if((context.message_type === 'group')){
+                            isload.isuplad = true;
+                            isload.name = pluginName
+                            if ((context.message_type === 'group')) {
                                 isload.id = context.group_id
-                            }else{
+                            } else {
                                 isload.id = context.sender.user_id
                             }
                             isload.isGroupMessage = (context.message_type === 'group');
@@ -356,7 +346,7 @@ export async function runplugins() {
                         botlogger.info(`[${context.user_id}]无权限执行命令: ${CMD_PREFIX}${plugin.id} ${command.cmd}`);
                         context.quick_action([{
                             type: 'text',
-                            data: {text: `你没有权限执行此命令`}
+                            data: { text: `你没有权限执行此命令` }
                         }]);
                         return;
                     }
@@ -366,7 +356,7 @@ export async function runplugins() {
                         botlogger.info(`[${context.group_id}]无权限执行命令: ${CMD_PREFIX}${plugin.id} ${command.cmd}`);
                         context.quick_action([{
                             type: 'text',
-                            data: {text: `你没有权限执行此命令`}
+                            data: { text: `你没有权限执行此命令` }
                         }])
                         return;
                     }
@@ -378,7 +368,7 @@ export async function runplugins() {
                 botlogger.error("处理消息时出错:", error);
                 await context.quick_action([{
                     type: 'text',
-                    data: {text: `处理消息时出错: ${error instanceof Error ? error.message : '未知错误'}`}
+                    data: { text: `处理消息时出错: ${error instanceof Error ? error.message : '未知错误'}` }
                 }]);
             }
         });
@@ -560,7 +550,7 @@ async function handleCommand(context: PrivateFriendMessage | PrivateGroupMessage
         const errorMessage = error instanceof Error ? error.message : '未知错误';
         await context.quick_action([{
             type: 'text',
-            data: {text: `执行命令时出错: ${errorMessage}`}
+            data: { text: `执行命令时出错: ${errorMessage}` }
         }]);
     }
 }
@@ -570,9 +560,6 @@ export async function loadplugins() {
     await runplugins();
 }
 
-export const getCommands = () => commandList;
-
-
 // 修改 runcod 装饰器
 export function runcod(cmd: string | string[], desc: string): MethodDecorator {
     return function decorator(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor): PropertyDescriptor {
@@ -654,8 +641,8 @@ async function parseCommandParams(message: string, context: PrivateFriendMessage
                 params.push(num);
             }
             params.push(paramArgs[i]);
-            
-        }  
+
+        }
     }
     // 添加 context 参数
     params.push(context);

+ 30 - 99
src/lib/decorators.ts

@@ -1,46 +1,33 @@
 import * as path from 'path';
 import botlogger from './logger.js';
-import type {WSSendParam as MessageContext } from 'node-napcat-ts/dist/Interfaces.js';
 // 读取配置文件
-import {Botconfig as config} from './config.js'
-const CMD_PREFIX = config?.cmd?.prefix??'#'; 
+import { Botconfig as config } from './config.js'
+const CMD_PREFIX = config?.cmd?.prefix ?? '#';
 import { fileURLToPath } from 'node:url';
-import { assert } from 'node:console';
-// 参数类型枚举
-export const ParamType = {
-    String: "string" as const,
-    Number: "number" as const,
-    Boolean: "boolean" as const,
-    Rest: "rest" as const
-} as const;
-
-// 从对象值中获取类型
-export type ParamType = typeof ParamType[keyof typeof ParamType];
-
-// 参数元数据接口
-interface ParamMetadata {
-    name: string; // 参数名称
-    type: ParamType; // 参数类型
-    index: number; // 参数索引
-    optional: boolean; // 是否可选
-}
+import { Command, CommandConfig, ParamMetadata, ParamType, PluginConfig } from '../interface/plugin.js';
+import { Plugin } from '../interface/plugin.js';
+
+
+
 
 // 存储参数元数据
 export const paramMetadata = new Map<Function, ParamMetadata[]>();
+// 存储命令的数组
+export const commandList: Plugin[] = [];
 
 // 修改参数装饰器
-export function param(name: string, type: ParamType = ParamType.String, optional:boolean = false): ParameterDecorator {
+export function param(name: string, type: ParamType = ParamType.String, optional: boolean = false): ParameterDecorator {
 
-return function(target: any, propertyKey: string | symbol | undefined, parameterIndex: number): void {
-    const actualPropertyKey = propertyKey!;
+    return function (target: any, propertyKey: string | symbol | undefined, parameterIndex: number): void {
+        const actualPropertyKey = propertyKey!;
         const fn = target[actualPropertyKey];
         let metadata = paramMetadata.get(fn);
-        
+
         if (!metadata) {
             metadata = [];
             paramMetadata.set(fn, metadata);
         }
-        
+
         const paramData: ParamMetadata = {
             name,
             type,
@@ -51,47 +38,7 @@ return function(target: any, propertyKey: string | symbol | undefined, parameter
         metadata[parameterIndex] = paramData;
     };
 }
-// 更新 Plugin 接口
-export interface Plugin {
-    id: string;
-    name: string;
-    commands: Command[];
-    class: any;
-    version?: string;
-    author?: string;
-    describe?: string;
-    config: PluginConfig
-}
-// 修改插件装饰器配置接口
-export interface PluginConfig {
-    id: string;// 插件ID
-    name: string;// 插件名称
-    version?: string;// 插件版本
-    describe?: string;// 插件描述
-    author?: string;// 插件作者
-    help?: {// 帮助命令配置,使用框架默认的帮助配置
-        enabled?: boolean;      // 是否启用帮助命令
-        command?: string[];     // 帮助命令
-        description?: string;   // 帮助命令描述
-    };
-    defaultCommandId?: string; // 默认函数
-}
 
-// 在 decorators.ts 中定义统一的接口
-export interface Command {
-    cmd: string;        // 命令名称
-    desc: string;       // 命令描述
-    fn: Function;       // 命令函数
-    aliases?: string[]; // 命令别名
-    cmdPrefix: string;  // 命令前缀
-    pluginId: string;   // 插件ID
-    class: new () => any;
-    template?: {
-        enabled: boolean;   // 是否启用模板
-        sendText: boolean;  // 是否发送文本
-        [key: string]: any; // 其他模板配置
-    };
-}
 
 
 
@@ -100,11 +47,11 @@ export function plugins(config: PluginConfig): ClassDecorator {
     return function (target: any): void {
         // 保存插件配置
         target.prototype.plugincfg = config;
-        
+
         // 确保插件名称正确
         const existingPlugin = commandList.find((x) => x.class === target);
         let plugin: Plugin;
-        
+
         if (existingPlugin) {
             // 更新现有插件的配置
             existingPlugin.name = config.name;
@@ -136,7 +83,7 @@ export function plugins(config: PluginConfig): ClassDecorator {
                 cmdPrefix: CMD_PREFIX,
                 pluginId: config.id,
                 class: target,
-                fn: async function(): Promise<object> {
+                fn: async function (): Promise<object> {
                     const plugin = commandList.find(p => p.class === target);
                     if (!plugin) {
                         return {
@@ -148,10 +95,10 @@ export function plugins(config: PluginConfig): ClassDecorator {
                         .filter(cmd => !cmd.cmd.endsWith('help'))
                         .map(cmd => {
                             const fullCmd = `${CMD_PREFIX}${plugin.id} ${cmd.cmd}`;
-                            const aliases = cmd.aliases?.map(alias => 
+                            const aliases = cmd.aliases?.map(alias =>
                                 `${CMD_PREFIX}${plugin.id} ${alias}`
                             ) || [];
-                            
+
                             return {
                                 name: cmd.cmd,
                                 fullCmd,
@@ -159,7 +106,7 @@ export function plugins(config: PluginConfig): ClassDecorator {
                                 aliases
                             };
                         });
-                        
+
                     const __dirname = path.dirname(fileURLToPath(import.meta.url));
                     // 返回支持模板的响应对象
                     return {
@@ -220,22 +167,6 @@ export function plugins(config: PluginConfig): ClassDecorator {
 
 
 
-// 存储命令的数组
-export const commandList: Plugin[] = [];
-
-// 添加模板配置接口
-interface TemplateConfig {
-    enabled: boolean;
-    sendText: boolean;
-    [key: string]: any;
-}
-
-// 修改命令装饰器配置
-interface CommandConfig {
-    template?: TemplateConfig;
-    [key: string]: any;
-}
-
 // 修改 runcod 装饰器
 /**
  * 运行命令装饰器
@@ -245,19 +176,19 @@ interface CommandConfig {
  */
 //权限
 export function runcod(cmd: string | string[], desc: string, config: CommandConfig = {}, IsTest = false): MethodDecorator {
-    return function(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
+    return function (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
         // 延迟执行命令注册
         const originalMethod = descriptor.value;
-        descriptor.value = function(...args: any[]) {
+        descriptor.value = function (...args: any[]) {
             // 获取插件配置
             const pluginConfig = target.constructor.prototype.plugincfg;
             if (!pluginConfig) {
                 botlogger.error(`未找到插件配置: ${target.constructor.name}`);
                 return originalMethod.apply(this, args);
             }
-            
+
             const pluginName = pluginConfig.name;
-            
+
             // 获取或创建插件的命令列表
             let plugin = commandList.find((p: Plugin) => p.class === target.constructor);
             if (!plugin) {
@@ -279,7 +210,7 @@ export function runcod(cmd: string | string[], desc: string, config: CommandConf
 
                 // 第一个命令作为主命令,其他的作为别名
                 const [mainCmd, ...aliases] = allCmds;
-                
+
                 // 添加命令
                 const command: Command = {
                     cmd: mainCmd,
@@ -295,22 +226,22 @@ export function runcod(cmd: string | string[], desc: string, config: CommandConf
                         ...(config.template || {})
                     }
                 };
-                
+
                 plugin.commands.push(command);
 
                 // 修改日志输出
                 botlogger.info(`注册插件${plugin.id}命令: ${CMD_PREFIX}${plugin.id} ${mainCmd} 成功`);
-                
+
                 // 添加命令标记
                 descriptor.value.isCommand = true;
                 descriptor.value.cmd = Array.isArray(cmd) ? cmd[0] : cmd;
                 descriptor.value.desc = desc;
                 descriptor.value.aliases = Array.isArray(cmd) ? cmd.slice(1) : [];
             }
-            
+
             return originalMethod.apply(this, args);
         };
-        
+
         return descriptor;
     };
 }
@@ -318,7 +249,7 @@ export function runcod(cmd: string | string[], desc: string, config: CommandConf
 
 // 添加定时任务装饰器
 export function schedule(cron: string): MethodDecorator {
-    return function(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
+    return function (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
         // 保存原始方法
         const originalMethod = descriptor.value;
 

+ 2 - 1
src/plugins/test.ts

@@ -1,11 +1,12 @@
 //PLUGIN test.ts
 
-import { param, ParamType, plugins, runcod, schedule } from '../lib/decorators.js';
+import { param, plugins, runcod, schedule } from '../lib/decorators.js';
 import path from 'path';
 import 'reflect-metadata';
 import { fileURLToPath } from 'node:url';
 import { qqBot } from '../app.js';
 import botlogger from '../lib/logger.js';
+import { ParamType } from '../interface/plugin.js';
 
 @plugins({
     id: "test", //插件ID,必须唯一,不能重复

+ 2 - 1
src/plugins/upload.ts

@@ -1,4 +1,4 @@
-import { param, ParamType, plugins, runcod } from '../lib/decorators.js';
+import { param, plugins, runcod } from '../lib/decorators.js';
 import path from 'path';
 import 'reflect-metadata';
 import { fileURLToPath } from 'node:url';
@@ -6,6 +6,7 @@ import { GroupMessage, PrivateFriendMessage, PrivateGroupMessage } from 'node-na
 import botlogger from '../lib/logger.js';
 import fs from 'fs/promises';
 import { qqBot } from '../app.js';
+import { ParamType } from '@/interface/plugin.js';
 
 @plugins({
     id: "downloadPlugins", //插件ID,必须唯一,不能重复