简体   繁体   中英

discord.py : How can I check to see if a user is in the server or not before issuing a ban?

I'm trying to make it so if one of my moderators go to ban a user, my bot will tell them if the user is no longer in the server if they left before action could be taken against them. This is the start of my ban command:

@client.command()
@commands.has_any_role("Head Honcho", "Discord Moderator")
async def ban(ctx, member : discord.Member, *, reason=None):
    if member is None:
        return await ctx.send("This member could not be found, or you did not provide an ID.")

    if reason is None:
        return await ctx.send("Please provide a reason for banning this user.")

    if user not in ctx.guild.members:
        return await ctx.send("This user is not in the server.")

    if ctx.channel.id == 805651955841236993:
        reaction_emote = ("<:Checkmark:820467149554319410>")
        await ctx.message.add_reaction(reaction_emote)

The issue I'm having is with this bit here:

if user not in ctx.guild.members:
        return await ctx.send("This user is not in the server.")

Nothing I'm trying seems to be working. Any help would be greatly appreciated!

Your code doesn't actually need a check since you have the argument member converted to a discord.Member object when defining your function arguments. A member object will always be in the guild, so you don't have to worry about getting an invalid user. Now if you'd like to catch the exception, you can do so using the on_command_error event.

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.errors.MemberNotFound):
        return await ctx.send("This user is not in the server.")

You can check if a member is not in a channel like this

if guild.get_member(ID_OF_MEMBER) == None:

I have my own way of doing that.

@client.command() # Ban command
@commands.has_permissions(manage_roles=True, kick_members=True, ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
    if member in ctx.guild.members():
        await ctx.channel.send(f"{member.mention} is  not a server member!")
    
    else:
        # Do Stuff

This will check for member in the server.

Thanks:D

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