Search code examples
pythonlistdiscorddelimited

Remove specific roles from delimited list of users (Discord/Python)


I'm trying to make a little bot that will remove specific roles from a list of users I specify. I have all of the id's and usernames of the users I need to remove roles from, but I don't know how to code it to allow for a long delimited list as a variable. My intended usage is something like

-strip (userid1,userid2,userid3)

...capable of a dynamic list that will vary in the number of members included.

Here's my use case for more context - I have a Patreon which grants roles to my Discord. However, Patreon can only give roles, not remove them. I've made a scraper that will compare a list of patrons to a list of discord members and their roles. It filters out a list of canceled patrons that still have Discord roles. I want to just be able to pop that list into a bot command and have it wipe the roles.

The script below currently allows me to remove specific roles from a single user. It's working fine, but need a way to allow for a list of users as opposed to a single user.

Thanks in advance!

import os
from discord.ext import commands
from discord.utils import get
import discord

client = commands.Bot(command_prefix = '-', help_command=None)

@client.event
async def on_ready():
  print(f'{client.user} has awakened!')
    
@client.command()
async def swipe(ctx, user: discord.Member):
    role_names = ("role1", "role2", "role3")
    roles = tuple(get(ctx.guild.roles, name=n) for n in role_names)
    await user.remove_roles(*roles)
    await ctx.send(f'Removed **all** Patreon roles from {user.mention}.')

my_secret = os.environ['TOKEN']
client.run(my_secret)

Solution

  • You can do this like so:

    import os
    from discord.ext import commands
    from discord.utils import get
    import discord
    
    client = commands.Bot(command_prefix = '-', help_command=None)
    
    @client.event
    async def on_ready():
      print(f'{client.user} has awakened!')
        
    async def helper(ctx, user_id):
        role_names = ("role1", "role2", "role3")
        roles = tuple(get(ctx.guild.roles, name=n) for n in role_names)
        user = await ctx.guild.fetch_member(int(user_id)) #notice the additional line here
        await user.remove_roles(*roles)
        await ctx.send(f'Removed **all** Patreon roles from {user.mention}.')
    
    @client.command()
    async def swipe(ctx, *args):
        for user in args:
            await helper(ctx, int(user))
    
    
    my_secret = os.environ['TOKEN']
    client.run(my_secret)
    

    Now swipe takes args like: -swipe user1 user2 user3 and calls your original function (now called helper) for each user.