Search code examples
pythondiscorddiscord.pypycord

Getting all guilds the bot is in and banning the member in all discords


So I am trying to get all guilds that the bot is in. Which I have done by:

for guild in self.bot.guilds:
  guild = guild

Using this I need to try and ban the member specified in all of the guilds that the bot is in. Can anyone help with this?

I have already tried by looping the code to ban the user in all of the servers but seems to not ban them with no error in the console.


Solution

  • Assuming that this is being called in an async function and you have gotten the USER_ID of the user you want to ban. You have the pycord label as well - so linked those docs.

    user_id = USER_ID  # the ID of the 'specified' member you want to ban
    async for guild in self.bot.fetch_guilds():
        # could also use guild.get_member(user_id) if you Intents.members enabled and member cache
        try:
            member = await guild.fetch_member(user_id)
        except discord.NotFound:
            # user wasn't in this guild
            # move to next guild
            continue
        await member.ban()
    

    Using fetch_guilds in case you don't have them in the cache. And fetch_member in case they're not cached either - but you can use get_member instead if you have Intents.members enabled and member caching enabled.

    member.ban docs.