Add channel to category by name

强颜欢笑 提交于 2020-12-30 07:42:31

问题


    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);

回答1:


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);


来源:https://stackoverflow.com/questions/53479542/add-channel-to-category-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!