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

discord.js获取所有guild用户ID时报client.guilds.forEach不是函数如何解决

报错原因

你遇到的TypeError: client.guilds.forEach is not a function报错是因为discord.js v12及更高版本对API做了调整:所有管理器类的属性(比如client.guilds、guild.members)都不会直接返回集合,需要先调用.cache属性拿到存储数据的Collection实例,才能使用forEach、get等集合方法。同时旧版的message事件已经被废弃,新版统一使用messageCreate事件。

前置准备

  • 前往Discord开发者后台,在你的机器人应用的「Bot」设置页,开启Privileged Gateway Intents下的Server Members Intent,否则无法正常拉取服务器成员列表
  • 初始化客户端时要声明需要的Intent,至少包含Guilds、GuildMembers、GuildMessages、MessageContent这几个

修改后可用代码

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent
  ]
});

// 监听消息创建事件
client.on('messageCreate', message => {
  if (message.content === '$listmids') {
    // 仅允许指定ID的用户触发命令
    if (message.author.id !== "651167823749578798") return;
    // 遍历所有服务器
    client.guilds.cache.forEach(guild => {
      console.log(`当前服务器ID:${guild.id}`);
      // 遍历当前服务器所有成员
      guild.members.cache.forEach(member => {
        console.log(`成员ID:${member.user.id}`);
      });
    });
  }
});

client.login('你的机器人Token');

额外说明

  • 如果你使用的是discord.js v13/14版本,上述代码直接可用,v12版本只需要把Intent的引用方式换成对应的枚举即可
  • 如果服务器成员数量较多,建议加入延时逻辑避免触发速率限制,比如每拉取一个服务器的成员列表后等待1-2秒再处理下一个

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 07:30:05