From b77e949662320f4b8d528c3964d27ba846752b81 Mon Sep 17 00:00:00 2001 From: alanfilho184 Date: Mon, 12 Aug 2024 02:03:02 -0300 Subject: [PATCH] v4.13.0 - Sharding --- .prettierrc.json | 10 + index.js | 13 +- package.json | 2 +- src/client.js | 384 ++++++++++++++---------- src/commands/gerais/botinfo.js | 146 +++++---- src/commands/gerais/sugestao.js | 99 ++++-- src/commands/owner/eval.js | 4 +- src/commands/owner/responder.js | 67 +++-- src/events/bot/activity.js | 4 + src/events/discord/interactionCreate.js | 66 ++-- src/events/discord/ready.js | 25 +- src/modules/websocket/server.js | 4 +- src/resources/scripts/botStatus.js | 182 ++++++----- src/resources/scripts/logs.js | 306 ++++++++++++------- 14 files changed, 805 insertions(+), 507 deletions(-) create mode 100644 .prettierrc.json diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..ea2512a --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,10 @@ +{ + "printWidth": 120, + "tabWidth": 4, + "useTabs": false, + "semi": true, + "singleQuote": true, + "trailingComma": "none", + "bracketSpacing": true, + "arrowParens": "avoid" + } \ No newline at end of file diff --git a/index.js b/index.js index 74f06a1..576ff8c 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,14 @@ require("colors") require("./src/resources/scripts/logs") require('dotenv').config() +const { ShardingManager } = require('discord.js') -const Client = require('./src/client') -const client = new Client() -client.login() \ No newline at end of file +// const Client = require('./src/client') +// const client = new Client() +// client.login() + +const manager = new ShardingManager('./src/client.js', { token: process.env.TOKEN, totalShards: 2, mode: 'worker' }); + +manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`)); + +manager.spawn(); \ No newline at end of file diff --git a/package.json b/package.json index 1520de9..663886e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "kami", - "version": "4.12.4", + "version": "4.13.0", "description": "Um BOT para Discord com foco em ajudar em mesas de RPG online, tendo suas principais funções criar fichas e rolar dados.", "main": "index.js", "scripts": { diff --git a/src/client.js b/src/client.js index 9927513..9f0c9ef 100644 --- a/src/client.js +++ b/src/client.js @@ -1,270 +1,346 @@ const Discord = require('discord.js'); -const glob = require("fast-glob") -const logs = require("./resources/scripts/logs.js") -const toMs = require("milliseconds-parser")() -const fs = require("fs"); -const time = require("luxon").DateTime - -var errorStack = 0 - -module.exports = class MenuClient extends Discord.Client { - +const glob = require('fast-glob'); +const logs = require('./resources/scripts/logs.js'); +const toMs = require('milliseconds-parser')(); +const fs = require('fs'); +const time = require('luxon').DateTime; + +var errorStack = 0; +class MenuClient extends Discord.Client { constructor() { super({ disableMentions: 'everyone', intents: 13825, - restTimeOffset: 0, - }) - - this.Discord = Discord - - this.setLog() - this.setUtils() - this.setDB() - this.loadCommands() - this.loadComponents() - this.loadEvents() - this.setCache() - this.setTl() - this.postInfo() - this.setWebSocket() - this.startup() + restTimeOffset: 0 + }); + + this.Discord = Discord; + + super.login(process.env.TOKEN); + + this.setLog(); + this.setUtils(); + this.setDB(); + this.loadCommands(); + this.loadComponents(); + this.loadEvents(); + this.setCache(); + this.setTl(); + this.postInfo(); + this.setWebSocket(); + this.startup(); } loadCommands() { - this.commands = new Discord.Collection() + this.commands = new Discord.Collection(); try { - var commands = glob.sync(["**/commands/**/*.js", "!node_modules", "!events", "!components"]) + var commands = glob.sync(['**/commands/**/*.js', '!node_modules', '!events', '!components']); commands.forEach(cmd => { - if (cmd.startsWith("src/commands/")) { - var cmdFunction = require("../" + cmd) + if (cmd.startsWith('src/commands/')) { + var cmdFunction = require('../' + cmd); - var info = new cmdFunction() + var info = new cmdFunction(); - if (info.name != "coletar" && info.ownerOnly == false) { - this.commands.set(info.nameEn, info) - } - else if (info.name != "coletar" && info.ownerOnly == true) { - this.commands.set(info.name, info) + if (info.name != 'coletar' && info.ownerOnly == false) { + this.commands.set(info.nameEn, info); + } else if (info.name != 'coletar' && info.ownerOnly == true) { + this.commands.set(info.name, info); } } - }) - } - catch (err) { - logs.log.error(err) + }); + } catch (err) { + logs.log.error(err); } - logs.log.start("Comandos") + logs.log.start('Comandos'); } loadComponents() { - this.components = new Discord.Collection() + this.components = new Discord.Collection(); try { - var components = glob.sync(["**/components/**/*.js", "!node_modules", "!events", "!commands"]) + var components = glob.sync(['**/components/**/*.js', '!node_modules', '!events', '!commands']); components.forEach(comp => { - if (comp.startsWith("src/components/")) { - var compFunction = require("../" + comp) + if (comp.startsWith('src/components/')) { + var compFunction = require('../' + comp); - var info = new compFunction() + var info = new compFunction(); - this.components.set(info.name, info) + this.components.set(info.name, info); } - }) - } - catch (err) { - logs.log.error(err) + }); + } catch (err) { + logs.log.error(err); } - logs.log.start("Componentes") + logs.log.start('Componentes'); } loadEvents() { - var events = glob.sync(["**/events/**/*.js", "!node_modules", "!commands"]) + var events = glob.sync(['**/events/**/*.js', '!node_modules', '!commands']); events.forEach(event => { - let eventFunction = require("../" + event) - - this.on(eventFunction.name, (...args) => { eventFunction.execute(this, ...args) }) - if (eventFunction.name == "interactionCreate") { - this.on("varUpdate", (...args) => { eventFunction.disableCmd(this, ...args) }) + let eventFunction = require('../' + event); + + this.on(eventFunction.name, (...args) => { + eventFunction.execute(this, ...args); + }); + if (eventFunction.name == 'interactionCreate') { + // this.on('varUpdate', (...args) => { + // eventFunction.disableCmd(this, ...args); + // }); + } else if (eventFunction.name == 'componentHandler') { + this.on('passInt', (...args) => { + eventFunction.passInt(this, ...args); + }); } - else if (eventFunction.name == "componentHandler") { - this.on("passInt", (...args) => { eventFunction.passInt(this, ...args) }) - } - }) + }); - logs.log.start("Eventos") + logs.log.start('Eventos'); } setUtils() { - const Utils = require('./modules/utils.js') - const utils = new Utils({ client: this }) - this.utils = utils - logs.log.start("Utils") + const Utils = require('./modules/utils.js'); + const utils = new Utils({ client: this }); + this.utils = utils; + logs.log.start('Utils'); } setDB() { const { Sequelize } = require('sequelize'); function conStr(DATABASE_URL) { - const dbURI = DATABASE_URL.replace("postgres://", ""); + const dbURI = DATABASE_URL.replace('postgres://', ''); const conStr = { - database: dbURI.split("/")[1], - username: dbURI.split(/@(?!.*@)/g)[0].split(":")[0], - password: dbURI.split(/@(?!.*@)/g)[0].split(":")[1], - host: dbURI.split(/@(?!.*@)/g)[1].split(":")[0], - port: dbURI.split(/@(?!.*@)/g)[1].split(":")[1], + database: dbURI.split('/')[1], + username: dbURI.split(/@(?!.*@)/g)[0].split(':')[0], + password: dbURI.split(/@(?!.*@)/g)[0].split(':')[1], + host: dbURI.split(/@(?!.*@)/g)[1].split(':')[0], + port: dbURI.split(/@(?!.*@)/g)[1].split(':')[1], logging: false, - dialect: "postgres", - } + dialect: 'postgres' + }; - if (process.env.NODE_ENV == "production") { - conStr["dialectOptions"] = { + if (process.env.NODE_ENV == 'production') { + conStr['dialectOptions'] = { ssl: { require: true, rejectUnauthorized: false } - } + }; } - return conStr + return conStr; } - let conObj = conStr(process.env.DB_URI) + let conObj = conStr(process.env.DB_URI); - if (process.env.DEPLOY == "production") { - conObj["dialectOptions"] = { + if (process.env.DEPLOY == 'production') { + conObj['dialectOptions'] = { ssl: { require: false, rejectUnauthorized: false } - } + }; } const db = new Sequelize(conObj); - this.db = db - logs.log.start("Database") - + this.db = db; + logs.log.start('Database'); } setLog() { - this.log = logs.log + this.log = logs.log; + + const logWebhook = new this.Discord.WebhookClient({ + id: process.env.WEBHOOK_ID, + token: process.env.WEBHOOK_TOKEN + }); + this.log.webhook = logWebhook; + + const logWebhook2 = new this.Discord.WebhookClient({ + id: process.env.LOG_WEBHOOK_ID, + token: process.env.LOG_WEBHOOK_TOKEN + }); - const logWebhook = new this.Discord.WebhookClient({ id: process.env.WEBHOOK_ID, token: process.env.WEBHOOK_TOKEN }); - this.log.webhook = logWebhook + this.log.logWebhook = logWebhook2; - process.on("uncaughtException", (err) => { + process.on('uncaughtException', err => { if (err == "TypeError: Cannot read property 'send' of null") { - process.exit(1) + process.exit(1); + } else if (err != 'DiscordAPIError: Unknown interaction') { + this.emit('err', err, true); } + logs.log.error(err, true); - logs.log.error(err, true) - - errorStack++ + errorStack++; if (errorStack >= 15) { - logs.log.error("Ocorreram 15 erros consecutivos, reiniciando o bot...") - process.exit(1) + logs.log.error('Ocorreram 15 erros consecutivos, reiniciando o bot...'); + process.exit(1); } - }) + }); - process.on("unhandledRejection", (err) => { + process.on('unhandledRejection', err => { if (err == "TypeError: Cannot read property 'send' of null") { - process.exit(1) + process.exit(1); + } else if (err != 'DiscordAPIError: Unknown interaction') { + this.emit('err', err, true); } + logs.log.error(err, true); - logs.log.error(err, true) - - errorStack++ + errorStack++; if (errorStack >= 15) { - logs.log.error("Ocorreram 15 erros consecutivos, reiniciando o bot...") - process.exit(1) + logs.log.error('Ocorreram 15 erros consecutivos, reiniciando o bot...'); + process.exit(1); } - }) - - process.on("SIGTERM", (signal) => { - fs.writeFileSync("log.txt", logs.logTxt()) - - this.channels.fetch(process.env.LOG_CHANNEL).then(async (c) => { - await c.send({ content: `Log completo - ${time.now({ zone: "America/Fortaleza" }).toFormat("dd/MM/y | HH:mm:ss ")}`, files: ["log.txt"] }) - process.exit(0) - }) - - }) + }); + + process.on('SIGTERM', signal => { + fs.writeFileSync('log.txt', logs.logTxt()); + + this.shard.broadcastEval( + async (c, ctx) => { + await c.log.logWebhook.send({ + content: `Shard ${c.shard.ids[0]} `+ JSON.parse(ctx).message, + files: ['log.txt'] + }); + + process.exit(0); + }, + { + context: JSON.stringify({ + message: `Log completo - ${time + .now({ zone: 'America/Fortaleza' }) + .toFormat('dd/MM/y | HH:mm:ss ')}` + }) + } + ); + }); } setCache() { - const cacheMaker = require("./resources/config/cache") - const cache = new cacheMaker(this) + const cacheMaker = require('./resources/config/cache'); + const cache = new cacheMaker(this); - const whitelistMaker = require("./resources/config/whitelist") - const whitelist = new whitelistMaker(this) + const whitelistMaker = require('./resources/config/whitelist'); + const whitelist = new whitelistMaker(this); - this.cache = cache - this.whitelist = whitelist + this.cache = cache; + this.whitelist = whitelist; } setTl() { this.resources = { - "pt-": require("./resources/texts/pt"), - "en-": require("./resources/texts/en"), - assets: require("./resources/assets/assets"), - msgs: require("./resources/messages/msgs.json") - } + 'pt-': require('./resources/texts/pt'), + 'en-': require('./resources/texts/en'), + assets: require('./resources/assets/assets'), + msgs: require('./resources/messages/msgs.json') + }; - this.resources.footer = this.resources["pt-"].footer + this.resources.footer = this.resources['pt-'].footer; - const ml = require("./resources/messages/msgHandler") - const tl = new ml(this) + const ml = require('./resources/messages/msgHandler'); + const tl = new ml(this); - this.tl = tl.tl - logs.log.start("Multi-Idioma") + this.tl = tl.tl; + logs.log.start('Multi-Idioma'); } startup() { - const botStatus = require("./resources/scripts/botStatus") - - const BS = new botStatus({ client: this }) - - this.botStatus = BS - - setTimeout(() => BS.updateBS(this), 10000) - setInterval(() => { - BS.updateBS(this) - }, toMs.parse("1 minuto")) + if (this.shard.ids[0] == 0) { + const botStatus = require('./resources/scripts/botStatus'); + + const BS = new botStatus({ client: this }); + + this.botStatus = BS; + try { + setTimeout(() => { + BS.updateBS(this); + + try { + this.shard + .broadcastEval(async c => { + const channel = await c.channels.cache.get('784035696414425108'); + + if (channel) { + const message = await channel.messages.fetch('784039521645101066'); + if (message) { + message.content = message.content + .split('<@720128587289722902> <@716053210179043409>') + .join(''); + message.content = message.content.split('```js').join(''); + message.content = message.content.split('```').join(''); + var msgConfig = JSON.parse(message.content); + c.emit('varUpdate', msgConfig); + + return [c.shard.ids[0], message.content]; + } else { + return null; + } + } else { + return null; + } + }) + .then(results => { + results.forEach(result => { + if (Array.isArray(result)) { + this.shard.broadcastEval( + (c, result) => { + result = JSON.parse(result); + if (c.shard.ids[0] != result[0]) { + c.emit('varUpdate', result[1]); + } + }, + { context: JSON.stringify(result) } + ); + } + }); + }) + .catch(console.error); + } catch (err) {} + }, 10000); + setInterval(() => { + BS.updateBS(this); + }, toMs.parse('1 minuto')); + } catch (err) { + logs.log.error(err); + } + } - logs.log.start("Recursos gerais") + logs.log.start('Recursos gerais'); } postInfo() { - if (process.env.DEPLOY == "production") { - const postApi = require("./modules/postinfo.js") - const API = new postApi(this) + if (process.env.DEPLOY == 'production' && this.shard.ids[0] == 0) { + const postApi = require('./modules/postinfo.js'); + const API = new postApi(this); setTimeout(() => { - API.postBotinfo() - API.postCommands() - }, toMs.parse("30 segundos")) + API.postBotinfo(); + API.postCommands(); + }, toMs.parse('30 segundos')); setInterval(() => { - API.postBotinfo() - API.postCommands() - }, toMs.parse("30 minutos")) + API.postBotinfo(); + API.postCommands(); + }, toMs.parse('30 minutos')); } } setWebSocket() { - const ws = require("./modules/websocket/server") - new ws(this) + const ws = require('./modules/websocket/server'); + new ws(this); } async login(token = process.env.TOKEN) { - super.login(token) + super.login(token); } } + +new MenuClient(); diff --git a/src/commands/gerais/botinfo.js b/src/commands/gerais/botinfo.js index 408053c..f679110 100644 --- a/src/commands/gerais/botinfo.js +++ b/src/commands/gerais/botinfo.js @@ -1,58 +1,63 @@ -const time = require("luxon").DateTime -const ac = require("ascii-table") -const pidusage = require("pidusage") -const os = require("os-utils") +const time = require('luxon').DateTime; +const ac = require('ascii-table'); +const pidusage = require('pidusage'); +const os = require('os-utils'); module.exports = class botinfo { constructor() { return { ownerOnly: false, - name: "botinfo", - nameEn: "botinfo", - fName: "Botinfo", - fNameEn: "Botinfo", + name: 'botinfo', + nameEn: 'botinfo', + fName: 'Botinfo', + fNameEn: 'Botinfo', desc: 'Mostra informações técnicas e links sobre o BOT.', descEn: 'Show technical information and links related with the BOT.', args: [], options: [], type: 1, helpPt: { - title: "<:outrosAjuda:766790214110019586> " + "/" + "botinfo", desc: `Este comando serve para ver informações do bot, como links relacionados ao bot, uso de recursos e quantidade de usuários + title: '<:outrosAjuda:766790214110019586> ' + '/' + 'botinfo', + desc: `Este comando serve para ver informações do bot, como links relacionados ao bot, uso de recursos e quantidade de usuários - Ex: **${"/"}botinfo**` + Ex: **${'/'}botinfo**` }, helpEn: { - title: "<:outrosAjuda:766790214110019586> " + "/" + "botinfo", desc: `This command is used to see bot information, such as links related to the bot, resource usage and amount of users + title: '<:outrosAjuda:766790214110019586> ' + '/' + 'botinfo', + desc: `This command is used to see bot information, such as links related to the bot, resource usage and amount of users - Ex: **${"/"}botinfo**` + Ex: **${'/'}botinfo**` }, run: this.execute - } + }; } async execute(client, int) { - const secret = client.utils.secret(client.cache.get(int.user.id), "geral") - await int.deferReply({ephemeral: secret}) - var count = 0 + const secret = client.utils.secret(client.cache.get(int.user.id), 'geral'); + await int.deferReply({ ephemeral: secret }); - client.guilds.cache.map(guild => { count += guild.memberCount }) + const promises = [ + client.shard.fetchClientValues('guilds.cache.size'), + client.shard.broadcastEval(c => c.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)) + ]; - const table = new ac("Kami Info") + const results = await Promise.all(promises); - var dbPing = time.now().toMillis() - await client.db.query("select 1") - .then(() => { - dbPing = time.now().toMillis() - dbPing - }) + const table = new ac('Kami Info'); - const owner = await client.users.fetch(process.env.OWNER) + var dbPing = time.now().toMillis(); + await client.db.query('select 1').then(() => { + dbPing = time.now().toMillis() - dbPing; + }); - var stats = await pidusage(process.pid) + const owner = await client.users.fetch(process.env.OWNER); - const ram = stats.memory / 1024 / 1024 + var stats = await pidusage(process.pid); - const commands = client.cache.getCount() + const ram = stats.memory / 1024 / 1024; + + const commands = client.cache.getCount(); var uptime = process.uptime(); var days = Math.floor((uptime % 31536000) / 86400); @@ -60,45 +65,72 @@ module.exports = class botinfo { var minutes = Math.floor((uptime % 3600) / 60); var seconds = Math.round(uptime % 60); var botuptime = - (days > 0 ? days == 1 ? days + " dia " : days + " dias " : "") - + (hours > 0 ? hours == 1 ? hours + " hora " : hours + " horas " : "") - + (minutes > 0 ? minutes == 1 ? minutes + " minuto " : minutes + " minutos " : "") - + (seconds > 0 ? seconds == 1 ? seconds + " segundo " : seconds + " segundos " : "") + (days > 0 ? (days == 1 ? days + ' dia ' : days + ' dias ') : '') + + (hours > 0 ? (hours == 1 ? hours + ' hora ' : hours + ' horas ') : '') + + (minutes > 0 ? (minutes == 1 ? minutes + ' minuto ' : minutes + ' minutos ') : '') + + (seconds > 0 ? (seconds == 1 ? seconds + ' segundo ' : seconds + ' segundos ') : ''); table - .addRow(`${client.tl({ local: int.lang + "botI-fStatusT1" })}`, `${stats.cpu.toFixed(2)} %`) - .addRow(`${client.tl({ local: int.lang + "botI-fStatusT2" })}`, `${ram.toFixed(2)} MB`) - .addRow(`${client.tl({ local: int.lang + "botI-fStatusRT" })}`, `${(os.totalmem() / 1024 - os.freemem() / 1024).toFixed(1)} GB / ${(os.totalmem() / 1024).toFixed(1)} GB`) - .addRow("Ping", `BOT: ${Math.round(int.ping)} ms - ` + `API: ${Math.round(client.ws.ping)} ms - ` + `DB: ${Math.round(dbPing)} ms`) - .addRow(`${client.tl({ local: int.lang + "botI-fStatusT4" })}`, `${client.guilds.cache.size}`) - .addRow(`${client.tl({ local: int.lang + "botI-fStatusT5" })}`, `${count}`) - .addRow(`${client.tl({ local: int.lang + "botI-fCmd" })}`, `${client.tl({ local: int.lang + "botI-cmdAI" })} ${commands.today} - Total: ${commands.total}`) - .addRow(`${client.tl({ local: int.lang + "botI-fBt" })}`, `${client.tl({ local: int.lang + "botI-cmdAI" })} ${commands.buttonsToday} - Total: ${commands.buttonsTotal}`) - .addRow(`${client.tl({ local: int.lang + "botI-uptime" })}`, botuptime) - - - const botIEmbed = new client.Discord.EmbedBuilder() - botIEmbed.setTitle(client.tl({ local: int.lang + "botI-fAu" }) + owner.tag) - botIEmbed.setColor(parseInt(parseInt(process.env.EMBED_COLOR))) - botIEmbed.setDescription("```\n" + table.toString() + "```") - botIEmbed.setTimestamp(Date.now()) - botIEmbed.setFooter({text: client.resources.footer(), iconURL: client.user.displayAvatarURL()}) + .addRow(`${client.tl({ local: int.lang + 'botI-fStatusT1' })}`, `${stats.cpu.toFixed(2)} %`) + .addRow(`${client.tl({ local: int.lang + 'botI-fStatusT2' })}`, `${ram.toFixed(2)} MB`) + .addRow( + `${client.tl({ local: int.lang + 'botI-fStatusRT' })}`, + `${(os.totalmem() / 1024 - os.freemem() / 1024).toFixed(1)} GB / ${(os.totalmem() / 1024).toFixed( + 1 + )} GB` + ) + .addRow( + 'Ping', + `BOT: ${Math.round(int.ping)} ms - ` + + `API: ${Math.round(client.ws.ping)} ms - ` + + `DB: ${Math.round(dbPing)} ms` + ) + .addRow( + `${client.tl({ local: int.lang + 'botI-fStatusT4' })}`, + `${results[0].reduce((acc, guildCount) => acc + guildCount, 0)}` + ) + .addRow( + `${client.tl({ local: int.lang + 'botI-fStatusT5' })}`, + `${results[1].reduce((acc, memberCount) => acc + memberCount, 0)}` + ) + .addRow( + `${client.tl({ local: int.lang + 'botI-fCmd' })}`, + `${client.tl({ local: int.lang + 'botI-cmdAI' })} ${commands.today} - Total: ${commands.total}` + ) + .addRow( + `${client.tl({ local: int.lang + 'botI-fBt' })}`, + `${client.tl({ local: int.lang + 'botI-cmdAI' })} ${commands.buttonsToday} - Total: ${ + commands.buttonsTotal + }` + ) + .addRow(`${client.tl({ local: int.lang + 'botI-uptime' })}`, botuptime); + + const botIEmbed = new client.Discord.EmbedBuilder(); + botIEmbed.setTitle(client.tl({ local: int.lang + 'botI-fAu' }) + owner.tag); + botIEmbed.setColor(parseInt(parseInt(process.env.EMBED_COLOR))); + botIEmbed.setDescription('```\n' + table.toString() + '```'); + botIEmbed.setTimestamp(Date.now()); + botIEmbed.setFooter({ text: client.resources.footer(), iconURL: client.user.displayAvatarURL() }); const bSup = new client.Discord.ButtonBuilder() .setStyle(5) - .setLabel(client.tl({ local: int.lang + "botI-f2V" })) - .setURL("https://kamiapp.com.br/suporte") + .setLabel(client.tl({ local: int.lang + 'botI-f2V' })) + .setURL('https://kamiapp.com.br/suporte'); const bVote = new client.Discord.ButtonBuilder() .setStyle(5) - .setLabel(client.tl({ local: int.lang + "botI-f3V" })) - .setURL("https://botsparadiscord.com.br/bots/716053210179043409") + .setLabel(client.tl({ local: int.lang + 'botI-f3V' })) + .setURL('https://botsparadiscord.com.br/bots/716053210179043409'); const bInv = new client.Discord.ButtonBuilder() .setStyle(5) - .setLabel(client.tl({ local: int.lang + "botI-f4V" })) - .setURL(`https://kamiapp.com.br/convite`) - - int.editReply({ content: null, embeds: [botIEmbed], components: [{ type: 1, components: [bSup, bVote, bInv] }] }) + .setLabel(client.tl({ local: int.lang + 'botI-f4V' })) + .setURL(`https://kamiapp.com.br/convite`); + + int.editReply({ + content: null, + embeds: [botIEmbed], + components: [{ type: 1, components: [bSup, bVote, bInv] }] + }); } -} \ No newline at end of file +}; diff --git a/src/commands/gerais/sugestao.js b/src/commands/gerais/sugestao.js index eada198..445f84f 100644 --- a/src/commands/gerais/sugestao.js +++ b/src/commands/gerais/sugestao.js @@ -1,64 +1,97 @@ -const time = require("luxon").DateTime +const time = require('luxon').DateTime; module.exports = class sugestao { constructor() { return { ownerOnly: false, - name: "suporte", - nameEn: "support", - fName: "Suporte", - fNameEn: "Support", + name: 'suporte', + nameEn: 'support', + fName: 'Suporte', + fNameEn: 'Support', desc: 'Envia uma mensagem para a equipe do BOT.', - descEn: 'Sends a message to the BOT\'s team.', + descEn: "Sends a message to the BOT's team.", args: [ - { name: "mensagem", desc: "A mensagem que deja enviar para a equipe.", type: "STRING", required: true, autocomplete: false } + { + name: 'mensagem', + desc: 'A mensagem que deja enviar para a equipe.', + type: 'STRING', + required: true, + autocomplete: false + } ], argsEn: [ - { name: "message", desc: "The message you want to send to the team.", type: "STRING", required: true, autocomplete: false } + { + name: 'message', + desc: 'The message you want to send to the team.', + type: 'STRING', + required: true, + autocomplete: false + } ], options: [], type: 1, helpPt: { - title: "<:outrosAjuda:766790214110019586> " + "/" + "suporte", desc: ` + title: '<:outrosAjuda:766790214110019586> ' + '/' + 'suporte', + desc: ` Esse comando serve para mandar um report de bug ou sugestão para o meu criador, também serve para tirar duvidas, mas, tenha paciencia, não tem uma equipe por trás de mim é só uma pessoa para fazer tudo. Para usar o comando basta seguir o exemplo: _Formato do comando:_ - **${"/"}suporte ** - Ex: **${"/"}suporte Oi, corrige todos os problemas do bot (são muitos)** + **${'/'}suporte ** + Ex: **${'/'}suporte Oi, corrige todos os problemas do bot (são muitos)** - Claro, se você disser o que é o problema fica mais fácil de corrigir.`}, + Claro, se você disser o que é o problema fica mais fácil de corrigir.` + }, helpEn: { - title: "<:outrosAjuda:766790214110019586> " + "/" + "suporte", desc: `This command is used to send a bug report or suggestion to my creator, it's also used to remove questions, but, be patient, there's not a team behind me is just one person to do everything. To use the command just follow the example: + title: '<:outrosAjuda:766790214110019586> ' + '/' + 'suporte', + desc: `This command is used to send a bug report or suggestion to my creator, it's also used to remove questions, but, be patient, there's not a team behind me is just one person to do everything. To use the command just follow the example: _Format of the command:_ - **${"/"}suporte ** - Ex: **${"/"}suporte Hi, fix all the bot problems (there are many)** + **${'/'}suporte ** + Ex: **${'/'}suporte Hi, fix all the bot problems (there are many)** - Of course, if you say what the problem is it becomes easier to fix.`}, + Of course, if you say what the problem is it becomes easier to fix.` + }, run: this.execute - } + }; } execute(client, int) { - int.deferReply({ ephemeral: true }) - .then(() => { - const args = client.utils.args(int) - const mensagem = args.get("message") + int.deferReply({ ephemeral: true }).then(() => { + const args = client.utils.args(int); + const mensagem = args.get('message'); - const embed = new client.Discord.EmbedBuilder() - .setAuthor({ name: `${int.user.tag} | ${int.user.id}`, iconURL: int.user.displayAvatarURL() }) - .setTitle("Mensagem recebida") - .setDescription(mensagem) - .setColor(parseInt(process.env.EMBED_COLOR)) - .setFooter({ text: "Mensagem recebida em: " + time.now({ zone: "America/Fortaleza" }).toFormat("dd/MM/y | HH:mm:ss ") + "(GMT -3)" }) + const embed = new client.Discord.EmbedBuilder() + .setAuthor({ name: `${int.user.tag} | ${int.user.id}`, iconURL: int.user.displayAvatarURL() }) + .setTitle('Mensagem recebida') + .setDescription(mensagem) + .setColor(parseInt(process.env.EMBED_COLOR)) + .setFooter({ + text: + 'Mensagem recebida em: ' + + time.now({ zone: 'America/Fortaleza' }).toFormat('dd/MM/y | HH:mm:ss ') + + '(GMT -3)' + }); - client.log.embed(embed, true, "sugestao") - .then((msg) => msg.pin()) + client.log.embed(embed, true, 'sugestao').then(msg => { + client.shard.broadcastEval((c, ctx) => { + const { msg } = JSON.parse(ctx); - int.editReply({ content: client.tl({ local: int.lang + "sugestao-mEnv" }) }) + const channel = c.channels.cache.get(process.env.LOG_CHANNEL); - return - }) + if (channel) { + const message = channel.messages.cache.get(msg.id); + + if (message) { + message.pin(); + } + } + }, { context: JSON.stringify({ msg: msg }) }); + }); + + int.editReply({ content: client.tl({ local: int.lang + 'sugestao-mEnv' }) }); + + return; + }); } -} +}; diff --git a/src/commands/owner/eval.js b/src/commands/owner/eval.js index 5a04b03..6548257 100644 --- a/src/commands/owner/eval.js +++ b/src/commands/owner/eval.js @@ -37,8 +37,8 @@ module.exports = class evaluate { var code = typeof r == "string" ? r : inspect(r, { depth: 99 }) var result = `\`\`\`js\n${String(code).slice(0, 4000) + (code.length >= 4000 ? '...' : '')}\n\`\`\`` - var settings = client.utils.objToMap(process.env) - settings.forEach((s) => { result = client.utils.replaceAll(result, s, "*") }) + // var settings = client.utils.objToMap(process.env) + // settings.forEach((s) => { result = client.utils.replaceAll(result, s, "*") }) evalEmbed .setDescription(result) diff --git a/src/commands/owner/responder.js b/src/commands/owner/responder.js index e1784dc..793fc50 100644 --- a/src/commands/owner/responder.js +++ b/src/commands/owner/responder.js @@ -1,35 +1,64 @@ - module.exports = class responder { constructor() { return { ownerOnly: true, - name: "responder", - fName: "Responder", + name: 'responder', + fName: 'Responder', desc: 'Envia uma mensagem a um usuário.', args: [ - { name: "id", desc: "ID do usuário.", type: "STRING", required: true, autocomplete: false }, - { name: "mensagem", desc: "Mensagem para enviar.", type: "STRING", required: true, autocomplete: false }, + { name: 'id', desc: 'ID do usuário.', type: 'STRING', required: true, autocomplete: false }, + { name: 'mensagem', desc: 'Mensagem para enviar.', type: 'STRING', required: true, autocomplete: false } ], options: [], type: 1, run: this.execute - } + }; } execute(client, int) { - int.deferReply({ ephemeral: true }) - .then(() => { - const args = client.utils.args(int) - - const respId = args.get("id") - const respMsg = args.get("mensagem") - - client.users.fetch(respId).then(user => { - user.send(respMsg) - .then(() => { - int.editReply(`Pronto, mensagem enviada!`) - }) + int.deferReply({ ephemeral: true }).then(() => { + const args = client.utils.args(int); + + const respId = args.get('id'); + const respMsg = args.get('mensagem'); + + client.shard.broadcastEval( + (c, ctx) => { + const { respId } = JSON.parse(ctx); + + if (c.users.cache.has(respId)) { + return c.shard.ids[0]; + } else { + return false; + } + }, + { context: JSON.stringify({ respId }) } + ) + .then(res => { + const shard = res.find(r => r !== false); + + if (shard === undefined) { + return int.editReply({ content: 'Usuário não encontrado.', ephemeral: true }); + } + + client.shard.broadcastEval( + (c, ctx) => { + const { respId, respMsg } = JSON.parse(ctx); + + const user = c.users.cache.get(respId); + user.send(respMsg); + }, + { context: JSON.stringify({ respId, respMsg }), shard: shard } + ) + .then(() => { + int.editReply({ content: 'Mensagem enviada com sucesso.', ephemeral: true }); }) + .catch(err => { + client.log.error(err, true); + int.editReply({ content: 'Erro ao enviar a mensagem.', ephemeral: true }); + }); }) + + }); } -} +}; diff --git a/src/events/bot/activity.js b/src/events/bot/activity.js index 80ca056..11ef693 100644 --- a/src/events/bot/activity.js +++ b/src/events/bot/activity.js @@ -30,6 +30,10 @@ module.exports = { } client.on("varUpdate", info => { + if (typeof info == "string") { + info = JSON.parse(info) + } + if (info.presence.statusMsg == "actsPadrao") { acts = actsPadrao } diff --git a/src/events/discord/interactionCreate.js b/src/events/discord/interactionCreate.js index 7061c1e..5f7e759 100644 --- a/src/events/discord/interactionCreate.js +++ b/src/events/discord/interactionCreate.js @@ -1,9 +1,9 @@ const time = require("luxon").DateTime; -const cmdConfig = new Object({ - disableCmds: new Array(), - reason: new Object() -}) +// const cmdConfig = new Object({ +// disableCmds: new Array(), +// reason: new Object() +// }) module.exports = { name: "interactionCreate", @@ -26,32 +26,32 @@ module.exports = { return int.reply({ content: client.tl({ local: int.lang + "onMsg-cmdBarrado" }), ephemeral: true }) } else { - if (cmdConfig.disableCmds.includes(cmd.name)) { - const disableEmbed = new client.Discord.EmbedBuilder() - .setTitle(client.tl({ local: int.lang + "onMsg-cmdDsbTi" })) - .setColor(parseInt(process.env.EMBED_COLOR)) - .setDescription(client.tl({ local: int.lang + "onMsg-cmdDsbDesc", cmd: cmdConfig.reason[cmd.name][int.lang] })) - .setFooter(client.resources[int.lang.replace("-", "")].footer(), client.user.displayAvatarURL()) - .setTimestamp() - return int.reply({ embeds: [disableEmbed], ephemeral: true }) - } - else { + // if (cmdConfig.disableCmds.includes(cmd.name)) { + // const disableEmbed = new client.Discord.EmbedBuilder() + // .setTitle(client.tl({ local: int.lang + "onMsg-cmdDsbTi" })) + // .setColor(parseInt(process.env.EMBED_COLOR)) + // .setDescription(client.tl({ local: int.lang + "onMsg-cmdDsbDesc", cmd: cmdConfig.reason[cmd.name][int.lang] })) + // .setFooter(client.resources[int.lang.replace("-", "")].footer(), client.user.displayAvatarURL()) + // .setTimestamp() + // return int.reply({ embeds: [disableEmbed], ephemeral: true }) + // } + // else { try { cmd.run(client, int) - .catch(err => { - client.log.error(err, true) - if (int.deferred) { - if (int.replied) { - return - } - else { - return int.editReply({ content: client.tl({ local: int.lang + "intCreate-onErr" }), ephemeral: true }) - } - } - else { - return int.reply({ content: client.tl({ local: int.lang + "intCreate-onErr" }), ephemeral: true }) - } - }) + // .catch(err => { + // client.log.error(err, true) + // if (int.deferred) { + // if (int.replied) { + // return + // } + // else { + // return int.editReply({ content: client.tl({ local: int.lang + "intCreate-onErr" }), ephemeral: true }) + // } + // } + // else { + // return int.reply({ content: client.tl({ local: int.lang + "intCreate-onErr" }), ephemeral: true }) + // } + // }) } catch (err) { client.log.error(err, true) @@ -71,11 +71,11 @@ module.exports = { client.emit("cmd", int, cmd.name) const args = client.utils.argsString(int) client.log.info(`Comando: ${cmd.name} executado por ${int.user.tag}(${int.user.id}) ${args ? `- Args: ${args}` : ``}`) - } + // } } }, - disableCmd: (client, info) => { - cmdConfig.disableCmds = info.disable.cmds - cmdConfig.reason = info.disable.reason - } + // disableCmd: (client, info) => { + // cmdConfig.disableCmds = info.disable.cmds + // cmdConfig.reason = info.disable.reason + // } } \ No newline at end of file diff --git a/src/events/discord/ready.js b/src/events/discord/ready.js index e777315..0f3f0ea 100644 --- a/src/events/discord/ready.js +++ b/src/events/discord/ready.js @@ -1,20 +1,11 @@ -const logs = require("../../resources/scripts/logs.js") +const logs = require('../../resources/scripts/logs.js'); module.exports = { - name: "ready", - type: "djs", - execute: async (client) => { - await logs.startup(client) - client.log.start("Logado com o BOT: " + client.user.tag, true) - client.emit("activity", "start") - client.channels.cache.get("784035696414425108").messages.fetch("784039521645101066") - .then((msg) => { - msg.content = msg.content.split("<@720128587289722902> <@716053210179043409>").join("") - msg.content = msg.content.split("```js").join("") - msg.content = msg.content.split("```").join("") - var msgConfig = JSON.parse(msg.content) - client.emit("varUpdate", msgConfig) - }) + name: 'ready', + type: 'djs', + execute: async client => { + await logs.startup(client); + client.log.start(`Iniciada Shard ${client.shard.ids[0]}`, true); + client.emit('activity', 'start'); } - -} \ No newline at end of file +}; diff --git a/src/modules/websocket/server.js b/src/modules/websocket/server.js index 2ea87d4..3d900da 100644 --- a/src/modules/websocket/server.js +++ b/src/modules/websocket/server.js @@ -164,6 +164,8 @@ module.exports = class WebSocket { } }); - httpServer.listen(process.env.PORT || 3005); + if(client.shard.ids[0] == 0) { + httpServer.listen(process.env.PORT || 3005); + } } } \ No newline at end of file diff --git a/src/resources/scripts/botStatus.js b/src/resources/scripts/botStatus.js index d4fd6a9..1210609 100644 --- a/src/resources/scripts/botStatus.js +++ b/src/resources/scripts/botStatus.js @@ -1,9 +1,9 @@ -const moment = require("moment-timezone") -const ac = require("ascii-table") -const os = require(`os-utils`) -const toMs = require("milliseconds-parser")() -const pidusage = require("pidusage") -const DBInfo = new Object() +const moment = require('moment-timezone'); +const ac = require('ascii-table'); +const os = require(`os-utils`); +const toMs = require('milliseconds-parser')(); +const pidusage = require('pidusage'); +const DBInfo = new Object(); var info = { serverCount: 130, @@ -13,45 +13,50 @@ var info = { commandsTotal: 29971, buttonsTotal: 0, buttonsToday: 0, - inviteLink: "https://discord.com/api/oauth2/authorize?client_id=716053210179043409&permissions=388160&scope=bot%20applications.commands", + inviteLink: + 'https://discord.com/api/oauth2/authorize?client_id=716053210179043409&permissions=388160&scope=bot%20applications.commands', oldInfo: true -} +}; module.exports = class botStatus { constructor(options = {}) { - this.client = options.client + this.client = options.client; - this.getDB() + this.getDB(); setInterval(async () => { - await this.getDB() - }, toMs.parse("1 hora")) + await this.getDB(); + }, toMs.parse('1 hora')); } async getDB() { - var dbSize = await this.client.db.query(`SELECT pg_database_size('${process.env.DB_URI.split("/")[3]}');`) + var dbSize = await this.client.db.query(`SELECT pg_database_size('${process.env.DB_URI.split('/')[3]}');`); - var ping = moment().valueOf() - var dbFichas = await this.client.db.query(`select nomerpg from fichas`) - ping = moment().valueOf() - ping + var ping = moment().valueOf(); + var dbFichas = await this.client.db.query(`select nomerpg from fichas`); + ping = moment().valueOf() - ping; - DBInfo.size = dbSize[0] - DBInfo.fichas = dbFichas[0] - DBInfo.ping = ping - return DBInfo + DBInfo.size = dbSize[0]; + DBInfo.fichas = dbFichas[0]; + DBInfo.ping = ping; + return DBInfo; } async updateBS(client) { - var year = new Date().getFullYear() + var year = new Date().getFullYear(); - var count = 0 - client.guilds.cache.map(guild => count += guild.memberCount) + const promises = [ + client.shard.fetchClientValues('guilds.cache.size'), + client.shard.broadcastEval(c => c.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)) + ]; - var dbSize = DBInfo.size[0].pg_database_size - var dbFichas = DBInfo.fichas + const results = await Promise.all(promises); - const botStatus = new client.Discord.EmbedBuilder() + var dbSize = DBInfo.size[0].pg_database_size; + var dbFichas = DBInfo.fichas; - var qFichas = dbFichas.length + const botStatus = new client.Discord.EmbedBuilder(); + + var qFichas = dbFichas.length; var uptime = process.uptime(); var days = Math.floor((uptime % 31536000) / 86400); @@ -59,21 +64,21 @@ module.exports = class botStatus { var minutes = Math.floor((uptime % 3600) / 60); var seconds = Math.round(uptime % 60); var botuptime = - (days > 0 ? days == 1 ? days + " dia " : days + " dias " : "") - + (hours > 0 ? hours == 1 ? hours + " hora " : hours + " horas " : "") - + (minutes > 0 ? minutes == 1 ? minutes + " minuto " : minutes + " minutos " : "") + (days > 0 ? (days == 1 ? days + ' dia ' : days + ' dias ') : '') + + (hours > 0 ? (hours == 1 ? hours + ' hora ' : hours + ' horas ') : '') + + (minutes > 0 ? (minutes == 1 ? minutes + ' minuto ' : minutes + ' minutos ') : ''); - const table = new ac("Kami") + const table = new ac('Kami'); - const stats = await pidusage(process.pid) + const stats = await pidusage(process.pid); - const ram = stats.memory / 1024 / 1024 + const ram = stats.memory / 1024 / 1024; - const commands = client.cache.getCount() + const commands = client.cache.getCount(); info = { - serverCount: client.guilds.cache.size, - userCount: count, + serverCount: results[0].reduce((acc, guildCount) => acc + guildCount, 0), + userCount: results[1].reduce((acc, memberCount) => acc + memberCount, 0), fichasCount: qFichas, commandsToday: commands.today, commandsTotal: commands.total, @@ -84,53 +89,80 @@ module.exports = class botStatus { dbPing: DBInfo.ping, inviteLink: `https://discord.com/api/oauth2/authorize?client_id=716053210179043409&permissions=${process.env.PERMISSIONS}&scope=bot%20applications.commands`, oldInfo: false - } + }; table .addRow(`Uso de CPU`, `${stats.cpu.toFixed(2)} %`) .addRow(`Uso de RAM`, `${ram.toFixed(2)} MB`) - .addRow(`RAM Total`, `${(os.totalmem() / 1024 - os.freemem() / 1024).toFixed(1)} GB / ${(os.totalmem() / 1024).toFixed(1)} GB`) - .addRow("Ping", `API: ${Math.round(client.ws.ping)} ms - ` + `DB: ${Math.round(DBInfo.ping)} ms`) - .addRow("Uso do DB", (dbSize / 1e+6).toFixed(1) + " MB") - .addRow("Fichas Criadas", `${qFichas} Fichas`) - .addRow("Fichas no Cache", `${client.cache.evalSync("fichas.length()")}`) - .addRow("Fichas IRT no Cache", `${client.cache.evalSync("irt.length()")}`) - .addRow("", "") - .addRow(`Servidores`, `${client.guilds.cache.size}`) - .addRow(`Usuários`, `${count}`) + .addRow( + `RAM Total`, + `${(os.totalmem() / 1024 - os.freemem() / 1024).toFixed(1)} GB / ${(os.totalmem() / 1024).toFixed( + 1 + )} GB` + ) + .addRow('Ping', `API: ${Math.round(client.ws.ping)} ms - ` + `DB: ${Math.round(DBInfo.ping)} ms`) + .addRow('Uso do DB', (dbSize / 1e6).toFixed(1) + ' MB') + .addRow('Fichas Criadas', `${qFichas} Fichas`) + .addRow('Fichas no Cache', `${client.cache.evalSync('fichas.length()')}`) + .addRow('Fichas IRT no Cache', `${client.cache.evalSync('irt.length()')}`) + .addRow('', '') + .addRow(`Servidores`, `${info.serverCount}`) + .addRow(`Usuários`, `${info.userCount}`) .addRow(`Comandos`, `Após iniciar: ${commands.today} - Total: ${commands.total}`) .addRow(`Botões`, `Após iniciar: ${commands.buttonsToday} - Total: ${commands.buttonsTotal}`) - .addRow("", "") - .addRow("Versão do BOT", "v" + require("../../../package.json").version) - .addRow("Node.js", process.version) - .addRow("Discord.js", "v" + require("../../../package.json").dependencies["discord.js"].replace("^", "")) - .addRow("", "") - .addRow(`Tempo Online`, botuptime) - - botStatus.setAuthor({ name: "Status atual do BOT" }) - botStatus.setDescription("```\n" + table.toString() + "```") - botStatus.setFooter({ text: `${year} © Kami`, iconURL: client.user.avatarURL() }) - botStatus.setTimestamp() - botStatus.setColor(parseInt(process.env.EMBED_COLOR)) - - if (client.user.id == "716053210179043409") { - var statusMsg = await client.channels.fetch("772970777787236352") - await statusMsg.messages.fetch("772971275903303721") - .then(msg => { - msg.edit({ embeds: [botStatus] }) - }) + .addRow('', '') + .addRow('Versão do BOT', 'v' + require('../../../package.json').version) + .addRow('Node.js', process.version) + .addRow('Discord.js', 'v' + require('../../../package.json').dependencies['discord.js'].replace('^', '')) + .addRow('', '') + .addRow(`Tempo Online`, botuptime); + + botStatus.setAuthor({ name: 'Status atual do BOT' }); + botStatus.setDescription('```\n' + table.toString() + '```'); + botStatus.setFooter({ text: `${year} © Kami`, iconURL: client.user.avatarURL() }); + botStatus.setTimestamp(); + botStatus.setColor(parseInt(process.env.EMBED_COLOR)); + + if (client.user.id == '716053210179043409') { + client.shard.broadcastEval( + async c => { + const channel = c.channels.cache.get('772970777787236352'); + + if (channel) { + const message = await channel.messages.fetch('772971275903303721'); + if (message) { + message.edit({ embeds: [JSON.parse(JSON.stringify(info))] }); + } else { + return null; + } + } + }, + { + context: JSON.stringify(info) + } + ); + } else { + client.shard.broadcastEval( + async (c, ctx) => { + const channel = c.channels.cache.get('784542287329886239'); + + if (channel) { + const message = await channel.messages.fetch('784543009982644245'); + if (message) { + message.edit({ embeds: [JSON.parse(ctx)] }); + } else { + return null; + } + } + }, + { + context: JSON.stringify(botStatus) + } + ); } - else { - var statusMsg = await client.channels.fetch("784542287329886239") - statusMsg.messages.fetch("784543009982644245") - .then(msg => { - msg.edit({ embeds: [botStatus] }) - }) - } - } api() { - return info + return info; } -} +}; diff --git a/src/resources/scripts/logs.js b/src/resources/scripts/logs.js index 10ab05b..a3d53e1 100644 --- a/src/resources/scripts/logs.js +++ b/src/resources/scripts/logs.js @@ -1,169 +1,251 @@ -const time = require("luxon").DateTime -const { inspect } = require('util') -var logTxt = `Log - ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }\n` +const time = require('luxon').DateTime; +require('colors'); +const { inspect } = require('util'); +var logTxt = `Log - ${time.now().setZone('America/Sao_Paulo').toFormat('dd/MM/y | HH:mm:ss ')}\n`; -const Inf = new Map() +const Inf = new Map(); async function startup(client) { - const ch = await client.channels.fetch(process.env.LOG_CHANNEL) + Inf.set('client', client); - Inf.set("client", client) - Inf.set("ch", ch) - - return "Iniciado" + return 'Iniciado'; } function info(msg, ds) { if (typeof msg === 'string') { - logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| INFO ] - ${msg}\n` + logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat('dd/MM/y | HH:mm:ss ')}| INFO ] - ${msg}\n`; - console.log(`[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| INFO ] - ${msg}`.green) - } - else { - logTxt += `---------------- [ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| INFO ] ----------------\n` - logTxt += inspect(msg, { depth: 99 }) + "\n" - logTxt += `---------------- [ FIM DA INFO ] ----------------\n` + console.log( + `[ ${time.now().setZone('America/Sao_Paulo').toFormat('dd/MM/y | HH:mm:ss ')}| INFO ] - ${msg}`.green + ); + } else { + logTxt += `---------------- [ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| INFO ] ----------------\n`; + logTxt += inspect(msg, { depth: 99 }) + '\n'; + logTxt += `---------------- [ FIM DA INFO ] ----------------\n`; - console.log(`---------------- [ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| INFO ] ----------------`.green); + console.log( + `---------------- [ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| INFO ] ----------------`.green + ); console.log(msg); - console.log(`---------------- [ FIM DA INFO ] ----------------`.green) + console.log(`---------------- [ FIM DA INFO ] ----------------`.green); } - if (ds === true) { - msg = typeof msg === 'string' ? msg : inspect(msg, { depth: 99 }) - Inf.get("ch").send({ - embeds: [{ - title: "INFO", - description: "```js\n" + msg + "```", - color: parseInt(process.env.EMBED_COLOR), - footer: { - text: `Informação em: ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") } (GMT -3)`, - icon_url: Inf.get("client").user.displayAvatarURL() - } - }] - }) - .then(msg => { - logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| EMBED ] - https://discord.com/channels/${msg.guild.id}/${msg.channel.id}/${msg.id}\n` + msg = typeof msg === 'string' ? msg : inspect(msg, { depth: 99 }); + Inf.get('client') + .log.logWebhook.send({ + embeds: [ + { + title: 'INFO', + description: '```js\n' + msg + '```', + color: parseInt(process.env.EMBED_COLOR), + footer: { + text: `Informação em: ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')} (GMT -3)`, + icon_url: Inf.get('client').user.displayAvatarURL() + } + } + ] }) + .then(msg => { + logTxt += `[ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| EMBED ] - https://discord.com/channels/${msg.channel_id}/${ + msg.id + }/${msg.id}\n`; + }); } } function start(msg, ds) { - logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| INICIADO ] - ${msg}\n` - console.log(`[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| INICIADO ] - ${msg}`.cyan) + logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat('dd/MM/y | HH:mm:ss ')}| INICIADO ] - ${msg}\n`; + console.log( + `[ ${time.now().setZone('America/Sao_Paulo').toFormat('dd/MM/y | HH:mm:ss ')}| INICIADO ] - ${msg}`.cyan + ); if (ds === true) { - Inf.get("ch").send({ - embeds: [{ - title: "INICIADO", - description: "```js\n" + msg + "```", - color: parseInt(process.env.EMBED_COLOR), - footer: { - text: `Iniciado em: ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") } (GMT -3)`, - icon_url: Inf.get("client").user.displayAvatarURL() - } - }] - }) - .then(msg => { - logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| EMBED ] - https://discord.com/channels/${msg.guild.id}/${msg.channel.id}/${msg.id}\n` + Inf.get('client') + .log.logWebhook.send({ + embeds: [ + { + title: 'INICIADO', + description: '```js\n' + msg + '```', + color: parseInt(process.env.EMBED_COLOR), + footer: { + text: `Iniciado em: ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')} (GMT -3)`, + icon_url: Inf.get('client').user.displayAvatarURL() + } + } + ] }) + .then(msg => { + logTxt += `[ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| EMBED ] - https://discord.com/channels/${msg.channel_id}/${ + msg.id + }/${msg.id}\n`; + }); } } function warn(msg, ds) { if (typeof msg === 'string') { - logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| AVISO ] - ${msg}\n` - console.log(`[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| AVISO ] - ${msg}`.yellow) - } - else { - logTxt += `---------------- [ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| AVISO ] ----------------\n` - logTxt += msg + "\n" - logTxt += `---------------- [ FIM DO AVISO ] ----------------\n` + logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat('dd/MM/y | HH:mm:ss ')}| AVISO ] - ${msg}\n`; + console.log( + `[ ${time.now().setZone('America/Sao_Paulo').toFormat('dd/MM/y | HH:mm:ss ')}| AVISO ] - ${msg}`.yellow + ); + } else { + logTxt += `---------------- [ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| AVISO ] ----------------\n`; + logTxt += msg + '\n'; + logTxt += `---------------- [ FIM DO AVISO ] ----------------\n`; - console.log(`---------------- [ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| AVISO ] ----------------`.yellow); + console.log( + `---------------- [ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| AVISO ] ----------------`.yellow + ); console.log(msg); console.log(`---------------- [ FIM DO AVISO ] ----------------`.yellow); } if (ds === true) { - msg = typeof msg === 'string' ? msg : inspect(msg, { depth: 99 }) - Inf.get("ch").send({ - content: `<@${process.env.OWNER}>`, - embeds: [{ - title: "AVISO", - description: "```js\n" + msg + "```", - color: parseInt(process.env.EMBED_COLOR), - footer: { - text: `Aviso em: ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") } (GMT -3)`, - icon_url: Inf.get("client").user.displayAvatarURL() - } - }] - }) - .then(msg => { - logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| EMBED ] - https://discord.com/channels/${msg.guild.id}/${msg.channel.id}/${msg.id}\n` + msg = typeof msg === 'string' ? msg : inspect(msg, { depth: 99 }); + Inf.get('client') + .log.logWebhook.send({ + embeds: [ + { + title: 'AVISO', + description: '```js\n' + msg + '```', + color: parseInt(process.env.EMBED_COLOR), + footer: { + text: `Aviso em: ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')} (GMT -3)`, + icon_url: Inf.get('client').user.displayAvatarURL() + } + } + ] }) + .then(msg => { + logTxt += `[ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| EMBED ] - https://discord.com/channels/${msg.channel_id}/${ + msg.id + }/${msg.id}\n`; + }); } } function error(msg, ds) { if (typeof msg === 'string') { - logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| ERRO ] - ${msg}\n` - console.log(`[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| ERRO ] - ${msg}`.red) - } - else { - logTxt += `---------------- [ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| ERRO ] ----------------\n` - logTxt += inspect(msg, { depth: 99 }) + "\n" - logTxt += `---------------- [ FIM DO ERRO ] ----------------\n` + logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat('dd/MM/y | HH:mm:ss ')}| ERRO ] - ${msg}\n`; + console.log( + `[ ${time.now().setZone('America/Sao_Paulo').toFormat('dd/MM/y | HH:mm:ss ')}| ERRO ] - ${msg}`.red + ); + } else { + logTxt += `---------------- [ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| ERRO ] ----------------\n`; + logTxt += inspect(msg, { depth: 99 }) + '\n'; + logTxt += `---------------- [ FIM DO ERRO ] ----------------\n`; - console.log(`---------------- [ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| ERRO ] ----------------`.red); + console.log( + `---------------- [ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| ERRO ] ----------------`.red + ); console.log(msg); - console.log(`---------------- [ FIM DO ERRO ] ----------------`.red) + console.log(`---------------- [ FIM DO ERRO ] ----------------`.red); } if (ds === true) { - msg = typeof msg === 'string' ? msg : inspect(msg, { depth: 99 }) - msg = `${String(msg).slice(0, 4000) + (msg.length >= 4000 ? '...' : '')}` + msg = typeof msg === 'string' ? msg : inspect(msg, { depth: 99 }); + msg = `${String(msg).slice(0, 4000) + (msg.length >= 4000 ? '...' : '')}`; try { - Inf.get("ch").send({ - content: `<@${process.env.OWNER}>`, - embeds: [{ - title: "ERRO", - description: "```js\n" + msg + "```", - color: parseInt(process.env.EMBED_COLOR), - footer: { - text: `Erro em: ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") } (GMT -3)`, - icon_url: Inf.get("client").user.displayAvatarURL() - } - }] - }) - .then(msg => { - logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| EMBED ] - https://discord.com/channels/${msg.guild.id}/${msg.channel.id}/${msg.id}\n` + Inf.get('client') + .log.logWebhook.send({ + content: `<@${process.env.OWNER}>`, + embeds: [ + { + title: 'ERRO', + description: '```js\n' + msg + '```', + color: parseInt(process.env.EMBED_COLOR), + footer: { + text: `Erro em: ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')} (GMT -3)`, + icon_url: Inf.get('client').user.displayAvatarURL() + } + } + ] }) + .then(msg => { + logTxt += `[ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| EMBED ] - https://discord.com/channels/${msg.channel_id}/${ + msg.id + }/${msg.id}\n`; + }); + } catch (err) { + process.emit('SIGTERM'); } - catch (err) { process.emit("SIGTERM") } - } } function embed(embed, ping, local) { if (ping) { - return Inf.get("ch").send({ content: `<@${process.env.OWNER}>`, embeds: [embed] }) + return Inf.get('client') + .log.logWebhook.send({ content: `<@${process.env.OWNER}>`, embeds: [embed] }) .then(msg => { - logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| EMBED ] - https://discord.com/channels/${msg.guild.id}/${msg.channel.id}/${msg.id}\n` - if (local == "sugestao") { - return msg + logTxt += `[ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| EMBED ] - https://discord.com/channels/${msg.channel_id}/${ + msg.id + }/${msg.id}\n`; + if (local == 'sugestao') { + return msg; } - }) - } - else { - return Inf.get("ch").send({ embeds: [embed] }) + }); + } else { + return Inf.get('client') + .log.logWebhook.send({ embeds: [embed] }) .then(msg => { - logTxt += `[ ${time.now().setZone('America/Sao_Paulo').toFormat("dd/MM/y | HH:mm:ss ") }| EMBED ] - https://discord.com/channels/${msg.guild.id}/${msg.channel.id}/${msg.id}\n` - if (local == "sugestao") { - return msg + logTxt += `[ ${time + .now() + .setZone('America/Sao_Paulo') + .toFormat('dd/MM/y | HH:mm:ss ')}| EMBED ] - https://discord.com/channels/${msg.channel_id}/${ + msg.id + }/${msg.id}\n`; + if (local == 'sugestao') { + return msg; } - }) + }); } } module.exports = { startup, log: { info, start, warn, error, embed }, - logTxt() { return logTxt } -} + logTxt() { + return logTxt; + } +};