Reputation: 265
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)
Upvotes: 0
Views: 1111
Reputation: 265
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')
Upvotes: 1
Reputation: 4137
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.
Upvotes: 0