Added command, reverted database service split

This commit is contained in:
Essem 2021-08-12 22:28:09 -05:00
parent da709c485f
commit 9f36a79a2b
No known key found for this signature in database
GPG key ID: 7D497397CC3A2A8C
20 changed files with 119 additions and 91 deletions

3
app.js
View file

@ -88,8 +88,7 @@ const Admiral = new Fleet({
},
services: [
{ name: "prometheus", path: path.join(__dirname, "./utils/services/prometheus.js") },
{ name: "image", path: path.join(__dirname, "./utils/services/image.js")},
{ name: "database", path: path.join(__dirname, "./utils/services/database.js")}
{ name: "image", path: path.join(__dirname, "./utils/services/image.js")}
]
});

View file

@ -8,7 +8,7 @@ class ChannelCommand extends Command {
if (this.args.length === 0) return "You need to provide whether I should be enabled or disabled in this channel!";
if (this.args[0] !== "disable" && this.args[0] !== "enable") return "That's not a valid option!";
const guildDB = await db(this.ipc, "getGuild", this.message.channel.guild.id);
const guildDB = await db.getGuild(this.message.channel.guild.id);
if (this.args[0].toLowerCase() === "disable") {
let channel;
@ -21,7 +21,7 @@ class ChannelCommand extends Command {
channel = this.message.channel;
}
await db(this.ipc, "disableChannel", channel);
await db.disableChannel(channel);
return `I have been disabled in this channel. To re-enable me, just run \`${guildDB.prefix}channel enable\`.`;
} else if (this.args[0].toLowerCase() === "enable") {
let channel;
@ -34,7 +34,7 @@ class ChannelCommand extends Command {
channel = this.message.channel;
}
await db(this.ipc, "enableChannel", channel);
await db.enableChannel(channel);
return "I have been re-enabled in this channel.";
}
}

View file

@ -0,0 +1,36 @@
const db = require("../../utils/database.js");
const Command = require("../../classes/command.js");
const collections = require("../../utils/collections.js");
class CommandCommand extends Command {
async run() {
if (!this.message.channel.guild) return "This command only works in servers!";
if (!this.message.member.permissions.has("administrator") && this.message.member.id !== process.env.OWNER) return "You need to be an administrator to enable/disable me!";
if (this.args.length === 0) return "You need to provide what command to enable/disable!";
if (this.args[0] !== "disable" && this.args[0] !== "enable") return "That's not a valid option!";
const guildDB = await db.getGuild(this.message.channel.guild.id);
if (this.args[0].toLowerCase() === "disable") {
if (!collections.commands.has(this.args[1].toLowerCase()) && !collections.aliases.has(this.args[1].toLowerCase())) return "That isn't a command!";
const command = collections.aliases.has(this.args[1].toLowerCase()) ? collections.aliases.get(this.args[1].toLowerCase()) : this.args[1].toLowerCase();
if (guildDB.disabled_commands && guildDB.disabled_commands.includes(command)) return "That command is already disabled!";
await db.disableCommand(this.message.channel.guild.id, command);
return `The command has been disabled. To re-enable it, just run \`${guildDB.prefix}command enable ${command}\`.`;
} else if (this.args[0].toLowerCase() === "enable") {
if (!collections.commands.has(this.args[1].toLowerCase()) && !collections.aliases.has(this.args[1].toLowerCase())) return "That isn't a command!";
const command = collections.aliases.has(this.args[1].toLowerCase()) ? collections.aliases.get(this.args[1].toLowerCase()) : this.args[1].toLowerCase();
if (guildDB.disabled_commands && !guildDB.disabled_commands.includes(command)) return "That command isn't disabled!";
await db.enableCommand(this.message.channel.guild.id, command);
return `The command \`${command}\` has been re-enabled.`;
}
}
static description = "Enables/disables a command for a server";
static aliases = ["cmd"];
static arguments = ["[enable/disable]", "[command]"];
}
module.exports = CommandCommand;

View file

@ -6,7 +6,7 @@ class CountCommand extends Command {
async run() {
if (this.message.channel.guild && !this.message.channel.permissionsOf(this.client.user.id).has("addReactions")) return "I don't have the `Add Reactions` permission!";
if (this.message.channel.guild && !this.message.channel.permissionsOf(this.client.user.id).has("embedLinks")) return "I don't have the `Embed Links` permission!";
const counts = await database(this.ipc, "getCounts");
const counts = await database.getCounts();
const countArray = [];
for (const entry of Object.entries(counts)) {
countArray.push(entry);

View file

@ -8,13 +8,13 @@ const Command = require("../../classes/command.js");
class HelpCommand extends Command {
async run() {
const { prefix } = this.message.channel.guild ? await database(this.ipc, "getGuild", this.message.channel.guild.id) : "N/A";
const { prefix } = this.message.channel.guild ? await database.getGuild(this.message.channel.guild.id) : "N/A";
const commands = collections.commands;
const aliases = collections.aliases;
if (this.args.length !== 0 && (commands.has(this.args[0].toLowerCase()) || aliases.has(this.args[0].toLowerCase()))) {
const command = aliases.has(this.args[0].toLowerCase()) ? collections.aliases.get(this.args[0].toLowerCase()) : this.args[0].toLowerCase();
const info = collections.info.get(command);
const counts = await database(this.ipc, "getCounts");
const counts = await database.getCounts();
const embed = {
"embed": {
"author": {

View file

@ -4,10 +4,10 @@ const Command = require("../../classes/command.js");
class PrefixCommand extends Command {
async run() {
if (!this.message.channel.guild) return "This command only works in servers!";
const guild = await database(this.ipc, "getGuild", this.message.channel.guild.id);
const guild = await database.getGuild(this.message.channel.guild.id);
if (this.args.length !== 0) {
if (!this.message.member.permissions.has("administrator") && this.message.member.id !== process.env.OWNER) return "You need to be an administrator to change the bot prefix!";
await database(this.ipc, "setPrefix", this.args[0], this.message.channel.guild);
await database.setPrefix(this.args[0], this.message.channel.guild);
return `The prefix has been changed to ${this.args[0]}.`;
} else {
return `The current prefix is \`${guild.prefix}\`.`;

View file

@ -7,12 +7,10 @@ class TagsCommand extends Command {
// todo: find a way to split this into subcommands
async run() {
if (!this.message.channel.guild) return "This command only works in servers!";
const guild = await database(this.ipc, "getGuild", this.message.channel.guild.id);
if ((guild.tagsDisabled || guild.tags_disabled) && this.args[0].toLowerCase() !== ("enable" || "disable")) return;
if (this.args.length === 0) return "You need to provide the name of the tag you want to view!";
const tags = await database(this.ipc, "getTags", this.message.channel.guild.id);
const blacklist = ["create", "add", "edit", "remove", "delete", "list", "random", "own", "owner", "enable", "disable"];
const tags = await database.getTags(this.message.channel.guild.id);
const blacklist = ["create", "add", "edit", "remove", "delete", "list", "random", "own", "owner"];
switch (this.args[0].toLowerCase()) {
case "create":
case "add":
@ -27,7 +25,7 @@ class TagsCommand extends Command {
if (this.args[1] === undefined) return "You need to provide the name of the tag you want to delete!";
if (!tags[this.args[1].toLowerCase()]) return "This tag doesn't exist!";
if (tags[this.args[1].toLowerCase()].author !== this.message.author.id && !this.message.member.permissions.has("manageMessages") && this.message.author.id !== process.env.OWNER) return "You don't own this tag!";
await database(this.ipc, "removeTag", this.args[1].toLowerCase(), this.message.channel.guild);
await database.removeTag(this.args[1].toLowerCase(), this.message.channel.guild);
return `The tag \`${this.args[1].toLowerCase()}\` has been deleted!`;
case "edit":
if (this.args[1] === undefined) return "You need to provide the name of the tag you want to edit!";
@ -72,11 +70,6 @@ class TagsCommand extends Command {
return paginator(this.client, this.message, embeds);
case "random":
return tags[random(Object.keys(tags))].content;
case "enable":
case "disable":
if (!this.message.member.permissions.has("manageMessages") && this.message.author.id !== process.env.OWNER) return "You don't have permission to disable tags!";
var toggleResult = await database(this.ipc, "toggleTags", this.message.channel.guild);
return `Tags for this guild have been ${toggleResult ? "disabled" : "enabled"}. To ${toggleResult ? "enable" : "disable"} them again, run ${guild.prefix}tags ${toggleResult ? "enable" : "disable"}.`;
default:
if (!tags[this.args[0].toLowerCase()]) return "This tag doesn't exist!";
return tags[this.args[0].toLowerCase()].content;
@ -86,11 +79,11 @@ class TagsCommand extends Command {
async setTag(content, name, message, edit = false) {
if ((!content || content.length === 0) && message.attachments.length === 0) return "You need to provide the content of the tag!";
if (message.attachments.length !== 0 && content) {
await database(this.ipc, edit ? "editTag" : "setTag", name, { content: `${content} ${message.attachments[0].url}`, author: message.author.id }, message.channel.guild);
await database[edit ? "editTag" : "setTag"](name, { content: `${content} ${message.attachments[0].url}`, author: message.author.id }, message.channel.guild);
} else if (message.attachments.length !== 0) {
await database(this.ipc, edit ? "editTag" : "setTag", name, { content: message.attachments[0].url, author: message.author.id }, message.channel.guild);
await database[edit ? "editTag" : "setTag"](name, { content: message.attachments[0].url, author: message.author.id }, message.channel.guild);
} else {
await database(this.ipc, edit ? "editTag" : "setTag", name, { content: content, author: message.author.id }, message.channel.guild);
await database[edit ? "editTag" : "setTag"](name, { content: content, author: message.author.id }, message.channel.guild);
}
return;
}
@ -102,8 +95,7 @@ class TagsCommand extends Command {
edit: "Edits a tag",
list: "Lists all tags in the server",
random: "Gets a random tag",
owner: "Gets the owner of a tag",
disable: "Disables/Enables the tag system"
owner: "Gets the owner of a tag"
};
static aliases = ["t", "tag", "ta"];
static arguments = {

View file

@ -4,5 +4,6 @@ const logger = require("../utils/logger.js");
// run when the bot is added to a guild
module.exports = async (client, cluster, worker, ipc, guild) => {
logger.log(`[GUILD JOIN] ${guild.name} (${guild.id}) added the bot.`);
await db(ipc, "addGuild", guild);
const guildDB = await db.getGuild(guild.id);
if (!guildDB) await db.addGuild(guild);
};

View file

@ -15,14 +15,15 @@ module.exports = async (client, cluster, worker, ipc, message) => {
if (message.channel.guild && !message.channel.permissionsOf(client.user.id).has("sendMessages")) return;
let prefixCandidate;
let guildDB;
if (message.channel.guild) {
const cachedPrefix = collections.prefixCache.get(message.channel.guild.id);
if (cachedPrefix) {
prefixCandidate = cachedPrefix;
} else {
let guildDB = await database(ipc, "getGuild", message.channel.guild.id);
guildDB = await database.getGuild(message.channel.guild.id);
if (!guildDB) {
guildDB = await database(ipc, "fixGuild", message.channel.guild);
guildDB = await database.fixGuild(message.channel.guild);
}
prefixCandidate = guildDB.prefix;
collections.prefixCache.set(message.channel.guild.id, guildDB.prefix);
@ -57,21 +58,31 @@ module.exports = async (client, cluster, worker, ipc, message) => {
preArgs.shift();
const command = rawContent.split(/\s+/g).shift().toLowerCase();
const parsed = parseCommand(preArgs);
const aliased = collections.aliases.get(command);
// don't run if message is in a disabled channel
if (message.channel.guild) {
if (collections.disabledCache.has(message.channel.guild.id)) {
const disabled = collections.disabledCache.get(message.channel.guild.id);
const disabled = collections.disabledCache.get(message.channel.guild.id);
if (disabled) {
if (disabled.includes(message.channel.id) && command != "channel") return;
} else if (message.channel.guild) {
const guildDB = await database(ipc, "getGuild", message.channel.guild.id);
} else {
guildDB = await database.getGuild(message.channel.guild.id);
collections.disabledCache.set(message.channel.guild.id, guildDB.disabled);
if (guildDB.disabled.includes(message.channel.id) && command !== "channel") return;
}
const disabledCmds = collections.disabledCmdCache.get(message.channel.guild.id);
if (disabledCmds) {
if (disabledCmds.includes(aliased ? aliased : command)) return;
} else {
guildDB = await database.getGuild(message.channel.guild.id);
collections.disabledCmdCache.set(message.channel.guild.id, guildDB.disabled_commands);
if (guildDB.disabled_commands.includes(aliased ? aliased : command)) return;
}
}
// check if command exists
const cmd = collections.commands.get(command) || collections.commands.get(collections.aliases.get(command));
// check if command exists and if it's enabled
const cmd = aliased ? collections.commands.get(aliased) : collections.commands.get(command);
if (!cmd) return;
// actually run the command
@ -88,7 +99,7 @@ module.exports = async (client, cluster, worker, ipc, message) => {
}
};
try {
await database(ipc, "addCount", collections.aliases.has(command) ? collections.aliases.get(command) : command);
await database.addCount(collections.aliases.has(command) ? collections.aliases.get(command) : command);
const startTime = new Date();
// eslint-disable-next-line no-unused-vars
const commandClass = new cmd(client, cluster, worker, ipc, message, parsed._, message.content.substring(prefix.length).trim().replace(command, "").trim(), (({ _, ...o }) => o)(parsed)); // we also provide the message content as a parameter for cases where we need more accuracy

View file

@ -1,5 +1,5 @@
const leaveHandler = require("./voiceChannelLeave.js");
module.exports = async (client, cluster, worker, ipc, member, newChannel, oldChannel) => {
await leaveHandler(client, cluster, ipc, member, oldChannel);
await leaveHandler(client, cluster, worker, ipc, member, oldChannel);
};

View file

@ -100,7 +100,7 @@ class Shard extends BaseClusterWorker {
// connect to lavalink
if (!sound.status && !sound.connected) sound.connect(this.bot);
database(this.ipc, "setup");
database.setup();
this.activityChanger();
@ -136,7 +136,7 @@ class Shard extends BaseClusterWorker {
for (const command in collections.commands) {
handler.unload(command);
}
database(this.ipc, "stop");
database.stop();
done();
}

View file

@ -27,4 +27,5 @@ exports.runningCommands = new TimedMap();
}*/
exports.prefixCache = new Map();
exports.disabledCache = new Map();
exports.disabledCache = new Map();
exports.disabledCmdCache = new Map();

View file

@ -5,8 +5,8 @@ const pool = new Pool({
});
(async () => {
console.log("Migrating tags...");
const guilds = (await pool.query("SELECT * FROM guilds")).rows;
console.log("Migrating tags...");
try {
await pool.query("CREATE TABLE tags ( guild_id VARCHAR(30) NOT NULL, name text NOT NULL, content text NOT NULL, author VARCHAR(30) NOT NULL, UNIQUE(guild_id, name) )");
} catch (e) {
@ -22,6 +22,11 @@ const pool = new Pool({
console.log(`Migrated tag ${name} in guild ${guild.guild_id}`);
}
}
console.log("Migrating disabled commands...");
for (const guild of guilds) {
await pool.query("UPDATE guilds SET disabled_commands = $1 WHERE guild_id = $2", [guild.tags_disabled ? ["tags"] : [], guild.guild_id]);
console.log(`Migrated disabled commands in guild ${guild.guild_id}`);
}
console.log("Done!");
return process.exit(0);
})();

View file

@ -1,5 +1,3 @@
// wrapper for the database service
// wrapper for the database drivers in ./database/
module.exports = async (ipc, name, ...args) => {
return ipc.command("database", { name, args }, true);
};
module.exports = require(`./database/${process.env.DB ? process.env.DB.split("://")[0] : "dummy"}.js`);

View file

@ -11,9 +11,10 @@ exports.addCount = async () => {};
exports.getCounts = async () => {
return {};
};
exports.disableCommand = async () => {};
exports.enableCommand = async () => {};
exports.disableChannel = async () => {};
exports.enableChannel = async () => {};
exports.toggleTags = async () => {};
exports.getTags = async () => {};
exports.setTag = async () => {};
exports.removeTag = async () => {};

View file

@ -37,11 +37,17 @@ exports.removeTag = async (name, guild) => {
await connection.query("DELETE FROM tags WHERE guild_id = $1 AND name = $2", [guild.id, name]);
};
exports.toggleTags = async (guild) => {
const guildDB = await this.getGuild(guild.id);
guildDB.tags_disabled = !guildDB.tags_disabled;
await connection.query("UPDATE guilds SET tags_disabled = $1 WHERE guild_id = $2", [guildDB.tags_disabled, guild.id]);
return guildDB.tags_disabled;
exports.disableCommand = async (guild, command) => {
const guildDB = await this.getGuild(guild);
await connection.query("UPDATE guilds SET disabled_commands = $1 WHERE guild_id = $2", [(guildDB.disabled_commands ? [...guildDB.disabled_commands, command] : [command]).filter((v) => v !== undefined), guild]);
collections.disabledCmdCache.set(guild, guildDB.disabled_commands ? [...guildDB.disabled_commands, command] : [command].filter((v) => v !== undefined));
};
exports.enableCommand = async (guild, command) => {
const guildDB = await this.getGuild(guild);
const newDisabled = guildDB.disabled_commands ? guildDB.disabled_commands.filter(item => item !== command) : [];
await connection.query("UPDATE guilds SET disabled_commands = $1 WHERE guild_id = $2", [newDisabled, guild]);
collections.disabledCmdCache.set(guild, newDisabled);
};
exports.disableChannel = async (channel) => {
@ -79,7 +85,7 @@ exports.addCount = async (command) => {
exports.addGuild = async (guild) => {
const query = await this.getGuild(guild);
if (query) return query;
await connection.query("INSERT INTO guilds (guild_id, prefix, disabled, tags_disabled) VALUES ($1, $2, $3, $4)", [guild.id, process.env.PREFIX, [], false]);
await connection.query("INSERT INTO guilds (guild_id, prefix, disabled, disabled_commands) VALUES ($1, $2, $3, $4)", [guild.id, process.env.PREFIX, [], []]);
return await this.getGuild(guild.id);
};

View file

@ -50,7 +50,7 @@ exports.fixGuild = async (guild) => {
try {
guildDB = connection.prepare("SELECT * FROM guilds WHERE guild_id = ?").get(guild.id);
} catch {
connection.prepare("CREATE TABLE guilds ( guild_id VARCHAR(30) NOT NULL PRIMARY KEY, prefix VARCHAR(15) NOT NULL, disabled text NOT NULL, tags_disabled integer NOT NULL DEFAULT 0 CHECK(tags_disabled IN (0,1)) )").run();
connection.prepare("CREATE TABLE guilds ( guild_id VARCHAR(30) NOT NULL PRIMARY KEY, prefix VARCHAR(15) NOT NULL, disabled text NOT NULL, disabled_commands text NOT NULL )").run();
}
if (!guildDB) {
logger.log(`Registering guild database entry for guild ${guild.id}...`);
@ -71,6 +71,19 @@ exports.getCounts = async () => {
return countObject;
};
exports.disableCommand = async (guild, command) => {
const guildDB = await this.getGuild(guild);
connection.prepare("UPDATE guilds SET disabled_commands = ? WHERE guild_id = ?").run(JSON.stringify((guildDB.disabledCommands ? [...JSON.parse(guildDB.disabledCommands), command] : [command]).filter((v) => v !== undefined)), guild);
collections.disabledCmdCache.set(guild, guildDB.disabled_commands ? [...JSON.parse(guildDB.disabledCommands), command] : [command].filter((v) => v !== undefined));
};
exports.enableCommand = async (guild, command) => {
const guildDB = await this.getGuild(guild);
const newDisabled = guildDB.disabledCommands ? JSON.parse(guildDB.disabledCommands).filter(item => item !== command) : [];
connection.prepare("UPDATE guilds SET disabled_commands = ? WHERE guild_id = ?").run(JSON.stringify(newDisabled), guild);
collections.disabledCmdCache.set(guild, newDisabled);
};
exports.disableChannel = async (channel) => {
const guildDB = await this.getGuild(channel.guild.id);
connection.prepare("UPDATE guilds SET disabled = ? WHERE guild_id = ?").run(JSON.stringify([...JSON.parse(guildDB.disabled), channel.id]), channel.guild.id);
@ -84,12 +97,6 @@ exports.enableChannel = async (channel) => {
collections.disabledCache.set(channel.guild.id, newDisabled);
};
exports.toggleTags = async (guild) => {
const guildDB = await this.getGuild(guild.id);
guildDB.tags_disabled = guildDB.tags_disabled ? 0 : 1;
connection.prepare("UPDATE guilds SET tags_disabled = ? WHERE guild_id = ?").run(guildDB.tags_disabled, guild.id);
};
exports.getTags = async (guild) => {
const tagArray = connection.prepare("SELECT * FROM tags WHERE guild_id = ?").all(guild);
const tags = {};
@ -130,9 +137,9 @@ exports.addGuild = async (guild) => {
id: guild.id,
prefix: process.env.PREFIX,
disabled: "[]",
tagsDisabled: 0
disabledCommands: "[]"
};
connection.prepare("INSERT INTO guilds (guild_id, prefix, disabled, tags_disabled) VALUES (@id, @prefix, @disabled, @tagsDisabled)").run(guildObject);
connection.prepare("INSERT INTO guilds (guild_id, prefix, disabled, disabled_commands) VALUES (@id, @prefix, @disabled, @tagsDisabled)").run(guildObject);
return guildObject;
};

View file

@ -2,7 +2,7 @@
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
CREATE TABLE guilds ( guild_id VARCHAR(30) NOT NULL PRIMARY KEY, prefix VARCHAR(15) NOT NULL, disabled text ARRAY NOT NULL, tags_disabled boolean NOT NULL );
CREATE TABLE guilds ( guild_id VARCHAR(30) NOT NULL PRIMARY KEY, prefix VARCHAR(15) NOT NULL, disabled text ARRAY NOT NULL, disabled_commands text ARRAY NOT NULL );
CREATE TABLE counts ( command VARCHAR NOT NULL PRIMARY KEY, count integer NOT NULL );
CREATE TABLE tags ( guild_id VARCHAR(30) NOT NULL, name text NOT NULL, content text NOT NULL, author VARCHAR(30) NOT NULL, UNIQUE(guild_id, name) );
EOSQL

View file

@ -1,29 +0,0 @@
// service wrapper for the database drivers in ../database/
const { BaseServiceWorker } = require("eris-fleet");
const database = require(`../database/${process.env.DB ? process.env.DB.split("://")[0] : "dummy"}.js`);
class DatabaseWorker extends BaseServiceWorker {
constructor(setup) {
super(setup);
this.serviceReady();
}
async handleCommand(data) {
try {
if (database[data.name]) {
return await database[data.name](...data.args);
} else {
throw "Unknown query";
}
} catch (err) {
return { err: typeof err === "string" ? err : err.message };
}
}
shutdown(done) {
database.stop().then(() => done);
}
}
module.exports = DatabaseWorker;

View file

@ -34,7 +34,7 @@ esmbot_connected_workers ${servers.length}
res.write(`esmbot_max_jobs{worker="${i}"} ${w.max}\n`);
}
}
const counts = await database(this.ipc, "getCounts");
const counts = await database.getCounts();
for (const [i, w] of Object.entries(counts)) {
res.write(`esmbot_command_count{command="${i}"} ${w}\n`);
}