I wanted to know how I could add a role to a specific user within DMs.
With the new Discord.js update, it's tricky, and can't find a way around it.
Thanks.
My attempt:
var guild = client.guilds.cache.get("[GUILDID]")
var buyerRole = guild.roles.cache.get("[ROLE ID]")
console.log(message.author.id) // Works
var guildMember = guild.members.fetch(message.author.id)
console.log(guildMember.displayName) // Returns 'undefined'
guildMember.setNickname(guildMember.username+" | Buyer") // Error
console.log(buyerRole.color) // Works
Output: guildMember.setNickname is not a function
That's because you fetch the member but never await it. .fetch returns a promise so the right way to get guildMember is like this:
const guildMember = await guild.members.fetch(message.author.id)
Related
Hey I wanted to check if a user had a role, although all other methods are quite outdated and I've tried a couple of things, none of them work.
My attempt:
var guild = client.guilds.cache.get("Guild ID")
var buyerRole = guild.roles.cache.get("Role ID")
await guild.members.fetch()
const guildMember = guild.members.cache.get(message.author.id)
if(guildMember.roles.find(buyerRole.id)){...
Well, you're going to want to use member.roles.cache.some() to achieve this.
var guild = client.guilds.cache.get("Guild ID")
var buyerRole = guild.roles.cache.get("Role ID")
const guildMember = await guild.members.fetch('User ID');
if(guildMember.roles.cache.some(x => x.id == buyerRole.id)){...
.some will always return a boolean, so it's better for you to use it like that.
After a bit of debugging, it turns out that you can use
message.author._roles instead of message.author.roles in order to get the complete list array.
I'm trying to create a command where if you say a slash command with a use parameter then it will give that user the role. I keep receiving this error even though I know that the member exists.
TypeError: Cannot read properties of undefined (reading 'roles')
My code:
const { commandName, options } = interaction;
const user = options.getUser('user');
if (commandName == 'givebetatester'){
console.log(user);
const role = interaction.guild.roles.cache.get('917609388154425374');
interaction.reply('Success');
user.member.roles.add(role);
}
I've double-checked that I have the role and the user exist and I have no idea what's wrong at this point. Any help would be appreciated.
You can only go from a GuildMember to User and not the other way around. You're trying to go from a User to a GuildMember by using user.member
Either change your slash command options to accept a Member instead of a User
Or ensure you have the Guild Member's Intent enabled and fetch the GuildMember object with the User id:
// Async/Await
const member = await interaction.guild.members.fetch(user.id);
Fixed! I switched from user to mentionable which might break if someone tries to type something other than a role but it does the trick.
Code:
const { commandName, options } = interaction;
const user = options.getMentionable('user');
if (commandName == 'givebetatester'){
const role = interaction.guild.roles.cache.get('917609388154425374');
user.roles.add(role);
interaction.reply('<a:ncheckmark:917609071195074600>');
}
So im doing a mute function where i add a muted role based on the channel they are muted from, my issue here is that it actually refuses to get the guild member by id, and ends up with hasRole erroring out because discordMember is undefined when trying with id, if i use mention way no problem it works as intended.
Anyone got a surgestion to fix this.
const discordMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
const channelName = message.mentions.channels.first()
var role = message.guild.roles.cache.find(role => role.name == channelName.name + "-mute");
var hasRole = discordMember.roles.cache.has(role.id);
Closing since original issue was fixed.
I've gotten many errors in my code that I believe has been the result of mix-ups between GuildMembers and Users. Can someone explain the difference?
const user = message.mentions.users.first();
// TypeError: user.kick() is not a function
user.kick({ reason: 'spamming' });
// TypeError: user.ban() is not a function
user.ban({ reason: 'DM Advertising' });
// TypeError: message.author.hasPermission() is not a function
if (!message.author.hasPermission('ADMINISTRATOR')) return;
console.log(user.displayName); // undefined
// TypeError: message.member.createdAt() is not a function
embed.addField('Account Created', message.member.createdAt());
client.on('guildMemberUpdate', (oldMember, newMember) => {
console.log(`${newMember.tag} was updated`); // 'undefined was updated'
});
if (message.member.bot) return; // undefined
// TypeError: Cannot read property 'add' of undefined
user.roles.add(newRole)
const target = message.client.users.cache.get(args[0])
console.log(target.displayName) // undefined
From Official Discord.js Guide - Common Questions:
A lot of users get confused as to what the difference between Users and GuildMembers is. The simple answer is that a User represents a global Discord user and a GuildMember represents a Discord user on a specific server. That means only GuildMembers can have permissions, roles, and nicknames, for example, because all of these things are server-bound information that could be different on each server that user is in.
Many errors in the code in question occur because you are trying to call a guild specific function on a global user. For example, GuildMember.kick() and GuildMember.ban(). A very common mistake that leads to this is using the message.mentions.users collection. As the name suggests, this returns a collection of Users.
If you simply want, for example, the mentioned user's avatar, or maybe they're username and discriminator, it would work out fine. But it will lead to errors if you ever try to, for example, try to get the date they joined your server using GuildMember.joinedAt()
Luckily, there are many easy ways to circumvent this issue. For example, using MessageMentions.members (returns a collection of GuildMembers) instead of MessageMentions.users
const member = message.mentions.members.first()
member.ban() // no error here!
Another common workaround is using the Guild.member() method, which accepts a User object or ID!
const user = client.user // get the user object
const guild = client.guilds.cache.get('Guild ID') // get the guild object
const member = guild.member(user) // convert the User object to a GuildMember!
Other useful tricks to easily convert Users to GuildMembers include:
Using message.member instead of message.author
Using guild.members.cache.get() instead of client.users.cache.get()
Using guild.members.fetch() instead of client.users.fetch()
Using presence.member instead of presence.user
It's also very useful to remember if specific event parameters provide Users or GuildMembers. For example, both guildMemberAdd() and guildMemberUpdate pass GuildMembers, but messageReactionAdd(), guildBanAdd(), and typingStart() all pass Users.
While many GuildMember properties and methods are not available for a User, the same is true the other way around. For example, GuildMember.tag does not exist. However, converting a GuildMember to a User is much easier than converting a User to a GuildMember. This is because of GuildMember.user:
The user that this guild member instance represents
So, although GuildMember.tag will return undefined, GuildMember.user.tag will not!
Just want to add to Lioness100's answer, the following no longer seems to work
const member = guild.member(user);
Instead you can use:
const member = guild.members.fetch(user);
This returns a promise so don't forget to deal with that accordingly
I am trying to send a message through discord.js and I am getting the following error:
(node:10328) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
Here is my code:
// Init
const Discord = require("discord.js");
const bot = new Discord.Client();
const channel = bot.users.cache.get('4257');
// Vars
// Code
bot.on("ready", () => {
console.log("The Bot is ready!");
channel.send("Test");
});
// Login
bot.login(" "); // I will hide this.
What is wrong? Is it the id on the channel variable? I just put in the id of my bot since I didn't know what to put in it.
At first I gave it all the permissions under "Text Permissions", but I also tried giving him admin privs. It still didn't work. What am I doing wrong?
The problem is this line:
const channel = bot.users.cache.get('4257');
Here's what's wrong with it:
const channel = bot.users.cache // this returns a collection of users, you want channels.
.get('4257'); // this is a user discriminator, you want a channel ID
Here's how to fix it:
const id = <ID of channel you want to send the message to>
const channel = bot.channels.cache.get(id)
// ...
channel.send('Test')
Here's an example:
const channel = bot.channels.cache.get('699220239698886679')
channel.send('This is the #general channel in my personal Discord')
How to get a Channel ID
ChannelManager Docs
const channel is empty here. You need to make sure value should be assigned in it.
channel.send("Test");
If its not mendatory that value will come then use try-catch.
try {
channel.send("Test");
} catch(e) {
console.log(e)
}
Please support with vote or answered if it helps, thanks.