Why doesn't Collection#find work for offline members who have no roles? (discord.js) - discord.js

My Goal
My goal is to figure out why Collection#find returns undefined when I try to find a user in my server, but they're offline and have no roles.
Expectation
Usually the console logs an array of all the properties of the user
Actual Result
The console logs Collection#find, as undefined if the user in my server is offline and has no roles
What I've Tried
I've tried using Collection#get, but it turns out that it returns the same response. I've tried searching this up on Google, but no one has asked this question before.
Reproduction Steps
const Discord = require('discord.js');
const client = new Discord.Client();
const {prefix, token} = require('./config.json');
client.once('ready', () => {
console.log('Client is online');
const user = client.users.cache.find(user => user.tag === 'Someone#1234');
console.log(user);
};
client.login(token);
Make sure that whoever is helping you, whether it's an alt account or your friend, that they have no roles, and they're completely offline in your server
Output:
Client is online undefined

I had the same problem. I don't know why this happens, but I used this line to fix that:
((await m.guild.members.fetch()).filter(mb => mb.id === "The ID")).first()`
Basically, this collect all the members, then filters them with the property you want, and the first() at the end is to make it a single object instead of a collection.

Instead of the user.tag property, try using the user.username and the user.discriminator properties. This worked for me
const user = client.users.cache.find(user => user.username === 'Someone' && user.discriminator === '1234');
Also check spelling, capitalization, ect.

A simple solution to my problem is just create an async function and use await guild.members.fetch() to cache the users and then use Collection#find to get the user.

Related

I want a discord bot send a dm to somebody by their id

if (message.content === "!test"){
client.users.cache.get('id').send('message');
console.log("message sent")
}
This method doesn't work and I wasn't able to find any other methods that worked
Is there a spelling mistake or this method is outdated?
I've actually encountered this error myself once. There are two problems you might be facing here:
The user isn't cached by discord.js yet
There isn't a DMChannel open for that user yet
To solve the first one, you have to fetch the user before doing anything with it. Remember this is a Promise, so you'll have to either await for it to complete or use .then(...).
const user = await client.users.fetch('id')
Once you've fetched your user by their ID, you can then create a DMChannel which, again, returns a promise.
const dmChannel = await user.createDM()
You can then use your channel like you normally would
dmChannel.send('Hello!')
Try to create a variable like this:
var user = client.users.cache.find(user => user.id === 'USER-ID')
And then do this:
user.send('your message')

How do i make discord.js list all the members in a role?

if(message.content == `${config.prefix}mods`) {
const ListEmbed = new Discord.MessageEmbed()
.setTitle('Mods:')
.setDescription(message.guild.roles.cache.get('813803673703809034').members.map(m=>m.user.tag).join('\n'));
message.channel.send(ListEmbed);
}
Hey so iam making a command which displays all the members with that role but it only seems to be sending 1 of the mods
await message.guild.roles.fetch();
let role = message.guild.roles.cache.find(role => role.id == args[0]);
if (!role) return message.channel.send('Role does not exist'); //if role cannot be found by entered ID
let roleMembers = role.members.map(m => m.user.tag).join('\n');
const ListEmbed = new Discord.MessageEmbed()
.setTitle(`Users with \`${role.name}\``)
.setDescription(roleMembers);
message.channel.send(ListEmbed);
};
Make sure your command is async, otherwise it will not run the await message.guild.roles.fetch(); - this fetches all roles in the server to make sure the command works reliably.
In Discord.jsV12 the get method was redacted and find was implemented.
Aswell as this, I would highly recommend defining variables to use in embeds and for searching since it is much more easy to error trap.
If you have many members with the role, you will encounter the maximum character limit for an embeds description. Simply split the arguments between multiple embeds.

Set Role Color for Discord.js bot

I am trying to make my bot's role a pink color for the current server using the Client.on("ready") However whenever I run the bot with what I currently have the console returns:
(node:6504) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cache' of undefined
Here is my code I am currently using. I know I need to for loop on every guild but I'm not sure how I would do that, I could use a for or just a .forEach however I can't find the correct way to do such.
const role = client.guild.roles.cache.get('Aiz Basic+');
role.edit({ name: 'Aiz Basic+', color: '#FFC0CB' });
In advance thank you to anybody who replies and helps with my message.
Client#Guild Isn‘t existing. Only Client#Guilds. You can fix this problem by looping through the cache of all your guilds with:
client.guilds.cache.forEach((g) => { })
And inside the loop you can use your code after fixing the .get function, because the get function needs a role id not a role name. You could find the role via the name by writing:
const role = <Guild>.roles.cache.find((r) => r.name === /* The role name */);
Make sure you replaced <Guild> with your guild variable.
Try this code if client.guild is not defined, it could also be because you are using bot instead of client
let role = message.guild.roles.cache.find(role => role.name === "Aiz Basic+");

Can't get user avatar

I'm trying to get user's avatars for a welcome message but when someone joins it never shows it. I've tried many different methods. Here is my current code.
bot.on('guildMemberAdd', member => {
const exampleEmbed = new MessageEmbed()
.setColor('#0000FF')
.addField('Welcome!', `Welcome to the server, ${member}! Go to <#channel> for the rules, then grab some roles at <#channel>!`)
.setThumbnail(member.user.displayAvatarURL)
member.guild.channels.cache.get('693219932904751177').send(exampleEmbed);
});
All you need to do it add a () behind the .displayAvatarURL
So the line would look like this:
.setThumbnail(member.user.displayAvatarURL())

How can i get mentioned user's username in discord.js

Read the title and will be glad if anyone can help me guys
For an example messages.mentions.first(). Like that, is there anything for mentioned user's username?
The best way would be to use the message.mentions.users.first(), as this will actually give you the first user mentioned in a message. (message.mentions is not a collection). If there are no users mentioned, the first will result in undefined, so you will probably want to check for that. Once you have a user, you will want to access the username property.
Example:
// Assuming we just need a message event
client.on('message', (message) => {
const user = message.mentions.users.first();
if (user === undefined) {
return; // Do not proceed, there is no user.
}
const name = user.username;
// Do stuff with the username
})
Sources:
message.mentions
message.mentions.users
message.mentions.members.first().user.username;
This would give you the username of the first mention.
You could also do message.mentions.users.first().username;

Resources