Random Role Creation in Discord Server

  • Share this:

Code introduction


This function creates a randomly named role and adds it to the specified member in a Discord server. If the role already exists, it returns the existing role.


Technology Stack : Discord.py, random, discord.ext.commands, discord.utils.get

Code Type : Function

Code Difficulty : Intermediate


                
                    
def create_random_role(member):
    from discord import Role
    from discord.ext import commands
    from discord.utils import get

    if not isinstance(member, commands.Member):
        raise TypeError("Expected a discord.Member object")

    guild = member.guild
    if not guild:
        raise Exception("Member is not in a guild")

    # Create a random role name
    import random
    role_name = f"RandomRole{random.randint(1000, 9999)}"

    # Check if the role already exists
    existing_role = get(guild.roles, name=role_name)
    if existing_role:
        return existing_role

    # Create a new role
    role_color = 0x00FF00  # Green color
    new_role = guild.create_role(name=role_name, color=role_color)

    return new_role