Discord.js报错:TypeError: Cannot read properties of undefined (reading 'FLAGS')求助
解决Discord机器人启动报错:TypeError: Cannot read properties of undefined (reading 'FLAGS')
问题场景
开发Discord机器人时,启动后触发报错,无法正常上线:
机器人代码
const Discord = require("discord.js") const { Client, Intents } = require('discord.js'); const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] }); client.on("ready", () => { console.log('Logged in as ${client.user.tag}!') console.log("Bot is online!") }) client.on("message", msg => { if (msg.content === "ping") { msg.reply("no1se"); } }) client.login("my token")
报错信息
TypeError: Cannot read properties of undefined (reading 'FLAGS') at Object.<anonymous> (/home/runner/no1seAlerts-1/index.js:4:47) at Module._compile (node:internal/modules/cjs/loader:1101:14) Hint: hit control+c anytime to enter REPL. (node:2004) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created)
解决方案
报错原因是你使用的Discord.js版本为v14+,该版本对Intents调用方式和事件名称做了变更,修复步骤如下:
- 替换Intents调用方式:v14+移除了
Intents.FLAGS,改用IntentsBitField.Flags声明网关意图 - 更新消息事件:原
message事件已更名为messageCreate,不修改会导致无法接收消息 - 修复模板字符串:原代码中
console.log用单引号包裹模板字符串,需改为反引号才能正确解析变量
修改后的完整代码:
const { Client, IntentsBitField } = require('discord.js'); const client = new Client({ intents: [ IntentsBitField.Flags.Guilds, IntentsBitField.Flags.GuildMessages ] }); client.on("ready", () => { console.log(`Logged in as ${client.user.tag}!`) console.log("Bot is online!") }) client.on("messageCreate", msg => { if (msg.content === "ping") { msg.reply("no1se"); } }) client.login("your-token-here")
额外说明
- 若坚持使用Discord.js v13版本,
Intents.FLAGS是可用的,但v13已停止维护,建议升级到最新稳定版 - 确保机器人在Discord开发者平台已开启对应的网关权限(Guilds、Guild Messages)
内容的提问来源于stack exchange,提问作者NO1SE
相关产品推荐
相关产品推荐

