Getting nicknames of users of my Discord bot - discord

I can see the names, ids and user numbers of the servers where my bot is located, but how can I get the list of users (nicknames)?

You can make use of guild.members.fetch() in order to get all members and then use the nickname property to receive their nicknames. Finally I removed all bots with a simple filter.
const members = (await message.guild.members.fetch())
.filter((m) => !m.user.bot)
.map((m) => m.displayName);
console.log(members);
Working example as a command:
client.on("message", async (message) => {
if (message.author.bot) return;
if (message.content === "!list") {
const members = (await message.guild.members.fetch())
.filter((m) => !m.user.bot)
.map((m) => m.displayName);
console.log(members);
}
});
client.login("your-token");
Thanks to #MrMythical who suggested using displayName only. That property automatically returns the normal username when no nickname has been set for a user.

Users do not have nicknames, only guild members, if you are trying to fetch a list of server member nicknames.
You can use the code snippet from below:
const map = message.guild.members.cache.filter(c=> !c.member.user.bot).map(c=>c.displayName).join('\n');
console.log(map)
The
message.guild.members.cache.filter(c=> !c.member.user.bot)
Filters bots from the list, the
.map(c=>c.displayName).join('\n');
maps the data and only the user nicknames and joins them by paragraph breaks.
If there are any issues, please comment!

Related

Discord.JS - How to get user ID from username?

can someone please help me to retrieve username from user ID and send a message to the chat with that ID?
if (message.content.startsWith(prefix)) {
const [CMD_NAME, ...args] = message.content
.trim()
.substring(prefix.length)
.split(/\s+/);
if (CMD_NAME === "getid") {
const getid1 = new MessageEmbed()
.setDescription("❗️ | Please tag the member to retrieve the ID!")
.setColor(10181046);
if (args.length === 0) return message.reply(getid1);
const username = client.guilds.cache.get('<GUILD ID>');
const userid = client.users.cache.find(username => username.tag === 'Someone#1234').id
message.channel.send(`${username} id is ${userid}`);
}
}
});
When I type the command "d!getid #Username", it shows me this error:
C:\Users\USER\Desktop\DiscordBotas\index.js:152 const userid = client.users.cache.find(username => username.tag === 'Someone#1234').id TypeError: Cannot read property 'id' of undefined at Client. (C:\Users\USER\Desktop\DiscordBotas\index.js:152:90)
You are creating a lambda of a variable that you just defined above the actual lambda, this could probably mess with your code.
The const username = client.guilds.cache.get('<GUILD ID>'); is wrong.
The fetching of the userId should probably work if you fix the line above it.
You are trying to get the user the wrong way. Firstly, why are you trying to match a user's tag with a guild? Maybe you think guild.cache has users? Well actually, this is client.guilds.cache, which only has guilds in it, and it returns a guild, not a user. Secondly, to get a user, you can try this method:
const user = client.users.cache.find(u => u.tag === 'SomeUser#0000')
console.log(user.id);
Below is code to get user by ID, but it probably won’t help with this, considering you would already have access to the ID
const user = client.users.cache.get("<UserID>");
console.log(user);
Also, you should add code to see if user isn’t found (client can’t find user with the condition). Here is some code to check that:
//... the find user code I put
if(!user) return message.reply('User could not be found');
message.channel.send(user.id);

Leave message discord.js v12

I have a porblem. My leave message. There I have:
client.on("guildMemberAdd", member => {
const welcomeChannel = member.guild.channels.cache.find(
channel => channel.name === "welcome"
);
welcomeChannel.send(`Hosgeldin :heart: ${member}`);
});
client.on("guildMemberRemove", member => {
const welcomeChannel = member.guild.channels.cache.find(
channel => channel.name === "gelen-giden"
);
welcomeChannel.send(`Bye ${member}!`);
});
and then when somebody left then came <#id>.
I want to find his id because then I can make an link of the person who left.
It look like https://discordapp.com/users/732569703142129685 .
And then it should write 'Member' and this 'member' should be the link.
Please in v12.
Discord returns <#id> because the member that left doesn't have more guilds(servers) in common with you and he is no more in your cache. If you need his id for some deletion of rows in db you can get it as member.id
When a user leaves, he is no longer on the guild, so you can't find a channel on a server he isn't anymore in. You'll need to use client.channels.cache.find() in this case.
have a good day.

How do I check what roles my bot has? [Discord.js]

I am trying to find if my bot has a specific role so it can do something else. For example:
client.user.roles.cache.find(r => r.name === 'specific role');
My error:
TypeError: Cannot read property 'cache' of undefined
Let's start of by stating that users do not have roles, therefore you have to fetch the guildMember.
Fetching the guild member is easy;
First of all, you will have to fetch the guild the user is in. For example:
var guild = client.guilds.cache.get('guild-id');
Secondly, you will have to find the user in that guild. For example:
var member = guild.members.cache.get('user-id');
Then you will be able to move forward and fetch the roles
member.roles.cache.find(r => r.name === 'role-name');
The full example:
const Discord = require('discord.js'); //Define discord.js
const client = new Discord.Client(); //Define the client
client.on('message' message => { //Event listener
//Do something here
var guild = client.guilds.cache.get(message.guild.id);
var member = guild.members.cache.get(client.user.id);
member.roles.cache.find(r => r.name === 'role-name');
});
client.login('token'); //Login
So maybe I didnt explain my problem very well but here is what I found working for me message.guild.me.roles.cache.find(r=> r.name === 'a role') thanks to everyone for helping me !!!
You need to resolve the user into a GuildMember, since users don't have roles.
To do that you need a Guild class,after that you can use the guild.member() method to convert it to a member
const guild = client.guilds.cache.get('id of the guild'),
member = guild.member(client.user.id);
member.roles.cache.find(r=> r.name === 'name')
Another issue you might run into here is, the member constant being undefined, this can be solved by using guild.members.fetch(id) or enabling the Privileged Member intent in the Discord Developer Portal

How to Edit Embedded Message on Discord When Role Has Been Assigned or Removed

I am working on a Discord bot and I have an embed that shows the names of people who has that role, I want to make it edit that one message everytime the role is assigned or removed. Help would be very appreciated 🙂
You can use the Client#guildMemberUpdate. The event is fired whenever the GuildMember is updated. (This includes: role added, role removed, nickname changes etc.)
Here's a simple example:
client.on("guildMemberUpdate", (oldGuildMember, newGuildMember) => {
if (oldGuildMember.guild.id == "GuildID") { // Checking if the event was fired within the required Guild.
if (!oldGuildMember.roles.cache.equals(newGuildMember.roles.cache)) { // Checking if the roles were changed.
const Channel = client.channels.cache.get("ChannelIUD"); // Getting the channel your MessageEmbed is in.
const Role = oldGuildMember.guild.roles.cache.get("RoleID"); // Getting the Role by ID.
if (!Role || !Channel) return console.error("Invalid role or channel.");
Channel.messages.fetch("MessageID").then(message => { // Getting the MessageEmbed as a Message by ID
const Embed = new Discord.MessageEmbed(); // Updating the MessageEmbed.
Embed.addField(`Members of ${Role.name}`, Role.members.size > 0 ? `${Role.members.map(member => member.user.tag).join("; \n")};` : "This role has no members.");
Embed.setColor("RED");
message.edit(Embed).catch(error => console.error("Couldn't edit the message."));
}).catch(error => console.error("Couldn't fetch the message."));
};
};
});

Add a role to people that react with a certain emoji in a certain channel

I'm trying to make a discord.js bot for my server I made for people in my school. I'm trying to make a #classes channel and if you react to certain messages it gives you a role (which gives you access to the text channel for that class).
client.on('messageReactionAdd', (reaction, user) => {
console.log("client.on completed.")
if (message.channel.name === 'classes') {
console.log("if(message) completed.")
if (reaction.emoji.name === "reminder_ribbon") {
console.log("emoji test completed.")
const guildMember = reaction.message.guild.members.get(user.id);
const role = reaction.message.guild.roles.find(role => role.name === "FACS");
guildMember.addRole(role);
}
}
});
This is what I have tried so far, however, it does not give me/the other people reacted to it the role nor does it return an error message.
P.S. Also, how would I be able to make it so when they unreact it removes the role?
Edit: It seems it only gets reactions from cached messages/messages sent after bot startup. Also, message is not defined on the first if(message.channel.id) message.
Try to use the following code:
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.channel.id === '552708152232116224') {
if (reaction.emoji.name === "reminder_ribbon") {
const guildMember = reaction.message.guild.members.get(user.id);
const role = reaction.message.guild.roles.get('552709290427940875');
guildMember.addRole(role);
}
}
});
First of all, reaction.users is an Object with all the users that reacted on the message, so you first have to define to which user you want to assign the role. I fixed this fetching the guildMember with user.id.
The second mistake was that you tried to assign a role ID to a guildMember although you first have to fetch the role and then assign the role Object to the guildMember.

Resources