Search code examples
pythonpython-3.xdiscorddiscord.py

Remove roles of a user with discord.py without commands


I want to remove a role(s) of my discord-server users without the need of using a command, only calling a python function and when calling it, it will remove the roles automatically, is that possible, if so, how can I do it?

async def removeRoles(ctx, user: discord.Member):
    role = discord.utils.get(ctx.guild, name='Miembro')
    await user.remove_roles(role)

The above code is an example of removing roles WITH help of a command, I want without it, and using it like something as this:

// calling this function somewhere in other module.py
removeRoles("user_discord_id", "role_to_remove") // removes the role given to the specified user

How can i do it with discord.py? thanks!


Solution

  • You can simply get the guild, then its member, and remove roles that way. But you need to explain if you want to do so in a synchronous or asynchronous function. If you want to do it an async function, then it's as simple as this:

    # I'm guessing you have a discord.ext.commands.Bot variable called bot
    
    guild = discord.utils.get(bot.guilds, name="GuildName") 
    # Using the guild's ID to get it would be better
    # But since you've used name in your example, I'm going to as well
    
    member = discord.utils.get(guild.members, name="MemberName")
    
    role = discord.utils.get(guild.roles, name="RoleName")
    
    await member.remove_roles(role)
    

    However, if you want to remove the member's roles in a synchronous function, be prepared to use the Discord API and the requests library. This page in the Discord API should be helpful: https://discord.com/developers/docs/resources/guild#remove-guild-member-role.

    Something like this should do the trick:

    #  I'm guessing you have a discord.ext.commands.Bot variable called bot
    
    guild = discord.utils.get(bot.guilds, name="GuildName")
    # Using the guild's ID to get it would be better
    # But since you've used name in your example, I'm going to as well
    
    member = discord.utils.get(guild.members, name="MemberName")
    
    role = discord.utils.get(guild.roles, name="RoleName")
    
    headers = {"authorization": "Bot " + "your_token_goes_here"}
    
    requests.delete(f"https://discord.com/api/guilds/{guild.id}/members/{member.id}/roles/{role.id}", headers=headers)