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

Discord.js严格相等判断失效,频道统计数值为0问题求助

解决Discord.js频道类型统计为0的问题

看起来你碰到的是Discord.js版本更新带来的频道类型常量变化问题,再加上不必要的重复API调用拖低了效率。我来帮你拆解并修复这个问题:

问题根源

从Discord.js v14开始,官方弃用了旧的频道类型字符串标识(比如"GUILD_CATEGORY"、"GUILD_TEXT"),改用ChannelType枚举类的成员来标识频道类型。你直接用旧字符串做全等判断,自然匹配不到任何频道,所以统计值全为0。另外你多次调用await interaction.guild.channels.fetch()会重复向Discord API发起请求,既浪费资源又没必要。

修复步骤

  1. 导入ChannelType枚举:确保代码顶部已经导入这个枚举(根据你的模块系统选择对应写法)
  2. 复用频道列表:只调用一次channels.fetch(),把结果存在变量里重复使用,避免重复请求
  3. 用枚举成员判断类型:替换旧的字符串常量为ChannelType的对应成员,比如ChannelType.GuildCategory

修改后的完整代码

// 先导入ChannelType(根据你的模块系统选择一种)
// CommonJS写法
const { ChannelType } = require('discord.js');
// ES模块写法
// import { ChannelType } from 'discord.js';

// 只请求一次API,把所有频道数据存下来复用
const allChannels = await interaction.guild.channels.fetch();

// 拼接统计文本
const channelStats = 
`**Channels:** \`${allChannels.filter(c => c.type !== ChannelType.GuildCategory).size}\`
**Category:** \`${allChannels.filter(c => c.type === ChannelType.GuildCategory).size}\`
**Text:** \`${allChannels.filter(c => c.type === ChannelType.GuildText).size}\`
**Voice:** \`${allChannels.filter(c => c.type === ChannelType.GuildVoice).size}\`
`;

补充说明

你尝试用channeltype.text报错是因为两个小问题:

  • 枚举的正确名称是ChannelType(首字母大写,驼峰命名)
  • 文本频道对应的枚举成员是GuildText,不是小写的text

这样修改后,既能准确统计各类频道的数量,也优化了API请求的效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 18:05:18