Home > other >  Channel permissionOverwrites is working perfectly in 90% of the guilds but in some guilds its return
Channel permissionOverwrites is working perfectly in 90% of the guilds but in some guilds its return

Time:07-03

So as I said in the title in some guilds the channel permissionOverwrites is not working which leads to crashing the bot.

Here's the code:

const qu = message.guild.roles.cache.find(
  (role) => role.name.toLowerCase() === '',
);
if (!qu) {
  try {
    let qu = await message.guild.roles.create({
      name: '',
      color: '#',
    });
    try {
      await message.guild.channels.cache.forEach(async (channel) => {
        await channel.permissionOverwrites
          .edit(qu, {
            VIEW_CHANNEL: false,
          })
          .then(console.log)
          .catch(console.error);
      });
    } catch (e) {
      await console.log(e);
    }
  } catch (e) {
    await console.log(e);
  }
}

Here's the error I get on the console:

TypeError: Cannot read properties of undefined (reading 'edit')

channel.permissionOverwrites.edit, .create and .set returns same error. I don't know what's behind this error, if you got any idea why please let me know.

CodePudding user response:

Not every channel has permissionOverwrites. ThreadChannels, and DirectoryChannels for example don't have them. If a guild has these channels cached, you will receive an error in your forEach loop. I'd log and check channel.type to see which types cause these errors.

To solve this, you either need to filter these out:

await message.guild.channels.cache
  .filter(
    (channel) =>
      ![
        'GUILD_DIRECTORY',
        'GUILD_NEWS_THREAD',
        'GUILD_PRIVATE_THREAD',
        'GUILD_PUBLIC_THREAD',
      ].includes(channel.type),
  )
  .forEach(async (channel) => {
    await channel.permissionOverwrites
      .edit(qu, {
        VIEW_CHANNEL: false,
      })
      .then(console.log)
      .catch(console.error);
  });

... or only include the ones you need (e.g. TextChannel, and CategoryChannel):

await message.guild.channels.cache
  .filter((channel) =>
    [
      'GUILD_CATEGORY',
      'GUILD_TEXT',
      'GUILD_VOICE',
    ].includes(channel.type),
  )
  .forEach(async (channel) => {
    await channel.permissionOverwrites
      .edit(qu, {
        VIEW_CHANNEL: false,
      })
      .then(console.log)
      .catch(console.error);
  });
  • Related