From a9af0af35c0b195c1694cb47ed1095f91758a98a Mon Sep 17 00:00:00 2001 From: AnxietyisReal <96593068+AnxietyisReal@users.noreply.github.com> Date: Sun, 3 Sep 2023 18:56:22 +1000 Subject: [PATCH] Optimize LogPrefix --- src/commands/mp-maintenance.ts | 2 +- src/commands/mp.ts | 6 +++--- src/commands/unpunish.ts | 4 +++- src/events/messageCreate.ts | 6 ++++-- src/events/messageDelete.ts | 4 +++- src/funcs/DatabaseServer.ts | 2 +- src/funcs/MPModule.ts | 6 +++--- src/funcs/Punish.ts | 3 ++- src/funcs/YTModule.ts | 3 ++- src/models/userLevels.ts | 3 ++- 10 files changed, 24 insertions(+), 15 deletions(-) diff --git a/src/commands/mp-maintenance.ts b/src/commands/mp-maintenance.ts index eabb6ea..86b2983 100644 --- a/src/commands/mp-maintenance.ts +++ b/src/commands/mp-maintenance.ts @@ -10,7 +10,7 @@ export default { const activePlayersChannel = '739084625862852715'; const channel = (client.channels.cache.get(activePlayersChannel) as Discord.TextChannel); const embed = new client.embed().setColor(client.config.embedColor).setAuthor({name: interaction.member.displayName, iconURL: interaction.member.displayAvatarURL({size:1024})}).setTimestamp(); - console.log(channel.permissionsFor(interaction.guildId).has('SendMessages')); + if (channel.permissionsFor(interaction.guildId).has('SendMessages')) { channel.permissionOverwrites.edit(interaction.guildId, {SendMessages: false}, {type: 0, reason: `Locked by ${interaction.member.displayName}`}); channel.send({embeds: [embed.setTitle('🔒 Channel locked').setDescription(`**Reason:**\n${maintenanceMessage}`)]}); diff --git a/src/commands/mp.ts b/src/commands/mp.ts index e5235dd..49bfb28 100644 --- a/src/commands/mp.ts +++ b/src/commands/mp.ts @@ -197,18 +197,18 @@ export default { const Url = await client.MPServer._content.findById(interaction.guildId); if (Url[serverSelector].ip && Url[serverSelector].code) return interaction.reply(Url[serverSelector].ip+'/feed/dedicated-server-stats.json?code='+Url[serverSelector].code) } catch(err){ - console.log(client.logTime(), `${LogPrefix('MPDB')} ${err}`); + console.log(client.logTime(), LogPrefix('MPDB'), err); interaction.reply(`\`\`\`${err}\`\`\``) } } else { if (!address.match(/dedicated-server-stats/)) return interaction.reply('The URL does not match `dedicated-server-stats.xml`'); const newURL = address.replace('xml','json').split('/feed/dedicated-server-stats.json?code='); try { - console.log(client.logTime(), `${LogPrefix('MPDB')} ${serverSelector}\'s URL for ${interaction.guild.name} has been updated by ${interaction.member.displayName} (${interaction.member.id})`); + console.log(client.logTime(), LogPrefix('MPDB'), `${serverSelector}\'s URL for ${interaction.guild.name} has been updated by ${interaction.member.displayName} (${interaction.member.id})`); const affected = await client.MPServer._content.findByIdAndUpdate({_id: interaction.guildId}, {$set: {[serverSelector]: {ip: newURL[0], code: newURL[1]}}}) if (affected) return interaction.reply('URL successfully updated.') } catch (err) { - console.log(client.logTime(), `${LogPrefix('MPDB')} ${serverSelector}\'s URL for ${interaction.guild.name} has been created by ${interaction.member.displayName} (${interaction.member.id})`); + console.log(client.logTime(), LogPrefix('MPDB'), `${serverSelector}\'s URL for ${interaction.guild.name} has been created by ${interaction.member.displayName} (${interaction.member.id})`); await client.MPServer._content.create({_id: interaction.guildId, [serverSelector]: { ip: newURL[0], code: newURL[1] }}) .then(()=>interaction.reply('This server doesn\'t have any data in the database, therefore I have created it for you.')) .catch((err:Error)=>interaction.reply(`I got hit by a flying brick while trying to populate the server data:\n\`\`\`${err.message}\`\`\``)) diff --git a/src/commands/unpunish.ts b/src/commands/unpunish.ts index 46b7de2..39599dc 100644 --- a/src/commands/unpunish.ts +++ b/src/commands/unpunish.ts @@ -1,5 +1,7 @@ import Discord from 'discord.js'; import TClient from '../client.js'; +import LogPrefix from '../helpers/LogPrefix.js'; + export default { async run(client: TClient, interaction: Discord.ChatInputCommandInteraction<'cached'>){ if (!client.isStaff(interaction.member as Discord.GuildMember)) return client.youNeedRole(interaction, 'dcmod'); @@ -8,7 +10,7 @@ export default { if (punishment.expired) return interaction.reply('This case has been overwritten by another case.'); const reason = interaction.options.getString('reason') ?? 'Reason unspecified'; await client.punishments.removePunishment(punishment.id, interaction.user.id, reason, interaction); - console.log(client.logTime(), `[UnpunishmentLog] Case #${interaction.options.getInteger('case_id')} was used in /${interaction.commandName} for ${reason}`); + console.log(client.logTime(), LogPrefix('UnpunishmentLog'), `Case #${interaction.options.getInteger('case_id')} was used in /${interaction.commandName} for ${reason}`); (client.channels.cache.get(client.config.mainServer.channels.punishment_log) as Discord.TextChannel).send({embeds:[new client.embed().setColor(client.config.embedColor).setTitle('Unpunishment Log').setDescription(`Case #${interaction.options.getInteger('case_id')} was used in \`/${interaction.commandName}\` for \`${reason}\``).setTimestamp()]}); }, data: new Discord.SlashCommandBuilder() diff --git a/src/events/messageCreate.ts b/src/events/messageCreate.ts index b199726..61148aa 100644 --- a/src/events/messageCreate.ts +++ b/src/events/messageCreate.ts @@ -1,6 +1,7 @@ import Discord from 'discord.js'; import TClient from '../client.js'; import Response from '../funcs/ResponseSystem.js'; +import LogPrefix from '../helpers/LogPrefix.js'; export default { async run(client:TClient, message:Discord.Message){ if (message.author.bot) return; @@ -38,9 +39,10 @@ export default { } if (client.config.botSwitches.automod && !message.member.roles.cache.has(client.config.mainServer.roles.admin) && message.guildId == client.config.mainServer.id){ + const automodFailReason = 'msg got possibly deleted by another bot.'; if (await client.bannedWords._content.findById(msgarr)/* && !Whitelist.includes(message.channelId) */){ automodded = true; - message.delete().catch(()=>console.log('bannedWords automod; msg got possibly deleted by another bot.')); + message.delete().catch(()=>console.log(LogPrefix('AUTOMOD-BANNEDWORDS'), automodFailReason)); message.channel.send('That word isn\'t allowed here.').then(x=>setTimeout(()=>x.delete(), 10000)); await repeatedMessages(30000, 3, 'bw', '30m', 'Constant swearing'); } else if (message.content.toLowerCase().includes('discord.gg/') && !client.isStaff(message.member as Discord.GuildMember)){ @@ -48,7 +50,7 @@ export default { const validInvite = await client.fetchInvite(url).catch(()=>undefined); if (validInvite && validInvite.guild?.id !== client.config.mainServer.id){ automodded = true; - message.delete().catch(()=>console.log('Advertisement automod; msg got possibly deleted by another bot.')); + message.delete().catch(()=>console.log(LogPrefix('AUTOMOD-ADVERT'), automodFailReason)); message.channel.send('Please don\'t advertise other Discord servers.').then(x=>setTimeout(()=>x.delete(), 15000)); await repeatedMessages(60000, 2, 'adv', '1h', 'Discord advertisement'); } diff --git a/src/events/messageDelete.ts b/src/events/messageDelete.ts index 817d765..e569377 100644 --- a/src/events/messageDelete.ts +++ b/src/events/messageDelete.ts @@ -1,11 +1,13 @@ import Discord from 'discord.js'; import TClient from '../client.js'; +import LogPrefix from '../helpers/LogPrefix.js'; + export default { run(client:TClient, msg:Discord.Message){ if (!client.config.botSwitches.logs) return; const disabledChannels = ['548032776830582794', '541677709487505408', '949380187668242483'] if (msg.guild?.id != client.config.mainServer.id || msg.partial || msg.author.bot || disabledChannels.includes(msg.channelId)) return; - if (Discord.DiscordAPIError.name === '10008') return console.log(client.logTime(), 'Caught an unexpected error returned by Discord API. (Unknown Message)'); + if (Discord.DiscordAPIError.name === '10008') return console.log(client.logTime(), LogPrefix('MsgDelete'), 'Caught an unexpected error returned by Discord API. (Unknown Message)'); const embed = new client.embed().setColor(client.config.embedColorRed).setTimestamp().setAuthor({name: `Author: ${msg.author.username} (${msg.author.id})`, iconURL: `${msg.author.displayAvatarURL()}`}).setTitle('Message deleted').setDescription(`<@${msg.author.id}>\n\`${msg.author.id}\``); if (msg.content.length != 0) embed.addFields({name: 'Content', value: `\`\`\`\n${msg.content.slice(0,1000)}\n\`\`\``}); embed.addFields( diff --git a/src/funcs/DatabaseServer.ts b/src/funcs/DatabaseServer.ts index 3cf9ca9..17d284a 100644 --- a/src/funcs/DatabaseServer.ts +++ b/src/funcs/DatabaseServer.ts @@ -5,7 +5,7 @@ import LogPrefix from '../helpers/LogPrefix.js'; const connection:mongoose.Connection = mongoose.connection; export default class DatabaseServer { static connect(client: TClient) { - const Logger = (logType:'log'|'error', msg:string)=>console[logType](client.logTime(), `${LogPrefix('DATABASE')} ${msg}`); + const Logger = (logType:'log'|'error', msg:string)=>console[logType](client.logTime(), LogPrefix('DATABASE'), msg); connection.set('strictQuery', true); connection.openUri(client.tokens.mongodb_uri, { diff --git a/src/funcs/MPModule.ts b/src/funcs/MPModule.ts index 1a10aad..0dc73df 100644 --- a/src/funcs/MPModule.ts +++ b/src/funcs/MPModule.ts @@ -24,7 +24,7 @@ export default async(client:TClient, Channel:string, Message:string, Server:TSer const hitCSG = await fetch(Server.ip+'/feed/dedicated-server-savegame.html?code='+Server.code+'&file=careerSavegame', sessionInit).then(async r=>(client.xjs.xml2js(await r.text(), {compact: true}) as any).careerSavegame as FSCareerSavegame); if (!hitDSS ?? !hitCSG){ - if (hitDSS && !hitDSS.slots) return console.log(`${LogPrefix('MPLoop')} DSS failed with unknown slots table for ${client.MPServerCache[ServerName].name}`); + if (hitDSS && !hitDSS.slots) return console.log(LogPrefix('MPModule'), `DSS failed with unknown slots table for ${client.MPServerCache[ServerName].name}`); if (hitDSS && !hitCSG.slotSystem) return msg.edit({content: 'No savegame found or autosave has ran.', embeds: [genericEmbed.setColor(client.config.embedColorOrange).setImage(noContentImage)]}); else return msg.edit({embeds: [serverErrorEmbed]}); } @@ -52,7 +52,7 @@ export default async(client:TClient, Channel:string, Message:string, Server:TSer const serverLog = client.channels.resolve(client.config.mainServer.channels.fs_server_log) as Discord.TextChannel; const playersOnServer = hitDSS.slots?.players.filter(x=>x.isUsed); const playersInCache = client.MPServerCache[ServerName].players; - if (!playersOnServer ?? playersOnServer === undefined) return console.log('[MPLoop] Empty array, ignoring...'); // For the love of god, stop throwing errors everytime. + if (!playersOnServer ?? playersOnServer === undefined) return console.log(LogPrefix('MPModule'), 'Empty array, ignoring...'); // For the love of god, stop throwing errors everytime. playersOnServer.forEach(player=>playerData.push(`**${player.name}${FormatPlayer.decoratePlayerIcons(player)}**\nFarming for ${FormatPlayer.uptimeFormat(player.uptime)}`)); // Player leaving @@ -90,7 +90,7 @@ export default async(client:TClient, Channel:string, Message:string, Server:TSer } catch(err) { if (err.message === 'The operation was aborted due to timeout') return msg.edit({content: 'Connection timed out.', embeds: [serverErrorEmbed]}); msg.edit({content: null, embeds: [serverErrorEmbed]}); - console.log(client.logTime(), `Failed to make a request for ${ServerName}:`, err.message) + console.log(client.logTime(), LogPrefix('MPModule'),`Failed to make a request for ${ServerName}:`, err.message) } } HITALL(); diff --git a/src/funcs/Punish.ts b/src/funcs/Punish.ts index 6946015..bfb5985 100644 --- a/src/funcs/Punish.ts +++ b/src/funcs/Punish.ts @@ -1,5 +1,6 @@ import Discord from 'discord.js'; import TClient from '../client.js'; +import LogPrefix from '../helpers/LogPrefix.js'; export default async(client:TClient, interaction: Discord.ChatInputCommandInteraction<'cached'>, type: string)=>{ if (!client.isStaff(interaction.member as Discord.GuildMember)) return client.youNeedRole(interaction, 'dcmod'); @@ -9,7 +10,7 @@ export default async(client:TClient, interaction: Discord.ChatInputCommandIntera const GuildMember = interaction.options.getMember('member') ?? undefined; const User = interaction.options.getUser('member', true); - console.log(client.logTime(), `[PunishmentLog] ${GuildMember?.user?.username ?? User?.username ?? 'No user data'} ${time ? ['warn', 'kick'].includes(type) ? 'and no duration set' : `and ${time} (duration)` : ''} was used in /${interaction.commandName} for ${reason}`); + console.log(client.logTime(), LogPrefix('PunishmentLog'), `${GuildMember?.user?.username ?? User?.username ?? 'No user data'} ${time ? ['warn', 'kick'].includes(type) ? 'and no duration set' : `and ${time} (duration)` : ''} was used in /${interaction.commandName} for ${reason}`); (client.channels.cache.get(client.config.mainServer.channels.punishment_log) as Discord.TextChannel).send({embeds:[new client.embed().setColor(client.config.embedColor).setAuthor({name: interaction?.user?.username, iconURL: interaction?.user?.displayAvatarURL({size:2048})}).setTitle('Punishment Log').setDescription(`${GuildMember?.user?.username ?? User?.username ?? 'No user data'} ${time ? ['warn', 'kick'].includes(client.punishments.type) ? 'and no duration set' : `and ${time} (duration)` : ''} was used in \`/${interaction.commandName}\` for \`${reason}\``).setTimestamp()]}); if (interaction.user.id === User.id) return interaction.reply(`You cannot ${type} yourself.`); if (!GuildMember && type != 'unban') return interaction.reply(`You cannot ${type} someone who is not in the server.`); diff --git a/src/funcs/YTModule.ts b/src/funcs/YTModule.ts index 764b6de..1c8b5f5 100644 --- a/src/funcs/YTModule.ts +++ b/src/funcs/YTModule.ts @@ -1,12 +1,13 @@ import {TextChannel} from 'discord.js'; import TClient from '../client.js'; +import LogPrefix from '../helpers/LogPrefix.js'; export default async(client: TClient, YTChannelID: string, YTChannelName: string, DiscordChannelID: string, DiscordRoleID: string)=>{ let Data: any; try { await fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${YTChannelID}`, {signal: AbortSignal.timeout(8000), headers: {'User-Agent': 'Daggerbot - Notification/undici'}}).then(async xml=>Data = client.xjs.xml2js(await xml.text(), {compact: true})) } catch(err){ - console.log(client.logTime(), `Failed to fetch "${YTChannelName}" from YouTube`) + console.log(client.logTime(), LogPrefix('YTModule'), `Failed to fetch "${YTChannelName}" from YouTube`) } if (!Data) return; diff --git a/src/models/userLevels.ts b/src/models/userLevels.ts index 61cfa38..f674391 100644 --- a/src/models/userLevels.ts +++ b/src/models/userLevels.ts @@ -1,6 +1,7 @@ import Discord from 'discord.js'; import TClient from '../client.js'; import mongoose from 'mongoose'; +import LogPrefix from '../helpers/LogPrefix.js'; const Schema = mongoose.model('userLevels', new mongoose.Schema({ _id: {type: String}, @@ -24,7 +25,7 @@ export default class userLevels extends Schema { if (userData.messages >= this.algorithm(userData.level+2)){ while (userData.messages > this.algorithm(userData.level+1)){ const newData = await this._content.findByIdAndUpdate(userid, {level:userData.level++}, {new: true}); - console.log(this.client.logTime(), `${userid} extended to level ${newData.level}`); + console.log(this.client.logTime(), LogPrefix('LevelSystem'), `${userid} extended to level ${newData.level}`); } } else if (userData.messages >= this.algorithm(userData.level+1)) { const newData = await this._content.findByIdAndUpdate(userid, {level:userData.level+1}, {new: true});