使用Discord.js时出现TypeError: 无法读取undefined的'GUILD_MESSAGES'属性
解决discord.js中TypeError: Cannot read properties of undefined (reading 'GUILD_MESSAGES')错误
错误根源
你的代码适配的是discord.js v13及更早版本,但你安装了最新版(v14+)。新版本对Intents系统做了重大调整,同时还有API用法的变更,导致出现该报错。
具体修复步骤
修正Intents的引用方式
v14+版本中,需要用GatewayIntentBits替代旧版的Intents枚举,且不再支持Intents.ALL这种批量授权写法,必须明确声明所需权限。更新事件名称
旧版的message事件已被废弃,v14+中需替换为messageCreate事件。调整集合操作API
- 原
channel.members.array()方法已移除,需改为Array.from(channel.members.values())来将成员集合转为数组; - 建议筛选有效频道(比如文本/语音频道),避免拿到分类频道这类无法获取成员的频道,防止后续报错。
- 补全代码结构
你的代码末尾缺失闭合括号,导致语法不完整。
修复后的完整代码
const { Client, GatewayIntentBits } = require('discord.js'); // 声明机器人所需的Intents权限 const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages, GatewayIntentBits.GuildMembers // 获取成员列表必须开启该权限 ] }); client.on('ready', () => { console.log(`已登录为 ${client.user.tag}!`); }); client.on('messageCreate', message => { if (message.content === '!ping') { // 筛选服务器内可发送消息且能获取成员的频道 const validChannels = message.guild.channels.cache.filter(channel => channel.isTextBased() || channel.isVoiceBased() ); if (validChannels.size === 0) return message.reply('当前服务器没有可提及成员的频道!'); const channel = validChannels.random(); // 将成员集合转为数组 const members = Array.from(channel.members.values()); if (members.length === 0) return message.reply('这个频道里没有成员可以提及!'); const member = members[Math.floor(Math.random() * members.length)]; channel.send(`${member}, 你被点名啦!`); } }); // 替换为你的机器人Token完成登录 client.login('你的机器人Token');
额外注意事项
- 务必在Discord开发者门户的机器人设置中,开启
Server Members Intent和Message Content Intent这两个特权网关权限,否则无法获取成员列表和消息内容; - discord.js v14+要求Node.js版本不低于16.9.0,请确认你的Node版本符合要求。
内容的提问来源于stack exchange,提问作者only1smokey
相关产品推荐
相关产品推荐

