Random Role Creation in Discord Server

  • Share this:

Code introduction


This function creates a random role with a random name and color in the specified Discord server. If the role already exists, it will not be created again.


Technology Stack : Discord.py

Code Type : The type of code

Code Difficulty :


                
                    
import discord
import random

def create_random_role(guild):
    # Create a random role in the Discord guild
    if not isinstance(guild, discord.Guild):
        raise TypeError("The first argument must be a discord.Guild instance.")

    role_name = f"RandomRole#{random.randint(1000, 9999)}"
    role_color = discord.Color(random.randint(0, 0xFFFFFF))

    new_role = discord.utils.get(guild.roles, name=role_name)
    if not new_role:
        await guild.create_role(name=role_name, color=role_color)

    return new_role                
              
Tags: