I want to include a '-random' command that will tag random member of a server. I have found the following code:
if(command === 'random'){
let randomUser = message.guild.members.cache.random().user;
message.channel.send('<@'+randomUser+'>');
}
It works but it will only tag me, the bot itself, or someone else if that person recently wrote in the channel. How do I fix this?
Fetch all the members first, then call random()
on the returning collection.
if (command == 'random') {
message.guild.members.fetch()
.then(allMembers => {
const member = allMembers.random();
message.channel.send(member.toString());
})
.catch(console.error);
}
Ensure you have the GuildMember's intent enabled for fetching to work.