You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在discord.js中统计指定分类下的频道数量?

在Discord.js v14中获取指定分类下的频道数量

直接给你修改后的可运行代码,同时拆解关键步骤帮你理解:

// 假设这是你的messageCreate事件回调,用fetch的话需要加async
client.on("messageCreate", async (message) => {
  const strMessage = message.content.trim().toLowerCase();
  if (strMessage === "!outline") {
    // 替换成你目标分类的实际ID(开启Discord开发者模式后右键分类复制)
    const targetCategoryId = "123456789012345678";
    
    // 方式1:从缓存获取(适合小型服务器,速度快)
    let category = message.guild.channels.cache.get(targetCategoryId);

    // 方式2:缓存中无数据时用fetch获取(适合大型服务器,需async/await)
    // let category = await message.guild.channels.fetch(targetCategoryId).catch(err => {
    //   message.reply(`获取分类失败:${err.message}`);
    //   return null;
    // });

    if (!category) return;

    // 校验是否为分类频道(v14中分类类型值为4,也可导入ChannelType用ChannelType.GuildCategory)
    if (category.type !== 4) {
      return message.reply("指定的ID不是分类频道!");
    }

    // category.children就是你提到的CategoryChannelChildManager,cache.size为频道总数
    const outlineSize = category.children.cache.size;

    // 用模板字符串拼接回复,比+号更清晰易读
    message.reply(`There are ${outlineSize} outlines currently hidden away. Type '?outline' to learn more about them.`);
  }
});

关键知识点拆解

  • 获取分类频道:通过服务器的channels管理器(message.guild.channels)的cache.get()或fetch()方法获取目标分类对象。
  • CategoryChannelChildManager的使用:分类频道的children属性就是CategoryChannelChildManager,它的cache.size直接返回该分类下所有频道的数量(包含文本、语音等类型频道)。
  • 类型校验:必须确认获取到的频道是分类类型,避免因ID错误导致逻辑异常。
  • async/await注意:如果使用fetch()方法,外层函数必须标记为async,否则会触发异步错误。

内容的提问来源于stack exchange,提问作者John Flamesinger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:50:26