Discord.js get user by nickname - node.js

I'm having a hard time figuring out
Is is possible to find a user by his or her nickname via the discord.js npm package.
How can I query a user by his or her nickname?
i've tried several things but nothing returns the nickname and I can't quite figure out how their documentation works.
So far I haven't been able to tell how to do it.
I've done as so in my code.
const { Client } = require('discord.js')
const discordClient = new Client()
discordClient.on('message', message => {
if (message.author.bot) return
if (message.content.startsWith('!gpwarn')) {
// The command is something like '!gpwarn thomas'.
// If his nick name is thomas but his username is john it doesn't work.
})

Yes, and it's pretty simple. Do this:
const user = client.users.cache.find(user => user.username == "The user's name");
Reference:
UserManager

To meet your exact requirements you would search the guild members cache for the provided nickname. However, I personally would suggest using either a direct tag or a UserID for this, as multiple people can have the same nickname in the server.
const U = message.guild.members.cache.find(E => E.nickname === 'NICKNAME')
Getting by Tag:
const U = message.mentions.members.first()
Getting by ID:
const U = message.guild.members.cache.find(U => U.id === 'IDHERE')

First you need to identify the nickname argument, you can do this by splitting, slicing, and joining message.content.
Next I recommend you fetch all of the GuildMembers from the guild using GuildMemberManager#fetch(), This way you don't run into the error of a member being uncached.
Handle the promise using async/await and use Collection#find() to return the member.
const { Client } = require('discord.js')
const discordClient = new Client()
discordClient.on('message', async message => {
if (message.author.bot) return
if (message.content.startsWith('!gpwarn')) {
// Returns all of the text after !gpwarn
const query = message.content.split(' ').slice(1).join(' ').toLowerCase()
const members = await message.guild.members.fetch()
const memberToWarn = members.find(m => m.nickname.toLowerCase() === query)
if (!memberToWarn) // No member found error
console.log(memberToWarn) // [GuildMember]
}
})

Related

discord.js shading find a user in a specific guild by id

My bot use shards. And I try to get user roles in a specific guild by they ids.
Before sharding:
const serverSupportGuild = client.guilds.cache.get('myGuildId');
const user = serverSupportGuild.members.cache.get(id);
console.log(user._roles);
Now I try to do this:
const getServer = async (guildID) => {
const req = await client.shard.broadcastEval((c, id) => c.guilds.cache.get(id), {
context: guildID
});
return req.find(res => !!res) || null;
}
const serverSupportGuild = await getServer('myGuildId');
console.log("members: ", serverSupportGuild.members);
const user = serverSupportGuild.members.cache.get(id); ←← log ERROR
console.log("user: ", user);
members: [
'829707635787825152',
'660435627757666311'
]
TypeError: Cannot read properties of undefined (reading 'get')
Before sharding with my method i was able to see all members from my guild with they respective informations.
But now, I just have an array with bot id and my id. How can I get all members from a guild with shards ?
Thanks.
Sharding doesn't return complex objects, it returns simple things, like strings, or arrays of strings, as you see in your results. If you have more complex things to do, you need to do them inside of the broadcastEval context, as that is where the guild/channel/cache/member etc objects are visible.
Perform your tasks, then return from the getServer (which you might want to rename now, given this insight) and continue on with the code after having done the task(s) you wanted on the member(s) etc.

Check status of user

How do i check the status of a user in my server? as user.presence.status is depreciated. And I won't use
let guild = await client.guilds.cache.find(guild => guild.id === "xxx");
let guildMembers = await guild.members.fetch({ withPresences: true });
var onlineMembers = await guildMembers.filter(member => !member.user.bot && member.presence?.status != "offline");
Since this just checks who's online but doesn't actually return the status of the specific user I need
You can access it through <GuildMember>.presence.status, provided that the appropriate intents are enabled.
For help on intents you may want to look at the guide.
If you have the ID, you can do:
const member = await guild.members.fetch(ID);
console.log(member.presence.status)

Discord.js: Verify channel

I'm trying to make my own bot for my server, for now i'm focusing on the verify. By acting to the check mark emoji it'll add the verified role, and then it should remove only the user reaction, but instead it'll remove every reaction right away
client.on('messageReactionAdd', async (reactionReaction, user) => {
const message = reactionReaction.message;
const verifyChannel = message.guild.channels.cache.find(c => c.name === 'approvazione');
const member = message.guild.members.cache.get(user.id);
if (member.user.bot) return;
const verify = message.guild.roles.cache.get('728000975046180988');
if (reactionReaction.emoji.name === '✅' && message.channel.id === verifyChannel.id) {
member.roles.add(verify).catch(console.error);
await reactionReaction.remove(member).catch(console.error);
}
here is the message sent by the bot with it's own reaction
and here is the same message after i reacted, and both mine and the bot reaction are removed, i just want my reaction to be removed
If you look at the docs it takes no parameter for the user:
https://discord.js.org/#/docs/main/stable/class/MessageReaction?scrollTo=remove
This was changed in v12, the method now is to use .users.remove:
reactionReaction.users.remove(member);

Is there a way to get invites from ALL the guilds my bot is in?

Any ideas on how to get invites from a discord you aren't in but my bot is in?
I guess you want to get invited to every guild your bot is in
client.guilds.cache.forEach(guild => {
guild.channels.cache.filter(x => x.type != "category").random().createInvite()
.then(inv => console.log(`${guild.name} | ${inv.url}`));
});
Rez's answer is a common one but not a secure one, the random channel you get could be a channel you don't have permission to create an invite in.
This approach is safer, (might be a bit slower since async/await):
(This needs to be in an async function)
const invites = [];
//cant use async inside of forEach
//https://www.coreycleary.me/why-does-async-await-in-a-foreach-not-actually-await/
for (const [guildID, guild] of client.guilds.cache) {
//if no invite was able to be created or fetched default to string
let invite = "No invite";
//fetch already made invites first
const fetch = await guild.fetchInvites().catch(() => undefined);
//if fetch worked and there is atleast one invite
if (fetch && fetch.size) {
invite = fetch.first().url;
invites.push({ name: guild.name, invite });
continue;
}
for (const [channelID, channel] of guild.channels.cache) {
//only execute if we don't already have invite and if the channel is not a category
if (!invite && channel.createInvite) {
const attempt = await channel.createInvite().catch(() => undefined);
if (attempt) {
invite = attempt.url;
}
}
}
invites.push({ name: guild.name, invite });
}
console.log(invites)

I need to fix the code for communicating people leaving the server and tracking their inviters Node js Discord

I do code for New members on Discord server and it works.But i do some errors in code for leavers.What commands i need to write to do working code.
//this is for new members
client.on('guildMemberAdd', member => {
member.guild.fetchInvites()
.then(invites => {
const ib = inviterses[member.guild.id];
inviterses[member.guild.id] = invites;
const logs = invites.find(i => ib.get(i.code).uses < i.uses);
const joinchannel = member.guild.channels.find(channel => channel.name === "joiners");
joinchannel.send(`${member} **join**. Inviter- **${logs.inviter.tag}** (**${logs.uses}** invites)`)
console.log(`${member} **join**. Inviter- **${logs.inviter.tag}** inviter(**${logs.uses}** invites)`)
});
})
// this code for leavers,it not working
client.on('guildMemberRemove', (member) => {
targetUser = member.id
member.guild.fetchInvites()
.then(invites => {
const userInvites = invites.array().filter(o => o.inviter.id === targetUser.id);
inviterses[userInvites.id].has[targetUser.id]
inviterses.delete(targetUser.id)
const leavchannel = member.guild.channels.find(channel => channel.name === "leavers");
leavchannel.send(`${targetUser.user.username} left;Invited by ${userInvites.inviter.tag}`)
})
})
Discord doesn't provide an efficient way to know who invite a member. The way you use in your case is not simple to understand for beginners.
You fetch all the server invites (with their use count) and store them in a local variable
When a member joins, you check which invite has its use count increased
You update your local variable with new data
It means that if the invitation was created after the fetch in your local variable, you won't be able to know who invite the member. Click here for more information.
To know who invited a member you need to store in a local variable (or in a database, it's better) who invited him in the guildMemberAdd event because you won't be able to know that in the guildMemberRemove event.
So tracking user invites is very complicated and difficult.

Resources