Discord.js 通过 ID 获取用户的角色:无法读取属性
Discord.js get Roles of a user by id: cannot read properties
我想制作一个 Discord.js 机器人,它只检查具有给定 ID 的成员是否有角色(按 ID)。我知道这是重复的,但是 .cache
对我不起作用,所以我使用了 guild.members.fetch
函数:
const { Client, Intents, GuildMemberManager } = require('discord.js');
const { token, server_id } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
function validateUser(user_id) {
const guild = server_id;
guild.members.fetch(user_id)
.then(console.log)
.catch(console.error);
}
validateUser(491553591434412057)
// Login to Discord with your client's token
client.login(token);
但是,我运行陷入了错误:
TypeError: Cannot read properties of undefined (reading ‘fetch‘).
有没有人知道在没有书面消息等的情况下获得角色的更好方法,或者如何解决这个问题?
问题是您的 guild
不是公会而是字符串 (server_id
)。您需要通过此 ID 获取公会:
const guild = client.guilds.cache.get(server_id);
if (!guild)
return console.log(`Can't find the guild with ID ${server_id}`);
guild.members.fetch(user_id)
.then(member => {
// member.roles.cache is a collection of roles the member has
console.log(member.roles.cache)
if (member.roles.cache.has('ROLE ID'))
console.log('member has the role')
})
.catch(console.error);
我想制作一个 Discord.js 机器人,它只检查具有给定 ID 的成员是否有角色(按 ID)。我知道这是重复的,但是 .cache
对我不起作用,所以我使用了 guild.members.fetch
函数:
const { Client, Intents, GuildMemberManager } = require('discord.js');
const { token, server_id } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
function validateUser(user_id) {
const guild = server_id;
guild.members.fetch(user_id)
.then(console.log)
.catch(console.error);
}
validateUser(491553591434412057)
// Login to Discord with your client's token
client.login(token);
但是,我运行陷入了错误:
TypeError: Cannot read properties of undefined (reading ‘fetch‘).
有没有人知道在没有书面消息等的情况下获得角色的更好方法,或者如何解决这个问题?
问题是您的 guild
不是公会而是字符串 (server_id
)。您需要通过此 ID 获取公会:
const guild = client.guilds.cache.get(server_id);
if (!guild)
return console.log(`Can't find the guild with ID ${server_id}`);
guild.members.fetch(user_id)
.then(member => {
// member.roles.cache is a collection of roles the member has
console.log(member.roles.cache)
if (member.roles.cache.has('ROLE ID'))
console.log('member has the role')
})
.catch(console.error);