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

如何使用discord.js获取成员数少于10人的guild

错误排查

  • 核心错误:你在遍历client.guilds.cache的回调中,判断条件误用了message.guild.memberCount,始终取触发命令所在服务器的成员数做校验,而非当前遍历到的guild对象的成员数,导致只要当前触发服务器成员数符合条件,就会输出所有遍历到的服务器名称
  • 额外问题:代码末尾存在多余的闭合大括号,属于语法冗余
  • 注意事项:如果使用discord.js v14及以上版本,需要先在Discord开发者后台开启Bot的Server Members Intent权限,同时初始化客户端时传入Guilds、GuildMembers网关意图,否则获取的成员数会不准确

正确实现

const Discord = require('discord.js');
// v14版本客户端初始化示例,需传入正确的网关意图
const client = new Discord.Client({
  intents: [
    Discord.GatewayIntentBits.Guilds,
    Discord.GatewayIntentBits.GuildMembers
  ]
});

// 示例:在消息创建事件中触发查询逻辑
client.on('messageCreate', async message => {
  // 可替换为你自己的触发命令规则
  if (message.content !== '!查询小服务器') return;
  // 先筛选所有符合条件的服务器,再统一输出避免触发发送频率限制
  const smallGuildNames = client.guilds.cache
    .filter(guild => guild.memberCount <= 10)
    .map(guild => guild.name);

  if (smallGuildNames.length === 0) {
    return message.channel.send('未找到成员数≤10的服务器');
  }
  message.channel.send(`成员数≤10的服务器列表:\n${smallGuildNames.join('\n')}`);
});

client.login('你的Bot令牌');

内容的提问来源于stack exchange,提问作者Mr.Unknown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:42:04