Search code examples
javascriptdiscorddiscord.js

Discord channel category name not found even though it exists


Im using the lastest Discord.js 14 and trying to create a new channel in the support category. I manually created the category so I know it exists. There are no channels in this category at present and this new channel the bot is trying to create will be the first one. When I run this code console.log(supportCategory) the terminal shows undefined

Why?

// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits, ChannelTypes } = require('discord.js');
const { token } = require('./config.json');

// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
    console.log(`Ready! Logged in as ${c.user.tag}`);
  
});

client.on('ready', async () => {
  console.log(`Logged in as ${client.user.tag}!`);
  const guild = client.guilds.cache.first();
  const supportCategory = guild.channels.cache.find(channel => channel.type === 'GUILD_CATEGORY' && channel.name === 'Support');

  console.log(supportCategory) //this produces undefined

  try {
    const channel = await guild.channels.create('new-channel-name', {
      type: 'GUILD_TEXT',
      parent: supportCategory.id,
      permissionOverwrites: [
        {
          id: guild.roles.everyone.id,
          deny: ['VIEW_CHANNEL'],
        },
      ],
    });
    console.log(`Channel created: ${channel.name}`);
  } catch (error) {
    console.error(error);
  }
});

// Log in to Discord with your client's token
client.login(token);

Solution

  • You need to use the ChannelType enum to check a channel's category.

    const supportCategory = guild.channels.cache.find(channel => channel.type === ChannelType.GuildCategory && channel.name === 'Support');