Search code examples
pythondiscorddiscord.py

How to add and create roles in discord.py?


I have searched around a lot to try and find a way to create roles in discord.py, but I haven't found anything. I would like to be able to use a command to create and/or add roles to a user. My code is:

await client.create_role(message.author)

Solution

  • To create roles,

    For the rewrite branch:

    guild = ctx.guild
    await guild.create_role(name="role name")
    

    to add color, just add colour=discord.Colour(0xffffff) as an option in create_role, and replace ffffff with the hex code for the color. To add permissions to the role, include permissions=discord.Permissions(permissions=<permission value>)

    For the async branch:

    author = ctx.message.author
    await client.create_role(author.server, name="role name")
    

    to add color (and probably permissions), just do the same as you would for the rewrite branch.

    Now, if you want to add roles to a user,

    For the rewrite branch:

    role = discord.utils.get(ctx.guild.roles, name="role to add name")
    user = ctx.message.author
    await user.add_roles(role)
    

    For the async branch:

    user = ctx.message.author
    role = discord.utils.get(user.server.roles, name="role to add name")
    await client.add_roles(user, role)
    

    To see which branch you have, do print(discord._version). If it says 1.0.0a, you have the rewrite branch. If it says 0.16.2 or a lower number, you have the async branch. To calculate permission values, you can use this website

    note: Discord.py is currently at 1.6