Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Accepted audit log types for this event
- const auditTypes = {
- "CHANNEL_UPDATE": "Channel Update",
- "CHANNEL_OVERWRITE_UPDATE": "Channel Permission Overwrite Update",
- "CHANNEL_OVERWRITE_CREATE": "Channel Permission Overwrite Creation",
- "CHANNEL_OVERWRITE_DELETE": "Channel Permission Overwrite Deletion"
- }
- module.exports = async (client, oldChannel, newChannel) => {
- console.log(oldChannel.permissionOverwrites);
- console.log(" ");console.log(" ");
- console.log(newChannel.permissionOverwrites);
- // Guild Data and Log channel
- let log = client.getGuildData(newChannel.guild.id, "log"),
- logChannel = newChannel.guild.channels.get(log.channel);
- if (!logChannel) return;
- // Bot Perms and verification of perms
- let botPerms = logChannel.permissionsFor(newChannel.guild.me);
- if (!(botPerms.hasPermission("SEND_MESSAGES") && botPerms.hasPermission("EMBED_LINKS") && botPerms.hasPermission("VIEW_AUDIT_LOG"))) return;
- // Server audit limited to previous 26, then filtering the audit entries by the accepted actions and if the target channel matches the newChannel argument of this event and getting the first result
- let auditEntry = await newChannel.guild.fetchAuditLogs({limit: 26}).then(audits => audits.entries.filter(audit => auditTypes[audit.action] && audit.target.id === newChannel.id).first());
- // updateType: Storing action in a variable to see if it is an overwrite or not later on in the code
- // channelChanges: Object which will contain resulting string structures to be a part of the final embed
- let updateType = auditTypes[auditEntry.action],
- channelChanges = {overwrites:[], changes: []};
- // Check if update type is an overwrite
- if (updateType.indexOf("Overwrite") !== -1) {
- // Getting overwrite objects for the channel objects passed as argument to this event
- let oldPerms = oldChannel.permissionOverwrites,
- newPerms = newChannel.permissionOverwrites;
- // Looping over the old perms Collection to compare changes with new perms Collection
- oldPerms.tap(overwrite => {
- // If the new perms collection doesn't contain the Overwrite object that the old perms collection has
- // Indicating that the overwrite was removed (Not sure if it works like this)
- if (!newPerms.get(overwrite.id)) {
- // Since overwrites can only be a role or user overwrite
- switch (overwrite.type) {
- case "role": {
- // Getting role object, then adding the structured string into the channelChanges object
- let roleObj = newChannel.guild.roles.get(overwrite.id);
- if (!roleObj) return console.log("Could not find role", overwrite.id);
- return channelChanges.overwrites.push(`Removed role ${roleObj.name}'s overwrite.`);
- }
- case "user": {
- // Getting user object, then adding the structured string into the channelChanges object
- let userObj = newChannel.guild.members.get(overwrite.id);
- if (!userObj) return console.log("Could not find member ", overwrite.id);
- return channelChanges.overwrites.push(`Removed user ${userObj.username}'s overwrite.`);
- }
- }
- }
- // A sub-structure object for categorizing the changed overwrites
- let changes = {allowed:[], neutralized:[], denied:[]};
- // Get the new perms Collection object
- let newOverwrite = newPerms.get(overwrite.id);
- console.log(newOverwrite);
- // Get allow and deny perms as an array, for each old and new overwrite collection
- let permDiff = {old: {allow: overwrite.allowed.toArray(), deny: overwrite.denied.toArray()}, new: {allow: newOverwrite.allowed.toArray(), deny: newOverwrite.denied.toArray()}};
- // Iterating over the new allow overwrites array
- permDiff.new.allow.forEach(perm => {
- console.log("Handling allow permission:", perm);
- // Delete and ignore the overwrite if it was previously in the same state, True to True in this case
- if (permDiff.old.allow.includes(perm)) return delete permDiff.old.allow[permDiff.old.allow.indexOf(perm)];
- // Check if the overwrite is a part of old deny overwrites array, which indicates that the overwrite was previously in the Denied state
- // Structuring the string by formatting the overwrite string to a readable format and text that indicates that this overwrite was previously a Denied overwrite
- else if (permDiff.old.deny.includes(perm)) changes.allowed.push(`Allowed **${perm.split("_").map(itm=>itm.toLowerCase().replace(/^(\w)/, (_, char)=>char.toUpperCase())).join(" ")}** from Deny`);
- // If previous conditions fail, then the overwrite has to be changed from Neutral to True
- else changes.allowed.push(`Allowed **${perm.split("_").map(itm=>itm.toLowerCase().replace(/^(\w)/, (_, char)=>char.toUpperCase())).join(" ")}** from Neutral`);
- // Deleting the overwrite entry from the old allow overwrites, for a purpose later in the code
- console.log("Deleted allow permission after handling:", delete permDiff.old.allow[permDiff.old.allow.indexOf(perm)]);
- console.log("Changes object after handling allow permission", changes.allowed);
- });
- // Similar to the previous loop, except with new deny overwrites array
- permDiff.new.deny.forEach(perm => {
- console.log("Handling deny permission:", perm);
- // Delete and ignore the overwrite if it was previously in the same state, False to False in this case
- if (permDiff.old.deny.includes(perm)) return delete permDiff.old.deny[permDiff.old.deny.indexOf(perm)];
- // Check if the overwrite is a part of old allow overwrites array, which indicates that the overwrite was previously in the Allowed state
- // Structuring the string by formatting the overwrite string to a readable format and text that indicates that this overwrite was previously an Allowed overwrite
- else if (permDiff.old.allow.includes(perm)) changes.denied.push(`Denied **${perm.split("_").map(itm=>itm.toLowerCase().replace(/^(\w)/, (_, char)=>char.toUpperCase())).join(" ")}** from Allow`);
- // If previous conditions fail, then the overwrite has to be changed from Neutral to False
- else changes.denied.push(`Denied **${perm.split("_").map(itm=>itm.toLowerCase().replace(/^(\w)/, (_, char)=>char.toUpperCase())).join(" ")}** from Neutral`);
- // Deleting the overwrite entry from the old deny overwrites, for a purpose later in the code
- console.log("Deleted deny permission after handling:", delete permDiff.old.deny[permDiff.old.deny.indexOf(perm)]);
- console.log("Changes object after handling deny permission", changes.denied);
- });
- console.log("Old allow permission leftovers:", permDiff.old.allow, permDiff.old.allow.length);
- console.log("Old deny permission leftovers:", permDiff.old.deny, permDiff.old.deny.length);
- // Checking if any overwrites are left for allow and deny arrays of the old overwrite collection
- // If an overwrite makes it to this point, it means that the overwrite was changed from True/False to Neutral
- // If the overwrites exist for each state, then structure the string for them indicating that they've changed from True/False to Neutral
- if (permDiff.old.allow.length !== 0) permDiff.old.allow.forEach(perm => changes.neutralized.push(`Neutralized **${perm.split("_").map(itm=>itm.toLowerCase().replace(/^(\w)/, (_, char)=>char.toUpperCase())).join(" ")}** from Allow`));
- if (permDiff.old.deny.length !== 0) permDiff.old.deny.forEach(perm => changes.neutralized.push(`Neutralized **${perm.split("_").map(itm=>itm.toLowerCase().replace(/^(\w)/, (_, char)=>char.toUpperCase())).join(" ")}** from Deny`));
- // Converting the sub-structure object to a string for the channelChanges object and indicating the type and name of the overwrite target
- switch (overwrite.type) {
- case "role": {
- let roleObj = newChannel.guild.roles.get(overwrite.id);
- if (!roleObj) console.log("Could not find role", overwrite.id);
- channelChanges.overwrites.push(`Overwrites for role ${roleObj.name}:
- ${changes.allowed.length ? `**Allowed:**\n - ${changes.allowed.join("\n - ")}`: ""}
- ${changes.denied.length ? `**Denied:**\n - ${changes.denied.join("\n - ")}`: ""}
- ${changes.neutralized.length ? `**Neutralized:**\n - ${changes.neutralized.join("\n - ")}`: ""}`);
- console.log("", channelChanges.overwrites);
- break;
- }
- case "user": {
- let userObj = newChannel.guild.members.get(overwrite.id);
- if (!userObj) console.log("Could not find member ", overwrite.id);
- channelChanges.overwrites.push(`Overwrites for ${userObj.name}:
- ${changes.allowed.length ? `**Allowed:**\n - ${changes.allowed.join("\n - ")}`: ""}
- ${changes.denied.length ? `**Denied:**\n - ${changes.denied.join("\n - ")}`: ""}
- ${changes.neutralized.length ? `**Neutralized:**\n - ${changes.neutralized.join("\n - ")}`: ""}`);
- break;
- }
- }
- // Deleting overwrites object from new perms collection, to detect if there are any new overwrites created for a user or object
- console.log("Deleted Perms", newPerms.delete(overwrite.id));
- });
- console.log(newPerms);
- // Detecting for any added overwrites
- if (newPerms.length !== 0) newPerms.tap(permObj => {
- console.log(permObj);
- switch (permObj.type) {
- case "role": {
- let roleObj = newChannel.guild.roles.get(permObj.id);
- if (!roleObj) return console.log("Could not find role", permObj.id);
- // Adding a string that only tells that the overwrite has been created for the role
- return channelChanges.overwrites.push(`Added role ${roleObj.name}'s overwrite.`);
- }
- case "user": {
- let userObj = newChannel.guild.members.get(permObj.id);
- if (!userObj) return console.log("Could not find member ", permObj.id);
- // Adding a string that only tells that the overwrite has been created for the user
- return channelChanges.overwrites.push(`Added user ${userObj.username}'s overwrite.`);
- }
- }
- });
- } else {
- // If the change was caused by edit to the channel, like its name or description
- channelChanges.changes = auditEntry.changes.map(changeObj => `**${changeObj.key.replace(/^(\w)/, (_, word) => word.toUpperCase())}:** From ${changeObj.old} to ${changeObj.new}.`);
- }
- // Embed that structures and finally sends to the Log channel
- return logChannel.send({embed:{
- author: {name: "Channel Update", icon_url: auditEntry.executor.avatarURL},
- description: `<@${auditEntry.executor.id}> updated a channel.`,
- fields: [
- {name: "Channel Details", value: `**Name:** ${newChannel.name} (<#${newChannel.id}>)
- **ID:** ${newChannel.id}`},
- {name: "Changes", value: `${channelChanges.changes[0] ? channelChanges.changes.join("\n") : "None"}`},
- {name: "Permission Overwrites", value: `${channelChanges.overwrites.join("\n")}`}
- ],
- timestamp: new Date().toISOString(),
- color: 4359924
- }});
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement