Search code examples
discord.pypycord

How do I add multiple roles form a list to a user?


I have a command that adds all the current roles of a user to a Database (MongoDB).

The code:

def add_roles_to_db(self):

    check = cursor.find_one({"_id": self.ctx.author.id})

    if check is None:
        cursor.insert_one({"_id": self.ctx.author.id, "roles": [str(r) for r in self.ctx.author.roles[1:]]})
    else:
        cursor.update_one({"_id": self.ctx.author.id}, {"$set": {"roles": [str(r) for r in self.ctx.author.roles[1:]]}})

The code to get the roles:

    def get_roles_from_db(self):
        return cursor.find_one({"_id": self.ctx.author.id})["roles"]

When I get the roles from the DB I get a list, everything I've tried led to an error. Error: "AttributeError: 'str' object has no attribute 'id'"

if len(roles) != 0:
    await author.add_roles(*roles)

I saw a other post where someone added roles via a list but that didn't work


Solution

  • await author.add_roles(*[discord.Object(role_id) for role_id in roles])