deezee
deezee

Reputation: 25

How can I kick all members without a role in my discord server ? (discord.py)

I'm trying to figure out a command to kick all members without a role in my discord server. I searched Google + this website and I found solutions that don't seem to work for me. Here's what I tried.

import discord
from discord.ext import commands
from discord.ext.commands import has_permissions

bot = commands.Bot(command_prefix='$')

@bot.command(pass_context=True)
async def noroleskick(ctx):
    server=ctx.message.server
    for member in tuple(server.members):
        if len(member.roles)==1:
            await bot.kick(member)

bot.run(token)

However, this didn't work, and here's the error:

File "main.py", line 111, in noroleskick
    server=ctx.message.server
AttributeError: 'Message' object has no attribute 'server'

I found this on Reddit. If this is no brainer, I sincerely apologize. I am a beginner at coding, so if you could go into detail I would highly appreciate it. 🤗

Upvotes: 1

Views: 5172

Answers (2)

BlackOut
BlackOut

Reputation: 36

import discord
from discord.ext import commands
from discord.ext.commands import has_permissions

intents = discord.Intents.all()

bot = commands.Bot(command_prefix='.', intents=intents)

@bot.command()
@has_permissions(administrator=True)
async def kicknorole(ctx: commands.Context):
    members = ctx.guild.members
        
    for member in members:
        if len(member.roles) == 1:
            await member.kick()
            print(member.name)
    await ctx.reply('Done!')

bot.run('TOKEN')

Here is what I used. I was asked by a friend to kick all the users from their server with no roles. This worked for me. 762 members, hope it works for you!

Upvotes: 1

You need to change ctx.message.server to ctx.message.guild or just ctx.guild and enable the members intent from the discord developer portal and then use the following code to enable it in your script

from discord import Intents
intents = Intents()
intents.members = True
bot = commands.Bot(command_prefix='$', intents=intents)

Upvotes: 1

Related Questions