Getting userID's through their username. Discord.JS - javascript

client.on("message", async message =>{
message.guild.members.fetch({query: "username here", limit: 1})
.then( members => console.log(members.user.id)) //results in undefined
.catch(console.error);
}
I would like to be able to get a users ID through their username. In this case I use the "fetch()" method and a query within it. However when i try to log (members.user.id) I get "undefined". The thing is whenever i fetch by a user ID(see code below) I am able to access the users ID,username, etc.. How would I able to fetch by their username and then be able to get a users ID. I was using this as a reference point https://discord.js.org/#/docs/main/master/class/GuildMemberManager?scrollTo=fetch
If theirs an easier way to get a users ID by their username please do tell.
client.on("message", async message =>{
message.guild.members.fetch("userID here")
.then( members => console.log(members.user.username))// a username is logged
.catch(console.error);
}

Looks like even if the limit is 1 it will still give back a collection, so you will need to get the first member of that collection
message.guild.members.fetch({query: "username here", limit: 1})
.then(members => {
const member = members.first();
//no need to convert it into a user
console.log(member.id);
});

Related

Discordjs - lastMessageId always null event after fetching

Introduction :
I'm pretty new at creating discord BOT and I'm currently trying to make like a ticket bot.
In order to do that, I need to check if the user that add the reaction is allow to do it or not.
Code :
I already checked this (successfully) when the user is using a command thanks to this (isAllow is a custom function that works when passing member object in params) :
if (Common.isAllow(message.member)) { /* code ... */ }
But I also want to check for the roles of the user that is reacting to a message, in order to create a new channel if the user is allowed to do it.
The problem is that when I get the user object, the lastMessageId is null, so I cannot get member object and check its roles.
The code that is checking for reaction is this one :
client.on("messageReactionAdd", async (reaction, user) => {
// When a reaction is received, check if the structure is partial
if (reaction.partial) {
// If the message this reaction belongs to was removed, the fetching might result in an API error which should be handled
try {
await reaction.fetch();
} catch (error) {
console.error('Something went wrong when fetching the message: ', error);
// Return as `reaction.message.author` may be undefined/null
return;
}
}
switch (reaction.message.channel.id) {
// Check if the message has been sent into the lawyer contact channel
case Config.CHANNELS.LAWYER_CONTACT:
case Config.CHANNELS.CONFIG:
checkForLawyerChannelReaction(reaction, user);
break;
default:
break;
}
});
If the reaction has been made in the good channel (LAWYER_CONTACT) or in the config channel (CONFIG), it will call this function, which is the one trying to check for permission :
function checkForLawyerChannelReaction(reaction, user) {
console.log('checkForLawyerChanelReaction');
console.log(user);
if (Common.isAllow( /* member object */ ) { /* code ... */ }
The response I get for console.log(user) is :
Result
I already tried to fetch user data like this, and it doesn't change a thing :
console.log(await client.users.fetch('123456789123456789'));
(ID has been changed, of course)
Note that the BOT has joined (again) yesterday with administrator permissions, and message has been sent by the user since yesterday.
Does somebody has a fix for this or information that I may not have yet ?
Thank you for your time.
You can get the GuildMember object by passing the user as an argument into the Guild.member(user) method.
const guildMember = reaction.message.guild.member(user);

Discord.js await messages from users other than the author

The title basically says it all, Is there a way for me to await for a message from a user other than the author. Like if a user #s someone in the command can I wait for the #ed person to respond to a certain question?
Basically just set the filter so it checks if the user who sent a message is the pinged/mentioned member.
Ex.
//just get a user from the message
let mentionedMember = message.mentions.users.first();
//checks if the user who send the message is the mentioned member
const filter = (message) => message.author == mentionedMember;
message.channel.awaitMessages(filter, { max: 1 }).then((collected) => {
//Whatever the mentioned member sent
});
You can use TextChannel#awaitMessages() to listen for new messages in a channel. The first parameter of this function is a filter method, which can look something like this:
const filter = (message) => message.content === 'COWS';
message.channel.awaitMessages(filter, { max: 1 }).then((collected) => {
// someone just said COWS in the channel
});
Just as I compared the message content, you can also compare the message author. This way you can listen for a specific person to respond to a question, collect their input, and then do something with it.

Strings/Arguments for a new person

I need help with a command, for example, if someone writes
" !report #user Spamming " How can I do so my discord account gets a message from the bot about =
Who reports who and for what reason
I've tried watching videos and posts but I can't get my head around it
client.on('message', async function(message) {
if (message.content.startsWith(prefix + "report")) {
const user = await client.fetchUser(args[1].match(/^<#!?(\d+)>$/)[1]);
if (!user) return message.channel.send('Oops! Please mention a valid user.');
const reason = args.slice(2).join(' ');
const me = await client.fetchUser('123456890'); //My id
me.send(`${message.author} reported ${user} for: \`${reason}\``)
.catch(err => console.error(err));
}
}
)
I want for example
In channel = !report #patrick#4245 He is spamming
Then The bot sends a message to me
#fadssa#2556 Reported #patrick#4245 Reason = He is spamming
Before just copying this code, let's actually think this through...
So, let's start by first getting everything we need for the message. First, we should retrieve a User from the argument provided. We do this by comparing the string to that of a mention and picking out the ID. If one doesn't exist, we return an error telling the user to mention someone.
Now, assuming you already have your arguments declared (if not, see this guide to help), we can simply put together the arguments used for the reason. To do so, we should use Array.slice() and then join those words with Array.join().
Then, since we want the bot to send you a DM, we'll have to find you in the Discord world. For this, we can use client.fetchUser().
Now, we can just send you the DM and you'll be alerted of all reports.
/*
* Should be placed within your command's code, after checking required arguments exist
* Assuming 'client' is the Discord Client and 'args' is the array of arguments
* Must be within an async function to use 'await'
*/
const user = await client.fetchUser(args[1].match(/^<#!?(\d+)>$/)[1]); // see below
if (!user) return message.channel.send('Oops! Please mention a valid user.');
const reason = args.slice(2).join(' ');
const me = await client.fetchUser('189855563893571595'); // replace with your ID
me.send(`${message.author} reported ${user} for: \`${reason}\``))
.catch(err => console.error(err));
Although it may look confusing, using regex is a much better option than message.mentions. There's plenty of whack examples where seemingly perfect code will not return the expected user, so this is why I would definitely choose retrieving the ID from a mention myself.

How to return a guild's owner name

This is the piece of my code where I'm having the problem:
const guild = client.guilds.get('500170876243935247');
message.channel.send(guild.owner);
I expected it to return the owner's name, instead it says in the console that it's an empty message. I've run guild.owner with console.log and apparently it's displaying all data from the guild, emojis, member's IDs and at the end, the owner's user details, how do I display them separately?
For the record, this is the last part that I think is the focus that I need:
user:
User {
id: '317669302549XXXXXX',
username: 'Flicker',
discriminator: 'XXXX',
avatar: 'a_161cc6f5d0466f7afd9a73dc2eba159d',
bot: false,
lastMessageID: null,
lastMessage: null },
joinedTimestamp: 1539320429681,
When you convert a User to a string, the User.toString() method is automatically called: that converts the User object into a mention, like #username. But if you do message.channel.send(User) it will not call User.toString() and so discord.js will be left with an object that it can't send (example for valid object: message.channel.send(RichEmbed)), and so the message will be empty.
To avoid this, you can try to replace the mention with something like User.tag: with this you also avoid being notified every time someone uses that command.
If you don't mind being notified you can use the first one when possible, otherwise the second one. Here's an example:
const guild = client.guilds.get('500170876243935247');
message.channel.send(message.guild.member(guild.owner) ? guild.owner.toString() : guild.owner.user.tag);
// if the user is in that guild it will mention him, otherwise it will use .tag
client.on('message', msg => {
const thisguild = msg.guild;
const owner = thisguild.owner.user.username;
}
Discordjs v11.5.1
In these examples Guild is a placeholder for where you get the guild. This can be message.guild or member.guild or just guild depending on the event. Or, you can get the guild by ID (see next section) and use that, too!
// Get a User by ID
client.users.get("user id here");
// Returns <User>
or
// Get a Member by ID
message.guild.members.get("user ID here");
// Returns <Member>
source: Github
My way of doing it using the docs above was:
let guild = msg.guild.members.get('372452704297025537');
let admin = msg.guild.member(guild);
message.channel.send(admin.user)
.catch(err => console.error(err))

firebase add user information while creating user (react.js)

I researched before asking this question but I couldn't find an answer.
I made a form in react js. When I click the button it creates a user with createUserWithEmailAndPassword() method. There is no problem with creating the user. I want to add extra information like; username : "Usernameeeee" to my database. The database will look like this:
users {
userUid1: {name: "Name User 1"}
userUid2: {name: "Name User 2"}
....
}
When I use createUserWithEmailAndPassword(), it creates a user and logs them in. But as you can see the above, I need the current user's id. I know how to get it normally, firebase.auth().currenUser... But while creating a user I can't catch the user's id. It returns null;
export function signUpUser({email, password}) {
return function (dispatch){
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(
() => dispatch({type: USER_SIGNUP_SUCCESS})
)
.then(console.log(firebase.auth().currentUser))
.catch(error => {
dispatch({type: USER_SIGNUP_FAIL, payload: error.message});
});
}
}
When I console the current user, the creating user is complete but not logged in yet. So how can I add information while creating a user ? (not after logged in some other way)
I found the answer after a day. I hope this will be helpful to others. As you understand, the main problem is getting the user id right after creating a user, before user sign in...
So the solution is:
export function signUpUser({email, password, username}) {
const db = firebase.database();
return function (dispatch){
firebase.auth().createUserWithEmailAndPassword(email, password)
// here we get user id if creating is successful.
.then(function(user){
dispatch({type: USER_SIGNUP_SUCCESS}); // I dispatched some message.
db.ref(`users/${user.uid}`).set({name: username}); // I added user
console.log('uid:',user.uid)
})

Categories