'Get Discord username from user ID (discord.py)
I'm trying to write a simple game in discord.py. The score is stored in a database, indexed by the Discord user ID (an integer).
Now I'd like to display the highscore in a nicely readable format.
For that, I am trying to get the Discord username (e.g. Example#1234) from the user ID (e.g. 354250329581841022). I've found this code:
user_hs = client.get_user(user_id)
print(user_hs.name)
but unfortunately, user_hs is always None type and throws an error that it doesn't have attribute name.
Minimal example:
import discord
client = discord.Client()
@client.event
async def on_message(message):
user_message = str(message.content)
if user_message.lower() == '&hs':
user_id = 354250329581841022
user_hs = client.get_user(user_id)
print(user_hs.name)
client.run(TOKEN)
Solution 1:[1]
What was missing was await. Adding that before fetch_user works flawlessly:
user = await client.fetch_user(id)
await message.channel.send(f'{user}: {score} points')
Solution 2:[2]
client.get_user(id_)
This works, then you can get its username this way:
client.get_user(id_).name
If the returned value is None, probably the user just doesn't exist.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dk2ax |
| Solution 2 | FLAK-ZOSO |
