Discordjs V13:从直接消息添加角色



我正试图为一个直接向机器人发送消息的用户分配一个角色。虽然该用户被分配了这个角色,但它抛出了下面的错误并关闭了我的程序。我已经研究这个问题几个小时了,但仍然没有运气。

TypeError: Cannot read properties of undefined (reading 'id')

错误堆栈

TypeError: Cannot read properties of undefined (reading 'id')
at GuildMemberRoleManager.get cache [as cache] (C:UsersjoshDesktopdiscordnode_modulesdiscord.jssrcmanagersGuildMemberRoleManager.js:36:101)
at Client.<anonymous> (C:UsersjoshDesktopdiscorddiscordBot.js:46:23)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
TypeError Cannot read properties of undefined (reading 'id')
UNHANDLED REJECTION! 💥 Shutting down...
[nodemon] app crashed - waiting for file changes before starting...

这是我的密码。

const { Client, Intents } = require('discord.js');
const client = new Client({
partials: ['CHANNEL'],
intents: [Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILD_MEMBERS],
});
client.once('ready', () => {
console.log(`Ready!`);
});
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
if (message.content.startsWith('/test')) {
const member = await client.guilds.cache
.get(process.env.DISCORD_GUILD_ID)
.members.fetch(message.author.id);
await member.roles.add('123456789012345678');
}
});
client.login(process.env.DISCORD_TOKEN);

这是因为缺乏GUILDS意图。如果你看一下源代码,在这里,它显示它试图从缓存中获取@everyone角色,但找不到它,因为它没有被缓存(给出undefined(。

提供修复的GUILDS意图

const client = new Client({
partials: ['CHANNEL'],
intents: [Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS],
})

最新更新