Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/dev' into dev
Browse files Browse the repository at this point in the history
# Conflicts:
#	src/utils/common/common.ts
#	src/utils/config/config.ts
  • Loading branch information
ChisatoNishikigi73 committed Sep 13, 2024
2 parents d5d1beb + 2309e9c commit 38f7923
Show file tree
Hide file tree
Showing 24 changed files with 444 additions and 199 deletions.
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
# 更新日志

## [0.12.5](https://github.com/KarinJS/Karin/compare/v0.12.4...v0.12.5) (2024-09-12)


### Bug Fixes

* build error ([92bb5e3](https://github.com/KarinJS/Karin/commit/92bb5e302f26873dbaaa3bd279b9573033aab4f8))

## [0.12.4](https://github.com/KarinJS/Karin/compare/v0.12.3...v0.12.4) (2024-09-12)


### Bug Fixes

* close [#157](https://github.com/KarinJS/Karin/issues/157) ([76aaa47](https://github.com/KarinJS/Karin/commit/76aaa476ea30170f8f023655c5a4f36d9e3c5f70))
* close [#162](https://github.com/KarinJS/Karin/issues/162) ([7e9ac29](https://github.com/KarinJS/Karin/commit/7e9ac29d1668d13f7d233ebd4c16f99e520cced2))
* close [#164](https://github.com/KarinJS/Karin/issues/164) ([ee71426](https://github.com/KarinJS/Karin/commit/ee7142610f2f1ee04e540cc51e399adba768a2cc))

## [0.12.3](https://github.com/KarinJS/Karin/compare/v0.12.2...v0.12.3) (2024-09-12)


### Bug Fixes

* close [#153](https://github.com/KarinJS/Karin/issues/153) [#156](https://github.com/KarinJS/Karin/issues/156) [#152](https://github.com/KarinJS/Karin/issues/152) ([8447b93](https://github.com/KarinJS/Karin/commit/8447b93b0e9d7f992a310c9bb4bbd1fd5f9ae0a6))
* store ([6f7bda3](https://github.com/KarinJS/Karin/commit/6f7bda3b4592059cede1505da95b88d1f46face0))

## [0.12.2](https://github.com/KarinJS/Karin/compare/v0.12.1...v0.12.2) (2024-08-27)


Expand Down
4 changes: 2 additions & 2 deletions config/defSet/group.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ default:
disable: []

# 单个Bot默认配置
Bot.self_id:
Bot:self_id:
# 群聊中所有消息冷却时间,单位秒,0则无限制
GroupCD: 0
# 群聊中 每个人的消息冷却时间,单位秒,0则无限制。注意,开启后所有消息都会进CD,无论是否触发插件。
Expand All @@ -37,7 +37,7 @@ Bot.self_id:
disable: []

# 单个Bot单个群配置
Bot.self_id.group_id:
Bot:self_id:group_id:
# 群聊中所有消息冷却时间,单位秒,0则无限制
GroupCD: 0
# 群聊中 每个人的消息冷却时间,单位秒,0则无限制。注意,开启后所有消息都会进CD,无论是否触发插件。
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "node-karin",
"version": "0.12.2",
"version": "0.12.5",
"private": false,
"description": "基于 Kritor 进行开发的nodejs机器人框架",
"homepage": "https://github.com/KarinJS/Karin",
Expand Down
3 changes: 3 additions & 0 deletions src/adapter/onebot/11/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,9 @@ export function KarinConvertAdapter (data: Array<KarinElement>, bot: AdapterOneB
elements.push({ type: 'weather', data: { city: i.city, type: i.type } })
break
}
case 'raw':
elements.push(i.data)
break
case 'button':
case 'markdown':
case 'keyboard':
Expand Down
32 changes: 29 additions & 3 deletions src/adapter/onebot/11/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,12 @@ export class OB11Event {
const self_id = data.self_id + ''
let notice = {} as KarinNotice

const user_id = data.user_id + ''
/** 别问为啥any... 我是any糕手~ */
const user_id = ((data as any).user_id || (data as any).operator_id) + ''
const event_id = `notice.${time}`
const sender = {
uid: data.user_id + '',
uin: data.user_id + '',
uid: user_id,
uin: user_id,
nick: '',
role: Role.Unknown,
}
Expand Down Expand Up @@ -370,6 +371,31 @@ export class OB11Event {
notice = new KarinNotice(options)
break
}
// Language表情动态上报
case 'reaction': {
const group_id = data.group_id + ''
const content = {
group_id,
message_id: data.message_id,
face_id: Number(data.code),
is_set: data.sub_type === 'add',
}

const options = {
raw_event: data,
time,
self_id,
user_id,
event_id,
sender,
contact,
content,
group_id,
sub_event: NoticeSubType.GroupMessageReaction,
}
notice = new KarinNotice(options)
break
}
default: {
return this.adapter.logger('error', '未知通知事件:', JSON.stringify(data))
}
Expand Down
17 changes: 17 additions & 0 deletions src/api/git.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import fs from 'fs'
import { dirName } from 'karin/types'

/**
* 获取git插件列表
* @param isPack - 是否屏蔽不带package.json的插件,默认为false
*/
export function getGitPlugins (isPack = false): Array<dirName> {
const dir = './plugins'
let list = fs.readdirSync(dir, { withFileTypes: true })
/** 忽略非文件夹、非 karin-plugin-开头的文件夹 */
list = list.filter(v => v.isDirectory() && v.name.startsWith('karin-plugin-'))
if (isPack) list = list.filter(v => fs.existsSync(`${dir}/${v.name}/package.json`))
const arr: dirName[] = []
list.map(v => arr.push(v.name as dirName))
return arr
}
68 changes: 68 additions & 0 deletions src/api/npm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import fs from 'fs'
import path from 'path'
import { NpmInfo } from 'karin/utils'
import { readJson } from './readJson'

/**
* 获取npm插件列表
* @param showDetails - 是否返回详细信息
* 默认只返回插件npm包名,为true时返回详细的{dir, name}[]
*/
export async function getNpmPlugins<T extends boolean> (showDetails: T): Promise<T extends true ? NpmInfo[] : string[]> {
/** 屏蔽的依赖包列表 */
const exclude = ['art-template', 'axios', 'chalk', 'chokidar', 'commander', 'express', 'level', 'lodash', 'log4js', 'moment', 'node-karin', 'node-schedule', 'redis', 'ws', 'yaml']

const pkg = readJson('./package.json')
const dependencies = Object.keys(pkg.dependencies).filter((name) => !exclude.includes(name))

if (!showDetails) {
const list: string[] = []
const readPackageJson = async (name: string) => {
try {
const pkgPath = path.join(process.cwd(), 'node_modules', name, 'package.json')
const pkg = readJson(pkgPath)
if (pkg?.karin) list.push(name)
} catch (error: any) {
logger.error(`[common] 解析 package.json 时出错:${error.stack || error.message || JSON.stringify(error)}`)
}
}

await Promise.all(dependencies.map(readPackageJson))
return list as T extends true ? NpmInfo[] : string[]
}

const list: NpmInfo[] = []
/** 获取详细的npm信息 */
const readPackageJson = async (files: string) => {
try {
const root = path.join(process.cwd(), 'node_modules', files)
const pkgPath = path.join(root, 'package.json')
const pkg = readJson(pkgPath)
if (!pkg?.karin) return

if (pkg?.main) {
list.push({ plugin: files, path: path.dirname(pkg.main), file: path.basename(pkg.main), isMain: true })
}

if (pkg?.karin?.apps?.length) {
pkg.karin.apps.forEach((app: string) => {
if (!fs.existsSync(path.join(root, app))) {
logger.error(`[common] npm插件${files}的app目录${app}不存在 已跳过`)
return
}

fs.readdirSync(path.join(root, app)).forEach((filename: string) => {
/** 忽略非js文件 npm包不考虑ts */
if (!filename.endsWith('.js')) return
list.push({ plugin: files, path: app, file: filename, isMain: false })
})
})
}
} catch (error: any) {
logger.error(`[common] 获取npm插件列表时出错:${error.stack || error.message || JSON.stringify(error)}`)
}
}

await Promise.all(dependencies.map(readPackageJson))
return list as T extends true ? NpmInfo[] : string[]
}
9 changes: 9 additions & 0 deletions src/api/readJson.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import fs from 'fs'

/**
* - 解析json文件
* @param file - 文件路径
*/
export function readJson (file: string): any {
return JSON.parse(fs.readFileSync(file, 'utf8'))
}
41 changes: 6 additions & 35 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import axios from 'axios'
import { fileURLToPath } from 'url'
import { getRegistry } from './pkg'
import { exec as execCmd, spawn, ChildProcess, ExecOptions } from 'child_process'
import { getNpmPlugins } from 'karin/api/npm'
import { getGitPlugins } from 'karin/api/git'

export const enum Runner {
Node = 'node',
Expand Down Expand Up @@ -153,7 +155,7 @@ export class KarinCli {

/** 修正入口文件路径 兼容0.6.28以前的版本 */
if (!fs.existsSync('./src') && filePath === './config/config/pm2.yaml') {
const script = './node_modules/node-karin/lib/index.js'
const script = './node_modules/node-karin/lib/cli/start.js'
if (data.apps[0].script !== script) {
data.apps[0].script = script
fs.writeFileSync(filePath, yaml.stringify(data))
Expand Down Expand Up @@ -206,25 +208,8 @@ export class KarinCli {
* 更新依赖
*/
async update () {
/** 屏蔽的依赖包列表 */
const pkgdependencies = [
'art-template',
'axios',
'chalk',
'chokidar',
'commander',
'express',
'level',
'lodash',
'log4js',
'moment',
'node-schedule',
'redis',
'ws',
'yaml',
]

const list = Object.keys(this.pkg(false).dependencies).filter(key => !pkgdependencies.includes(key))
const list = await getNpmPlugins(false)
list.push('node-karin')

/** 获取包管理器 */
const pkg = getRegistry()
Expand Down Expand Up @@ -252,7 +237,7 @@ export class KarinCli {

console.log('[依赖更新] 所有npm依赖已更新完成~')
console.log('[依赖更新] 开始更新git插件...')
const gitList = this.getGitPlugins()
const gitList = getGitPlugins()
if (!gitList.length) return console.log('[依赖更新] 没有git插件需要更新~')

await Promise.all(gitList.map(async item => {
Expand Down Expand Up @@ -310,20 +295,6 @@ export class KarinCli {
return text.trim()
}

/**
* 获取git插件列表
*/
getGitPlugins (): Array<string> {
const dir = path.resolve(process.cwd(), 'plugins')
let list = fs.readdirSync(dir, { withFileTypes: true })
/** 忽略非文件夹、非 karin-plugin-开头的文件夹 */
list = list.filter(v => v.isDirectory() && v.name.startsWith('karin-plugin-'))
list = list.filter(v => fs.existsSync(`${dir}/${v.name}/package.json`))
const arr: string[] = []
list.map(v => arr.push(v.name))
return arr
}

/**
* 封装exec
* @param cmd - 命令
Expand Down
3 changes: 3 additions & 0 deletions src/cli/start.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { program } from 'commander'
import { KarinCli, Mode, Runner, Lang } from './index'

/** 兼容node .启动方式 */
if (process.argv.length === 2) process.argv.push('.')

const karin = new KarinCli()
program.version(karin.pkg(true).version, '-v, --version', '显示版本号')
program.command('.').description('启动karin').action(() => karin.start(Mode.Prod, Lang.Js, Runner.Node))
Expand Down
9 changes: 5 additions & 4 deletions src/core/init/dir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import path from 'path'
import { fileURLToPath } from 'url'

const filename = fileURLToPath(import.meta.url)
/**
* - 获取当前npm包的根目录
*/
export const karinDir = path.resolve(filename, '../../../../').replace(/\\/g, '/').replace(/\/$/, '')
/** 获取当前npm包的根目录 */
export const karinDir = path.resolve(filename, '../../../..').replace(/\/$/, '')

/** 当前是否处于npm包环境 否则代表处于开发环境 */
export const isPkg = karinDir.includes('node_modules')
2 changes: 1 addition & 1 deletion src/core/init/init.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { logger } from 'karin/utils'
import { logger } from 'karin/utils/core/logger'

/**
* 启动日志
Expand Down
31 changes: 31 additions & 0 deletions src/core/listener/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
KarinNoticeType,
KarinRequestType,
KarinMessageType,
NodeElement,
} from 'karin/types'

type AdapterType = KarinAdapter['adapter']['type']
Expand Down Expand Up @@ -115,6 +116,36 @@ export class Listeners extends EventEmitter {
this.list.push({ index, type: data.type, bot: data.bot })
logger.info(`[机器人][注册][${data.type}] ` + logger.green(`[account:${data.bot.account.uid || data.bot.account.uin}(${data.bot.account.name})]`))
this.#online(data.bot.account.uid || data.bot.account.uin)

/** 对sendForwardMessage方法进行修改 添加中间键 */
const sendForwardMessage = data.bot.sendForwardMessage
data.bot.sendForwardMessage = async (contact: Contact, elements: Array<NodeElement>) => {
for (const info of pluginLoader.use.forwardMsg) {
try {
let next = false
let exit = false
const nextFn = () => { next = true }
const exitFn = () => { exit = true }

await info.fn(contact, elements, nextFn, exitFn)

if (exit) {
const plugin = pluginLoader.plugin.get(info.key)!
logger.debug(`[消息中间件][${plugin.plugin}][${plugin.file}] 主动操作退出`)
return { message_id: '' }
}

if (!next) break
} catch (e) {
logger.error('[消息中间件] 调用失败,已跳过')
logger.error(e)
}
}

const result = await sendForwardMessage(contact, elements)
return result
}

logger.debug('注册', this.list)
return index
}
Expand Down
Loading

0 comments on commit 38f7923

Please sign in to comment.