Skip to content

Commit

Permalink
improvement: 代码优化
Browse files Browse the repository at this point in the history
  • Loading branch information
rainbowwarmth committed Jan 18, 2025
1 parent 719a358 commit 9483e17
Show file tree
Hide file tree
Showing 26 changed files with 663 additions and 640 deletions.
12 changes: 6 additions & 6 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { initialize } from "./lib/index.js";
import logger from "./lib/config/logger.js";
import { Bot } from "./lib/config/config.js";
import chalk from "chalk";
import { initialize } from "./lib/index.js"
import logger from "./lib/config/logger.js"
import { Bot } from "./lib/config/config.js"
import chalk from "chalk"
initialize().then(() => {
logger.mark(chalk.cyan('KazuhaBot' + ' v' + Bot.version + '启动成功'));
});
logger.mark(chalk.cyan('KazuhaBot' + ' v' + Bot.version + '启动成功'))
})
47 changes: 26 additions & 21 deletions lib/common/common.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,58 @@
import fs from "fs";
import { _path, redis } from "../../lib/global/global.js";
import fs from "fs"
import { _path, redis } from "../../lib/global/global.js"

export function writeFileSyncEx(filePath, data, options) {
const pathPart = filePath.split("/").slice(0, -1);
const dirPath = pathPart.join("/");
const pathPart = filePath.split("/").slice(0, -1)
const dirPath = pathPart.join("/")
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
fs.mkdirSync(dirPath, { recursive: true })
}
fs.writeFileSync(filePath, data, options);
fs.writeFileSync(filePath, data, options)
}

export function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
return new Promise(resolve => setTimeout(resolve, ms))
}

export function cacheJson(opt, app, data) {
const jsonPath = `${_path}/generate/cache/${app}.json`;
const jsonPath = `${_path}/generate/cache/${app}.json`
try {
if (opt === "r") {
if (!fs.existsSync(jsonPath))
return null;
const jsonData = fs.readFileSync(jsonPath, "utf8");
return JSON.parse(jsonData);
const jsonData = fs.readFileSync(jsonPath, "utf8")
return JSON.parse(jsonData)
}
else {
writeFileSyncEx(jsonPath, JSON.stringify(data), { encoding: "utf8" });
return true;
writeFileSyncEx(jsonPath, JSON.stringify(data), { encoding: "utf8" })
return true
}
}
catch (error) {
logger.error(error);
return opt === "r" ? null : false;
logger.error(error)
return opt === "r" ? null : false
}
}

export async function redisCache(type, key, field, data, expire) {
if (type === "r") {
return await redis.hGet(key, field) || null;
return await redis.hGet(key, field) || null
}
if (type === "w") {
await redis.hSet(key, field, data);
await redis.hSet(key, field, data)
if (expire) {
await redis.expire(key, expire);
await redis.expire(key, expire)
}
}
return null;
return null
}

export const Format = {
int: (d) => parseInt(d),
comma: (num, fix = 0) => {
const [integer, decimal] = num.toFixed(fix).split('.');
return integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + (decimal ? '.' + decimal : '');
const [integer, decimal] = num.toFixed(fix).split('.')
return integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + (decimal ? '.' + decimal : '')
},
pct: (num, fix = 1) => num.toFixed(fix) + '%',
percent: (num, fix = 1) => Format.pct(num * 100, fix)
};
}
18 changes: 10 additions & 8 deletions lib/config/config.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import * as fs from 'fs';
import * as path from 'path';
const configFilePath = path.resolve(process.cwd(), 'config', 'config.json');
const botFilePath = path.resolve(process.cwd(), 'package.json');
import * as fs from 'fs'
import * as path from 'path'

const configFilePath = path.resolve(process.cwd(), 'config', 'config.json')
const botFilePath = path.resolve(process.cwd(), 'package.json')

if (!fs.existsSync(configFilePath)) {
console.log(`配置文件 config.json 不存在`)
console.log(`退出运行`)
process.exit(1);
process.exit(1)
}
const config = JSON.parse(fs.readFileSync(configFilePath, 'utf8'));
const Bot = JSON.parse(fs.readFileSync(botFilePath, 'utf8'));
export { config, Bot };
const config = JSON.parse(fs.readFileSync(configFilePath, 'utf8'))
const Bot = JSON.parse(fs.readFileSync(botFilePath, 'utf8'))
export { config, Bot }
52 changes: 26 additions & 26 deletions lib/config/init.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
import chalk from 'chalk';
import logger from '../../lib/config/logger.js';
import initGlobals from '../../lib/plugins/initGlobals.js';
import { Bot, config } from '../../lib/config/config.js';
import Task from '../../lib/core/schedule.js';
import { client, ws } from '../../lib/core/link.js';
import loadGuildTree from '../../lib/core/loadGuildTree.js';
import database from '../../lib/config/redis.js';
import renderinit from '../render/init.js';
import chalk from 'chalk'
import logger from '../../lib/config/logger.js'
import initGlobals from '../../lib/plugins/initGlobals.js'
import { Bot, config } from '../../lib/config/config.js'
import Task from '../../lib/core/schedule.js'
import { client, ws } from '../../lib/core/link.js'
import loadGuildTree from '../../lib/core/loadGuildTree.js'
import database from '../../lib/config/redis.js'
import renderinit from '../render/init.js'

export async function init() {
logger.mark(`-------(≡^∇^≡)-------`);
logger.mark(chalk.cyan('KazuhaBot' + ' v' + Bot.version + '启动中...'));
logger.mark(chalk.greenBright('https://github.com/rainbowwarmth/KazuhaBot_Newmys.git'));
process.title = 'KazuhaBot' + ' v' + Bot.version + ' © 2023-2025 ' + '@' + Bot.author;
process.env.TZ = "Asia/Shanghai";
await initGlobals();
await renderinit();
await Task();
await database();
global.chalk = chalk;
global.logger = logger;
client;
ws;
logger.info('初始化:正在创建频道树');
global.saveGuildsTree = [];
await loadGuildTree(config.loadGuildTree);

logger.mark(`-------(≡^∇^≡)-------`)
logger.mark(chalk.cyan('KazuhaBot' + ' v' + Bot.version + '启动中...'))
logger.mark(chalk.greenBright('https://github.com/rainbowwarmth/KazuhaBot_Newmys.git'))
process.title = 'KazuhaBot' + ' v' + Bot.version + ' © 2023-2025 ' + '@' + Bot.author
process.env.TZ = "Asia/Shanghai"
await initGlobals()
await renderinit()
await Task()
await database()
global.chalk = chalk
global.logger = logger
client
ws
logger.info('初始化:正在创建频道树')
global.saveGuildsTree = []
await loadGuildTree(config.loadGuildTree)
}
19 changes: 10 additions & 9 deletions lib/config/logger.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import log4js from "log4js";
import { _path } from "../../lib/global/global.js";
import { config } from "../config/config.js";
import log4js from "log4js"
import { _path } from "../../lib/global/global.js"
import { config } from "../config/config.js"

const logger = log4js.configure({
appenders: {
console: {
Expand Down Expand Up @@ -31,11 +32,11 @@ const logger = log4js.configure({
level: "error"
}
},
}).getLogger();
}).getLogger()
export function setDevLog() {
logger.setParseCallStackFunction((error, linesToSkip) => {
const stacklines = error.stack?.split("\n").splice(4);
const lineMatch = /at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/.exec(stacklines[0]);
const stacklines = error.stack?.split("\n").splice(4)
const lineMatch = /at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/.exec(stacklines[0])
/* istanbul ignore else: failsafe */
if (lineMatch && lineMatch.length === 6)
return {
Expand All @@ -44,7 +45,7 @@ export function setDevLog() {
columnNumber: 35,
callStack: 'CallStackInformation',
fileName: ` [${lineMatch[2].replace(`${_path}/`, "")}:${lineMatch[3]}:${lineMatch[4]}]`
};
});
}
})
}
export default logger;
export default logger
17 changes: 9 additions & 8 deletions lib/config/redis.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { redis } from "../../lib/global/global.js";
import logger from "../../lib/config/logger.js";
import { redis } from "../../lib/global/global.js"
import logger from "../../lib/config/logger.js"

async function database() {
logger.info('初始化:正在连接数据库');
logger.info('初始化:正在连接数据库')
await redis.connect().then(() => {
logger.info('初始化:redis数据库连接成功');
logger.info('初始化:redis数据库连接成功')
}).catch(err => {
logger.error(`初始化:redis数据库连接失败,正在退出程序\n${err}`);
process.exit();
});
logger.error(`初始化:redis数据库连接失败,正在退出程序\n${err}`)
process.exit()
})
}
export default database;
export default database
Loading

0 comments on commit 9483e17

Please sign in to comment.