(discord.js) Add role to "user" - discord

Is there a way to get "member" from "user"?
I use slash command and i want to add role to a member. But there is no way to find member in slash command. Here the way how I find user.
const user = interaction.options.getUser('user')
when i try
user.roles.add(role id)
some error occur:
user.roles.add(role id)
^
"add" is not a function

When you get the user through interaction.options, you receive a User object. But to add roles, you need a GuildMember object. So you have to change user to:
const user = interaction.guild.members.cache.get(interaction.options.getUser('user').id)
Easier Way
At the time of writing the answer, I didn't know we could do this but you can just use interaction.options.getMember('user') to get the GuildMember details of the mentioned user. Even if you use .addUserOption to add the option, this method would work. So you can do this:
const user = interaction.options.getMember('user')

Related

How do I check if anyone in a guild has a role? discord.js

I want to be able to check if anyone in the whole server has a specific role. Is this possible?
Role.members returns a collection of every cached member who has the given role. Note: you will need to update the required intents to use this correctly.
// get the role
const role = guild.roles.cache.get('role-id');
role.members.each((member) => console.log(`${member.username} has the role!`));

Add / Remove user from role by ID [DISCORD.JS]

Hey today I'd like give and remove roles from a user by their ID
First try:
const user = '5454654687868768'
const role = '451079228381724672'
user.roles.remove(role)
Second Try:
const user = '5454654687868768'
const role = '451079228381724672'
user.removeRole(role)
Neither one of these methods seems to work, however.
const user = '5454654687868768'
const role = '451079228381724672'
These are just numbers which happen to be the id of your user and role object. They are nothing on their own and you can't call any Discordjs methods on them. To get the user and role object you will first have to get them using their respective ID.
Let's assume you want to add a role when someone joins the server, you can do the same thing in any type of event but we will use guildMemberAdd event for example:
bot.on('guildMemberAdd', async member => {
const memberID = '5454654687868768'; // you want to add/remove roles. Only members have roles not users. So, that's why I named the variable memberID for keeping it clear.
const roleID = '451079228381724672';
const guild = bot.guilds.cache.get('guild-ID'); // copy the id of the server your bot is in and paste it in place of guild-ID.
const role = guild.roles.cache.get(roleID); // here we are getting the role object using the id of that role.
const member = await guild.members.fetch(memberID); // here we are getting the member object using the id of that member. This is the member we will add the role to.
member.roles.add(role); // here we just added the role to the member we got.
}
See these methods are only working because they are real discordjs objects and not some numbers like you were trying to do. Also the async/await thing is there because we need to wait for the bot to get the member object from the API before we can add role to it.
Your first try was actually not that far off. The only problem is that roles.remove() is a guildMember function.
So first we need to define the member.
const member = message.guild.members.cache.get("member ID here");
Now we can remove or add a role. Source
member.roles.remove("role ID here");

Is there a way to add a role to someone without mentioning/pinging them? [discord.js]

Pretty much the title. Every time I try adding a role to someone using this:
const member = message.author;
member.roles.add('732727208774205460');
I end up with this TypeError:
TypeError: Cannot read property 'add' of undefined
However, if I use it like this:
const member = message.mentions.members.first();
member.roles.add('732727208774205460');
It works completely fine. Problem is, that only works if the person I'm adding a role to was mentioned/pinged by the user. I'm trying to add a role to the user himself where the user doesn't ping anyone (for censorship, mainly). Is there a way I could do this without getting the TypeError?
You are receiving an error because message.author.roles is undefined, so trying to use .add() on it causes an error.
message.author is of type User, which represents a discord user, and is not associated with any particular server.
You're looking instead for message.member which has type GuildMember, which represents a particular user's profile inside of a guild (message.member is just message.author but as a GuildMember instead of a User). It is the GuildMember type that has roles.
Solution:
const member = message.member;
member.roles.add('732727208774205460');
Official Documentation:
User,
GuildMember

Discord.py get user object from id/tag

So i'm trying to get a user object from an id or tag, however i am using a user account not a bot account so i cant use get_user_info()
Is there any way to do this on an user account?
If you know the user id, I suggest using bot.get_user(user_id) instead.
If you're using commands, you can use a converter:
#bot.command(pass_context=True)
async def mycommand(ctx, user: discord.User):
# user is a User object
Other wise, you can use Client.get_all_members to get all Member objects you can see.
from discord.utils import get
user = get(bot.get_all_members(), id="1234")
if user:
# found the user
else:
# Not found the user
You can use:
ctx.message.server.get_member(id) or message.server.get_member(id) # id must be of type int
This will return you a discord.Member object.
This also will return your user object, but not your member object. If you want the member object, please follow AJ Lee's answer
user = await client.fetch_user(user_id)
ctx.message.server.get_member(id) or message.server.get_member(id)
I couldn't write a comment to the previous answer (because of reputation) but make sure that id is int type here.
If you already have the id, call user = await ctx.bot.fetch_user(user_id). No messing about with permissions.
If you only have the username and tag, you can use:
guild.fetch_members()
user = guild.get_member_named("Example#1234")
Note you'll also need to turn the Members intent on in your code and the Discord Developer Portal in order to call fetch_members()
intents = discord.Intents.default()
intents.members = True
super().__init__(
command_prefix='!',
intents=intents
)
For me, only this worked, so if none of the others worked you could try this:
user = await message.guild.query_members(user_ids=[userid]) # list of members with userid
user = user[0] # there should be only one so get the first item in the list
Okay so there are many ways to do so but I use this
#commands.command()
async def id(self, ctx, *, user_id):
user = ctx.message.guild.get_member(user_id) or None
if user != None:
# Found the user
ctx.send(user)
else:
# Can't find the user
ctx.send("**Try that again**, this time add a user's id(**of this server**)")

How to get username from client id after the user has left the guild

I have statistics. I am downloading from the User Id database and I am replacing the ID with its name, but if the user has left the server, there is an error because there is no such user.
I have bot.users.get(id) but when a user leaves the server, an error pops up.
Can I get the username with the ID differently if the user is not on the server?
Sorry for being late, like literally. You can perform a request to get a user from Discord by a UserResolvable with Client#fetchUser(<UserResolvable>);.
In practice, the code should look like this;
const Discord = require("discord.js");
const Client = new Discord.Client();
Client.login("YoUr.nIcE.toKe.n");
Client.on("ready", function () { // Should do that when the client is ready.
const User = Client.fetchUser("123456789012345678");
console.log(User); // Some user object.
});
Hope I helped you nonetheless.
~Q
Since client.users stores only cached users, you won't be able to retrieve their username in a reliable way from there.
DISCLAIMER: This method is really inefficient, but discord.js hasn't been made for this kind of work. If you want to make it easier, just write Unknown user (client_id)
If you're not able to get the username from a user list you could try to use messages: use channel.fetchMessages() on every channel of your guild until you find a message in which message.author.id == your_id, when you find it you can get the username with message.author.username
There's also another solution: a self-bot. Keep in mind that this one is not supported by Discord itself, and could result in a permanent ban for the account you're using.
With that said, if you use a self-bot you can use the TextChannel.search() method to quickly find a message with your author id and then grab the username from the author.

Resources