简体   繁体   中英

Ban a user if they leave the server when they have a specific role discord.py

I want make it so if a user leaves the server while they have the Muted or [Banned] role they get permanently banned.

This is the code that I tried:

@bot.event
async def on_member_remove(ctx, member, reason=None):
    role="[Banned]"
    guild = ctx.guild
    if role in member.roles:
        await guild.ban(discord.Object(id=member.id), reason="Leaved the server when soft banned")

*this is just a try with only the banned role.

The user doesn't get banned, there is also no error or anything that could help me troubleshoot it.

member.roles returns a List of Role

You need to get the Role object which one way you can use is:

role = discord.utils.find(lambda r: r.name == '[Banned]', member.guild.roles)

on_member_remove takes in Member. You cannot have reason or Context( ctx )

@bot.event
async def on_member_remove(member):
    role = discord.utils.find(lambda r: r.name == '[Banned]', member.guild.roles)
    guild = member.guild
    if role in member.roles:
        await guild.ban(discord.Object(id=member.id), reason="Leaved the server when soft banned")

Please also ensure you have the Members intent enabled. You can do this by going here then selecting Bot -> SERVER MEMBERS INTENT

You will need to do enable intents in your code by using:

intents = discord.Intents.default()
intents.members = True

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

Your code seems fine.

Check that you have enabled the Intents.members on your Discord Developper portal and in your bot code, if you're using Discord API v8 (as intents are mandatory in this API version), as explained here in Discord.py docs .

For your information, by default, all intents are enabled except members and presence intents.

On Discord Developer Portal, enable this in the "Bot" section of your app: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM