pythondiscord.py

Remove role from a Discord user using the server and role IDs?


I want to have a Discord bot that I am coding in Discord.py simultaneously remove two specific roles in two different servers from the same user. Everywhere I look, I can only find code to remove a role from the same server that an async event is triggered in, but note instructions on how to do this using a server's id and the id of the role I wish to remove. How can I accomplish this?


Solution

  • For this you will require

    This can be accomplished using the code :

    @bot.command()
    async def remove_roles(ctx, member: discord.Member):
        #get guild and role of 1st guild
        guild1 = client.get_guild(<ID>) # ID of 1st guild
        role1 = guild1.get_role(<Role ID>) # ID of the role of 1st guild
        #get guild and role of 2nd guild
        guild2 = client.get_guild(<ID>) # ID of 2nd guild
        role2 = guild2.get_role(<Role ID>) # ID of the role of 2nd guild
        
        #remove role from user in 1st guild
        m1 = guild1.get_member(member.id)
        await m1.remove_roles(role1)
        
        #remove role from user in 2nd guild
        m2 = guild2.get_member(member.id)
        await m2.remove_roles(role2)
        
        await ctx.send("Roles are removed from the user.")
    

    This is a minimal reproducible example and you can further change it according to your needs.


    Reference: