Skip to content

Commit

Permalink
新增 定时更新/重启/关机/开机,优化 原关机改为停止,现关机与开机配合使用
Browse files Browse the repository at this point in the history
  • Loading branch information
TimeRainStarSky committed May 30, 2024
1 parent 9423a3e commit 00fb64c
Show file tree
Hide file tree
Showing 7 changed files with 155 additions and 74 deletions.
9 changes: 9 additions & 0 deletions config/default_config/bot.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ port: 2536
update_time: 1440
# 自动重启时间
restart_time: 0
# 定时更新cron表达式
update_cron:
# 定时重启cron表达式
restart_cron:
# 定时关机cron表达式
stop_cron:
# 定时开机cron表达式
start_cron:

# 上线推送通知的冷却时间
online_msg_exp: 1440
# 文件保存时间
Expand Down
2 changes: 1 addition & 1 deletion lib/listener/listener.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default class EventListener {
* @param data.event 监听的事件
* @param data.once 是否只监听一次
*/
constructor (data) {
constructor(data) {
this.prefix = data.prefix || ""
this.event = data.event
this.once = data.once || false
Expand Down
2 changes: 1 addition & 1 deletion lib/listener/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class ListenerLoader {
/**
* 监听事件加载
*/
async load () {
async load() {
Bot.makeLog("info", "-----------", "Listener")
Bot.makeLog("info", "加载监听事件中...", "Listener")
let eventCount = 0
Expand Down
72 changes: 36 additions & 36 deletions lib/plugins/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,27 @@ global.segment = segment
* 加载插件
*/
class PluginsLoader {
constructor() {
this.priority = []
this.handler = {}
this.task = []
this.dir = "plugins"

/** 命令冷却cd */
this.groupCD = {}
this.singleCD = {}

/** 插件监听 */
this.watcher = {}
this.eventMap = {
message: ["post_type", "message_type", "sub_type"],
notice: ["post_type", "notice_type", "sub_type"],
request: ["post_type", "request_type", "sub_type"],
}
priority = []
handler = {}
task = []
dir = "plugins"

/** 命令冷却cd */
groupCD = {}
singleCD = {}

/** 插件监听 */
watcher = {}
eventMap = {
message: ["post_type", "message_type", "sub_type"],
notice: ["post_type", "notice_type", "sub_type"],
request: ["post_type", "request_type", "sub_type"],
}

this.msgThrottle = {}
msgThrottle = {}

/** 星铁命令前缀 */
this.srReg = /^#?(\*|星铁|星轨|穹轨|星穹|崩铁|星穹铁道|崩坏星穹铁道|铁道)+/
}
/** 星铁命令前缀 */
srReg = /^#?(\*|星铁|星轨|穹轨|星穹|崩铁|星穹铁道|崩坏星穹铁道|铁道)+/

async getPlugins() {
const files = await fs.readdir(this.dir, { withFileTypes: true })
Expand Down Expand Up @@ -132,7 +130,7 @@ class PluginsLoader {
/** 执行初始化,返回 return 则跳过加载 */
if (plugin.init && await plugin.init() == "return") return
/** 初始化定时任务 */
this.collectTask(plugin.task)
this.collectTask(plugin.task, plugin.name)
this.priority.push({
class: p,
key: file.name,
Expand Down Expand Up @@ -523,26 +521,28 @@ class PluginsLoader {
}

/** 收集定时任务 */
collectTask(task) {
collectTask(task, name) {
for (const i of Array.isArray(task) ? task : [task])
if (i.cron && i.name)
if (i.cron && i.fnc) {
i.name ??= name
this.task.push(i)
}
}

/** 创建定时任务 */
createTask() {
for (const i of this.task)
i.job = schedule.scheduleJob(i.cron, async () => {
try {
if (i.log == true)
Bot.makeLog("mark", `开始定时任务 ${i.name}`, "Task")
await i.fnc()
if (i.log == true)
Bot.makeLog("mark", `定时任务完成 ${i.name}`, "Task")
} catch (err) {
Bot.makeLog("error", [`定时任务报错 ${i.name}`, err], "Task")
}
})
for (const i of this.task) {
const name = `${logger.blue(`[${i.name}(${i.cron})]`)}`
Bot.makeLog("debug", `加载定时任务 ${name}`, "Task")
i.job = schedule.scheduleJob(i.cron, async () => { try {
const start_time = Date.now()
Bot.makeLog(i.log === false ? "debug" : "mark", `${name}${logger.yellow("[开始处理]")}`, false)
await i.fnc()
Bot.makeLog(i.log === false ? "debug" : "mark", `${name}${logger.green(`[完成${Bot.getTimeDiff(start_time)}]`)}`, false)
} catch (err) {
Bot.makeLog("error", [name, err], false)
}})
}
}

/** 检查命令冷却cd */
Expand Down
11 changes: 2 additions & 9 deletions lib/plugins/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default class plugin {
namespace,
event = "message",
priority = 5000,
task = { fnc: "", cron: "" },
task = { name: "", fnc: "", cron: "" },
rule = []
}) {
/** 插件名称 */
Expand All @@ -48,14 +48,7 @@ export default class plugin {
/** 优先级 */
this.priority = priority
/** 定时任务,可以是数组 */
this.task = {
/** 任务名 */
name: "",
/** 任务方法名 */
fnc: task.fnc || "",
/** 任务cron表达式 */
cron: task.cron || ""
}
this.task = task
/** 命令规则 */
this.rule = rule

Expand Down
109 changes: 90 additions & 19 deletions plugins/other/restart.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
import cfg from "../../lib/config/config.js"
import { spawn } from "child_process"
import PluginsLoader from "../../lib/plugins/loader.js"

const temp = {}
class Start extends plugin {
constructor(e) {
super({
name: "开机",
dsc: "#开机",
event: "message",
rule: [
{
reg: "^#开机$",
fnc: "start"
}
]
})
if (e) this.e = e
}

async start() {
if (!this.e.isMaster || !temp.priority) return false
PluginsLoader.priority = temp.priority
delete temp.priority
temp.start_time = Date.now()
return this.reply(`开机成功,距离上次关机${Bot.getTimeDiff(temp.stop_time)}`)
}
}

export class Restart extends plugin {
constructor(e = "") {
constructor(e) {
super({
name: "重启",
dsc: "#重启",
name: "进程管理",
dsc: "#重启 #关机 #停止",
event: "message",
priority: 10,
rule: [
Expand All @@ -15,32 +42,64 @@ export class Restart extends plugin {
permission: "master"
},
{
reg: "^#(停|关)(机|止)$",
reg: "^#关机$",
fnc: "stop",
permission: "master"
},
{
reg: "^#停(机|止)$",
fnc: "exit",
permission: "master"
}
]
})

if (e) this.e = e
this.key = "Yz:restart"
}
key = "Yz:restart"

init() {
Bot.once("online", () => this.restartMsg())
if (cfg.bot.restart_time) {
this.e = { reply: msg => Bot.sendMasterMsg(msg) }
setTimeout(() => this.restart(), cfg.bot.restart_time*60000)
this.e = {
reply: msg => Bot.sendMasterMsg(msg),
isMaster: true,
}
if (cfg.bot.restart_time)
setTimeout(() => this.restart(), cfg.bot.restart_time*60000)

this.task = []
if (cfg.bot.restart_cron)
for (const i of Array.isArray(cfg.bot.restart_cron) ? cfg.bot.restart_cron : [cfg.bot.restart_cron])
this.task.push({
name: "定时重启",
cron: i,
fnc: () => this.restart(),
})
if (cfg.bot.stop_cron)
for (const i of Array.isArray(cfg.bot.stop_cron) ? cfg.bot.stop_cron : [cfg.bot.stop_cron])
this.task.push({
name: "定时关机",
cron: i,
fnc: () => this.stop(),
})
if (cfg.bot.start_cron)
for (const i of Array.isArray(cfg.bot.start_cron) ? cfg.bot.start_cron : [cfg.bot.start_cron])
this.task.push({
name: "定时开机",
cron: i,
fnc: () => new Start(this.e).start(),
})
}

async restartMsg() {
let restart = await redis.get(this.key)
if (!restart) return
await redis.del(this.key)
restart = JSON.parse(restart)
if (restart.isStop)
return this.stop(restart.time)

const time = Bot.getTimeDiff(restart.time)
const msg = [restart.isStop ? `开机成功,距离上次关机${time}` : `重启成功,用时${time}`]
const msg = [restart.isExit ? `开机成功,距离上次停止${time}` : `重启成功,用时${time}`]
if (restart.msg_id)
msg.unshift(segment.reply(restart.msg_id))

Expand All @@ -50,14 +109,17 @@ export class Restart extends plugin {
await Bot.sendFriendMsg(restart.bot_id, restart.user_id, msg)
else
await Bot.sendMasterMsg(msg)

return redis.del(this.key)
}

async set(isStop) {
await this.e.reply(`开始${isStop ? "关机" : "重启"},本次运行时长:${Bot.getTimeDiff()}`)
async set(isExit) {
if (temp.priority)
return redis.set(this.key, JSON.stringify({
isStop: true,
time: temp.stop_time,
}))
await this.reply(`开始${isExit ? "停止" : "重启"},本次运行时长${Bot.getTimeDiff()}`)
return redis.set(this.key, JSON.stringify({
isStop,
isExit,
group_id: this.e.group_id,
user_id: this.e.user_id,
bot_id: this.e.self_id,
Expand All @@ -71,17 +133,26 @@ export class Restart extends plugin {
if (process.env.app_type == "pm2") {
const ret = await Bot.exec("pnpm run restart")
if (!ret.error) process.exit()
await this.e.reply(`重启错误\n${ret.error}\n${ret.stdout}\n${ret.stderr}`)
await this.reply(`重启错误\n${ret.error}\n${ret.stdout}\n${ret.stderr}`)
Bot.makeLog("error", ["重启错误", ret])
} else process.exit()
}

async stop() {
async stop(time) {
if (temp.priority) return false
temp.priority = PluginsLoader.priority
PluginsLoader.priority = [{ class: Start }]
if (typeof time === "number") return temp.stop_time = time
temp.stop_time = Date.now()
return this.reply(`关机成功,本次运行时长${Bot.getTimeDiff(temp.start_time)}`)
}

async exit() {
await this.set(true)
if (process.env.app_type == "pm2") {
const ret = await Bot.exec("pnpm stop")
await this.e.reply(`关机错误\n${ret.error}\n${ret.stdout}\n${ret.stderr}`)
Bot.makeLog("error", ["关机错误", ret])
await this.reply(`停止错误\n${ret.error}\n${ret.stdout}\n${ret.stderr}`)
Bot.makeLog("error", ["停止错误", ret])
} else process.exit(1)
}
}
24 changes: 16 additions & 8 deletions plugins/other/update.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,23 @@ export class update extends plugin {
}

init() {
if (cfg.bot.update_time) {
this.e = {
isMaster: true,
logFnc: "[自动更新]",
msg: "#全部静更新",
reply: msg => Bot.sendMasterMsg(msg),
}
this.autoUpdate()
this.e = {
isMaster: true,
logFnc: "[自动更新]",
msg: "#全部静更新",
reply: msg => Bot.sendMasterMsg(msg),
}
if (cfg.bot.update_time)
this.autoUpdate()

this.task = []
if (cfg.bot.update_cron)
for (const i of Array.isArray(cfg.bot.update_cron) ? cfg.bot.update_cron : [cfg.bot.update_cron])
this.task.push({
name: "定时更新",
cron: i,
fnc: () => this.updateAll(),
})
}

autoUpdate() {
Expand Down

0 comments on commit 00fb64c

Please sign in to comment.