How to get Member object from user id discord.py

Viewed 5409

I want to get the nickname of a user from their Id. I have the following code:

id = 235088799074484224 # User Id
member2 = bot.guilds[guild_id].get_member(id)
print(member2.nick)

But the code gives an error:

Traceback (most recent call last):
  File "C:\Users\Vlad\PycharmProjects\untitled\venv\lib\site-packages\discord\client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "C:/Users/Vlad/PycharmProjects/untitled/static/bot.py", line 61, in on_message
    messages = await clean_up_messages(messages)
  File "C:/Users/Vlad/PycharmProjects/untitled/static/bot.py", line 21, in clean_up_messages
    nick = await replace_nick(i.author.id)
  File "C:/Users/Vlad/PycharmProjects/untitled/static/bot.py", line 15, in replace_nick
    return member2.display_name  # or .nick
AttributeError: 'NoneType' object has no attribute 'display_name'

The error seems to come from the fact that member2 is always None. It is None no matter what id I use.
I have read the documentation and the bot.guilds[guild_id] is correct, but the get_member() function seems to cause the error.
How do I fix this?

1 Answers

In the new version of discord.py(1.5.x), there're some updates about Intents. Intents are like permissions, you have to define it to get channels, members(like guild.get_member()) and some events etc. You have to define it before defining the client = discord.Bot(prefix='').

import discord

intents = discord.Intents().all()
client = discord.Bot(prefix='', intents=intents)

If you want to get more information about Intents, you can look at the API References.

Related