guild.get_member returns None when getting discord.Member object using an ID

Viewed 38

What I have is a command that assigns a role. ;assigntestrole <@user>. I've tried multiple different ways of getting a member object including client.fetch_user, getting the object through a guild and other stuff. I keep getting NoneType objects. Here's my code so far:

import discord
client = discord.Client()
TOKEN = 'MYTOKEN'
prefix = ';'

@client.event
async def on_message(message):
    if str(message.content)[0] != prefix:
        return

    user = str(message.content).split(' ')[1]
    guild = client.get_guild(message.guild.id)
    user_obj = guild.get_member(int(user[2:-1]))
    print(user_obj)

client.run(TOKEN)

The output I'm getting is None no matter which method I use (tried client.fetch_member(int(user[2:-1])), discord.utils.get(message.guild.members, id=int(user[2:-1]) and others). Any ideas as to what might be causing such behavior?

1 Answers

Yeah, my suspicion was correct. In order for get_member to work, it actually does require the members intent. It's hidden deep inside the docs here

Whether guild member related events are enabled.

This also corresponds to the following attributes and classes in terms of cache:

...
Guild.get_member()

Enable the members intent and it will be solved.

intents = discord.Intents.default()
intents.members = True
#intents.message_content = True  # if you need this
client = discord.Client(intents=intents)

Note that fetch_member can still be used without that intent if you really don't want it, but it costs an extra API call.

Related