Skip to content

Commit

Permalink
fix: answer plugin currentInstance set
Browse files Browse the repository at this point in the history
  • Loading branch information
YunYouJun committed Sep 25, 2024
1 parent addebc5 commit 6676d94
Show file tree
Hide file tree
Showing 12 changed files with 76 additions and 74 deletions.
15 changes: 6 additions & 9 deletions packages/el-bot/core/bot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import Webhook from './webhook'
import type { Plugin, PluginInstallFunction } from './plugins/class'
import consola from 'consola'
import yargs from 'yargs'
import { setCurrentInstance } from '../composition-api/litecycle'
import { logger } from './logger'

export * from './logger'
Expand Down Expand Up @@ -222,13 +223,13 @@ export class Bot {

try {
await this.napcat.connect()
const data = await this.napcat.get_version_info()
consola.success(`${data.app_name} ${colors.yellow(data.app_version)} ${colors.cyan(data.protocol_version)} connected!`)
}
catch (err: any) {
consola.error('NapCat by SDK 连接失败')
handleError(err)
}
const data = await this.napcat.get_version_info()
consola.success(`${data.app_name} ${colors.yellow(data.app_version)} ${colors.cyan(data.protocol_version)} connected!`)

// get login info
try {
Expand All @@ -241,19 +242,15 @@ export class Bot {

// reset
this.hooks.removeAllHooks()

// 加载插件
consola.log('')
consola.start('加载插件...')
consola.log('')
await this.plugins.load('default')
// await this.plugins.load('official')
await this.plugins.load('community')

setCurrentInstance(this)
await this.plugins.loadConfig()
// 自动加载自定义插件
if (this.el.bot.autoloadPlugins) {
await this.plugins.loadCustom(this.el.bot.pluginDir)
}

consola.log('')
consola.success('插件加载完成')
consola.log('')
Expand Down
68 changes: 16 additions & 52 deletions packages/el-bot/core/bot/plugins/class.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import path from 'node:path'
import process from 'node:process'
import consola from 'consola'
import fs from 'fs-extra'
import colors from 'picocolors'
import { type Bot, BotPlugin, logger } from '..'
import { setCurrentInstance } from '../../../composition-api/litecycle'

import { isFunction } from '../../shared'
import { merge } from '../../utils/config'
Expand Down Expand Up @@ -83,67 +81,34 @@ export class Plugins {
}

/**
* 加载对应类型插件
* @param type 插件类型 default | custom
* import ts
* 加载配置中的插件
* plugins: []
*/
async load(type: PluginType) {
async loadConfig() {
const botConfig = this.ctx.el.bot!
if (botConfig.plugins && botConfig.plugins[type]) {
for (const name of botConfig.plugins[type]) {
const pkgName = this.getPluginFullName(name, type)
// colorize
const cPluginType = colors.dim(type)
if (botConfig.plugins) {
consola.start(`加载配置插件 - 共 ${colors.green(botConfig.plugins.length)} 个...`)
consola.log('')

for (const plugin of botConfig.plugins) {
const pkgName = plugin.pkg?.name || '未知'
try {
const pluginPath = type === 'default' ? `../../../plugins/${pkgName}` : pkgName
const suffix = 'ts'
const importedPath = await fs.exists(`${pluginPath}.${suffix}`) ? `${pluginPath}.${suffix}` : `${pluginPath}/index.${suffix}`
const { default: plugin } = await import(importedPath)

let pkg = {
name: pkgName,
version: '未知',
description: '未知',
}

// load plugin package.json
const packagePath = path.resolve(import.meta.dirname, pluginPath, `package.json`)
if (await fs.exists(packagePath)) {
pkg = await fs.readJson(packagePath)
}
else {
pluginLogger.warning(`${name} 插件没有相关描述信息`)
}

if (plugin) {
if (pkg)
plugin.pkg = pkg

this[type].add({
name: name || pkgName,
version: plugin.version || pkg.version,
description: plugin.description || pkg.description,
})

const basename = path.basename(name)
this.add(basename, {
install: plugin,
})

await plugin.setup(this.ctx)
pluginLogger
.child({ plugin: name })
.success(`${cPluginType} 加载成功`)
.child({ plugin: pkgName })
.success(`加载成功`)
}
}
catch (err: any) {
handleError(err as Error)
pluginLogger
.child({ plugin: name })
.error(`${cPluginType} 加载失败`)
.child({ plugin: pkgName })
.error(`加载失败`)
}
}
}
consola.log('')
}

/**
Expand All @@ -156,11 +121,10 @@ export class Plugins {
else {
const absolutePluginDir = path.resolve(process.cwd(), pluginDir)
consola.info(`自定义插件目录: ${colors.cyan(absolutePluginDir)}`)
consola.log('')

const customPlugins = await getAllPlugins(absolutePluginDir)
consola.start(`加载自定义插件 - 共 ${colors.green(customPlugins.length)} 个...`)
consola.log('')

setCurrentInstance(this.ctx)
for (const customPluginName of customPlugins) {
const pluginPath = path.resolve(absolutePluginDir, `${customPluginName}.ts`)
const importedCustomPlugin = (await import(pluginPath)).default
Expand Down
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Bot } from '../types'
import { Bot } from '../../types'

/**
* Current bot instance
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@ export type CommonMessage = NapcatMessage
/**
* listen to all message
* - napcat
* - TODO
* - TODO: other platform
* @param handler
*/
export function onMessage(
handler: (msg: NapcatMessage) => void | Promise<void>,
) {
currentInstance?.hooks.hook('onMessage', handler)
// consola.info('onMessage', handler)
currentInstance?.hooks.addHooks({
onMessage: handler,
})
}

/**
Expand All @@ -25,5 +28,7 @@ export function onMessage(
export function onNapcatMessage(
handler: (msg: NapcatMessage) => void | Promise<void>,
) {
currentInstance?.hooks.hook('onNapcatMessage', handler)
currentInstance?.hooks.addHooks({
onNapcatMessage: handler,
})
}
27 changes: 27 additions & 0 deletions packages/el-bot/core/composition-api/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import consola from 'consola'
import { createHooks } from 'hookable'

// Create a hookable instance
const hooks = createHooks()

// Hook on 'hello'
hooks.addHooks({
hello: () => {
consola.info('Hello World 1')
},
})

hooks.addHooks({
hello: () => {
consola.info('Hello World 2')
},
})

hooks.addHooks({
hello: () => {
consola.info('Hello World 3')
},
})

// Call 'hello' hook
hooks.callHook('hello')
1 change: 1 addition & 0 deletions packages/el-bot/core/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// export * from './nest'
export * from './bot'
export * from './composition-api'

export * from './config'
export * as utils from './utils'
1 change: 0 additions & 1 deletion packages/el-bot/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from './composition-api'
export * from './core'
export * from './plugins'
export * from './types'
8 changes: 7 additions & 1 deletion packages/el-bot/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ serve({
await sleep(10)
const end = performance.now()
consola.info(req.url)
return new Response(`Slept for ${end - start}ms`)
// return new Response(`Slept for ${end - start}ms`)
// return json
return new Response(JSON.stringify({ slept: end - start }), {
headers: {
'content-type': 'application/json',
},
})
},
})
4 changes: 2 additions & 2 deletions packages/el-bot/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "el-bot",
"type": "module",
"version": "1.0.0-beta.9",
"version": "1.0.0-beta.10",
"description": "A quick qq bot framework for mirai.",
"author": {
"name": "云游君",
Expand Down Expand Up @@ -90,8 +90,8 @@
"@types/html-to-text": "^9.0.4",
"@types/js-yaml": "^4.0.9",
"@types/koa": "^2.15.0",
"@types/koa__cors": "^5.0.0",
"@types/koa-bodyparser": "^4.3.12",
"@types/koa__cors": "^5.0.0",
"@types/node": "^22.7.0",
"@types/node-schedule": "^2.1.7",
"@types/progress": "^2.0.7",
Expand Down
13 changes: 8 additions & 5 deletions packages/el-bot/plugins/answer/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import type { AnswerOptions } from './utils'
import { onMessage } from '../../composition-api'
import consola from 'consola'
// import axios from 'axios'
// import * as nodeSchdule from 'node-schedule'
import { defineBotPlugin } from '../../core'
import { defineBotPlugin, onNapcatMessage } from '../../core'
// import { displayAnswerList, renderString } from './utils'
import pkg from './package.json'

export * from './utils'

export default defineBotPlugin<AnswerOptions>((options) => {
return {
pkg,
// extendCli: (cli) => {
// cli
// .command('answer')
Expand Down Expand Up @@ -36,13 +38,13 @@ export default defineBotPlugin<AnswerOptions>((options) => {
// }
// })

consola.info('answer setup')
// 应答
onMessage(async (msg) => {
onNapcatMessage(async (msg) => {
// use async in some
// https://advancedweb.hu/how-to-use-async-functions-with-array-some-and-every-in-javascript/
for await (const ans of options.list) {
// const replyContent = null

// const replyContent = null
// if (ans.at) {
// if (!(msg.type === 'GroupMessage' && msg.isAt()))
// return
Expand Down Expand Up @@ -74,6 +76,7 @@ export default defineBotPlugin<AnswerOptions>((options) => {
// }
}
})
consola.info('answer setup done')
},
}
})

0 comments on commit 6676d94

Please sign in to comment.