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,23 +0,0 @@
class Command {
constructor (client, {
name = null,
description = 'No description provided.',
category = 'Miscellaneous',
usage = 'No usage provided.',
parameters = '',
examples = '',
enabled = true,
guildOnly = false,
devOnly = false,
aliases = new Array(),
userPerms = new Array(),
botPerms = new Array (),
cooldown = 2000
}) {
this.client = client;
this.conf = { enabled, guildOnly, devOnly, aliases, userPerms, botPerms, cooldown };
this.help = { name, description, category, usage, parameters, examples };
}
}
module.exports = Command;

View file

@ -1,92 +0,0 @@
const Command = require('../../base/Command.js');
class Blacklist extends Command {
constructor (client) {
super(client, {
description: 'Add and remove users from the blacklist, preventing them from using commands in this server.',
usage: '`blacklist [add <user> | remove <user>]`',
examples: '`blacklist`\n`blacklist add @annoyinguser123`\n`blacklist remove @cooluser456`',
userPerms: ['ADMINISTRATOR'],
guildOnly: true
});
}
async run (message, [action, ...user], data) { // eslint-disable-line no-unused-vars
if (!action) {
return;
} else {
if (!user) return message.channel.send(
'You didn\'t specify a user!'
);
let member = message.mentions.users.first();
if (!member && message.guild) {
member = this.client.functions.searchForMembers(message.guild, user);
if (member.length > 1) {
return message.channel.send(
'Found multiple users, please be more specific or @mention the user instead.'
);
}
if (member.length < 1) {
return message.channel.send(
'Specified user couldn\'t be found, check for typing errors.'
);
}
}
member = member[0];
const array = data.guild.blacklist;
action = action.toLowerCase();
if (action === 'add') {
if (member.user.id === message.guild.owner.id) return message.channel.send(
'You can\'t add the owner to the blocklist!'
);
if (member.roles.highest.position >= message.guild.member(message.author).roles.highest.position && message.author.id !== message.guild.ownerID) {
return message.channel.send(
'You can\'t add people higher ranked than yourself to the blocklist!'
);
}
if (array.includes(member.user.id)) return message.channel.send(
'This user has already been blacklisted.'
);
array.push(member.user.id);
await this.client.db.updateGuild(message.guild.id, 'blacklist', array);
return message.channel.send(
`Added \`${member.user.tag}\` to the blocklist.`
);
}
if (action === 'remove') {
if (member.roles.highest.position >= message.guild.member(message.author).roles.highest.position && message.author.id !== message.guild.ownerID) {
return message.channel.send(
'You can\'t remove people higher ranked than yourself from the blocklist!'
);
}
if (!array.includes(member.user.id)) return message.channel.send(
'This user isn\'t blacklisted.'
);
array.remove(member.user.id);
await this.client.db.updateGuild(message.guild.id, 'blacklist', array);
return message.channel.send(
`Removed \`${member.user.tag}\` from the blocklist.`
);
}
}
}
}
module.exports = Blacklist;

View file

@ -1,90 +0,0 @@
const Command = require('../../base/Command.js');
class Disable extends Command {
constructor (client) {
super(client, {
description: 'Disables a command/category so they can\'t be used in this server.',
usage: '`disable command [command]` - Disables the specified command.\n`disable category [category]` - Disables the specified category.',
examples: '`disable command cuddle`\n`disable category music`',
userPerms: ['ADMINISTRATOR'],
guildOnly: true
});
}
async run (message, args, data) {
const essentialCategories = [
'Configuration',
'Developer'
];
const essentialCommands = [
'help'
];
if (!args[0]) {
return;
} else {
if (!args[1]) return message.channel.send(
'You didn\'t specify a command/category to disable!'
);
if (args[0] === 'command') {
const array = data.guild.disabledcommands;
const name = args[1].toLowerCase();
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 message.channel.send(
`\`${args[0]}\` does not exist as a command or an alias.`
);
if (essentialCategories.includes(command.help.category) || essentialCommands.includes(command.help.name)) {
return message.channel.send('This command is essential, and cannot be disabled.');
}
if (array.includes(command.help.name)) return message.channel.send(
'This command has already been disabled. Use `enable` to re-enable it.'
);
array.push(command.help.name);
await this.client.db.updateGuild(message.guild.id, 'disabledcommands', array);
return message.channel.send(`Disabled command \`${name}\``);
}
if (args[0] === 'category') {
const array = data.guild.disabledcategories;
const name = args[1].toProperCase();
if (!this.client.categories.includes(name)) return message.channel.send(
'I couldn\'t find this category. Are you sure you spelt it correctly?'
);
if (essentialCategories.includes(name)) return message.channel.send(
'This category is essential, and cannot be disabled.'
);
if (array.includes(name)) return message.channel.send(
'This command has already been disabled. Use `enable` to re-enable it.'
);
array.push(name);
await this.client.db.updateGuild(message.guild.id, 'disabledcategories', array);
return message.channel.send(`Disabled category \`${name}\``);
}
}
return message.channel.send('didn\'t specify whether to disable a command or category');
}
}
module.exports = Disable;

View file

@ -1,73 +0,0 @@
const Command = require('../../base/Command.js');
class Enable extends Command {
constructor (client) {
super(client, {
description: 'Re-enables a previously disabled command/category.',
usage: '`enable command [command]` - Enables the specified command.\n`enable category [category]` - Enables the specified category.',
examples: '`enable command cuddle`\n`enable category music`',
userPerms: ['ADMINISTRATOR'],
guildOnly: true
});
}
async run (message, args, data) {
if (!args[0]) {
return;
} else {
if (!args[1]) return message.channel.send(
'You didn\'t specify a command/category to enable!'
);
if (args[0] === 'command') {
const array = data.guild.disabledcommands;
const name = args[1].toLowerCase();
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 message.channel.send(
`\`${args[0]}\` does not exist as a command or an alias.`
);
if (!array.includes(command.help.name)) return message.channel.send(
'This command isn\'t disabled.'
);
array.remove(command.help.name);
await this.client.db.updateGuild(message.guild.id, 'disabledcommands', array);
return message.channel.send(`Enabled command \`${name}\``);
}
if (args[0] === 'category') {
const array = data.guild.disabledcategories;
const name = args[1].toProperCase();
if (!this.client.categories.includes(name)) return message.channel.send(
'I couldn\'t find this category. Are you sure you spelt it correctly?'
);
if (!array.includes(name)) return message.channel.send(
'This command isn\'t disabled.'
);
array.remove(name);
await this.client.db.updateGuild(message.guild.id, 'disabledcategories', array);
return message.channel.send(`Enabled category \`${name}\``);
}
}
return message.channel.send('didn\'t specify whether to enable a command or category');
}
}
module.exports = Enable;

View file

@ -1,26 +0,0 @@
const { MessageEmbed } = require('discord.js');
const Command = require('../../base/Command.js');
class Settings extends Command {
constructor (client) {
super(client, {
description: 'View all of your server\'s settings.',
usage: 'settings',
guildOnly: true,
aliases: ['config']
});
}
async run (message, args) { // eslint-disable-line no-unused-vars
const settings = await this.client.db.getGuild(message.guild.id);
const embed = new MessageEmbed()
.setAuthor('Settings Panel', message.guild.iconURL({dynamic: true}))
.setDescription('All the settings for this server are listed below. To set a setting, use `set [setting] [what you want to set it to]')
.addFields(
{ name: '**Prefix**', value: settings.prefix }
);
}
}
module.exports = Settings;

View file

@ -1,25 +0,0 @@
const Command = require('../../base/Command.js');
class Userprefix extends Command {
constructor (client) {
super(client, {
description: 'Change the prefix you use for Woomy. This will affect servers and commands in DM\'s.',
usage: '`userprefix` <new prefix>',
examples: '`userprefix !!` - Sets your personal prefix to !!'
});
}
async run (message, args, data) { // eslint-disable-line no-unused-vars
if (!args[0]) {
return message.channel.send(
`Your prefix for Woomy is currently: \`${data.user.prefix}\``
);
}
await this.client.db.updateUser(message.author.id, 'prefix', args[0]);
message.channel.send(`Your personal prefix has been set to: \`${args[0]}\``);
}
}
module.exports = Userprefix;

View file

@ -1,17 +0,0 @@
const Command = require('../../base/Command.js');
class Help extends Command {
constructor (client) {
super(client, {
description: 'Lists what commands Woomy has, what they do, and how to use them.',
usage: '`help` - Lists all commands.\n`help <command>` - Shows detailed information on a specific command.',
aliases: ['cmds'],
});
}
async run (message, args, data) { // eslint-disable-line no-unused-vars
}
}
module.exports = Help;

View file

@ -1,24 +0,0 @@
const Command = require('../../base/Command.js');
class Ping extends Command {
constructor (client) {
super(client, {
description: 'Latency and API response times.',
usage: 'ping',
aliases: ['pong']
});
}
async run (message, args, data) { // eslint-disable-line no-unused-vars
try {
const msg = await message.channel.send('Pinging...');
msg.edit(
`Pong! \`${msg.createdTimestamp - message.createdTimestamp}ms\` (💗 \`${Math.round(this.client.ws.ping)}ms\`)`
);
} catch (err) {
this.client.logger.err(err);
}
}
}
module.exports = Ping;

View file

@ -1,37 +0,0 @@
const Command = require('../../base/Command.js');
const Discord = require('discord.js');
class Eval extends Command {
constructor (client) {
super(client, {
description: 'Evaluates arbitrary Javascript.',
usage: 'eval <expression>',
aliases: ['ev'],
permLevel: 'Bot Owner',
devOnly: true
});
}
async run (message, args, data) { // eslint-disable-line no-unused-vars
const code = args.join(' ');
try {
const evaled = eval(code);
const clean = await this.client.functions.clean(evaled);
const MAX_CHARS = 3 + 2 + clean.length + 3;
if (MAX_CHARS > 2000) {
message.channel.send({ files: [new Discord.MessageAttachment(Buffer.from(clean), 'output.txt')] });
}
message.channel.send(`\`\`\`js\n${clean}\n\`\`\``);
} catch (err) {
const e = await this.client.functions.clean(err);
const MAX_CHARS = 1 + 5 + 1 + 3 + e.length + 3;
if (MAX_CHARS > 2000) {
return message.channel.send({ files: [new Discord.MessageAttachment(Buffer.from(e), 'error.txt')] });
}
message.channel.send(`\`ERROR\` \`\`\`xl\n${e}\n\`\`\``);
}
}
}
module.exports = Eval;

View file

@ -1,38 +0,0 @@
const Command = require('../../base/Command.js');
class Reload extends Command {
constructor (client) {
super(client, {
description: 'Latency and API response times.',
usage: '`reload [command]` - Reloads the specified command.',
examples: '`reload ping`',
devOnly: true
});
}
async run (message, args, data) { // eslint-disable-line no-unused-vars
if (!args[0]) return message.channel.send('You didnt tell me what command to reload!');
let command;
if (this.client.commands.has(args[0])) {
command = this.client.commands.get(args[0]);
} else if (this.client.aliases.has(args[0])) {
command = this.client.commands.get(this.client.aliases.get(args[0]));
}
if (!command) return message.channel.send(
`\`${args[0]}\` does not exist as a command or an alias.`
);
let res = await this.client.commandHandler.unload(command.help.name, command.help.category);
if (res) return message.channel.send('Error unloading: '+ res);
res = await this.client.commandHandler.load(command.help.name, command.help.category);
if (res) return message.channel.send('Error loading: ' + res);
return message.channel.send(`Reloaded \`${args[0]}\``);
}
}
module.exports = Reload;

View file

@ -1,17 +0,0 @@
const Command = require('../../base/Command.js');
class Lastmessage extends Command {
constructor (client) {
super(client, {
description: 'Grab last message sent to a channel.',
usage: 'lastmessage',
});
}
async run (message, args, data) { // eslint-disable-line no-unused-vars
const lastMsg = await this.client.functions.getLastMessage(message.channel);
message.channel.send(lastMsg);
}
}
module.exports = Lastmessage;

View file

@ -1,36 +0,0 @@
const Command = require('../../base/Command.js');
class Msearch extends Command {
constructor (client) {
super(client, {
description: 'Lists all members found that match the input',
usage: '`msearch` [query] - Finds users in this server that match the query.`',
aliases: ['membersearch']
});
}
async run (message, args, data) { // eslint-disable-line no-unused-vars
if (!args[0]) return message.channel.send('No username provided.');
let mlist = '';
let count = 0;
this.client.functions.searchForMembers(message.guild, args[0]).forEach((member) => {
if (member) {
mlist += `\`${member.user.tag}\``;
count = count + 1;
}
mlist += '**, **';
});
mlist = mlist.substring(0, mlist.length - 6);
const mlist1 = `Found ${count} users:\n` + mlist;
if (!mlist1) return message.channel.send('No users found!');
message.channel.send(mlist1);
}
}
module.exports = Msearch;

View file

@ -1,32 +0,0 @@
const Command = require('../../base/Command.js');
class Retrieve extends Command {
constructor (client) {
super(client, {
description: 'Retrieves a key\'s value from the Postgres DB.',
usage: 'retrieve [setting]',
guildOnly: true
});
}
async run (message, args, data) { // eslint-disable-line no-unused-vars
if (!args[0]) return message.channel.send('You didn\'t specify what database to access!');
if (args[0].toLowerCase() !== 'guild' && args[0].toLowerCase() !== 'member' && args[0].toLowerCase() !== 'user') {
return message.channel.send('Invalid database. Valid databases: `guild`, `member`, `user`');
}
if (!args[1]) {
message.channel.send(
`\`\`\`js
${JSON.stringify(data[args[0]])}
\`\`\``
);
} else {
const res = data[args[0]][args[1]];
if (!res) return message.channel.send('Invalid key. Check for typing errors and try again.');
message.channel.send('```' + res + '```');
}
}
}
module.exports = Retrieve;

View file

@ -1,55 +0,0 @@
const Discord = require('discord.js');
const Command = require('../../base/Command.js');
class Avatar extends Command {
constructor (client) {
super(client, {
description: 'View a full-sized image of a person\'s profile picture.',
usage: 'avatar <user>',
examples: '`avatar` - Gets your avatar.\n`avatar emily` - Gets the avatar of the user "emily"',
aliases: ['pfp'],
botPerms: ['EMBED_LINKS']
});
}
async run (message, args, data) { // eslint-disable-line no-unused-vars
if (!args[0]) {
const embed = this.createEmbed(message.author);
return message.channel.send(embed);
}
let user = message.mentions.users.first();
if (!user && message.guild) {
user = this.client.functions.searchForMembers(message.guild, args[0]);
if (user.length > 1) {
return message.channel.send(
'Found multiple users, please be more specific or @mention the user instead.'
);
}
if (user.length < 1) {
return message.channel.send(
'Specified user couldn\'t be found, check for typing errors.'
);
}
}
user = user[0].user;
const embed = this.createEmbed(user);
return message.channel.send(embed);
}
createEmbed (user) {
const URL = user.avatarURL({format: 'png', dynamic: true, size: 2048});
const embed = new Discord.MessageEmbed()
.setTitle(user.tag)
.setDescription(`**[Avatar URL](${URL})**`)
.setImage(URL);
return embed;
}
}
module.exports = Avatar;

View file

@ -1,9 +0,0 @@
module.exports = class {
constructor (client) {
this.client = client;
}
async run (error) {
this.client.logger.log(`An error event was sent by Discord.js: \n${JSON.stringify(error)}`, 'error');
}
};

View file

@ -1,127 +0,0 @@
// The MESSAGE event runs anytime a message is received
// Note that due to the binding of client to every event, every event
// goes `client, other, args` when this function is run.
module.exports = class {
constructor (client) {
this.client = client;
}
async run (message) {
if (message.author.bot) return;
const prefixes = [];
const data = {};
data.user = await this.client.db.getUser(message.author.id);
if (!data.user) data.user = await this.client.db.createUser(message.author.id);
prefixes.push(data.user.prefix);
if (message.guild) {
data.guild = await this.client.db.getGuild(message.guild.id);
if (!data.guild) await this.client.db.createGuild(message.guild.id);
prefixes.push(data.guild.prefix);
data.member = await this.client.db.getMember(message.guild.id, message.author.id);
if (!data.member) data.member = await this.client.db.createMember(message.guild.id, message.author.id);
}
// Blacklist
if (data.guild.blacklist.includes(message.author.id)) return;
// Respond with prefixes when pinged
if (message.content === `<@${this.client.user.id}>` || message.content === `<@!${this.client.user.id}>`) {
return message.channel.send(`Hi! The server prefix is \`${data.guild.prefix}\`, and your personal prefix is \`${data.user.prefix}\`. You can also ping me ^-^`);
}
// Allow pings to be used as prefixes
prefixes.push(`<@${this.client.user.id}> `, `<@!${this.client.user.id}> `);
let prefix;
for (const thisPrefix of prefixes) {
if (message.content.startsWith(thisPrefix)) prefix = thisPrefix;
}
if (message.content.indexOf(prefix) !== 0) return;
if (prefix === `<@${this.client.user.id}> ` || prefix === `<@!${this.client.user.id}> `) {
message.prefix = '@Woomy ';
} else {
message.prefix = prefix;
}
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
// Cache uncached members
if (message.guild && !message.member) await message.guild.fetchMember(message.author);
const cmd = this.client.commands.get(command) || this.client.commands.get(this.client.aliases.get(command));
if (!cmd) return;
if (message.guild) {
if (!message.channel.permissionsFor(this.client.user).has('SEND_MESSAGES')) {
try {
return message.author.send(`I don't have permission to speak in \`#${message.channel.name}\`, Please ask a moderator to give me the send messages permission!`);
} catch (err) {} //eslint-disable-line no-empty
}
if (data.guild.disabledcommands.includes(cmd.help.name)) return message.channel.send(
'This command has been disabled by a server administrator.'
);
if (data.guild.disabledcategories.includes(cmd.help.category)) return message.channel.send(
'The category this command is apart of has been disabled by a server administrator.'
);
}
if (cmd && cmd.conf.enabled === false) {
return message.channel.send('This command has been disabled by my developers.');
}
if (cmd && cmd.conf.devOnly && this.client.functions.isDeveloper(message.author.id) !== true) {
return message.channel.send('devs only!');
}
if (cmd && !message.guild && cmd.conf.guildOnly === true) {
return message.channel.send('This command is unavailable via private message. Please run this command in a guild.');
}
// Permission handler
if (message.guild) {
const missingUserPerms = this.client.functions.checkPermissions(cmd, message, message.member);
if (missingUserPerms) return message.channel.send(`
You don't have sufficient permissions to run this command! Missing: ${missingUserPerms}
`);
const missingBotPerms = this.client.functions.checkPermissions(cmd, message, message.guild.member(this.client.user));
if (missingBotPerms) return message.channel.send(`
I can't run this command because I'm missing these permissions: ${missingBotPerms}
`);
}
// Cooldown
if (this.client.cooldowns.get(cmd.help.name).has(message.author.id)) {
const init = this.client.cooldowns.get(command).get(message.author.id);
const curr = new Date();
const diff = Math.round((curr - init) / 1000);
const time = cmd.conf.cooldown / 1000;
return message.reply(`this command is on cooldown! You'll be able to use it again in ${time - diff} seconds.`);
} else {
this.client.cooldowns.get(cmd.help.name).set(message.author.id, new Date());
setTimeout(() => {
this.client.cooldowns.get(cmd.help.name).delete(message.author.id);
}, this.client.commands.get(cmd.help.name).conf.cooldown);
}
message.flags = [];
while (args[0] &&args[0][0] === '-') {
message.flags.push(args.shift().slice(1));
}
cmd.run(message, args, data);
this.client.logger.cmd(`Command ran: ${message.content}`);
}
};

View file

@ -1,11 +0,0 @@
module.exports = class {
constructor (client) {
this.client = client;
}
async run () {
await this.client.functions.wait(1000);
this.client.user.setActivity(`BNA | v${this.client.version}`, { type: 'WATCHING' }); // lol
this.client.logger.ready(`Connected to Discord as ${this.client.user.tag}`);
}
};

View file

@ -1,74 +0,0 @@
// Copyright 2020 Emily J. / mudkipscience and contributors. Subject to the AGPLv3 license.
const { Client, Collection } = require('discord.js');
const { CommandHandler, EventHandler } = require('./util/handlers');
const Functions = require('./util/functions');
const Database = require('./util/database');
const logger = require('./util/logger');
const sentry = require('@sentry/node'); // eslint-disable-line no-unused-vars
const { readdirSync } = require('fs');
const config = require('../config.json');
const pkg = require('../package.json');
class WoomyClient extends Client {
constructor () {
super();
// Important information our bot needs to access
this.config = config;
this.path = __dirname;
this.version = pkg.version;
this.categories = readdirSync('./commands/');
// dev mode, disables some features if enabled
this.dev = false;
if (this.config.devmode === true) {
this.dev = true;
// sentry.init({ dsn: this.config.keys.sentry });
}
// Essential modules
this.logger = logger;
this.functions = new Functions(this);
this.db = new Database(this);
// collections, to store commands, their aliases and their cooldown timers in
this.commands = new Collection();
this.aliases = new Collection();
this.cooldowns = new Collection();
// Handlers, to load commands and events
this.commandHandler = new CommandHandler(this);
this.eventHandler = new EventHandler(this);
}
}
async function init () {
const client = new WoomyClient({ ws: {}});
client.logger.info(`Initializing Woomy v${client.version}`);
require('./util/prototypes');
await client.commandHandler.loadAll();
await client.eventHandler.loadAll();
if (client.dev === true) {
client.logger.warn('Development mode is enabled. Some features (such as Sentry) have been disabled.');
client.login(client.config.devtoken);
} else {
client.login(client.config.token);
}
}
init();
process.on('uncaughtException', (err) => {
const errorMsg = err.stack.replace(new RegExp(`${__dirname}/`, 'g'), './');
console.error('Uncaught Exception: ', errorMsg);
process.exit(1);
});
process.on('unhandledRejection', err => {
console.error('Uncaught Promise Error: ', err);
});

View file

@ -1,13 +0,0 @@
const discord = require('discord.js');
const config = require('../config.json');
const manager = new discord.ShardingManager('./index.js', {
totalShards: 'auto',
token: config.token
});
manager.on('shardCreate', (shard) => {
console.log('Shard ' + shard.id + ' launched');
});
manager.spawn();

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