Get Discord user ID from username
In one line just do
discord.utils.get(client.get_all_members(), name="ExampleUser", discriminator="1234").id
notice the .id
at the end, that gives you the ID of that person.
Also for the discriminator part don't include the hash(#)
Discord.JS - How to get user ID from username?
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);
How to get user ID from Discord username?
In your example guild.members
is undefined because .fetch()
returns a promise and the returned guild
doesn't have a member
property.
You either need to use the .then
method, to access the fetched guild
:
client.guilds.fetch('705686666043457606')
.then(guild => {
const applicant = guild.members.cache
.find((member) => member.user.tag === tag.value)
})
.catch(console.error)
...or use async/await:
async yourFunction() {
try {
const guild = await client.guilds.fetch('705686666043457606')
const applicant = guild.members.cache
.find((member) => member.user.tag === tag.value)
} catch(err) {
console.error(err)
}
}
Please note that you can only use await
in async
functions, so make sure to convert the function where your code is by adding the async
keyword.
Also, make sure you use the user tag not the username. Find the member by comparing member.user.tag
in the .find()
method, and not member.name
.
Discord: Get User by Id
You can use the Discord API.
First, create a Discord application here. Once you've done that, click 'Bot' on the sidebar and create a bot for that application. There, you'll see a section called 'Token' under the bot username. Copy this and store it somewhere secure. It is important to never share your token. If you do, you should regenerate it to prevent abuse.
You can then use the Get User endpoint (/users/{user.id}/
) to retrieve the user for an ID. This should be done by the backend as it involves authenticating with the bot token.
Using the API directly
Here is a minimal example of how you would fetch a user by their ID using the Discord API using Node.js:
const fetch = require('node-fetch')
// You might want to store this in an environment variable or something
const token = 'YOUR_TOKEN'
const fetchUser = async id => {
const response = await fetch(`https://discord.com/api/v9/users/${id}`, {
headers: {
Authorization: `Bot ${token}`
}
})
if (!response.ok) throw new Error(`Error status code: ${response.status}`)
return JSON.parse(await response.json())
}
The response would be something like this:
{
"id": "123456789012345678",
"username": "some username",
"avatar": null,
"discriminator": "1234",
"public_flags": 0,
"banner": null,
"banner_color": null,
"accent_color": null
}
Using a library
Alternatively, you may be able to use a Discord library to do this instead. The following examples also handle rate limits.
@discordjs/rest + discord-api-types
const {REST} = require('@discordjs/rest')
const {Routes} = require('discord-api-types/v9')
const token = 'YOUR_TOKEN'
const rest = new REST().setToken(token)
const fetchUser = async id => rest.get(Routes.user(id))
The result would be the same JSON as described above.
For TypeScript users:
import type {RESTGetAPIUserResult, Snowflake} from 'discord-api-types/v9'
const fetchUser = async (id: Snowflake): Promise<RESTGetAPIUserResult> =>
rest.get(Routes.user(id)) as Promise<RESTGetAPIUserResult>
discord.js
When I first posted this answer, @discordjs/rest didn't exist yet.
const {Client} = require('discord.js')
const token = 'YOUR_TOKEN'
const client = new Client({intents: []})
client.token = token
const fetchUser = async id => client.users.fetch(id)
The result of fetchUser
would be a discord.js User
object.
How to get userid from a string in discord.py
You can use discord.py MemberConverter to convert the string user into the user object. Docs of memberconverter
It will give you the member object and the properties of it is here mentioned in docs
Resulting code can be something like -
from discord.ext import commands
@commands.has_permissions(ban_members=True)
@commands.command()
async def banlist(self, ctx):
with open(file, encoding='utf-8') as file_in:
for line in file_in:
try:
member = await commands.MemberConverter().convert(ctx, line)
await ctx.guild.ban(member.id, reason='blacklist')
except commands.errors.MemberNotFound:
# member not found here, handle it
Related Topics
How to Put a Space Between Two String Items in Python
List Available Font Families in 'Tkinter'
How to Count the Number of Messages
How to Mention a User in Discord.Py
How to Convert Datetime to Integer in Python
Best Way to Get the Max Value in a Spark Dataframe Column
Using Python, How to Access a Shared Folder on Windows Network
Python, Delete Json Element Having Specific Key from a Loop
How to Allocate Array With Shape and Data Type
Python Pandas - Get Row Based on Previous Row Value
How to I Close Down a Python Server Built Using Flask
How to Make a Tkinter Label Background Transparent
How to Drop Rows from Pandas Data Frame That Contains a Particular String in a Particular Column
Pandas Get the Most Frequent Values of a Column
Macos: How to Downgrade Homebrew Python
How to Insert String Value into Specific Column Value on Python Pandas