如何使用discord.js获取Discord服务器全部成员并输出到控制台
问题解决思路与修正代码
现有代码核心问题
- 未定义
server变量,无法定位到目标服务器,需要替换为你要查询的Discord服务器ID - 缺少Discord Bot必填的
Server Members Intent特权网关权限,该权限是获取服务器成员列表的硬性要求 list.members是discord.js的成员管理器对象,不能直接遍历,需要先从缓存读取或主动拉取全量成员- 外部
if (member)判断逻辑无效,member是forEach循环内的局部变量,外部访问会直接抛出引用错误 - 未做非空判断,若服务器ID错误导致获取不到Guild对象,代码会直接崩溃
操作前置步骤
- 打开Discord开发者后台,进入你的Bot应用设置页,找到「Bot」分类,下滑到Privileged Gateway Intents区域,打开
Server Members Intent开关并保存设置 - 初始化Bot Client时需要声明对应的网关意图:
- 若使用discord.js v13版本,初始化代码如下:
const { Client, Intents } = require('discord.js'); const client = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, // 必须添加该意图才可读取成员列表 Intents.FLAGS.GUILD_MESSAGES ] });- 若使用discord.js v14版本,初始化代码调整为:
const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, // 必须添加该意图才可读取成员列表 GatewayIntentBits.GuildMessages ] });
修正后的命令代码
exports.run = async (bot, message, args) => { // 将此处替换为你的目标服务器ID,字符串格式 const targetGuildId = '你的服务器ID'; const guild = bot.guilds.cache.get(targetGuildId); // 提前判断服务器是否存在,避免报错 if (!guild) return console.log('未找到对应服务器,请检查ID是否正确'); try { // 主动拉取全量成员,避免缓存不全导致数据遗漏 const allMembers = await guild.members.fetch(); // 遍历打印用户名 allMembers.forEach(member => { console.log(member.user.username); }); console.log(`共获取到 ${allMembers.size} 名成员`); } catch (err) { console.error('拉取成员列表失败:', err); } } exports.help = { name: 'memberlog' }
内容的提问来源于stack exchange,提问作者shrimp580
相关产品推荐
相关产品推荐

