bulk delete logs

This commit is contained in:
Erik 2020-08-17 23:24:23 +03:00
parent cd1125e7b2
commit d094ffa765

View File

@ -1,7 +1,10 @@
const { MessageAttachment, WebhookClient } = require('discord.js');
const { Observer } = require('../../../interfaces/');
const { Util } = require('../../../../util');
const { Util, Constants: { EmbedLimits } } = require('../../../../util');
const { inspect } = require('util');
const { stripIndents } = require('common-tags');
const moment = require('moment');
const CONSTANTS = {
COLORS: {
@ -197,12 +200,106 @@ class GuildLogger extends Observer {
async messageDeleteBulk(messages) {
//Status: Should be complete, though additional testing might be necessary
const { guild, channel } = messages.first();
if (!guild) return;
const settings = await guild.settings();
const chatlogs = settings.messageLog;
if (!chatlogs.channel) return;
const { ignoredChannels, ignoredRoles } = chatlogs;
if (ignoredChannels.includes(channel.id)) return;
const hook = await guild.getWebhook('messageLog');
if(!hook) return;
const cutOff = EmbedLimits.fieldValue;// - 3;
const fields = [];
//Compile messages into fields that can be compiled into embeds
messages: //Oldest messages first
for (const message of messages.array().sort((a, b) => b.createdTimestamp - a.createdTimestamp)) {
let { member } = message;
const { content, author, id } = message;
if (author.bot) continue messages;
if (!member || member.partial) member = await guild.members.fetch(message.author.id).catch(() => { return false });
if (member && member.roles.cache.size) {
const roles = member.roles.cache.map((role) => role.id);
for (const role of roles) {
if (ignoredRoles.includes(role)) continue messages;
}
}
//const attStr = message.attachments.map((att) => `${att.name} (${att.id})`).join(', ');
const value = stripIndents`${content ? content.substring(0, cutOff) : message.format('BULK_DELETE_NO_CONTENT')}`;
//${message.attachments.size > 0 ? `__(Attachments: ${attStr})__` : '' }
fields.push({
name: `${Util.escapeMarkdown(author.tag)} @ ${moment.utc(message.createdAt).format('D/M/YYYY H:m:s')} UTC (MSG ID: ${id})`,
value
});
if (content && content.length > cutOff) fields.push({
name: '\u200b',
value: content.substring(cutOff)
});
}
//Compile embeds
const embedCutoff = EmbedLimits.embed - 100;
const embeds = [];
let embed = {// title gets set later
fields: [],
color: CONSTANTS.COLORS.RED
};
let length = 0;
fields.reduce((acc, field) => {
//Make sure the total character count doesn't exceed the limit
const fieldLength = field.name.length + field.value.length;
if (acc.fields.length < EmbedLimits.fiedObjects && length + fieldLength < embedCutoff) {
acc.fields.push(field);
} else {
//"clone" the embed into the array
embeds.push({ ...acc });
acc.fields = [field];
length = 0;
}
length += fieldLength;
return acc;
}, embed);
embeds.push(embed);
//Post messages
let showed = 0;
for (let i = 0; i < embeds.length; i++) {
const embed = embeds[i];
//Amount of messages showing
const x = embed.fields.filter((field) => field.name !== '\u200b').length;
embed.title = guild.format('BULK_DELETE_TITLE', { embedNr: i + 1, channel: channel.name });
embed.footer = { text: guild.format('BULK_DELETE_FOOTER', { rangeStart: showed + 1, rangeEnd: showed += x, total: messages.size }) };
const result = await hook.send({ embeds: [embed] }).catch((err) => {
//Unknown webhook -> webhook was deleted, remove it from db so it doesn't make any more unnecessary calls
if (err.code === 10015) {
guild.updateWebhook('messageLog');
} else this.client.logger.error(err.stack);
return { error: true };
});
if (result.error) break;
}
}
async messageEdit(oldMessage, newMessage) {
//Status: Uses webhook, complete
// embeds loading in (ex. when a link is posted) would cause a message edit event
if(oldMessage.embeds.length !== newMessage.embeds.length) return;
if(oldMessage.embeds.length !== newMessage.embeds.length && oldMessage.content === newMessage.content) return;
if(oldMessage.author.bot) return;
const { guild } = oldMessage;
@ -216,11 +313,8 @@ class GuildLogger extends Observer {
if (!chatlogs.channel) return;
const { ignoredRoles, ignoredChannels } = chatlogs;
const logChannel = await guild.resolveChannel(chatlogs.channel);
if(!logChannel) return;
const perms = logChannel.permissionsFor(guild.me);
if(!perms.has('SEND_MESSAGES') || !perms.has('VIEW_CHANNEL') || !perms.has('EMBED_LINKS')) return;
const hook = await guild.getWebhook('messageLog');
if (!hook) return;
if (ignoredRoles && member.roles.cache.size) {
const roles = member.roles.cache.map((r) => r.id);
@ -245,7 +339,7 @@ class GuildLogger extends Observer {
if(img.height && img.width) embed.image = { url: img.url };
}
await logChannel.send({ embed }).catch(this.client.logger.error);
await hook.send({ embeds: [embed] }).catch(this.client.logger.error);
} else {
@ -293,7 +387,7 @@ class GuildLogger extends Observer {
//if(oldMessage.content.length > 1024) embed.description += '\n' + oldMessage.format('MSGLOG_EDIT_OLD_CUTOFF');
//if(newMessage.content.length > 1024) embed.description += '\n' + oldMessage.format('MSGLOG_EDIT_NEW_CUTOFF');
await logChannel.send({ embed }).catch((err) => {
await hook.send({ embeds: [embed] }).catch((err) => {
this.client.logger.error('Error in message edit:\n' + err.stack);
this.client.logger.error(perms.toArray());
});