Trying To Make a Discord Bot – Error Role Not Found

Question:

I have asked this question on the Replit forum but the developers are unsure of the problem.

My friend and I want to add a function to our bot that gives a user the role Baguette_Team, and posts a message saying that they received the role if they post a message that says I love baguettes!.

Code

import os, re, discord
from discord.ext import commands

DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")


client = 
commands.Bot(command_prefix="!", intents= discord.Intents.all())

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    print("message was: " + message.content)
    if message.author == client.user:
        return
    if message.content == 'I love baguettes!':
        role = message.guild.get_role(1085983212855115887)
        #discord.utils.get(message.guild.roles, id="1085983212855115887")
        await message.author.add_roles(message.author, role, reason="You said the magic words!", atomic=True)
        await message.channel.send('So do I! In fact, I have given you the Baguette Team role!')

client.run(DISCORD_TOKEN)

Traceback

Traceback (most recent call last):
File "/home/runner/Blockcoin-Bot/venv/lib/python 3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 22, in on_message
    await member.add_roles(role) 
  File "/home/runner/Blockcoin-BotIvenv/lib/python 3.10/site-packages/discord/member.py", line 1044, in add rotes
    await req(guild_id, user_id, role.id, reason, eason)
AttributeError: 'NoneType' object has no attribute 'id'
Asked By: Tyler

||

Answers:

What the error most likely means

The error most likely means that the role wasn’t found, or you’re not adding the role properly. Assuming you have the right role ID,

How to get a role

The way that you’re getting the role is correct. In the docs you get the role from the guild by Guild.get_role(role_id) (non-async command).

You could alternatively use discord.utils.get if that isn’t working.

How to add a role to a user

This is where the issue likely is. You’re using the right command, but the parameters are incorrect. In the docs it shows that you use the following: await add_roles(*roles, reason=None, atomic=True). However, you put message.author as the first positional parameter. Instead, change it to the role.

For example:

await message.author.add_roles(role, reason="You said the magic words!", atomic=True)

Just remove the message.author from the positional arguments.

Answered By: Blue Robin