refactor DB

This commit is contained in:
Neko-Life 2021-07-24 14:05:58 +07:00
parent 2dd90d398a
commit e5765e3745
17 changed files with 128 additions and 151 deletions

View file

@ -18,7 +18,7 @@ module.exports = class eventlog extends commando.Command {
async run(msg, arg) { async run(msg, arg) {
if (!msg.guild.DB) await msg.guild.dbLoad(); if (!msg.guild.DB) await msg.guild.dbLoad();
const set = parseDoubleDash(arg); const set = parseDoubleDash(arg);
let eventChannels = msg.guild.DB.settings.eventChannels; let eventChannels = msg.guild.DB.eventChannels;
if (!set || set.length < 2 && set[0].length === 0) return trySend(this.client, msg, await resultEmbed(this)); if (!set || set.length < 2 && set[0].length === 0) return trySend(this.client, msg, await resultEmbed(this));
let report = "", joinlog, leavelog, channellog, banlog, unbanlog, mesEdlog = { channel: undefined, ignore: [] }, invitelog, rolelog, let report = "", joinlog, leavelog, channellog, banlog, unbanlog, mesEdlog = { channel: undefined, ignore: [] }, invitelog, rolelog,
guildlog, membernicklog, emotelog, memberroleslog, remove = false, [setMesEdIgnore, setMesDelIgnore] = [false, false], mesDellog = { channel: undefined, ignore: [] }; guildlog, membernicklog, emotelog, memberroleslog, remove = false, [setMesEdIgnore, setMesDelIgnore] = [false, false], mesDellog = { channel: undefined, ignore: [] };

View file

@ -73,12 +73,12 @@ module.exports = class mute extends commando.Command {
async run(msg, arg) { async run(msg, arg) {
msg.channel.startTyping(); msg.channel.startTyping();
if (!msg.guild.DB) await msg.guild.dbLoad(); if (!msg.guild.DB) await msg.guild.dbLoad();
const MOD = msg.guild.DB.moderation.settings, const MOD = msg.guild.DB.settings,
MUTE = MOD.mute || {}, MUTE = MOD.mute || {},
args = parseDoubleDash(arg), args = parseDoubleDash(arg),
mentions = parseComa(args?.shift()); mentions = parseComa(args?.shift());
if (!MOD.mute) msg.guild.DB.moderation.settings.mute = {}; if (!MOD.mute) msg.guild.DB.settings.mute = {};
let reason = "No reason provided", duration = {}, resultMsg = "", targetUsers = []; let reason = "No reason provided", duration = {}, resultMsg = "", targetUsers = [];
if (args?.[1]) { if (args?.[1]) {
@ -120,25 +120,28 @@ module.exports = class mute extends commando.Command {
try { try {
const RES = await EXEC.mute(msg.guild, { duration: duration, infraction: infractionToDoc.infraction, moderator: msg.member }, reason); const RES = await EXEC.mute(msg.guild, { duration: duration, infraction: infractionToDoc.infraction, moderator: msg.member }, reason);
if (RES.infraction) infractionN.push(RES.infraction); if (RES.infraction) infractionN.push(RES.infraction);
console.log(RES);
muted.push(EXEC.id); muted.push(EXEC.id);
} catch (e) { } catch (e) {
if (/Missing Permissions|someone with higher position/.test(e.message)) cant.push(EXEC.id); if (/Missing Permissions|someone with higher position/.test(e.message)) cant.push(EXEC.id);
else if (/already muted/.test(e.message)) already.push(EXEC.id); else trySend(msg.client, msg, e.message); continue; else if (/already muted/.test(e.message)) already.push(EXEC.id); else trySend(msg.client, msg, e.message); continue;
} }
const emb = defaultEventLogEmbed(msg.guild); if (!EXEC.bot) {
emb.setTitle("You have been muted") const emb = defaultEventLogEmbed(msg.guild);
.setDescription("**Reason**\n" + reason) emb.setTitle("You have been muted")
.addField("At", defaultDateFormat(duration.invoked), true) .setDescription("**Reason**\n" + reason)
.addField("For", duration.duration?.strings.join(" ") || "Indefinite", true) .addField("At", defaultDateFormat(duration.invoked), true)
.addField("Until", duration.until ? defaultDateFormat(duration.until) : "Never", true); .addField("For", duration.duration?.strings.join(" ") || "Indefinite", true)
EXEC.createDM().then(r => trySend(msg.client, r, emb)); .addField("Until", duration.until ? defaultDateFormat(duration.until) : "Never", true);
EXEC.createDM().then(r => trySend(msg.client, r, emb));
}
} }
infractionToDoc.executed = muted; infractionToDoc.executed = muted;
infractionToDoc.aborted = already; infractionToDoc.aborted = already;
infractionToDoc.failed = cant; infractionToDoc.failed = cant;
if (muted.length > 0) msg.guild.addInfraction(infractionToDoc); if (muted.length > 0) await msg.guild.addInfraction(infractionToDoc);
const NAME = msg.guild.id + "/" + infractionToDoc.infraction, const NAME = msg.guild.id + "/" + infractionToDoc.infraction,
newUnmuteSchedule = { newUnmuteSchedule = {

View file

@ -31,7 +31,7 @@ async function detonate(msg, data) {
const pleaseWait = await trySend(msg.client, msg, `Setting up for ${map.length} channel${map.length < 2 ? "" : "s"}... This message will be edited when done.`); const pleaseWait = await trySend(msg.client, msg, `Setting up for ${map.length} channel${map.length < 2 ? "" : "s"}... This message will be edited when done.`);
data.permissions = 0; data.permissions = 0;
const ROLE = await msg.guild.roles.create({ data: data, reason: "Create Mute Role" }).catch(() => { }); const ROLE = await msg.guild.roles.create({ data: data, reason: "Create Mute Role" }).catch(() => { });
msg.guild.DB.moderation.settings.mute.role = ROLE.id; msg.guild.DB.settings.mute.role = ROLE.id;
let cant = []; let cant = [];
if (ROLE) { if (ROLE) {
for (const U of map) { for (const U of map) {

View file

@ -9,7 +9,7 @@ const { Message, User } = require("discord.js");
* @param {string} reason * @param {string} reason
*/ */
module.exports = (msg, targetUsers, punishment, reason) => { module.exports = (msg, targetUsers, punishment, reason) => {
let infractionCase = msg.guild.DB.moderation.infractions?.length; let infractionCase = msg.guild.DB.infractions.size;
return { return {
infraction: infractionCase ? infractionCase++ : 1, infraction: infractionCase ? infractionCase++ : 1,
by: targetUsers, by: targetUsers,

View file

@ -8,7 +8,7 @@ module.exports = (msg, arg) => {
if (!msg.member.isAdmin) return trySend(msg.client, msg, msg.author + " you're not an Administrator <:nekohmLife:846371737644957786>"); if (!msg.member.isAdmin) return trySend(msg.client, msg, msg.author + " you're not an Administrator <:nekohmLife:846371737644957786>");
const args = parseDash(arg); const args = parseDash(arg);
let setEmb = defaultImageEmbed(msg, null, "Mute Configuration"), let setEmb = defaultImageEmbed(msg, null, "Mute Configuration"),
MUTE = msg.guild.DB.moderation.settings.mute || {}, MUTE = msg.guild.DB.settings.mute || {},
duration, duration,
role, role,
resultMsg = ""; resultMsg = "";
@ -22,18 +22,18 @@ module.exports = (msg, arg) => {
continue; continue;
} }
if (key?.length > 0) role = getRole(msg.guild, key)?.id; if (key?.length > 0) role = getRole(msg.guild, key)?.id;
if (role === undefined) resultMsg += `No role found for: **${ARG}**\n`; else msg.guild.DB.moderation.settings.mute.role = role; if (role === undefined) resultMsg += `No role found for: **${ARG}**\n`; else msg.guild.DB.settings.mute.role = role;
} }
if (ARG.startsWith("d ")) { if (ARG.startsWith("d ")) {
const D = ARG.slice(2).trim(); const D = ARG.slice(2).trim();
console.log(D); console.log(D);
if (/^[\-\+]?\d{1,16}(?![^ymwdhs])[ymwdhs]?o?/i.test(D)) { if (/^[\-\+]?\d{1,16}(?![^ymwdhs])[ymwdhs]?o?/i.test(D)) {
duration = fn.duration(msg.createdAt, D); duration = fn.duration(msg.createdAt, D);
msg.guild.DB.moderation.settings.mute.defaultDuration = duration; msg.guild.DB.settings.mute.defaultDuration = duration;
} else resultMsg += "Valid duration format: `number_[y|mo|w|d|h|m|s]`. Example: `69y420w5m72s3mo`"; } else resultMsg += "Valid duration format: `number_[y|mo|w|d|h|m|s]`. Example: `69y420w5m72s3mo`";
} }
} }
MUTE = msg.guild.DB.moderation.settings.mute; MUTE = msg.guild.DB.settings.mute;
msg.guild.setDb(msg.guild.DB); msg.guild.setDb(msg.guild.DB);
} }

View file

@ -19,6 +19,7 @@ module.exports = class unmute extends commando.Command {
} }
async run(msg, arg) { async run(msg, arg) {
if (!msg.guild.DB) await msg.guild.dbLoad();
msg.channel.startTyping(); msg.channel.startTyping();
if (!arg) return trySend(msg.client, msg, this.details); if (!arg) return trySend(msg.client, msg, this.details);
const args = parseDoubleDash(arg), const args = parseDoubleDash(arg),
@ -38,23 +39,24 @@ module.exports = class unmute extends commando.Command {
for (const USER of targetUsers) { for (const USER of targetUsers) {
if (!USER.DB) await USER.dbLoad(); if (!USER.DB) await USER.dbLoad();
const L = USER.getMutedIn(msg.guild.id);
if (!L.data) { notMuted.push(USER.id); continue } else { await USER.unmute(msg.guild, msg.member, reason)
await USER.unmute(msg.guild, msg.member, reason) .then(() => {
.then(() => { success.push(USER.id);
success.push(USER.id); if (!USER.bot) {
const emb = defaultEventLogEmbed(msg.guild); const emb = defaultEventLogEmbed(msg.guild);
emb.setTitle("You have been unmuted") emb.setTitle("You have been unmuted")
.setDescription("**Reason**\n" + reason); .setDescription("**Reason**\n" + reason);
USER.createDM().then(r => trySend(msg.client, r, emb)); USER.createDM().then(r => trySend(msg.client, r, emb));
}) }
.catch((e) => { })
console.log(e); cant.push(USER.id) .catch((e) => {
}); console.log(e);
} if (/isn't muted in/.test(e.message)) return notMuted.push(USER.id);
cant.push(USER.id)
});
} }
let emb = defaultImageEmbed(msg, null, "Unmute"); let emb = defaultImageEmbed(msg, null, "Unmute");

View file

@ -16,7 +16,7 @@ module.exports = class servav extends commando.Command {
description: "Show server avatar." description: "Show server avatar."
}); });
} }
run(msg, arg) { async run(msg, arg) {
if (!msg.author.DB) await msg.author.dbLoad(); if (!msg.author.DB) await msg.author.dbLoad();
if (msg.guild && !msg.guild.DB) await msg.guild.dbLoad(); if (msg.guild && !msg.guild.DB) await msg.guild.dbLoad();
const server_ID = arg.split(/ +/)[0]; const server_ID = arg.split(/ +/)[0];

View file

@ -29,13 +29,13 @@ module.exports = class quoteotd extends commando.Command {
if (startW.startsWith('c ')) { if (startW.startsWith('c ')) {
data = arr.slice('c '.length).trim(); data = arr.slice('c '.length).trim();
const CHAN = getChannel(msg, data, ["category", "voice"]); const CHAN = getChannel(msg, data, ["category", "voice"]);
msg.guild.DB.settings.quoteOTD.channel = CHAN.id; msg.guild.DB.quoteOTD.channel = CHAN.id;
result += `Channel set: **${CHAN.name}**\n`; result += `Channel set: **${CHAN.name}**\n`;
continue; continue;
} }
if (startW.startsWith('t ')) { if (startW.startsWith('t ')) {
data = arr.slice('t '.length).trim(); data = arr.slice('t '.length).trim();
msg.guild.DB.settings.quoteOTD.footerText = data; msg.guild.DB.quoteOTD.footerText = data;
result += `Footer text set: \`${data}\`\n`; result += `Footer text set: \`${data}\`\n`;
continue; continue;
} }
@ -45,7 +45,7 @@ module.exports = class quoteotd extends commando.Command {
result += 'Invalid icon URL provided!\n'; result += 'Invalid icon URL provided!\n';
continue; continue;
} else { } else {
msg.guild.DB.settings.quoteOTD.footerIcon = data; msg.guild.DB.quoteOTD.footerIcon = data;
result += `Footer icon set!\n`; result += `Footer icon set!\n`;
continue; continue;
} }

View file

@ -17,7 +17,7 @@ module.exports = class setfootq extends commando.Command {
} }
async run(msg, args) { async run(msg, args) {
try { try {
let oldQ = msg.guild ? msg.guild.DB.settings.defaultEmbed : msg.author.DB.defaultEmbed; let oldQ = msg.guild ? msg.guild.DB.defaultEmbed : msg.author.DB.defaultEmbed;
if (!oldQ) oldQ = {}; if (!oldQ) oldQ = {};
const newQ = oldQ?.footerQuote; const newQ = oldQ?.footerQuote;
oldQ.footerQuote = args.trim(); oldQ.footerQuote = args.trim();

View file

@ -9,10 +9,13 @@ class TimedPunishment {
* @param {{userID: string, duration: { invoked: DateTime, interval: Interval, until: DateTime, duration: { "object": DurationObject, strings: string[] } }, infraction: number, type: "ban" | "mute"}} data * @param {{userID: string, duration: { invoked: DateTime, interval: Interval, until: DateTime, duration: { "object": DurationObject, strings: string[] } }, infraction: number, type: "ban" | "mute"}} data
*/ */
constructor(data = {}) { constructor(data = {}) {
this.userID = data.userID; this.userID = data?.userID;
this.duration = data.duration || {}; /**
this.infraction = data.infraction; * @type {{ invoked: DateTime, interval: Interval, until: DateTime, duration: { "object": DurationObject, strings: string[] } }}
this.type = data.type; */
this.duration = data?.duration || {};
this.infraction = data?.infraction;
this.type = data?.type;
} }
setUserID(ID) { setUserID(ID) {

View file

@ -12,8 +12,8 @@ const { GuildMember } = require("discord.js"),
* @returns * @returns
*/ */
module.exports = (member) => { module.exports = (member) => {
if (member.guild.DB.settings.eventChannels?.join) { if (member.guild.DB.eventChannels?.join) {
const log = getChannel(member, member.guild.DB.settings.eventChannels.join); const log = getChannel(member, member.guild.DB.eventChannels.join);
if (!log) return; if (!log) return;
const emb = defaultEventLogEmbed(member.guild); const emb = defaultEventLogEmbed(member.guild);
emb emb

View file

@ -12,8 +12,8 @@ Settings.defaultZone = "utc";
* @returns * @returns
*/ */
module.exports = (member) => { module.exports = (member) => {
if (member.guild.DB.settings.eventChannels?.leave) { if (member.guild.DB.eventChannels?.leave) {
const log = getChannel(member, member.guild.DB.settings.eventChannels.leave); const log = getChannel(member, member.guild.DB.eventChannels.leave);
if (!log) return; if (!log) return;
const emb = defaultEventLogEmbed(member.guild), const emb = defaultEventLogEmbed(member.guild),
RO = member.roles.cache.sort((a, b) => b.position - a.position).map(r => r.id).slice(0, -1), RO = member.roles.cache.sort((a, b) => b.position - a.position).map(r => r.id).slice(0, -1),

View file

@ -10,7 +10,7 @@ const getColor = require("../getColor");
* @returns * @returns
*/ */
module.exports = (memberold, membernew) => { module.exports = (memberold, membernew) => {
if (!membernew.guild.DB.settings.eventChannels?.memberRole && !membernew.guild.DB.settings.eventChannels?.member) { if (!membernew.guild.DB.eventChannels?.memberRole && !membernew.guild.DB.eventChannels?.member) {
if (membernew.user.DB.cachedAvatarURL != membernew.user.displayAvatarURL({ format: "png", size: 4096, dynamic: true })) { if (membernew.user.DB.cachedAvatarURL != membernew.user.displayAvatarURL({ format: "png", size: 4096, dynamic: true })) {
membernew.user.DB.cachedAvatarURL = membernew.user.displayAvatarURL({ format: "png", size: 4096, dynamic: true }); membernew.user.DB.cachedAvatarURL = membernew.user.displayAvatarURL({ format: "png", size: 4096, dynamic: true });
}; };
@ -22,8 +22,8 @@ module.exports = (memberold, membernew) => {
emb.setTitle("Profile `" + memberold.user.tag + "` updated") emb.setTitle("Profile `" + memberold.user.tag + "` updated")
.setColor(getColor("blue")); .setColor(getColor("blue"));
if (oldAV) thumbMes += "This embed's thumbnail is the user's old avatar.\n"; if (oldAV) thumbMes += "This embed's thumbnail is the user's old avatar.\n";
if (membernew.guild.DB.settings.eventChannels?.memberRole) { if (membernew.guild.DB.eventChannels?.memberRole) {
log = getChannel(membernew, membernew.guild.DB.settings.eventChannels.memberRole); log = getChannel(membernew, membernew.guild.DB.eventChannels.memberRole);
if (membernew.roles.cache.size > memberold.roles.cache.size) { if (membernew.roles.cache.size > memberold.roles.cache.size) {
emb.addField("Role added", ("<@&" + membernew.roles.cache.difference(memberold.roles.cache).sort((a, b) => b.position - a.position).map(r => r.id).join(">, <@&") + ">").slice(0, 2048)) emb.addField("Role added", ("<@&" + membernew.roles.cache.difference(memberold.roles.cache).sort((a, b) => b.position - a.position).map(r => r.id).join(">, <@&") + ">").slice(0, 2048))
.setDescription("**Old roles**\n" + (memberold.roles.cache.size > 1 ? "<@&" + memberold.roles.cache.sort((a, b) => b.position - a.position).map(r => r.id).slice(0, -1).join(">, <@&") + ">" : "`[NONE]`")); .setDescription("**Old roles**\n" + (memberold.roles.cache.size > 1 ? "<@&" + memberold.roles.cache.sort((a, b) => b.position - a.position).map(r => r.id).slice(0, -1).join(">, <@&") + ">" : "`[NONE]`"));
@ -33,8 +33,8 @@ module.exports = (memberold, membernew) => {
.setDescription("**Current roles**\n" + (membernew.roles.cache.size > 1 ? "<@&" + membernew.roles.cache.sort((a, b) => b.position - a.position).map(r => r.id).slice(0, -1).join(">, <@&") + ">" : "`[NONE]`")); .setDescription("**Current roles**\n" + (membernew.roles.cache.size > 1 ? "<@&" + membernew.roles.cache.sort((a, b) => b.position - a.position).map(r => r.id).slice(0, -1).join(">, <@&") + ">" : "`[NONE]`"));
} }
} }
if (membernew.guild.DB.settings.eventChannels?.member && membernew.roles.cache.size === memberold.roles.cache.size) { if (membernew.guild.DB.eventChannels?.member && membernew.roles.cache.size === memberold.roles.cache.size) {
log = getChannel(membernew, membernew.guild.DB.settings.eventChannels.member); log = getChannel(membernew, membernew.guild.DB.eventChannels.member);
if (membernew.displayName !== memberold.displayName) { if (membernew.displayName !== memberold.displayName) {
emb.addField("Nickname", "Changed from `" + memberold.displayName + "` to `" + membernew.displayName + "`"); emb.addField("Nickname", "Changed from `" + memberold.displayName + "` to `" + membernew.displayName + "`");
} }

View file

@ -11,11 +11,11 @@ const getColor = require("../getColor");
*/ */
module.exports = async (msg) => { module.exports = async (msg) => {
if (msg.partial) return; if (msg.partial) return;
const ignored = msg.guild.DB.settings.eventChannels.mesDel?.ignore?.includes(msg.channel.id) ?? false; const ignored = msg.guild.DB.eventChannels.mesDel?.ignore?.includes(msg.channel.id) ?? false;
let check = false; let check = false;
if (msg.channel.id === msg.guild.DB.settings.eventChannels.mesDel?.channel && msg.author ? msg.author !== msg.client.user : false && ignored === false) check = true; if (msg.channel.id === msg.guild.DB.eventChannels.mesDel?.channel && msg.author ? msg.author !== msg.client.user : false && ignored === false) check = true;
if (msg.guild.DB.settings.eventChannels.mesDel?.channel !== msg.channel.id && ignored === false || check) { if (msg.guild.DB.eventChannels.mesDel?.channel !== msg.channel.id && ignored === false || check) {
const log = getChannel(msg, msg.guild.DB.settings.eventChannels.mesDel?.channel); const log = getChannel(msg, msg.guild.DB.eventChannels.mesDel?.channel);
if (!log || !msg.author) return; if (!log || !msg.author) return;
const emb = defaultEventLogEmbed(msg.guild); const emb = defaultEventLogEmbed(msg.guild);
emb.setColor(getColor("yellow")) emb.setColor(getColor("yellow"))

View file

@ -14,11 +14,11 @@ module.exports = async (msgold, msgnew) => {
if (msgnew.partial) msgnew = await msgnew.fetch(); if (msgnew.partial) msgnew = await msgnew.fetch();
if (msgnew.partial) return; if (msgnew.partial) return;
if (msgnew.content === msgold.content) return; if (msgnew.content === msgold.content) return;
const ignored = msgnew.guild.DB.settings.eventChannels.mesEd?.ignore?.includes(msgnew.channel.id) || false; const ignored = msgnew.guild.DB.eventChannels.mesEd?.ignore?.includes(msgnew.channel.id) || false;
let check = false; let check = false;
if (msgnew.channel.id === msgnew.guild.DB.settings.eventChannels.mesEd?.channel && msgnew.author ? msgnew.author !== msgnew.client.user : false && ignored === false) check = true; if (msgnew.channel.id === msgnew.guild.DB.eventChannels.mesEd?.channel && msgnew.author ? msgnew.author !== msgnew.client.user : false && ignored === false) check = true;
if (msgnew.guild.DB.settings.eventChannels.mesEd?.channel !== msgnew.channel.id && ignored === false || check) { if (msgnew.guild.DB.eventChannels.mesEd?.channel !== msgnew.channel.id && ignored === false || check) {
const log = getChannel(msgnew, msgnew.guild.DB.settings.eventChannels.mesEd?.channel); const log = getChannel(msgnew, msgnew.guild.DB.eventChannels.mesEd?.channel);
if (!log || !msgnew.author) return; if (!log || !msgnew.author) return;
const emb = defaultEventLogEmbed(msgnew.guild); const emb = defaultEventLogEmbed(msgnew.guild);
emb emb

View file

@ -439,7 +439,7 @@ function defaultEventLogEmbed(guild) {
.setColor(getColor(C.displayColor)) .setColor(getColor(C.displayColor))
.setAuthor(guild.name) .setAuthor(guild.name)
.setFooter((guild.DB?.settings?.defaultEmbed?.footerQuote ? .setFooter((guild.DB?.settings?.defaultEmbed?.footerQuote ?
guild.DB.settings.defaultEmbed.footerQuote : ""), guild.iconURL({ format: "png", size: 128, dynamic: true })) guild.DB.defaultEmbed.footerQuote : ""), guild.iconURL({ format: "png", size: 128, dynamic: true }))
.setTimestamp(new Date()); .setTimestamp(new Date());
} }
@ -511,7 +511,7 @@ async function getUser(msg, key, inGuild = false) {
if (/^\d{17,19}$/.test(use)) { if (/^\d{17,19}$/.test(use)) {
const ret = msg.client.users.cache.get(use); const ret = msg.client.users.cache.get(use);
if (ret) return ret; else return msg.client.users.fetch(use); if (ret) return ret; else return msg.client.users.fetch(use);
} else if (inGuild) return getMember(msg.guild, use)?.[0].user; } else if (inGuild) return getMember(msg.guild, use)[0]?.user;
} }
function getRole(guild, key) { function getRole(guild, key) {

View file

@ -14,46 +14,33 @@ Structures.extend("Guild", u => {
async dbLoad() { async dbLoad() {
return database.collection("Guild").findOne({ document: this.id }).then((r, e) => { return database.collection("Guild").findOne({ document: this.id }).then((r, e) => {
if (e) return errLog(e, null, this.client); if (e) return errLog(e, null, this.client);
r = r?.DB;
if (!r) r = {}; if (!r) r = {};
if (!r.eventChannels) r.eventChannels = {};
if (!r.settings) r.settings = {}; if (!r.settings) r.settings = {};
if (!r.moderation) r.moderation = {};
if (!r.settings.eventChannels) r.settings.eventChannels = {};
if (!r.moderation.settings) r.moderation.settings = {};
let infractions = new Map(), let infractions = new Map(),
timedPunishments = new Map(); timedPunishments = new Map();
if (r.moderation.infractions) if (r.infractions)
for (const U in r.moderation.infractions) for (const U in r.infractions)
infractions.set(U, r.moderation.infractions[U]); infractions.set(U, r.infractions[U]);
if (r.moderation.timedPunishments) if (r.timedPunishments)
for (const U in r.moderation.timedPunishments) for (const U in r.timedPunishments) {
timedPunishments.set(U, new TimedPunishment(r.moderation.timedPunishments[U])); const tr = new TimedPunishment(r.timedPunishments[U]);
r.moderation.infractions = infractions; console.log(timedPunishments.set(U, tr));
r.moderation.timedPunishments = timedPunishments; }
r.infractions = infractions;
r.timedPunishments = timedPunishments;
return this.DB = r; return this.DB = r;
}); });
} }
async setDb(Db, empty = false) { async setDb(query, set) {
if (typeof Db !== "object") throw new TypeError("Expected 'object'; Got '" + typeof Db + "'"); return database.collection("Guild").updateOne({ document: this.id }, { $set: { [query]: set }, $setOnInsert: { document: this.id } },
if (Db === {} && !empty) throw new TypeError("Empty!");
return database.collection("Guild").updateOne({ document: this.id }, { $set: { DB: Db }, $setOnInsert: { document: this.id } },
{ upsert: true }).then((r, e) => { { upsert: true }).then((r, e) => {
if (e) return errLog(e, null, this.client); if (e) return errLog(e, null, this.client);
return this.DB = Db; return this.DB[query] = set;
}); });
} }
/**
* @param {object} data - Data to set
* @returns
*/
async refreshDb(data) {
if (!this.DB) await this.dbLoad();
if (data) for (const D in data) if (this.DB[D]) this.DB[D] = data[D];
return this.setDb(this.DB);
}
/** /**
* Get user infractions * Get user infractions
* @param {string} userID - User ID * @param {string} userID - User ID
@ -61,7 +48,7 @@ Structures.extend("Guild", u => {
*/ */
async getInfractions(userID) { async getInfractions(userID) {
let ret = [] let ret = []
for (const [k, v] of this.DB.moderation.infractions) for (const [k, v] of this.DB.infractions)
if (v.by.map(r => r.id).includes(userID)) ret.push(v); if (v.by.map(r => r.id).includes(userID)) ret.push(v);
return ret; return ret;
} }
@ -69,42 +56,46 @@ Structures.extend("Guild", u => {
async addInfraction(add) { async addInfraction(add) {
try { try {
if (!this.DB) await this.dbLoad(); if (!this.DB) await this.dbLoad();
this.DB.moderation.infractions.set(add.infraction, add); console.log("SETTING INF");
return this.setDb(this.DB); const ret = this.DB.infractions.set(add.infraction, add);
console.log(ret);
await this.setDb("infractions", this.DB.infractions);
return ret;
} catch (e) { } } catch (e) { }
} }
async setQuoteOTD(set) { async setQuoteOTD(set) {
if (!this.DB) await this.dbLoad(); if (!this.DB) await this.dbLoad();
this.DB.settings.quoteOTD = set; this.DB.quoteOTD = set;
return this.setDb(this.DB); return this.setDb("quoteOTD", this.DB.quoteOTD);
} }
async setEventChannels(set) { async setEventChannels(set) {
if (!this.DB) await this.dbLoad(); if (!this.DB) await this.dbLoad();
this.DB.settings.eventChannels = set; this.DB.eventChannels = set;
return this.setDb(this.DB); return this.setDb("eventChannels", this.DB.eventChannels);
} }
async setDefaultEmbed(set) { async setDefaultEmbed(set) {
if (!this.DB) await this.dbLoad(); if (!this.DB) await this.dbLoad();
this.DB.settings.defaultEmbed = set; this.DB.defaultEmbed = set;
return this.setDb(this.DB); return this.setDb("defaultEmbed", this.DB.defaultEmbed);
} }
async setModerationSettings(set) { async setModerationSettings(set) {
if (!this.DB) await this.dbLoad(); if (!this.DB) await this.dbLoad();
this.DB.moderation.settings = set; this.DB.settings = set;
return this.setDb(this.DB); return this.setDb("settings", this.DB.settings);
} }
/** /**
* @param {TimedPunishment} Punishment * @param {TimedPunishment} Punishment
* @returns {Map} * @returns {Map}
*/ */
setTimedPunishment(Punishment) { async setTimedPunishment(Punishment) {
const ret = this.DB.moderation.timedPunishments.set(Punishment.userID + "/" + Punishment.type, Punishment); console.log("SET TIMED PUNISHMENT");
this.setDb(this.DB); const ret = this.DB.timedPunishments.set(Punishment.userID + "/" + Punishment.type, Punishment);
await this.setDb("timedPunishments", this.DB.timedPunishments);
return ret; return ret;
} }
@ -114,7 +105,8 @@ Structures.extend("Guild", u => {
* @returns * @returns
*/ */
getTimedPunishment(userID, type) { getTimedPunishment(userID, type) {
return this.DB.moderation.timedPunishments.get(userID + "/" + type); console.log("GET TIMEDPUNISHMENT");
return this.DB.timedPunishments.get(userID + "/" + type);
} }
/** /**
@ -123,7 +115,7 @@ Structures.extend("Guild", u => {
*/ */
searchTimedPunishment(userID) { searchTimedPunishment(userID) {
let ret = []; let ret = [];
for (const [k, v] of this.DB.moderation.timedPunishments) if (v.userID === userID) ret.push(v); for (const [k, v] of this.DB.timedPunishments) if (v.userID === userID) ret.push(v);
return ret; return ret;
} }
@ -133,9 +125,11 @@ Structures.extend("Guild", u => {
* @param {"mute"|"ban"} type * @param {"mute"|"ban"} type
* @returns {boolean} * @returns {boolean}
*/ */
removeTimedPunishment(userID, type) { async removeTimedPunishment(userID, type) {
const ret = this.DB.moderation.timedPunishments.delete(userID + "/" + type) console.log("REMOVE TIMEDPUNISHMENT");
this.setDb(this.DB); const ret = this.DB.timedPunishments.delete(userID + "/" + type);
console.log(ret);
await this.setDb("timedPunishments", this.DB.timedPunishments);
return ret; return ret;
} }
} }
@ -151,7 +145,6 @@ Structures.extend("User", u => {
async dbLoad() { async dbLoad() {
return database.collection("User").findOne({ document: this.id }).then((r, e) => { return database.collection("User").findOne({ document: this.id }).then((r, e) => {
if (e) return errLog(e, null, this.client); if (e) return errLog(e, null, this.client);
r = r?.DB;
if (!r) r = {}; if (!r) r = {};
if (!r.F) r.F = "<:pepewhysobLife:853237646666891274>"; if (!r.F) r.F = "<:pepewhysobLife:853237646666891274>";
if (!r.cachedAvatarURL) r.cachedAvatarURL = this.displayAvatarURL({ format: "png", size: 4096, dynamic: true }); if (!r.cachedAvatarURL) r.cachedAvatarURL = this.displayAvatarURL({ format: "png", size: 4096, dynamic: true });
@ -160,48 +153,36 @@ Structures.extend("User", u => {
}); });
} }
async setDb(Db, empty = false) { async setDb(query, set) {
if (typeof Db !== "object") throw new TypeError("Expected 'object'; Got '" + typeof Db + "'"); return database.collection("User").updateOne({ document: this.id }, { $set: { [query]: set }, $setOnInsert: { document: this.id } },
if (Db === {} && !empty) throw new TypeError("Empty!");
return database.collection("User").updateOne({ document: this.id }, { $set: { DB: Db }, $setOnInsert: { document: this.id } },
{ upsert: true }).then((r, e) => { { upsert: true }).then((r, e) => {
if (e) return errLog(e, null, this.client); if (e) return errLog(e, null, this.client);
return this.DB = Db; return this.DB[query] = set;
}); });
} }
/**
* @param {object} data - Data to set
* @returns
*/
async refreshDb(data) {
if (!this.DB) await this.dbLoad();
if (data) for (const D in data) if (this.DB[D]) this.DB[D] = data[D];
return this.setDb(this.DB);
}
async setF(string) { async setF(string) {
if (!this.DB) await this.dbLoad(); if (!this.DB) await this.dbLoad();
this.DB.F = string; this.DB.F = string;
return this.setDb(this.DB); return this.setDb("F", this.DB.F);
} }
async setInteractions(count) { async setInteractions(count) {
if (!this.DB) await this.dbLoad(); if (!this.DB) await this.dbLoad();
this.DB.interactions = count; this.DB.interactions = count;
return this.setDb(this.DB); return this.setDb("interactions", this.DB.interactions);
} }
async setDescription(set) { async setDescription(set) {
if (!this.DB) await this.dbLoad(); if (!this.DB) await this.dbLoad();
this.DB.description = set; this.DB.description = set;
return this.setDb(this.DB); return this.setDb("description", this.DB.description);
} }
async setDefaultEmbed(set) { async setDefaultEmbed(set) {
if (!this.DB) await this.dbLoad(); if (!this.DB) await this.dbLoad();
this.DB.defaultEmbed = set; this.DB.defaultEmbed = set;
return this.setDb(this.DB); return this.setDb("defaultEmbed", this.DB.defaultEmbed);
} }
/** /**
@ -220,13 +201,13 @@ Structures.extend("User", u => {
} }
const MC = guild.getTimedPunishment(this.id, "mute"), const MC = guild.getTimedPunishment(this.id, "mute"),
TP = new TimedPunishment({ userID: this.id, duration: data.duration, infraction: data.infraction, type: "mute" }); TP = new TimedPunishment({ userID: this.id, duration: data.duration, infraction: data.infraction, type: "mute" });
return { set: guild.setTimedPunishment(TP), existing: MC } return { set: await guild.setTimedPunishment(TP), existing: MC }
} }
async unmute(guild, moderator, reason) { async unmute(guild, moderator, reason) {
if (!guild || !(guild instanceof Guild)) throw new TypeError("Guild is " + typeof guild); if (!guild || !(guild instanceof Guild)) throw new TypeError("Guild is " + typeof guild);
if (!guild.DB) await guild.dbLoad(); if (!guild.DB) await guild.dbLoad();
const MC = suild.getTimedPunishment(this.id, "mute"); const MC = guild.getTimedPunishment(this.id, "mute");
if (!MC) throw new Error(this.tag + " isn't muted in " + guild.name); if (!MC) throw new Error(this.tag + " isn't muted in " + guild.name);
const MEM = guild.member(this); const MEM = guild.member(this);
if (MEM) { if (MEM) {
@ -306,26 +287,14 @@ Structures.extend("GuildMember", u => {
}); });
} }
async setDb(Db, empty = false) { async setDb(query, set) {
if (typeof Db !== "object") throw new TypeError("Expected 'object'; Got '" + typeof Db + "'"); return database.collection("GuildMember").updateOne({ document: this.id }, { $set: { [query]: set }, $setOnInsert: { document: this.id } },
if (Db === {} && !empty) throw new TypeError("Empty!");
return database.collection("GuildMember").updateOne({ document: this.id }, { $set: { DB: Db }, $setOnInsert: { document: this.id } },
{ upsert: true }).then((r, e) => { { upsert: true }).then((r, e) => {
if (e) return errLog(e, null, this.client); if (e) return errLog(e, null, this.client);
return this.DB = Db; return this.DB[query] = set;
}); });
} }
/**
* @param {object} data - Data to set
* @returns
*/
async refreshDb(data) {
if (!this.DB) await this.dbLoad();
if (data) for (const D in data) if (this.DB[D]) this.DB[D] = data[D];
return this.setDb(this.DB);
}
async infractions() { async infractions() {
return this.guild.getInfractions(this.id); return this.guild.getInfractions(this.id);
} }
@ -343,21 +312,21 @@ Structures.extend("GuildMember", u => {
const ROLES = this.roles.cache.filter((r) => !r.managed).map(r => r.id); const ROLES = this.roles.cache.filter((r) => !r.managed).map(r => r.id);
if (data.saveTakenRoles && ROLES?.length > 0) { if (data.saveTakenRoles && ROLES?.length > 0) {
console.log("populating takenRoles M"); console.log("populating takenRoles M");
this.DB.takenRoles = ROLES; this.DB.muted.takenRoles = ROLES;
} }
this.DB.muteRole = this.guild.DB.moderation.settings.mute.role; this.DB.muted.muteRole = this.guild.DB.mute.role;
try { try {
if (ROLES?.length > 0) await this.roles.remove(ROLES, reason); if (ROLES?.length > 0) await this.roles.remove(ROLES, reason);
await this.roles.add(this.DB.muteRole, reason); await this.roles.add(this.DB.muted.muteRole, reason);
this.setDb(this.DB); await this.setDb("muted", this.DB.muted);
return true; return true;
} catch (e) { } catch (e) {
if (this.DB.takenRoles?.length > 0) await this.roles.add(this.DB.takenRoles, reason).catch(() => { }); if (this.DB.muted.takenRoles?.length > 0) await this.roles.add(this.DB.muted.takenRoles, reason).catch(() => { });
if (this.DB.muteRole) await this.roles.remove(this.DB.muteRole, reason).catch(() => { }); if (this.DB.muted.muteRole) await this.roles.remove(this.DB.muted.muteRole, reason).catch(() => { });
console.log("clear takenRoles M"); console.log("clear takenRoles M");
this.DB.takenRoles = []; this.DB.muted.takenRoles = [];
this.DB.muteRole = undefined; this.DB.muted.muteRole = undefined;
throw e; throw e;
} }
} }
@ -365,12 +334,12 @@ Structures.extend("GuildMember", u => {
async unmute(reason) { async unmute(reason) {
if (!this.DB) await this.dbLoad(); if (!this.DB) await this.dbLoad();
try { try {
if (this.DB.takenRoles.length > 0) await this.roles.add(this.DB.takenRoles, reason); if (this.DB.muted.takenRoles.length > 0) await this.roles.add(this.DB.muted.takenRoles, reason);
if (this.DB.muteRole) await this.roles.remove(this.DB.muteRole, reason); if (this.DB.muted.muteRole) await this.roles.remove(this.DB.muted.muteRole, reason);
console.log("clear takenRoles UM"); console.log("clear takenRoles UM");
this.DB.takenRoles = []; this.DB.muted.takenRoles = [];
this.DB.muteRole = undefined; this.DB.muted.muteRole = undefined;
this.setDb(this.DB); await this.setDb("muted", this.DB.muted);
return true; return true;
} catch (e) { } catch (e) {
throw e; throw e;