Random Role Creation in Discord

  • Share this:

Code introduction


This function creates a new role in a specified Discord server with a random name and color. If a role with the same name already exists in the server, no new role will be created.


Technology Stack : Discord.py

Code Type : Discord API Function

Code Difficulty : Intermediate


                
                    
import discord
import random

def create_random_role(guild):
    # This function creates a random role in a Discord guild with a random name and color
    
    # Generate a random role name
    role_name = f"RandomRole#{random.randint(1000, 9999)}"
    
    # Generate a random color for the role
    random_color = discord.Color(random.randint(0, 0xFFFFFF))
    
    # Create the role
    new_role = discord.utils.get(guild.roles, name=role_name)
    if not new_role:
        new_role = await guild.create_role(name=role_name, color=random_color)
    
    return new_role

# JSON Explanation                
              
Tags: