This commit is contained in:
Emily 2020-10-20 12:27:34 +11:00
parent 4ac2d2e927
commit 00bbebcf4a
32 changed files with 0 additions and 3610 deletions

View file

@ -1,162 +0,0 @@
/* eslint-disable no-unused-vars */
const { Pool } = require('pg');
const format = require('pg-format');
const { level } = require('winston');
const { pgCredentials } = require('../../config.json');
class Database {
constructor (client) {
this.client = client;
this.pool = new Pool(pgCredentials);
this.pool.on('error', err => {
this.client.logger.error('Postgres error: ' + err);
});
}
async getGuild (id) {
const res = await this.pool.query('SELECT * FROM guilds WHERE guild_id = $1;', [id]);
return res.rows[0];
}
async getMember (guild_id, user_id) {
const key = guild_id + ':' + user_id;
const res = await this.pool.query('SELECT * FROM members WHERE member_id = $1;', [key]);
return res.rows[0];
}
async getUser (id) {
const res = await this.pool.query('SELECT * FROM users WHERE user_id = $1;', [id]);
return res.rows[0];
}
async getGuildField (id, column) {
const sql = format('SELECT %I FROM guilds WHERE guild_id = $1;', column);
const query = {
text: sql,
values: [id],
rowMode: 'array'
};
const res = await this.pool.query(query);
return res.rows[0][0];
}
async getMemberField (guild_id, user_id, column) {
const key = guild_id + ':' + user_id;
const sql = format('SELECT %I FROM members WHERE member_id = $1;', column);
const query = {
text: sql,
values: [key],
rowMode: 'array'
};
const res = await this.pool.query(query);
return res.rows[0][0];
}
async getUserField (id, column) {
const sql = format('SELECT %I FROM users WHERE user_id = $1;', column);
const query = {
text: sql,
values: [id],
rowMode: 'array'
};
const res = await this.pool.query(query);
return res.rows[0][0];
}
async updateGuild (id, column, newValue) {
const sql = format('UPDATE guilds SET %I = $1 WHERE guild_id = $2;', column);
await this.pool.query(sql, [newValue, id]);
return;
}
async updateMember (guild_id, user_id, column, newValue) {
const key = guild_id + ':' + user_id;
const sql = format('UPDATE members SET %I = $1 WHERE member_id = $2;', column);
await this.pool.query(sql, [newValue, key]);
return;
}
async updateUser (id, column, newValue) {
const sql = format('UPDATE users SET %I = $1 WHERE user_id = $2;', column);
await this.pool.query(sql, [newValue, id]);
return;
}
async resetGuild (id, column) {
const regexp = /(?<=\')(.*?)(?=\')/; //eslint-disable-line no-useless-escape
const res = await this.client.db.pool.query(
'SELECT column_default FROM information_schema.columns WHERE table_name=\'guilds\' AND column_name = $1;', [column]);
const def = res.rows[0].column_default.match(regexp)[0];
await this.updateGuild(id, column, def);
return;
}
async resetMember (guild_id, user_id, column) {
const key = guild_id + ':' + user_id;
const regexp = /(?<=\')(.*?)(?=\')/; //eslint-disable-line no-useless-escape
const res = await this.client.db.pool.query(
'SELECT column_default FROM information_schema.columns WHERE table_name=\'members\' AND column_name = $1;', [column]);
const def = res.rows[0].column_default.match(regexp)[0];
await this.updateGuild(key, column, def);
return;
}
async resetUser (id, column) {
const regexp = /(?<=\')(.*?)(?=\')/; //eslint-disable-line no-useless-escape
const res = await this.client.db.pool.query(
'SELECT column_default FROM information_schema.columns WHERE table_name=\'users\' AND column_name = $1;', [column]);
const def = res.rows[0].column_default.match(regexp)[0];
await this.updateGuild(id, column, def);
return;
}
async deleteGuild (id) {
await this.pool.query('DELETE FROM guilds WHERE guild_id = $1;', [id]);
await this.pool.query('DELETE FROM members WHERE member_id LIKE $1;', [`${id}%`]);
return;
}
async deleteMember (guild_id, user_id) {
const key = guild_id + ':' + user_id;
await this.pool.query('DELETE FROM members WHERE member_id = $1;', [key]);
return;
}
async deleteUser (id) {
await this.pool.query('DELETE FROM users WHERE user_id = $1;', [id]);
await this.pool.query('DELETE FROM members WHERE member_id LIKE $1;', [`${id}%`]);
return;
}
async createGuild (id) {
const res = await this.pool.query('INSERT INTO guilds (guild_id) VALUES ($1) RETURNING *;', [id]);
return res;
}
async createMember (guild_id, user_id) {
const key = guild_id + ':' + user_id;
const res = await this.pool.query('INSERT INTO members (member_id) VALUES ($1) RETURNING *;', [key]);
return res.rows[0];
}
async createUser (id) {
const res = await this.pool.query('INSERT INTO users (user_id) VALUES ($1) RETURNING *;', [id]);
return res.rows[0];
}
}
module.exports = Database;

View file

@ -1,8 +0,0 @@
/*
* - Will work on this soon. Triggered when a mismatch between DB and Discord occurs
* For instance, when a user deletes a role that the database has stored.
*
* - Will be implemented so if Woomy fails to find a role, user, etc. with the ID stored in
* the database, database doctor is triggered. Will attempt to resolve the discrepancy, or reset
* to default
*/

View file

@ -1,147 +0,0 @@
const { MessageEmbed } = require('discord.js');
const { inspect, promisify } = require('util');
class Functions {
constructor (client) {
this.client = client;
}
userError (channel, cmd, error) {
const embed = new MessageEmbed()
.setColor('#EF5350')
.setTitle(`${cmd.help.name}:${cmd.help.category.toLowerCase()}`)
.setDescription(error)
.addField('**Usage**', cmd.help.usage)
.setFooter(`Run 'help ${cmd.help.name}' for more information.`);
channel.send(embed);
}
async getLastMessage (channel) {
const messages = await channel.messages.fetch({ limit: 2 });
return messages.last().content;
}
async awaitReply (message, question, limit = 60000) {
const filter = (m) => m.author.id === message.author.id;
await message.channel.send(question);
try {
const collected = await message.channel.awaitMessages(filter, {
max: 1,
time: limit,
errors: ['time']
});
return collected.first().content;
} catch (err) {
return false;
}
}
searchForMembers (guild, query) {
query = query.toLowerCase();
const matches = [];
let match;
try {
match = guild.members.cache.find(x => x.displayName.toLowerCase() == query);
if (!match) guild.members.cache.find(x => x.user.username.toLowerCase() == query);
} catch (err) {} //eslint-disable-line no-empty
if (match) matches.push(match);
guild.members.cache.forEach(member => {
if (
(member.displayName.toLowerCase().startsWith(query) ||
member.user.tag.toLowerCase().startsWith(query)) &&
member.id != (match && match.id)
) {
matches.push(member);
}
});
return matches;
}
findRole (input, message) {
let role;
role = message.guild.roles.cache.find(r => r.name.toLowerCase() === input.toLowerCase());
if (!role) {
role = message.guild.roles.cache.get(input.toLowerCase());
}
if (!role) return;
return role;
}
checkPermissions (command, message, member) {
const missingPerms = [];
if (member.user.bot) {
command.conf.botPerms.forEach(p => {
if (!message.channel.permissionsFor(member).has(p)) missingPerms.push(p);
});
} else {
command.conf.userPerms.forEach(p => {
if (!message.channel.permissionsFor(member).has(p)) missingPerms.push(p);
});
}
if (missingPerms.length > 0) return missingPerms;
}
intBetween (min, max) {
return Math.round((Math.random() * (max - min) + min));
}
isDeveloper (id) {
if (this.client.config.ownerIDs.includes(id)) {
return true;
} else {
return false;
}
}
shutdown () {
const exitQuotes = [
'Shutting down.',
'I don\'t blame you.',
'I don\'t hate you.',
'Whyyyyy',
'Goodnight.',
'Goodbye'
];
this.client.db.pool.end().then(() => {
this.client.logger.info('Connection to database closed.');
});
this.client.destroy();
console.log(exitQuotes);
}
async clean (text) {
if (text && text.constructor.name === 'Promise') {
text = await text;
}
if (typeof text !== 'string') {
text = inspect(text, { depth: 1});
}
text = text
.replace(/`/g, '`' + String.fromCharCode(8203))
.replace(/@/g, '@' + String.fromCharCode(8203))
.replace(this.client.token, 'mfa.VkO_2G4Qv3T--NO--lWetW_tjND--TOKEN--QFTm6YGtzq9PH--4U--tG0');
return text;
}
wait () {
promisify(setTimeout);
}
}
module.exports = Functions;

View file

@ -1,126 +0,0 @@
const fs = require('fs');
class CommandHandler {
constructor (client) {
this.client = client;
}
load (name, category) {
try {
const path = this.client.path + '/commands/' + category + '/' + name + '.js';
const props = new (require(path))(this.client);
this.client.logger.debug(`Loading command ${category}/${name}`);
props.help.name = name;
props.help.category = category;
if (props.init) {
props.init(this.client);
}
this.client.commands.set(props.help.name, props);
this.client.cooldowns.set(props.help.name, new Map());
props.conf.aliases.forEach(alias => {
this.client.aliases.set(alias, props.help.name);
});
return;
} catch (err) {
return `Failed to load command ${name}: ${err.stack}`;
}
}
loadAll () {
const commandDirectories = fs.readdirSync('./commands/');
this.client.logger.debug(`Found ${commandDirectories.length} command directories.`);
commandDirectories.forEach((dir) => {
const commandFiles = fs.readdirSync('./commands/' + dir + '/');
commandFiles.filter((cmd) => cmd.split('.').pop() === 'js').forEach((cmd) => {
cmd = cmd.substring(0, cmd.length - 3);
const resp = this.load(cmd, dir);
if (resp) {
this.client.logger.error(resp);
}
});
});
this.client.logger.info(`Loaded a total of ${this.client.commands.size} commands.`);
}
unload (name, category) {
const path = this.client.path + '/commands/' + category + '/' + name + '.js';
let command;
if (this.client.commands.has(name)) {
command = this.client.commands.get(name);
} else if (this.client.aliases.has(name)) {
command = this.client.commands.get(this.client.aliases.get(name));
}
if (!command) return `\`${name}\` does not exist as a command or an alias.`;
this.client.logger.debug(`Unloading command ${category}/${name}`);
for (const alias of command.conf.aliases) this.client.aliases.delete(alias);
this.client.commands.delete(command.help.name);
delete require.cache[require.resolve(path)];
return;
}
unloadAll () {
const commandDirectories = fs.readdirSync('./commands/');
this.client.logger.debug(`Found ${commandDirectories.length} command directories.`);
commandDirectories.forEach((dir) => {
const commandFiles = fs.readdirSync('./commands/' + dir + '/');
commandFiles.filter((cmd) => cmd.split('.').pop() === 'js').forEach((cmd) => {
cmd = cmd.substring(0, cmd.length - 3);
const res = this.unload(cmd, dir);
if (res) this.client.logger.error('Command unload: ' + res);
});
});
}
}
class EventHandler {
constructor (client) {
this.client = client;
}
load (name) {
try {
this.client.logger.debug(`Loading event ${name}`);
const path = this.client.path + '/events/' + name + '.js';
const event = new (require(path))(this.client);
this.client.on(name, (...args) => event.run(...args));
delete require.cache[require.resolve(path)];
return;
} catch (err) {
return `Failed to load event ${name}: ${err}`;
}
}
loadAll () {
const eventFiles = fs.readdirSync(this.client.path + '/events');
eventFiles.forEach(file => {
const name = file.split('.')[0];
const resp = this.load(name);
if (resp) {
this.client.logger.error(resp);
}
});
}
// TO-DO: EVENT UNLOADING/RELOADING
}
module.exports = {
CommandHandler: CommandHandler,
EventHandler: EventHandler
};

View file

@ -1,53 +0,0 @@
const { createLogger, format, transports, addColors } = require('winston');
const fmt = format.printf(({ level, message, timestamp }) => {
return '[' + timestamp + '] ' + level + ' ' + message;
});
const customLevels = {
levels: {
debug: 0,
cmd: 1,
info: 2,
ready: 3,
warn: 4,
error: 5
},
colours: {
debug: 'black magentaBG',
cmd: 'black whiteBG',
info: 'black cyanBG',
ready: 'black greenBG',
warn: 'black yellowBG',
error: 'black redBG'
}
};
const logger = createLogger({
levels: customLevels.levels,
level: 'error',
format: format.combine(
format.timestamp({
format: 'YYYY-MM-DD hh:mm:ss'
}),
fmt
),
transports: [
new transports.Console({
level: 'error',
format: format.combine(
format.timestamp({
format: 'YYYY-MM-DD hh:mm:ss'
}),
format.colorize(),
fmt
)
})
]
});
addColors(customLevels.colours);
module.exports = logger;

View file

@ -1,15 +0,0 @@
// YEAH IM EXTENDING PROTOTYPES FUCK YOU
String.prototype.toProperCase = function () {
return this.replace(/([^\W_]+[^\s-]*) */g, function (txt) {return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
Array.prototype.random = function () {
return this[Math.floor(Math.random() * this.length)];
};
Array.prototype.remove = function (element) {
const index = this.indexOf(element);
if (index !== -1) this.splice(index, 1);
return this;
};

View file

@ -1 +0,0 @@
// postgres schemas so i can remember them