RealLuby
RealLuby

Reputation: 29

How to check if a role already exists in discord.py

How to check if a role already exist in discord.py

I am trying a command which creates a role, but if the role already exist the code won't create a new role.

@bot.command()
async def modrole(ctx):
    guild = ctx.guild
    if guild.has_role(name="BotMod"):
        await ctx.send("Role already exists")
    else:
        await guild.create_role(name="BotMod", colour=discord.Colour(0x0062ff))

Upvotes: 1

Views: 3590

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60944

You can use discord.utils.get to iterate through ctx.guild.roles to find one with that name:

from discord.utils import get

@bot.command()
async def modrole(ctx):
    if get(ctx.guild.roles, name="BotMod"):
        await ctx.send("Role already exists")
    else:
        await ctx.guild.create_role(name="BotMod", colour=discord.Colour(0x0062ff))

Upvotes: 6

Related Questions