UNPKG

telegraf-tools

Version:
64 lines (53 loc) 2.19 kB
const fs = require('fs'); const logDirectory = `${process.mainModule.path}/logs`; if (!fs.existsSync(logDirectory)) fs.mkdirSync(logDirectory); const logFile = fs.createWriteStream(`${logDirectory}/loadLib.log`, { flags: 'a' }); const log = (level, message) => { const timestamp = new Date().toISOString(), log = `\x1b[2m${timestamp}\x1b[0m \x1b[90m[\x1b[0m${level}\x1b[90m] ${message}`; logFile.write(`${removeAnsi(log)}\n`); console.log(log) }; const info = (message) => log('\x1b[31mINFO', message); const error = (message) => log('\x1b[31mERROR', message); const removeAnsi = (text) => text.replace(/[\u001b][[()#;?]*([0-9]{1,2}(;[0-9]{1,2})*)?[0-9A-PR-T]*[@-~]/g, ''); module.exports = (bot) => { const loadlib = function(filename, defaultPath){ info(`\x1b[2mLoading library: ${filename}\x1b[0m...`); const result = require(`${process.cwd()}${defaultPath ?? ''}/${filename}.js`)(bot); if (result) bot.context[filename] = result; info(`\x1b[32mLibrary \x1b[90m[\x1b[36m\x1b[1m${filename}\x1b[0m\x1b[90m]\x1b[32m loaded successfully.\x1b[0m`); }; const checkFileExists = (filePath) => { return fs.existsSync(`${process.cwd()}/${filePath}`); }; const renameLib = (oldName, newName) => { bot.context[newName] = bot.context[oldName]; delete bot.context[oldName]; info(`Library \x1b[36m\x1b[1m${oldName}\x1b[0m renamed to \x1b[36m\x1b[1m${newName}\x1b[0m`); }; const multipleLoader = (libs, defaultPath) => { libs.forEach(lib => { loadlib(lib, defaultPath); }); }; const folderLoader = (folderPath) => { const files = fs.readdirSync(`${process.cwd()}/${folderPath}`); files.forEach(file => { const parts = file.split('.'); const extension = parts[parts.length - 1]; if (extension === 'js') { const filename = parts.slice(0, parts.length - 1).join('.'); loadlib(filename, `/${folderPath}`); } }); }; return { loadlib, checkFileExists, renameLib, multipleLoader, folderLoader, createJsonBase: () => loadlib("jsonbase", `/node_modules/telegraf-tools/src`), } };