Search code examples
javascriptmovecategorieschanneldiscord.js

Add channel to category by name


    var server = message.guild;
    for (var i = 0; i < server.channels.array().length; i++) {
        server.channels.array()[i].delete();
    }

    server.createChannel("Text Channels", "category");
    server.createChannel('general', "text");

I am trying to make the text channel 'general` go into the category 'Text Channels'

All the solutions I have found rely on you knowing the categories id. I was wondering if there is a way I could get the category id, or else move general into "Text Channels" simply by its name.

NOTE:: Currently I am thinking of something along these lines to get the category id:

var categoryID = server.categories.find("name","Text Channels");

Then to use

server.channels.find("name","general").setParent(categoryID);

Solution

  • You can use GuildChannel.setParent(). Please keep in mind that categories are considered as channels by Discord: CategoryChannel extends GuildChannel, so you can check the type with GuildChannel.type

    To assign an existing channel:

    let category = server.channels.find(c => c.name == "Text Channels" && c.type == "category"),
      channel = server.channels.find(c => c.name == "general" && c.type == "text");
    
    if (category && channel) channel.setParent(category.id);
    else console.error(`One of the channels is missing:\nCategory: ${!!category}\nChannel: ${!!channel}`);
    

    To create a new channel:

    server.createChannel("general", "text")
      .then(channel => {
        let category = server.channels.find(c => c.name == "Text Channels" && c.type == "category");
    
        if (!category) throw new Error("Category channel does not exist");
        channel.setParent(category.id);
      }).catch(console.error);
    

    Edit: discord.js@v12
    The only thing that changes is that you have to use the GuildChannelManager for everything.

    let category = server.channels.cache.find(c => c.name == "Text Channels" && c.type == "category"),
      channel = server.channels.cache.find(c => c.name == "general" && c.type == "text");
    
    if (category && channel) channel.setParent(category.id);
    else console.error(`One of the channels is missing:\nCategory: ${!!category}\nChannel: ${!!channel}`);
    
    server.channels.create("general")
      .then(channel => {
        let category = server.channels.cache.find(c => c.name == "Text Channels" && c.type == "category");
    
        if (!category) throw new Error("Category channel does not exist");
        channel.setParent(category.id);
      }).catch(console.error);