Skip to content

Commit

Permalink
add priority, fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
JulianVennen committed Jul 2, 2021
1 parent 49e9e08 commit 0a0f438
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 46 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "modbot",
"version": "0.4.0",
"version": "0.5.0",
"description": "Discord Bot for the Aternos Discord server",
"main": "index.js",
"scripts": {
Expand Down
6 changes: 3 additions & 3 deletions src/BadWord.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class BadWord extends ChatTriggeredFeature {

static tableName = 'badWords';

static columns = ['guildid', 'trigger', 'punishment', 'response', 'global', 'channels'];
static columns = ['guildid', 'trigger', 'punishment', 'response', 'global', 'channels', 'priority'];

/**
* constructor - create a bad word
Expand Down Expand Up @@ -57,7 +57,7 @@ class BadWord extends ChatTriggeredFeature {
* @returns {(*|string)[]}
*/
serialize() {
return [this.gid, JSON.stringify(this.trigger), JSON.stringify(this.punishment), this.response, this.global, this.channels.join(',')];
return [this.gid, JSON.stringify(this.trigger), JSON.stringify(this.punishment), this.response, this.global, this.channels.join(','), this.priority];
}

/**
Expand Down Expand Up @@ -110,7 +110,7 @@ class BadWord extends ChatTriggeredFeature {
* @param {String} triggerContent
* @returns {Promise<{success:boolean, badWord: BadWord, message: String}>}
*/
static async create(guildID, global, channels, triggerType, triggerContent) {
static async new(guildID, global, channels, triggerType, triggerContent) {

let trigger = this.getTrigger(triggerType, triggerContent);
if (!trigger.success) return trigger;
Expand Down
83 changes: 46 additions & 37 deletions src/ChatTriggeredFeature.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,30 +124,48 @@ class ChatTriggeredFeature {
return false;
}

/**
* serialize this object
* must return data in same order as the static columns array
* @returns {(*|string)[]}
*/
serialize() {
throw 'Abstract method not overridden!';
}

/**
* Save to db and cache
* @async
* @return {Promise<Number>} id in db
*/
async save() {
if (!this.channels) this.channels = null;

let dbentry = await database.queryAll(`INSERT INTO ${database.escapeId(this.constructor.tableName)} (${database.escapeIdArray(this.constructor.columns).join(', ')}) VALUES (${',?'.repeat(this.constructor.columns.length).slice(1)})`,this.serialize());

this.id = dbentry.insertId;
if (this.id) {
let assignments = [],
columns = this.constructor.columns,
data = this.serialize();
for (let i = 0; i < columns.length; i++) {
assignments.push(`${database.escapeId(columns[i])}=${database.escapeValue(data[i])}`);
}
if (data.length !== columns.length) throw 'Unable to update, lengths differ!';
await database.queryAll(`UPDATE ${database.escapeId(this.constructor.tableName)} SET ${assignments.join(', ')} WHERE id = ?`, [this.id]);
}
else {
let dbentry = await database.queryAll(`INSERT INTO ${database.escapeId(this.constructor.tableName)} (${database.escapeIdArray(this.constructor.columns).join(', ')}) VALUES (${',?'.repeat(this.constructor.columns.length).slice(1)})`,this.serialize());
this.id = dbentry.insertId;
}

if (this.global) {
if (!this.constructor.getGuildCache().has(this.gid)) this.constructor.getGuildCache().set(this.gid, new Discord.Collection());
if (!this.constructor.getGuildCache().has(this.gid)) return this.id;
this.constructor.getGuildCache().get(this.gid).set(this.id, this);
}
else {
for (const channel of this.channels) {
if(!this.constructor.getChannelCache().has(channel)) this.constructor.getChannelCache().set(channel, new Discord.Collection());
if(!this.constructor.getChannelCache().has(channel)) continue;
this.constructor.getChannelCache().get(channel).set(this.id, this);
}
}

return dbentry.insertId;
return this.id;
}

/**
Expand All @@ -172,6 +190,22 @@ class ChatTriggeredFeature {
}
}

/**
* create this object from data retrieved from the database
* @param data
* @returns {Promise<ChatTriggeredFeature>}
*/
static fromData(data) {
return new this(data.guildid, {
trigger: JSON.parse(data.trigger),
punishment: data.punishment,
response: data.response,
global: data.global === 1,
channels: data.channels.split(','),
priority: data.priority
}, data.id);
}

/**
* Get a single bad word / autoresponse
* @param {String|Number} id
Expand All @@ -180,13 +214,7 @@ class ChatTriggeredFeature {
static async getByID(id) {
const result = await database.query(`SELECT * FROM ${database.escapeId(this.tableName)} WHERE id = ?`, [id]);
if (!result) return null;
return new this(result.guildid, {
trigger: JSON.parse(result.trigger),
punishment: result.punishment,
response: result.response,
global: result.global === 1,
channels: result.channels.split(',')
}, result.id);
return this.fromData(result);
}

/**
Expand Down Expand Up @@ -246,13 +274,7 @@ class ChatTriggeredFeature {

const collection = new Discord.Collection();
for (const res of result) {
collection.set(res.id, new this(res.guildid, {
trigger: JSON.parse(res.trigger),
punishment: res.punishment,
response: res.response,
global: res.global === 1,
channels: res.channels.split(',')
}, res.id));
collection.set(res.id, this.fromData(res));
}

return collection.sort((a, b) => a.id - b.id);
Expand All @@ -268,14 +290,7 @@ class ChatTriggeredFeature {

const newItems = new Discord.Collection();
for (const res of result) {
const o = new this(res.guildid, {
trigger: JSON.parse(res.trigger),
punishment: res.punishment,
response: res.response,
global: true,
channels: []
}, res.id);
newItems.set(res.id, o);
newItems.set(res.id, this.fromData(res));
}
this.getGuildCache().set(guildId, newItems);
setTimeout(() => {
Expand All @@ -293,13 +308,7 @@ class ChatTriggeredFeature {

const newItems = new Discord.Collection();
for (const res of result) {
newItems.set(res.id, new this(res.guildid, {
trigger: JSON.parse(res.trigger),
response: res.response,
punishment: res.punishment,
global: false,
channels: res.channels.split(',')
}, res.id));
newItems.set(res.id, this.fromData(res));
}
this.getChannelCache().set(channelId, newItems);
setTimeout(() => {
Expand Down
11 changes: 10 additions & 1 deletion src/Database.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class Database {
await this.query('CREATE TABLE IF NOT EXISTS `channels` (`id` VARCHAR(20) NOT NULL, `config` TEXT NOT NULL, PRIMARY KEY (`id`), `guildid` VARCHAR(20))');
await this.query('CREATE TABLE IF NOT EXISTS `guilds` (`id` VARCHAR(20) NOT NULL, `config` TEXT NOT NULL, PRIMARY KEY (`id`))');
await this.query('CREATE TABLE IF NOT EXISTS `responses` (`id` int PRIMARY KEY AUTO_INCREMENT, `guildid` VARCHAR(20) NOT NULL, `trigger` TEXT NOT NULL, `response` TEXT NOT NULL, `global` BOOLEAN NOT NULL, `channels` TEXT NULL DEFAULT NULL)');
await this.query('CREATE TABLE IF NOT EXISTS `badWords` (`id` int PRIMARY KEY AUTO_INCREMENT, `guildid` VARCHAR(20) NOT NULL, `trigger` TEXT NOT NULL, `punishment` TEXT NOT NULL, `response` TEXT NOT NULL, `global` BOOLEAN NOT NULL, `channels` TEXT NULL DEFAULT NULL)');
await this.query('CREATE TABLE IF NOT EXISTS `badWords` (`id` int PRIMARY KEY AUTO_INCREMENT, `guildid` VARCHAR(20) NOT NULL, `trigger` TEXT NOT NULL, `punishment` TEXT NOT NULL, `response` TEXT NOT NULL, `global` BOOLEAN NOT NULL, `channels` TEXT NULL DEFAULT NULL, `priority` int NULL)');
await this.query('CREATE TABLE IF NOT EXISTS `moderations` (`id` int PRIMARY KEY AUTO_INCREMENT, `guildid` VARCHAR(20) NOT NULL, `userid` VARCHAR(20) NOT NULL, `action` VARCHAR(10) NOT NULL,`created` bigint NOT NULL, `value` int DEFAULT 0,`expireTime` bigint NULL DEFAULT NULL, `reason` TEXT,`moderator` VARCHAR(20) NULL DEFAULT NULL, `active` BOOLEAN DEFAULT TRUE)');
}

Expand Down Expand Up @@ -132,6 +132,15 @@ class Database {
return mysql.escapeId(...args);
}

/**
* escape a value
* @param args
* @returns {string}
*/
escapeValue(...args) {
return mysql.escape(...args);
}

/**
* Escape an array of table/column names
*
Expand Down
5 changes: 2 additions & 3 deletions src/commands/settings/BadWordCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class BadWordCommand extends Command {
}
}

static names = ['badword','badwords','blacklist'];
static names = ['badword','badwords','bw'];

static userPerms = ['MANAGE_GUILD'];

Expand Down Expand Up @@ -71,14 +71,13 @@ class BadWordCommand extends Command {
const global = this.args[0].toLowerCase() === 'global';

let channels;
console.log(!!this.message.guild.channels.resolve('749286933171142780'));
if (!global) channels = await util.channelMentions(this.message.guild, this.args);
else this.args.shift();

const type = this.args.shift().toLowerCase();
const content = this.args.join(' ');

let badWord = await BadWord.create(this.message.guild.id, global, channels, type, content);
let badWord = await BadWord.new(this.message.guild.id, global, channels, type, content);
if (!badWord.success) return this.message.channel.send(badWord.message);

await this.message.channel.send(badWord.badWord.embed('Added new bad word', util.color.green));
Expand Down
2 changes: 1 addition & 1 deletion src/features/message/badwordmod.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const strike = require('../../commands/legacy/strike');
exports.event = async (options, message) => {
if (!message.guild || await util.ignoresAutomod(message)) return;

const words = await BadWord.get(message.channel.id, message.guild.id);
const words = (await BadWord.get(message.channel.id, message.guild.id)).sort((a,b) => b.priority - a.priority);
for (let [,word] of words) {
if (word.matches(message)) {
const reason = 'Using forbidden words or phrases';
Expand Down
18 changes: 18 additions & 0 deletions update/0.5.0.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const Database = require('../src/Database');
const config = require('../config.json');
const database = new Database(config.db);

async function update() {
console.log('Starting update to v0.5.0');

console.log('Updating tables');
await database.waitForConnection();
await database.query('ALTER TABLE badWords ADD `priority` int NULL;');
console.log('Done!');
process.exit(0);
}

update().catch(e => {
console.error(e);
process.exit(1);
});

0 comments on commit 0a0f438

Please sign in to comment.