fix: update forward

This commit is contained in:
ikechan8370 2023-09-12 11:14:08 +08:00
parent f620e10abb
commit a91e2c25b3

View file

@ -1,316 +1,323 @@
// modified from StarRail-plugin | 已经过StarRail-plugin作者本人同意 // modified from StarRail-plugin | 已经过StarRail-plugin作者本人同意
import plugin from '../../../lib/plugins/plugin.js' import plugin from '../../../lib/plugins/plugin.js'
import { createRequire } from 'module' import { createRequire } from 'module'
import _ from 'lodash' import _ from 'lodash'
import { Restart } from '../../other/restart.js' import { Restart } from '../../other/restart.js'
import fs from 'fs' import fs from 'fs'
import {} from "../utils/common.js"; import {} from '../utils/common.js'
const _path = process.cwd() const _path = process.cwd()
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
const { exec, execSync } = require('child_process') const { exec, execSync } = require('child_process')
const checkAuth = async function (e) { const checkAuth = async function (e) {
if (!e.isMaster) { if (!e.isMaster) {
e.reply(`只有主人才能命令ChatGPT哦~(*/ω\*)`) e.reply('只有主人才能命令ChatGPT哦~(*/ω\*)')
return false return false
} }
return true return true
} }
// 是否在更新中 // 是否在更新中
let uping = false let uping = false
/** /**
* 处理插件更新 * 处理插件更新
*/ */
export class Update extends plugin { export class Update extends plugin {
constructor () { constructor () {
super({ super({
name: 'chatgpt更新插件', name: 'chatgpt更新插件',
event: 'message', event: 'message',
priority: 1000, priority: 1000,
rule: [ rule: [
{ {
reg: '^#?(chatgpt|柴特寄批踢|GPT|ChatGPT|柴特鸡批踢|Chat|CHAT|CHATGPT|柴特|ChatGPT-Plugin|ChatGPT-plugin|chatgpt-plugin)(插件)?(强制)?更新$', reg: '^#?(chatgpt|柴特寄批踢|GPT|ChatGPT|柴特鸡批踢|Chat|CHAT|CHATGPT|柴特|ChatGPT-Plugin|ChatGPT-plugin|chatgpt-plugin)(插件)?(强制)?更新$',
fnc: 'update' fnc: 'update'
} }
] ]
}) })
} }
/**
* rule - 更新chatgpt插件
* @returns
/** */
* rule - 更新chatgpt插件 async update () {
* @returns if (!this.e.isMaster) return false
*/
async update () { /** 检查是否正在更新中 */
if (!this.e.isMaster) return false if (uping) {
await this.reply('已有命令更新中..请勿重复操作')
/** 检查是否正在更新中 */ return
if (uping) { }
await this.reply('已有命令更新中..请勿重复操作')
return /** 检查git安装 */
} if (!(await this.checkGit())) return
/** 检查git安装 */ const isForce = this.e.msg.includes('强制')
if (!(await this.checkGit())) return
/** 执行更新 */
const isForce = this.e.msg.includes('强制') await this.runUpdate(isForce)
/** 执行更新 */ /** 是否需要重启 */
await this.runUpdate(isForce) if (this.isUp) {
// await this.reply("更新完毕,请重启云崽后生效")
/** 是否需要重启 */ setTimeout(() => this.restart(), 2000)
if (this.isUp) { }
// await this.reply("更新完毕,请重启云崽后生效") }
setTimeout(() => this.restart(), 2000)
} restart () {
} new Restart(this.e).restart()
}
restart () {
new Restart(this.e).restart() /**
} * chatgpt插件更新函数
* @param {boolean} isForce 是否为强制更新
/** * @returns
* chatgpt插件更新函数 */
* @param {boolean} isForce 是否为强制更新 async runUpdate (isForce) {
* @returns let command = 'git -C ./plugins/chatgpt-plugin/ pull --no-rebase'
*/ if (isForce) {
async runUpdate (isForce) { command = `git -C ./plugins/chatgpt-plugin/ checkout . && ${command}`
let command = 'git -C ./plugins/chatgpt-plugin/ pull --no-rebase' this.e.reply('正在执行强制更新操作,请稍等')
if (isForce) { } else {
command = `git -C ./plugins/chatgpt-plugin/ checkout . && ${command}` this.e.reply('正在执行更新操作,请稍等')
this.e.reply('正在执行强制更新操作,请稍等') }
} else { /** 获取上次提交的commitId用于获取日志时判断新增的更新日志 */
this.e.reply('正在执行更新操作,请稍等') this.oldCommitId = await this.getcommitId('chatgpt-plugin')
} uping = true
/** 获取上次提交的commitId用于获取日志时判断新增的更新日志 */ let ret = await this.execSync(command)
this.oldCommitId = await this.getcommitId('chatgpt-plugin') uping = false
uping = true
let ret = await this.execSync(command) if (ret.error) {
uping = false logger.mark(`${this.e.logFnc} 更新失败chatgpt-plugin`)
this.gitErr(ret.error, ret.stdout)
if (ret.error) { return false
logger.mark(`${this.e.logFnc} 更新失败chatgpt-plugin`) }
this.gitErr(ret.error, ret.stdout)
return false /** 获取插件提交的最新时间 */
} let time = await this.getTime('chatgpt-plugin')
/** 获取插件提交的最新时间 */ if (/(Already up[ -]to[ -]date|已经是最新的)/.test(ret.stdout)) {
let time = await this.getTime('chatgpt-plugin') await this.reply(`chatgpt-plugin已经是最新版本\n最后更新时间:${time}`)
} else {
if (/(Already up[ -]to[ -]date|已经是最新的)/.test(ret.stdout)) { await this.reply(`chatgpt-plugin\n最后更新时间:${time}`)
await this.reply(`chatgpt-plugin已经是最新版本\n最后更新时间:${time}`) this.isUp = true
} else { /** 获取chatgpt组件的更新日志 */
await this.reply(`chatgpt-plugin\n最后更新时间:${time}`) let log = await this.getLog('chatgpt-plugin')
this.isUp = true await this.reply(log)
/** 获取chatgpt组件的更新日志 */ }
let log = await this.getLog('chatgpt-plugin')
await this.reply(log) logger.mark(`${this.e.logFnc} 最后更新时间:${time}`)
}
return true
logger.mark(`${this.e.logFnc} 最后更新时间:${time}`) }
return true /**
} * 获取chatgpt插件的更新日志
* @param {string} plugin 插件名称
/** * @returns
* 获取chatgpt插件的更新日志 */
* @param {string} plugin 插件名称 async getLog (plugin = '') {
* @returns let cm = `cd ./plugins/${plugin}/ && git log -20 --oneline --pretty=format:"%h||[%cd] %s" --date=format:"%m-%d %H:%M"`
*/
async getLog (plugin = '') { let logAll
let cm = `cd ./plugins/${plugin}/ && git log -20 --oneline --pretty=format:"%h||[%cd] %s" --date=format:"%m-%d %H:%M"` try {
logAll = await execSync(cm, { encoding: 'utf-8' })
let logAll } catch (error) {
try { logger.error(error.toString())
logAll = await execSync(cm, { encoding: 'utf-8' }) this.reply(error.toString())
} catch (error) { }
logger.error(error.toString())
this.reply(error.toString()) if (!logAll) return false
}
logAll = logAll.split('\n')
if (!logAll) return false
let log = []
logAll = logAll.split('\n') for (let str of logAll) {
str = str.split('||')
let log = [] if (str[0] == this.oldCommitId) break
for (let str of logAll) { if (str[1].includes('Merge branch')) continue
str = str.split('||') log.push(str[1])
if (str[0] == this.oldCommitId) break }
if (str[1].includes('Merge branch')) continue let line = log.length
log.push(str[1]) log = log.join('\n\n')
}
let line = log.length if (log.length <= 0) return ''
log = log.join('\n\n')
let end = ''
if (log.length <= 0) return '' end =
'更多详细信息请前往github查看\nhttps://github.com/ikechan8370/chatgpt-plugin'
let end = ''
end = log = await this.makeForwardMsg(`chatgpt-plugin更新日志${line}`, log, end)
'更多详细信息请前往github查看\nhttps://github.com/ikechan8370/chatgpt-plugin'
return log
log = await this.makeForwardMsg(`chatgpt-plugin更新日志${line}`, log, end) }
return log /**
} * 获取上次提交的commitId
* @param {string} plugin 插件名称
/** * @returns
* 获取上次提交的commitId */
* @param {string} plugin 插件名称 async getcommitId (plugin = '') {
* @returns let cm = `git -C ./plugins/${plugin}/ rev-parse --short HEAD`
*/
async getcommitId (plugin = '') { let commitId = await execSync(cm, { encoding: 'utf-8' })
let cm = `git -C ./plugins/${plugin}/ rev-parse --short HEAD` commitId = _.trim(commitId)
let commitId = await execSync(cm, { encoding: 'utf-8' }) return commitId
commitId = _.trim(commitId) }
return commitId /**
} * 获取本次更新插件的最后一次提交时间
* @param {string} plugin 插件名称
/** * @returns
* 获取本次更新插件的最后一次提交时间 */
* @param {string} plugin 插件名称 async getTime (plugin = '') {
* @returns let cm = `cd ./plugins/${plugin}/ && git log -1 --oneline --pretty=format:"%cd" --date=format:"%m-%d %H:%M"`
*/
async getTime (plugin = '') { let time = ''
let cm = `cd ./plugins/${plugin}/ && git log -1 --oneline --pretty=format:"%cd" --date=format:"%m-%d %H:%M"` try {
time = await execSync(cm, { encoding: 'utf-8' })
let time = '' time = _.trim(time)
try { } catch (error) {
time = await execSync(cm, { encoding: 'utf-8' }) logger.error(error.toString())
time = _.trim(time) time = '获取时间失败'
} catch (error) { }
logger.error(error.toString()) return time
time = '获取时间失败' }
}
return time /**
} * 制作转发消息
* @param {string} title 标题 - 首条消息
/** * @param {string} msg 日志信息
* 制作转发消息 * @param {string} end 最后一条信息
* @param {string} title 标题 - 首条消息 * @returns
* @param {string} msg 日志信息 */
* @param {string} end 最后一条信息 async makeForwardMsg (title, msg, end) {
* @returns let nickname = (this.e.bot ?? Bot).nickname
*/ if (this.e.isGroup) {
async makeForwardMsg (title, msg, end) { let info = await (this.e.bot ?? Bot).getGroupMemberInfo(this.e.group_id, (this.e.bot ?? Bot).uin)
let nickname = (this.e.bot ?? Bot).nickname nickname = info.card || info.nickname
if (this.e.isGroup) { }
let info = await (this.e.bot ?? Bot).getGroupMemberInfo(this.e.group_id, (this.e.bot ?? Bot).uin) let userInfo = {
nickname = info.card || info.nickname user_id: (this.e.bot ?? Bot).uin,
} nickname
let userInfo = { }
user_id: (this.e.bot ?? Bot).uin,
nickname let forwardMsg = [
} {
...userInfo,
let forwardMsg = [ message: title
{ },
...userInfo, {
message: title ...userInfo,
}, message: msg
{ }
...userInfo, ]
message: msg
} if (end) {
] forwardMsg.push({
...userInfo,
if (end) { message: end
forwardMsg.push({ })
...userInfo, }
message: end
}) /** 制作转发内容 */
} if (this.e.group?.makeForwardMsg) {
forwardMsg = await this.e.group.makeForwardMsg(forwardMsg)
/** 制作转发内容 */ } else if (this.e?.friend?.makeForwardMsg) {
if (this.e.isGroup) { forwardMsg = await this.e.friend.makeForwardMsg(forwardMsg)
forwardMsg = await this.e.group.makeForwardMsg(forwardMsg) } else {
} else { return msg.join('\n')
forwardMsg = await this.e.friend.makeForwardMsg(forwardMsg) }
}
let dec = 'chatgpt-plugin 更新日志'
/** 处理描述 */ /** 处理描述 */
forwardMsg.data = forwardMsg.data if (typeof (forwardMsg.data) === 'object') {
.replace(/\n/g, '') let detail = forwardMsg.data?.meta?.detail
.replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___') if (detail) {
.replace(/___+/, `<title color="#777777" size="26">${title}</title>`) detail.news = [{ text: dec }]
}
return forwardMsg } else {
} forwardMsg.data = forwardMsg.data
.replace(/\n/g, '')
/** .replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___')
* 处理更新失败的相关函数 .replace(/___+/, `<title color="#777777" size="26">${dec}</title>`)
* @param {string} err }
* @param {string} stdout
* @returns return forwardMsg
*/ }
async gitErr (err, stdout) {
let msg = '更新失败!' /**
let errMsg = err.toString() * 处理更新失败的相关函数
stdout = stdout.toString() * @param {string} err
* @param {string} stdout
if (errMsg.includes('Timed out')) { * @returns
let remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '') */
await this.reply(msg + `\n连接超时:${remote}`) async gitErr (err, stdout) {
return let msg = '更新失败!'
} let errMsg = err.toString()
stdout = stdout.toString()
if (/Failed to connect|unable to access/g.test(errMsg)) {
let remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '') if (errMsg.includes('Timed out')) {
await this.reply(msg + `\n连接失败:${remote}`) let remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '')
return await this.reply(msg + `\n连接超时:${remote}`)
} return
}
if (errMsg.includes('be overwritten by merge')) {
await this.reply( if (/Failed to connect|unable to access/g.test(errMsg)) {
msg + let remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '')
`存在冲突:\n${errMsg}\n` + await this.reply(msg + `\n连接失败:${remote}`)
'请解决冲突后再更新,或者执行#强制更新,放弃本地修改' return
) }
return
} if (errMsg.includes('be overwritten by merge')) {
await this.reply(
if (stdout.includes('CONFLICT')) { msg +
await this.reply([ `存在冲突:\n${errMsg}\n` +
msg + '存在冲突\n', '请解决冲突后再更新,或者执行#强制更新,放弃本地修改'
errMsg, )
stdout, return
'\n请解决冲突后再更新或者执行#强制更新,放弃本地修改' }
])
return if (stdout.includes('CONFLICT')) {
} await this.reply([
msg + '存在冲突\n',
await this.reply([errMsg, stdout]) errMsg,
} stdout,
'\n请解决冲突后再更新或者执行#强制更新,放弃本地修改'
/** ])
* 异步执行git相关命令 return
* @param {string} cmd git命令 }
* @returns
*/ await this.reply([errMsg, stdout])
async execSync (cmd) { }
return new Promise((resolve, reject) => {
exec(cmd, { windowsHide: true }, (error, stdout, stderr) => { /**
resolve({ error, stdout, stderr }) * 异步执行git相关命令
}) * @param {string} cmd git命令
}) * @returns
} */
async execSync (cmd) {
/** return new Promise((resolve, reject) => {
* 检查git是否安装 exec(cmd, { windowsHide: true }, (error, stdout, stderr) => {
* @returns resolve({ error, stdout, stderr })
*/ })
async checkGit () { })
let ret = await execSync('git --version', { encoding: 'utf-8' }) }
if (!ret || !ret.includes('git version')) {
await this.reply('请先安装git') /**
return false * 检查git是否安装
} * @returns
return true */
} async checkGit () {
} let ret = await execSync('git --version', { encoding: 'utf-8' })
if (!ret || !ret.includes('git version')) {
await this.reply('请先安装git')
return false
}
return true
}
}