How do I check if a permission is set to neutral (“/”) with discord.js?

I want to check if a channel override is set to neutral/null/”/”. I know how to set a permission to neutral, but not how to check if it is in that state. Any help would be highly appreciated.

Answer

You could create a helper function that checks the permissionOverwrites in a channel. channel.permissionOverwrites returns a collection of permissionOverwrites.

  1. If the size of the collection is zero, you know that everything is in neutral position. If there is at least one permission allowed or denied for the @everyone role, the collection size won’t be zero.
  2. If there is at least one element in the collection, you can check their allow and deny properties. If their bitfield property is larger than zero, it is not set to neutral.

Collections have an .every() method that checks if every element in the collection passes the test implemented in the callback function. If both the allow and deny props bitfield is 0, you know that it’s set to neutral.

Check the function below:

function isNeutral({ channel }) {
  const { permissionOverwrites } = channel;

  if (permissionOverwrites.size === 0) return true;

  return permissionOverwrites.every(
    (perm) => perm.allow.bitfield === 0 && perm.deny.bitfield === 0,
  );
}

If you only want to check a single overwrite in a channel, you can update the function like this:

function isNeutral({ channel, overwriteID = null }) {
  const { permissionOverwrites } = channel;

  if (permissionOverwrites.size === 0) return true;

  if (overwriteID) {
    const perm = permissionOverwrites.get(overwriteID);
    if (!perm) {
      throw new Error(
        `No permission overwrite found with the role ID or user ID of "${overwriteID}" in this channel.`,
      );
    }
    return perm.allow.bitfield === 0 && perm.deny.bitfield === 0;
  }

  return permissionOverwrites.every(
    (perm) => perm.allow.bitfield === 0 && perm.deny.bitfield === 0,
  );
}

And this is how you can use it inside your event handlers:

client.on('message', (message) => {
  if (message.author.bot) return;

  try {
    const neutral = isNeutral({
      channel: message.channel,
    });

    console.log(`All of the permission overwrites are set to neutral: ${neutral}`);
  } catch (error) {
    console.log(error);
  }
});