2
votes

I was trying to create a bot using discord.py, and was trying to use the add_roles member function using discord.ext commands.

Here is my code:

import os

import discord
from dotenv import load_dotenv

from discord.ext import commands

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)


@client.event


async def on_ready():
    guild = discord.utils.get(client.guilds, name=GUILD)

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name} (id: {guild.id})'
    )
    members = guild.members
    for member in members:
        role = discord.utils.get(member.guild.roles, name='test 2')
        await member.add_roles([role],False)

When it calls the "await member.add_roles([role], False)," it gives an error of the following:

    Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/Users/tanay/Documents/Python CYOA/bot.py", line 31, in on_ready
    await member.add_roles([role],False)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/member.py", line 676, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'list' object has no attribute 'id'

I've been doing a bunch of internet searches and just can't find how to fix this. Does anyone know what I did wrong?

Thank you so much!

1
Just to clarify, what does the False in await member.add_roles(role, False) do? - IPSDSILVA
This is a quote from the discord API: "atomic (bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache." - Tanay

1 Answers

1
votes

When you're adding one role, you don't have to put it in []. That's why you're getting this error. So you just have to remove the brackets.

...
for member in members:
    role = discord.utils.get(member.guild.roles, name='test 2')
    await member.add_roles(role)