galactic-bot/structure/moderation/ModerationManager.js

462 lines
18 KiB
JavaScript
Raw Normal View History

const { stripIndents } = require('common-tags');
2020-09-30 23:02:54 +02:00
// eslint-disable-next-line no-unused-vars
const { Message } = require('discord.js');
2020-07-16 09:54:39 +02:00
const { Collection, Util, Emojis } = require('../../util/');
const { User } = require('../extensions/');
const { Warn, Unmute, Mute, Kick, Softban, Unban, Ban } = require('./infractions/');
2020-09-30 23:02:54 +02:00
// eslint-disable-next-line no-unused-vars
const Infraction = require('./interfaces/Infraction');
const Constants = {
2020-06-16 00:15:13 +02:00
MaxTargets: 10, //10+(10*premium-tier), theoretical max = 40
Infractions: {
2020-07-16 09:54:39 +02:00
WARN: Warn,
2020-06-16 00:15:13 +02:00
UNMUTE: Unmute,
2020-07-16 09:54:39 +02:00
MUTE: Mute,
KICK: Kick,
SOFTBAN: Softban,
UNBAN: Unban,
BAN: Ban
2020-06-16 00:15:13 +02:00
},
Opposites: {
MUTE: "UNMUTE",
BAN: "UNBAN"
2020-07-16 09:54:39 +02:00
},
Hierarchy: {
WARN: 0,
MUTE: 1,
KICK: 2,
SOFTBAN: 3,
BAN: 4
2020-06-16 00:15:13 +02:00
}
};
class ModerationManager {
constructor(client) {
this.client = client;
this.callbacks = new Collection();
this._permissionCheck = null;
}
2020-06-16 00:15:13 +02:00
async initialize() {
//TODO: Load infractions for non-cached guilds...
this.client.storageManager.mongodb.infractions.find({
duration: { $gt: 0 },
guild: { $in: this.client.guilds.cache.keyArray() },
callbacked: false
2020-06-16 00:15:13 +02:00
}).then((results) => {
2020-08-13 22:47:09 +02:00
this.client.logger.info(`Filtering ${results.length} infractions for callback.`);
2020-06-16 00:15:13 +02:00
this._handleExpirations(results);
});
}
2020-09-30 23:02:54 +02:00
/**
*
*
* @param {Infraction} Infraction
* @param {Message} message
* @param {object} { targets, reason, duration, data }
* @return {object|Message} The successfully moderated targets of the response message for failure
* @memberof ModerationManager
*/
async handleInfraction(Infraction, message, { targets, reason, duration, data }) {
const maxTargets = Constants.MaxTargets + message.guild.premium*Constants.MaxTargets;
if(targets.length > maxTargets) {
return message.respond(stripIndents`${message.format('MODERATIONMANAGER_INFRACTION_MAXTARGETS', { maxTargets, type: Infraction.targetType })}
${maxTargets < 40 ? message.format('MODERATIONMANAGER_INFRACTION_MAXTARGETSALT') : ''}`, { emoji: 'failure' });
}
2020-06-04 19:59:09 +02:00
const silent = Boolean(message.guild._settings.silent || message.arguments.silent);
2020-07-16 09:54:39 +02:00
const { autoModeration, moderationPoints } = message.guild._settings;
let points = 0,
expiration = 0;
2020-06-04 19:59:09 +02:00
2020-09-30 23:02:54 +02:00
if(moderationPoints.enabled) { // Default point and expiration are handled in arguments
if(message.arguments.points) {
2020-07-16 09:54:39 +02:00
points = parseInt(message.arguments.points.value);
}
if(message.arguments.expiration) {
expiration = parseInt(message.arguments.expiration.value);
}
}
const force = message.arguments.force && message.arguments.force.value;
let original = null;
const responses = [];
2020-09-30 23:02:54 +02:00
for (const target of targets) {
2020-07-16 09:54:39 +02:00
const infraction = new Infraction(this.client, { //this will not save to db unless executed dw, only utilizes the constructor.
executor: message.member,
guild: message.guild,
channel: message.channel,
arguments: message.arguments,
message,
target,
reason,
2020-06-04 19:59:09 +02:00
duration,
silent,
2020-07-16 09:54:39 +02:00
data,
points,
expiration
});
2020-07-16 09:54:39 +02:00
if(!original) original = infraction.type;
2020-07-16 09:54:39 +02:00
let verification = infraction.verify(message.member, target, message.channel);
if(verification instanceof Promise) verification = await verification;
if(verification.error) {
responses.push(verification);
continue;
}
if(infraction.targetType === 'USER') {
2020-07-16 09:54:39 +02:00
const userTarget = target instanceof User ? target : target.user;
const oldPoints = await userTarget.totalPoints(message.guild);
2020-08-31 18:47:20 +02:00
const newPoints = oldPoints + points;
2020-07-16 09:54:39 +02:00
if(autoModeration.enabled && points > 0 && !force) {
let result = null;
for(let [threshold, action] of Object.entries(autoModeration.thresholds)) { //eslint-disable-line prefer-const
threshold = parseInt(threshold);
if(oldPoints >= threshold) continue; //Should have already executed the threshold.
2020-08-31 18:47:20 +02:00
if(newPoints >= threshold) {
2020-07-16 09:54:39 +02:00
result = {
threshold,
...action
};
}
}
if(result && Constants.Hierarchy[infraction.type] <= Constants.Hierarchy[result.type]) {
const escalation = new Constants.Infractions[result.type](this.client, {
2020-07-20 00:42:21 +02:00
executor: message.member,
2020-07-16 09:54:39 +02:00
guild: message.guild,
channel: message.channel,
2020-07-20 00:42:21 +02:00
reason: stripIndents`${reason}
*${message.format('INFRACTION_AUTOMODESCALATION')}*`,
2020-07-16 09:54:39 +02:00
message,
target,
duration: result.length,
silent,
data,
points,
expiration
});
let verification = escalation.verify(message.member, target, message.channel);
if(verification instanceof Promise) verification = await verification;
if(verification.error) {
responses.push(verification);
continue;
}
2020-08-31 19:04:23 +02:00
escalation.totalPoints = await userTarget.totalPoints(message.guild, { points, expiration, timestamp: infraction.timestamp });
2020-07-16 09:54:39 +02:00
responses.push(await escalation.execute());
continue;
2020-08-31 19:04:23 +02:00
} else {
infraction.totalPoints = await userTarget.totalPoints(message.guild, { points, expiration, timestamp: infraction.timestamp });
}
2020-07-16 09:54:39 +02:00
}
}
responses.push(await infraction.execute());
}
2020-07-16 09:54:39 +02:00
const success = Boolean(responses.some((r) => !r.error));
const succeeded = responses.filter((r) => !r.error);
const failed = responses.filter((r) => r.error);
2020-06-16 00:15:13 +02:00
const fatals = failed.filter((f) => f.fatal);
if(fatals.length > 0) {
const [ error ] = fatals;
return message.respond(message.format(error.reason), { emoji: 'failure' });
2020-06-16 00:15:13 +02:00
}
2020-07-16 09:54:39 +02:00
const successes = {};
const fails = {};
for(const response of responses) {
const { type, target } = response.infraction;
2020-07-16 09:54:39 +02:00
if(!response.error) {
if(!silent) {
if(successes[type]) {
successes[type].targets.push(target.display);
2020-07-16 09:54:39 +02:00
} else {
successes[type] = {
targets: [target.display],
2020-07-16 09:54:39 +02:00
infraction: response.infraction
};
}
}
} else {
if(fails[type]) {
fails[type].targets.push(target.display);
2020-07-16 09:54:39 +02:00
} else {
fails[type] = {
targets: [target.display],
2020-07-16 09:54:39 +02:00
infraction: response.infraction,
reason: response.reason
};
}
}
}
2020-07-20 00:42:21 +02:00
const succeededTargets = succeeded.map((s) => s.infraction.target);
const actions = await this._handleArguments(message, succeededTargets); //eslint-disable-line no-unused-vars
let string = "";
2020-07-16 09:54:39 +02:00
for(const [ type, data ] of Object.entries(successes)) {
if(silent) continue;
const { dictionary, targetType } = data.infraction;
const reason = type === original ? Util.escapeMarkdown(data.infraction.reason) : message.format('INFRACTION_ESCALATIONREASON');
const str = `${Emojis.success} ${message.format('INFRACTION_SUCCESS', {
infraction: dictionary.past,
targetType: `${targetType.toLowerCase()}${data.targets.length === 1 ? '' : 's'}`,
2020-07-16 09:54:39 +02:00
target: data.targets.map((t) => `**${Util.escapeMarkdown(t)}**`).join(' '),
2020-07-20 00:42:21 +02:00
text: type === original ? ` ${reason.length > 120 ? `for: \`${reason.substring(0, 117)}...\`` : `for: \`${reason}\``}` : ` because \`${reason}\``
2020-07-16 09:54:39 +02:00
})}`;
type === original //eslint-disable-line
? string = `${str}\n${string}`
: string += str;
}
2020-07-16 09:54:39 +02:00
for(const [ type, data ] of Object.entries(fails)) {
const { dictionary, targetType } = data.infraction;
const str = `${Emojis.failure} ${message.format('INFRACTION_FAIL', {
infraction: dictionary.present,
targetType: `${targetType.toLowerCase()}${data.targets.length === 1 ? '' : 's'}`,
2020-07-16 09:54:39 +02:00
target: data.targets.map((t) => `**${Util.escapeMarkdown(t)}**`).join(' '),
2020-07-29 21:21:58 +02:00
reason: message.format(data.reason)
2020-07-16 09:54:39 +02:00
})}`;
(type === original && !success) //eslint-disable-line
? string = `${str}\n${string}`
: string += str;
}
if(success && silent) { //Delete message if silent.
try {
await message.delete();
} catch(e) {} //eslint-disable-line no-empty
}
2020-07-16 09:54:39 +02:00
if(string) message.respond(string);
2020-06-04 19:59:09 +02:00
return succeeded;
}
2021-05-04 16:16:04 +02:00
// Similar to handleInfraction, but meant for automod, deals with only 1 target
async autoModerate({ guild, action, message, reason, silent, data }) {
const { autoModeration, moderationPoints } = guild._settings;
let points = 0,
expiration = 0,
response = null;
const { force } = action;
const Infraction = Constants.Infractions[action.type];
if (moderationPoints.enabled) {
points = action.points || moderationPoints.points[action.type];
expiration = action.expiration || moderationPoints.expirations[action.type];
}
const infractionData = {
executor: guild.me,
guild,
channel: message.channel,
message,
target: message.member,
reason,
duration: action.duration,
silent,
data,
points,
expiration
};
const infraction = new Infraction(this.client, infractionData);
const verification = await infraction.verify();
if (verification.error) {
this.client.logger.debug(`Automod infraction failed verification.\n${infraction.type}:\n${JSON.stringify(infractionData)}`);
return; // Possibly add a automod error log channel setting and do something here -- skip for now
}
if (autoModeration.enabled && points && !force) {
const userTarget = message.author;
const oldPoints = await userTarget.totalPoints(guild);
const newPoints = oldPoints + points;
let result = null;
// eslint-disable-next-line prefer-const
for (let [threshold, action] of Object.entries(autoModeration.thresholds)) {
threshold = parseInt(threshold);
if (oldPoints >= threshold) continue;
if (newPoints >= threshold) result = {
threshold,
...action
};
}
if (result && Constants.Hierarchy[infraction.type] <= Constants.Hierarchy[result.type]) {
infractionData.duration = result.length;
infractionData.reason += `\n*${message.format('INFRACTION_AUTOMODESCALATION')}*`;
const escalation = new Constants.Infractions[result.type](this.client, infractionData);
const verification = await escalation.verify();
if (verification.error) {
this.client.logger.debug(`Automod escalated infraction failed verification.\n${infraction.type}:\n${JSON.stringify(infractionData)}`);
return; // Possibly add a automod error log channel setting and do something here -- skip for now
}
//: moderationPoints.expirations[escalation.type]
escalation.totalPoints = await userTarget.totalPoints(guild, { points, expiration, timestamp: infraction.timestamp });
response = await escalation.execute();
} else {
infraction.totalPoints = await userTarget.totalPoints(guild, { points, expiration, timestamp: infraction.timestamp });
}
}
if (!response) response = await infraction.execute();
if (response.error) this.client.logger.debug(`Automod infraction execution failed:\n${JSON.stringify(response)}`);
// TODO:
// Figure out what we want to do with these errors if anything apart from potentially log them
// Most errors here would probably be permission issues/edge cases caused by server configuration/discord perms
}
async _handleArguments(message, targets) {
const actions = {
prune: async (message, argument, targets) => {
const users = targets.map((t) => t.id);
let messages = await message.channel.messages.fetch({
limit: argument.value
});
2020-07-20 00:42:21 +02:00
messages = messages.filter((m) => {
return users.includes(m.author.id) && m.deletable;
});
try {
await message.channel.bulkDelete(messages, true);
} catch(err) {} //eslint-disable-line no-empty
return messages.size;
}
};
const responses = {};
for(const arg of Object.values(message.arguments)) {
2020-07-20 00:42:21 +02:00
// console.log(arg, targets);
if(actions[arg.name]) {
let action = actions[arg.name](message, arg, targets);
if(action instanceof Promise) action = await action;
responses[arg.name] = action;
}
}
return responses;
}
2020-06-16 00:15:13 +02:00
async _handleExpirations(infractions = []) {
const currentDate = Date.now();
const resolve = async (i) => {
this.client.logger.debug("Resolving infraction");
2020-06-16 00:15:13 +02:00
const undoClass = Constants.Infractions[Constants.Opposites[i.type]];
if(!undoClass) return false;
const guild = this.client.guilds.resolve(i.guild);
await guild.settings(); //just incase
2020-06-16 00:15:13 +02:00
let target = null;
if(i.targetType === 'USER') {
2020-06-16 00:15:13 +02:00
target = await guild.members.resolve(i.target);
if(!target) {
try {
target = await guild.members.fetch(i.target);
} catch(e) {} //eslint-disable-line no-empty
if(!target && i.type === 'BAN') {
try {
target = await this.client.users.fetch(i.target);
} catch(e) {} //eslint-disable-line no-empty
}
2020-06-16 00:15:13 +02:00
}
} else if(i.targetType === 'CHANNEL') {
2020-06-16 00:15:13 +02:00
target = guild.channels.resolve(i.target);
}
2020-06-16 00:15:13 +02:00
if(!target) {
this.client.logger.debug(`User left the guild or channel was deleted? Unable to resolve target.\n${i}`);
2020-06-16 00:15:13 +02:00
return false;
}
const executor = guild.members.resolve(i.executor) || guild.me;
await new undoClass(this.client, {
2020-06-16 00:15:13 +02:00
reason: `AUTO-${Constants.Opposites[i.type]} from Case ${i.case}`,
channel: guild.channels.resolve(i.channel),
hyperlink: i.logMessage && i.moderationLog ? `https://discord.com/channels/${i.guild}/${i.moderationLog}/${i.logMessage}` : null,
2020-06-16 00:15:13 +02:00
data: i.data,
guild,
target,
executor
}).execute();
//TODO: Log this, should never error... hopefully.
await this.client.storageManager.mongodb.infractions.updateOne(
{ _id: i._id },
{ callbacked: true }
).catch((e) => {}); //eslint-disable-line no-empty, no-unused-vars, no-empty-function
2020-06-16 00:15:13 +02:00
return true;
};
for(const infraction of infractions) {
const expiration = infraction.timestamp + infraction.duration*1000;
2020-08-09 01:23:19 +02:00
if(expiration-currentDate <= 0) {
2020-06-16 00:15:13 +02:00
await resolve(infraction);
continue;
}
this.client.logger.debug(`Going to resolve infraction in: ${expiration-currentDate}`);
this.callbacks.set(infraction.id, {
2020-06-16 00:15:13 +02:00
timeout: setTimeout(() => {
resolve(infraction);
}, expiration-currentDate),
infraction
});
}
}
async _removeExpiration(expiration) {
2020-07-16 09:54:39 +02:00
this.client.logger.debug(`Expired infraction ${expiration.infraction.type} for user ${expiration.infraction.target}.`);
2020-08-09 01:23:19 +02:00
await this.client.storageManager.mongodb.infractions.updateOne(
{ id: expiration.infraction.id },
{ callbacked: true }
).catch((e) => {}); //eslint-disable-line no-empty, no-unused-vars, no-empty-function
2020-07-16 09:54:39 +02:00
clearTimeout(expiration.timeout); //just incase node.js is doing some bullshit
this.callbacks.delete(expiration.infraction.id);
}
}
module.exports = ModerationManager;