Search code examples
pythondiscorddiscord.py

Why doesn't my code detect the member in the guild even with a valid ID?


For reference, memID is initialized to message.author.id

    if message.content.startswith(prefix+'jail'):
       serv = client.get_guild(message.guild.id)

       mod = serv.get_member(memID)

       if 'Moderator' in mod.roles:
           await message.channel.send("Signal")`

I even debugged to print memID and it printed out my ID, however this function does not detect me as a member even with the valid ID, instead initializing to NoneType. Help.

Error Log:

File "/home/runner/NKBot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 81, in on_message
    if 'Moderator' in mod.roles:
AttributeError: 'NoneType' object has no attribute 'roles'

Solution

  • Firstly, the members intent was not enabled, so your discord.Member instance couldn't be found. See the docs for how to enable them: https://discordpy.readthedocs.io/en/stable/intents.html

    Next, you're checking if a string ("Moderator") is in mod.roles. This is always False, because Member.roles is a list of discord.Role instances, not strings. You can also find this in the docs: https://discordpy.readthedocs.io/en/stable/api.html?highlight=member%20roles#discord.Member.roles

    You can find the role by name using a loop, or more easily using the built-in utils.get() method. The docs page has plenty of examples that explain how it works.

    Lastly, instead of manually parsing message content consider just using the built-in Commands framework that does all this for you.