Advertisement
Guest User

Untitled

a guest
Nov 18th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Accepted audit log types for this event
  2. const auditTypes = {
  3.   "CHANNEL_UPDATE": "Channel Update",
  4.   "CHANNEL_OVERWRITE_UPDATE": "Channel Permission Overwrite Update",
  5.   "CHANNEL_OVERWRITE_CREATE": "Channel Permission Overwrite Creation",
  6.   "CHANNEL_OVERWRITE_DELETE": "Channel Permission Overwrite Deletion"
  7. }
  8. module.exports = async (client, oldChannel, newChannel) => {
  9.   console.log(oldChannel.permissionOverwrites);
  10.   console.log(" ");console.log(" ");
  11.   console.log(newChannel.permissionOverwrites);
  12.   // Guild Data and Log channel
  13.   let log = client.getGuildData(newChannel.guild.id, "log"),
  14.       logChannel = newChannel.guild.channels.get(log.channel);
  15.   if (!logChannel) return;
  16.   // Bot Perms and verification of perms
  17.   let botPerms = logChannel.permissionsFor(newChannel.guild.me);
  18.   if (!(botPerms.hasPermission("SEND_MESSAGES") && botPerms.hasPermission("EMBED_LINKS") && botPerms.hasPermission("VIEW_AUDIT_LOG"))) return;
  19.   // 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
  20.   let auditEntry = await newChannel.guild.fetchAuditLogs({limit: 26}).then(audits => audits.entries.filter(audit => auditTypes[audit.action] && audit.target.id === newChannel.id).first());
  21.   // updateType: Storing action in a variable to see if it is an overwrite or not later on in the code
  22.   // channelChanges: Object which will contain resulting string structures to be a part of the final embed
  23.   let updateType = auditTypes[auditEntry.action],
  24.     channelChanges = {overwrites:[], changes: []};
  25.   // Check if update type is an overwrite
  26.   if (updateType.indexOf("Overwrite") !== -1) {
  27.     // Getting overwrite objects for the channel objects passed as argument to this event
  28.     let oldPerms = oldChannel.permissionOverwrites,
  29.         newPerms = newChannel.permissionOverwrites;
  30.     // Looping over the old perms Collection to compare changes with new perms Collection
  31.     oldPerms.tap(overwrite => {
  32.       // If the new perms collection doesn't contain the Overwrite object that the old perms collection has
  33.       // Indicating that the overwrite was removed (Not sure if it works like this)
  34.       if (!newPerms.get(overwrite.id)) {
  35.         // Since overwrites can only be a role or user overwrite
  36.         switch (overwrite.type) {
  37.           case "role": {
  38.             // Getting role object, then adding the structured string into the channelChanges object
  39.             let roleObj = newChannel.guild.roles.get(overwrite.id);
  40.             if (!roleObj) return console.log("Could not find role", overwrite.id);
  41.             return channelChanges.overwrites.push(`Removed role ${roleObj.name}'s overwrite.`);
  42.          }
  43.          case "user": {
  44.            // Getting user object, then adding the structured string into the channelChanges object
  45.            let userObj = newChannel.guild.members.get(overwrite.id);
  46.            if (!userObj) return console.log("Could not find member ", overwrite.id);
  47.            return channelChanges.overwrites.push(`Removed user ${userObj.username}'s overwrite.`);
  48.           }
  49.         }
  50.       }
  51.       // A sub-structure object for categorizing the changed overwrites
  52.       let changes = {allowed:[], neutralized:[], denied:[]};
  53.       // Get the new perms Collection object
  54.       let newOverwrite = newPerms.get(overwrite.id);
  55.       console.log(newOverwrite);
  56.       // Get allow and deny perms as an array, for each old and new overwrite collection
  57.       let permDiff = {old: {allow: overwrite.allowed.toArray(), deny: overwrite.denied.toArray()}, new: {allow: newOverwrite.allowed.toArray(), deny: newOverwrite.denied.toArray()}};
  58.       // Iterating over the new allow overwrites array
  59.       permDiff.new.allow.forEach(perm => {
  60.         console.log("Handling allow permission:", perm);
  61.         // Delete and ignore the overwrite if it was previously in the same state, True to True in this case
  62.         if (permDiff.old.allow.includes(perm)) return delete permDiff.old.allow[permDiff.old.allow.indexOf(perm)];
  63.         // Check if the overwrite is a part of old deny overwrites array, which indicates that the overwrite was previously in the Denied state
  64.         // Structuring the string by formatting the overwrite string to a readable format and text that indicates that this overwrite was previously a Denied overwrite
  65.         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`);
  66.         // If previous conditions fail, then the overwrite has to be changed from Neutral to True
  67.         else changes.allowed.push(`Allowed **${perm.split("_").map(itm=>itm.toLowerCase().replace(/^(\w)/, (_, char)=>char.toUpperCase())).join(" ")}** from Neutral`);
  68.         // Deleting the overwrite entry from the old allow overwrites, for a purpose later in the code
  69.         console.log("Deleted allow permission after handling:", delete permDiff.old.allow[permDiff.old.allow.indexOf(perm)]);
  70.         console.log("Changes object after handling allow permission", changes.allowed);
  71.       });
  72.       // Similar to the previous loop, except with new deny overwrites array
  73.       permDiff.new.deny.forEach(perm => {
  74.         console.log("Handling deny permission:", perm);
  75.         // Delete and ignore the overwrite if it was previously in the same state, False to False in this case
  76.         if (permDiff.old.deny.includes(perm)) return delete permDiff.old.deny[permDiff.old.deny.indexOf(perm)];
  77.         // Check if the overwrite is a part of old allow overwrites array, which indicates that the overwrite was previously in the Allowed state
  78.         // Structuring the string by formatting the overwrite string to a readable format and text that indicates that this overwrite was previously an Allowed overwrite
  79.         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`);
  80.         // If previous conditions fail, then the overwrite has to be changed from Neutral to False
  81.         else changes.denied.push(`Denied **${perm.split("_").map(itm=>itm.toLowerCase().replace(/^(\w)/, (_, char)=>char.toUpperCase())).join(" ")}** from Neutral`);
  82.         // Deleting the overwrite entry from the old deny overwrites, for a purpose later in the code
  83.         console.log("Deleted deny permission after handling:", delete permDiff.old.deny[permDiff.old.deny.indexOf(perm)]);
  84.         console.log("Changes object after handling deny permission", changes.denied);
  85.       });
  86.       console.log("Old allow permission leftovers:", permDiff.old.allow, permDiff.old.allow.length);
  87.       console.log("Old deny permission leftovers:", permDiff.old.deny, permDiff.old.deny.length);
  88.       // Checking if any overwrites are left for allow and deny arrays of the old overwrite collection
  89.       // If an overwrite makes it to this point, it means that the overwrite was changed from True/False to Neutral
  90.       // If the overwrites exist for each state, then structure the string for them indicating that they've changed from True/False to Neutral
  91.       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`));
  92.       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`));
  93.       // Converting the sub-structure object to a string for the channelChanges object and indicating the type and name of the overwrite target
  94.       switch (overwrite.type) {
  95.         case "role": {
  96.           let roleObj = newChannel.guild.roles.get(overwrite.id);
  97.           if (!roleObj) console.log("Could not find role", overwrite.id);
  98.           channelChanges.overwrites.push(`Overwrites for role ${roleObj.name}:
  99.           ${changes.allowed.length ? `**Allowed:**\n - ${changes.allowed.join("\n - ")}`: ""}
  100.           ${changes.denied.length ? `**Denied:**\n - ${changes.denied.join("\n - ")}`: ""}
  101.           ${changes.neutralized.length ? `**Neutralized:**\n - ${changes.neutralized.join("\n - ")}`: ""}`);
  102.           console.log("", channelChanges.overwrites);
  103.           break;
  104.         }
  105.         case "user": {
  106.           let userObj = newChannel.guild.members.get(overwrite.id);
  107.           if (!userObj) console.log("Could not find member ", overwrite.id);
  108.           channelChanges.overwrites.push(`Overwrites for ${userObj.name}:
  109.           ${changes.allowed.length ? `**Allowed:**\n - ${changes.allowed.join("\n - ")}`: ""}
  110.           ${changes.denied.length ? `**Denied:**\n - ${changes.denied.join("\n - ")}`: ""}
  111.           ${changes.neutralized.length ? `**Neutralized:**\n - ${changes.neutralized.join("\n - ")}`: ""}`);
  112.           break;
  113.         }
  114.       }
  115.       // Deleting overwrites object from new perms collection, to detect if there are any new overwrites created for a user or object
  116.       console.log("Deleted Perms", newPerms.delete(overwrite.id));
  117.     });
  118.     console.log(newPerms);
  119.     // Detecting for any added overwrites
  120.     if (newPerms.length !== 0) newPerms.tap(permObj => {
  121.       console.log(permObj);
  122.       switch (permObj.type) {
  123.         case "role": {
  124.           let roleObj = newChannel.guild.roles.get(permObj.id);
  125.           if (!roleObj) return console.log("Could not find role", permObj.id);
  126.           // Adding a string that only tells that the overwrite has been created for the role
  127.           return channelChanges.overwrites.push(`Added role ${roleObj.name}'s overwrite.`);
  128.        }
  129.        case "user": {
  130.          let userObj = newChannel.guild.members.get(permObj.id);
  131.          if (!userObj) return console.log("Could not find member ", permObj.id);
  132.          // Adding a string that only tells that the overwrite has been created for the user
  133.          return channelChanges.overwrites.push(`Added user ${userObj.username}'s overwrite.`);
  134.         }
  135.       }
  136.     });
  137.   } else {
  138.     // If the change was caused by edit to the channel, like its name or description
  139.     channelChanges.changes = auditEntry.changes.map(changeObj => `**${changeObj.key.replace(/^(\w)/, (_, word) => word.toUpperCase())}:** From ${changeObj.old} to ${changeObj.new}.`);
  140.   }
  141.   // Embed that structures and finally sends to the Log channel
  142.   return logChannel.send({embed:{
  143.     author: {name: "Channel Update", icon_url: auditEntry.executor.avatarURL},
  144.     description: `<@${auditEntry.executor.id}> updated a channel.`,
  145.     fields: [
  146.       {name: "Channel Details", value: `**Name:** ${newChannel.name} (<#${newChannel.id}>)
  147.       **ID:** ${newChannel.id}`},
  148.       {name: "Changes", value: `${channelChanges.changes[0] ? channelChanges.changes.join("\n") : "None"}`},
  149.       {name: "Permission Overwrites", value: `${channelChanges.overwrites.join("\n")}`}
  150.   ],
  151.     timestamp: new Date().toISOString(),
  152.     color: 4359924
  153.   }});
  154. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement