Alternative Ways to Define Users in Discord.JS - discord.js

So to define users for things like displaying avatars, etc. i've been using this;
var user = message.mentions.users.first() || message.author;
But i've been trying to figure out how people have been able to define users without mentions. Example - my command requires me to tag someone whereas Dyno can do it with partial names. Any tips would be great, thanks!

An easy way to do so would probably be using the .find() function, where you can search for a certain object based on a method.
For example, if we were to have an args variable in our callback (Very easy to do so using a proper command handler - I'd suggest looking for tutorials if you aren't familiar with command handlers), and we were to ask a user to pass in a member's name, we could very easily get the user object using:
const user = message.guild.users.cache.find(user => user.username === args[0]);
// Keep in mind, 'user' is just a variable I've defined. It could also be 'monke => monke.username' if you wish.
Or, if we were to ask for their ID, we could use the .get() function to get the user object by ID:
const user = message.guild.users.cache.get(args[0]);
Do keep in mind it's not the greatest to have these kinds of object getting functions, as there are always multiple conflicts that could occur whilst getting the object, such as if there are multiple users with the same name/tag. I'd highly recommend sticking to your mention-based user objects, as it's the most accurate and non-conflicting method.

Every guild has a list of members which you can search through by enabling the Server Members Intent for your bot via the Discord Developer Portal. Once you have done that, you can fetch a collection of all members of a guild by doing
guild.members.cache;
You can then search this collection to find a member based on a search query using .includes(), .filter() or something similar. For example:
let query = "something";
let list = guild.members.cache.filter(member => member.user.username.includes(query));
console.log(Object.entries(list));
// expected output: list of all server members who's usernames contain "something"
You could also use the .find() method (since a collection is a map) to return a member with an exact username:
let member = guild.members.cache.find(member => member.user.username === query);
console.log(member.tag);
// expected output: tag of the user who's username is "something"

This is as simple as that:
var user = message.guild.members.cache.find(u => u.user.username.toUpperCase() === args.join(" ") || u.user.username.toLowerCase() === args.join(" ") || u.user.username === args.join(" "))
This will find the user on the current guild but you can also search your bot for this user by doing:
var user = client.users.cache.find(u => u.username.toUpperCase() === args.join(" ") || u.username.toLowerCase() === args.join(" ") || u.username === args.join(" "))
I have to assume that you already defined args and client. The example above will find users just by typing their name. toUpperCase means if you type the username in uppercase letters it will find the users anyways. toLowerCase means if you type the username in lowercase letters it will find the user as well. And you could also just type the username as it is. || means or so you can decide how you write the username, it will be found anyways.

Related

Adding a user to a role by name using arguments Discord.JS

so I am currently trying to find out if there is a way I could give a user a role by typing the a variable name. Like, example, '!role testrole', and then the bot will give them what the testrole is defined at. Like, 'if(args[1] === "testrole")...'. Testrole can just be defined as that, but the actual role name can just be like test. You can add multiple roles, and it will add it. '!role hello', etc...? Discord.JS
You can try something simple using a function to find the role name. You can do something like:
const roleName = message.guild.roles.cache.find(r => (r.name === args[1].toString()) || (r.id === args[1].toString().replace(/[^\w\s]/gi, '')));
This will either check for a mentioned role or a role name given

How can i make a guild-side variable using Discord.js

im trying to make a server/guild side variable for my bot (have a variable that has a different value in each server). I dont know how to make that so i really need help... How can i get a variable to have a different value in each server?
You should use a discord.js Collection, which is:
A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has an ID, for significantly improved performance and ease-of-use.
A Map object holds key-value pairs and remembers the original insertion order of the keys. Any value may be used as either a key or a value. Here's a quick demo:
// let's say we had two people: John and Sarah
const people = new Map();
// each of them were a different age
people.set('John', 25); // in this example, 'John' is the key, and 25 is the value
people.set('Sarah', 19); // in this example, 'Sarah' is the key, and 25 is the value
// each person has an individual age
// you can `get()` the key, and it will return the value
console.log(`Sarah is ${people.get('Sarah')} years old.`);
console.log(`John is ${people.get('John')} years old.`);
You can use this type of format to create a collection with each key being a different guild ID, and each value being... whatever you want. Here's an example:
// const { Collection } = require('discord.js');
const guilds = new Collection();
// put some data in an object as the key
guilds.set("Guild ID", {
name: "Guild Name",
welcomeMsg: "Welcome new person!",
welcomeChannel: "...",
blacklistedIDs: ["123456", "67890"],
});
client.on("guildMemberAdd", (member) => {
const guild = guilds.get(member.guild.id); // get the collection element via guild id
if (!guild) return;
// then access all its data!
console.log(`Somebody joined ${guild.name}`);
if (guild.blacklistedIDs.includes(member.id)) return member.kick();
guild.welcomeChannel.send(guild.welcomeMsg);
});
I believe Tin Nguyen posted this idea as a comment, I am just elaborating on that. To achieve what you want, you can use what is known as a "data dictionary" which is basically just a file storing a list of something.
For your specific use case, you can use a simple JSON file to store your variables. For each guild that your bot is in, you can add a new object to a list of objects in a local JSON file called variable.json for example.
Here is an idea of what it might look like:
[
{
"guild": "INSERT GUILD ID",
"value": "INSERT VARIABLE VALUE"
},
]
guild will store the id of the guild, so you can identify the correct value. To get the value stored in value for a certain guild, all you have to do is loop through the JSON file, and find the object with the correct guild ID:
const variables = require("variable.json"); //imports the JSON data
const value; //creates a new variable
for (i = 0; i < variables.length; i++) { //loops through the guilds
if (variables[i].guild === message.guild.id) { //if the IDs are the same...
value = variables[i].value; //...sets "value" to the retrieved value
}
}
This of course relies on the fact that your bot also adds each guild it joins to the list. To do this, you can use the guildCreate event. Documentation for this can be found here.

Is there a way to list all members in a specific role?

I was wondering if it is possible to list every member within a specific role.
If possible to make it so I can search for every role without changing the code, and changing roleid..
There is multiple ways to get a list of every GuildMember that has a specific Role.
You can use .members Role property to get a Collection of GuildMember
Example :
// Getting a Collection of all GuildMember that have the role stored in "myRole" var.
let myRole = client.guilds.resolve("651196009896214543").roles.cache.get("651197514506305555");
let members = myRole.members
Or you can filter all GuildMember of a Guild like that :
let members = client.guilds.resolve("651196009896214543").members.cache;
members = members.filter(guildMember => guildMember.roles.cache.has("651197514506305555"));

?members command for my discord bot - discord.js

So I've been trying to create a ?members command which lists all the users with a role.
So far I've got this:
if (message.content.startsWith("?members")) {
let roleName = message.content.split(" ").slice(1).join(" ");
let membersWithRole = message.guild.members.filter(member => {
return member.roles.find("name", roleName);
}).map(member => {
return member.user.username;
})
const embed = new Discord.RichEmbed({
"title": `Members in ${roleName}`,
"description": membersWithRole.join("\n"),
"color": 0xFFFF
});
return message.channel.send(embed);
}
So, it works if you type the exact name of the role, but not when you ping it or type the first word. I've been trying for hours to figure out how to do it, and I figured I should ask for help.
Thanks in advance!
Pings get translated into a code as they come through, there is a lot of information on how to parse them in the official guide After it's parsed into a role id you can just use members.roles.get() because that is what they are indexed by.
As for finding a partial name, for that you are going to have to run a function on your find and use String.includes.
return member.roles.find(role => role.name.includes(roleName));
This will also work for find the whole name of course, so it can replace your existing line.
However, this may result in more than one role. This is also true for searching by the entire role name, however, as there are no restrictions on duplicate named roles. For this you may want to invert you design and search through message.guild.roles first for any matching roles, then search for members with the roles found.

Collection#find: pass a function instead

I'm fairly new to node.js and I'm working on a discord bot with discord.js, I'm am trying to do assigned roles with commands. When I do the code and type in the command it works successfully but pops up with "DeprecationWarning: Collection#find: pass a function instead" in the console, how can I get rid of this?
https://i.imgur.com/agKFNsF.png
This warning is caused by the following line:
var role = message.guild.roles.find('name', 'Epic Gamer');
On an earlier version of Discord.js, this would be valid, but they have now redone the find function. Instead of taking in a property and a value, you pass in a filtering function instead. This should work:
var role = message.guild.roles.find(role => role.name === "Epic Gamer")
Instead of passing in 'name' (the property), and 'Epic Gamer' (the value we want to search for/filter out), we pass in the arrow function role => role.name === 'Epic Gamer'. This is like mapping. find passes every role from message.guild.roles into the function as role, and then checks if the property we want equals the value we want.
If you would like to learn more about the find function, please check out the official documentation.
Pass a predicate function in find method, take a look at the discord.js document on the find function.
Change the find statement to
var role = message.guild.roles.find(role => role.name === 'Epic Gamer');
Hope this will help!

Resources