Skip to content

Commit

Permalink
细节优化
Browse files Browse the repository at this point in the history
  • Loading branch information
TimeRainStarSky committed Apr 7, 2024
1 parent 91ce3a1 commit 0fe5152
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
20 changes: 18 additions & 2 deletions lib/bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,15 @@ export default class Yunzai extends EventEmitter {
if (Buffer.isBuffer(data))
return String(data)
}
return JSON.stringify(data)

try {
return JSON.stringify(data)
} catch (err) {
if (typeof data.toString == "function")
return String(data)
else
return "[object null]"
}
}

Loging(data) {
Expand Down Expand Up @@ -353,15 +361,23 @@ export default class Yunzai extends EventEmitter {

async exec(cmd, opts = {}) {
return new Promise(resolve => {
this.makeLog("mark", `[执行命令] ${logger.blue(cmd)}`)
if (!opts.quiet)
this.makeLog("mark", `[执行命令] ${logger.blue(cmd)}`)
exec(cmd, opts, (error, stdout, stderr) => {
resolve({ error, stdout, stderr })
if (opts.quiet) return
this.makeLog("mark", `[执行命令完成] ${logger.blue(cmd)}${stdout?`\n${String(stdout).trim()}`:""}${stderr?logger.red(`\n${String(stderr).trim()}`):""}`)
if (error) this.makeLog("error", `[执行命令错误] ${logger.blue(cmd)}\n${logger.red(this.Loging(error).trim())}`)
})
})
}

async cmdPath(cmd, opts = {}) {
const ret = await this.exec(`${process.platform == "win32" ? "where" : "command -v"} "${cmd}"`, { quiet: true, ...opts })
if (ret.error) return false
return ret.stdout.trim()
}

makeLog(level, msg, id) {
const log = []
if (id) log.push(logger.blue(`[${id}]`))
Expand Down
10 changes: 10 additions & 0 deletions lib/plugins/stdin.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import readline from "node:readline/promises"
import fs from "node:fs/promises"
import path from "node:path"
import { spawn } from "node:child_process"

Bot.adapter.push(new class stdinAdapter {
constructor() {
this.id = "stdin"
this.name = "标准输入"
this.path = "data/stdin/"
this.catimg = () => {}
}

async sendMsg(msg) {
Expand All @@ -32,6 +34,7 @@ Bot.adapter.push(new class stdinAdapter {
Bot.makeLog("info", `发送文本:${i.text}`, this.id)
break
case "image":
await this.catimg(file.path)
Bot.makeLog("info", `发送图片:${file.url}\n文件已保存到:${logger.cyan(file.path)}`, this.id)
break
case "record":
Expand Down Expand Up @@ -100,7 +103,14 @@ Bot.adapter.push(new class stdinAdapter {
Bot.em(`${data.post_type}.${data.message_type}`, data)
}

async loadCatimg() {
this.catimgPath = await Bot.cmdPath("catimg")
if (this.catimgPath)
this.catimg = file => new Promise(resolve => spawn(this.catimgPath, [file], { stdio:"inherit" }).on("close", resolve))
}

async load() {
this.loadCatimg()
await Bot.mkdir(this.path)
Bot[this.id] = {
adapter: this,
Expand Down

0 comments on commit 0fe5152

Please sign in to comment.