import { CQWebSocket , MessageListenerReturn } from 'cq-websocket' ; import { CQError , CQLog } from '@/models' ; import { printTime } from '@/utils' ; import { IS_DEBUG } from '@/config' ; /**
 * 如果返回值为真，则后续的都不再响应。如果返回值为假，则会继续向下匹配
 */ export type CQPlugin = ( bot : CQWebSocket , context : Record < string , any > ) => MessageListenerReturn ; export class CQApp { author CaoMeiYouRen
     *  date param { string } prefix constructor ( prefix ? ) { this . prefix = prefix ; } private plugins = new Map < string | RegExp , CQPlugin > ( ) ; type { string } private prefix ? : string ; author CaoMeiYouRen
     *  date param { ( string | RegExp ) } path param { CQPlugin } plugin returns public use ( path , plugin ) { this . plugins . set ( path , plugin ) ; return this ; } author CaoMeiYouRen
     *  date public run ( bot ) { bot . on ( 'message' , async ( event , ctx , tags ) => { try { const plugins = [ ... this . plugins ] ; let message = ctx . message ; if ( this . prefix ) { if ( ! message . toUpperCase ( ) . startsWith ( this . prefix . toUpperCase ( ) ) ) { return ; } message = message . slice ( this . prefix . length ) ; ctx . message = message ; } for ( let i = 0 ; i < plugins . length ; i ++ ) { const [ path , plugin ] = plugins [ i ] ; if ( typeof path === 'string' && path === message || path instanceof RegExp && path . test ( message ) ) { let result = plugin ( bot , ctx ) ; if ( result instanceof Promise ) { result = await result ; } if ( result ) { if ( ctx . group_id ) { printTime ( `[发送群消息] 群号:${ ctx . group_id } msg:${ JSON . stringify ( result ) }` , CQLog . LOG_INFO_SEND ) ; } else { printTime ( `[发送私聊消息] QQID:${ ctx . user_id } msg:${ JSON . stringify ( result ) }` , CQLog . LOG_INFO_SEND ) ; } if ( ! IS_DEBUG ) { return result ; } } } } } catch ( error ) { if ( error instanceof CQError ) { printTime ( error . message , CQLog . LOG_ERROR ) ; return error . message ; } console . error ( error ) ; } } ) ; } }