Discord Bot Role Assignment Extension

  • Share this:

Code introduction


This function is an extension of a Discord Bot that automatically assigns a specified role to a specified user. It uses the Discord.py library to operate on a Discord server.


Technology Stack : Discord.py

Code Type : Discord Bot Function

Code Difficulty : Intermediate


                
                    
def auto_role_user(user, role_name):
    from discord.ext import commands
    from discord import Client

    def fetch_role(client, role_name):
        for role in client.guilds[0].roles:
            if role.name == role_name:
                return role
        return None

    def assign_role(client, user, role):
        if role:
            client.add_roles(user, role)
            return True
        return False

    client = commands.Bot(command_prefix='!')

    @client.event
    async def on_ready():
        print(f'Logged in as {client.user.name}')

    @client.command()
    async def assignrole(ctx, user: commands.Member, *, role_name: str):
        role = fetch_role(client, role_name)
        if assign_role(client, user, role):
            await ctx.send(f"{user.mention} has been assigned the role {role_name}.")
        else:
            await ctx.send(f"Role {role_name} not found.")

    with open('token.txt', 'r') as token_file:
        client.run(token_file.read())                
              
Tags: