简体   繁体   中英

Discord.py ban someone specific by userid

I'm currently learning how to make discord bots using python and my main goal right now is to ban a specific user by his user ID.Right now, my code just bans someone who is mentioned after the command is used. picture of code that bans someone using the command

my main goal right now is to ban a specific user by his user ID

So what you need it so create a command ( @client.command() in your case) which takes an ID (integer), retrieves a discord.Member object and then bans.

my code just bans someone who is mentioned after the command is used

In the code example which you provided (though notice that next time you better to provide code to the question in the code blocks, not as images) you have already implemented a command which bans mentioned member using it's discord.Member object:

async def ban(ctx, member: discord.Member, *, reason=None):
    await member.ban()

Take a closer look at the member.ban() that's all you need. But here's the question: how would you edit this function so it will take ID and bans by it? Everything is simple.

Context ctx object which your function takes as an argument at the first place contains guild variable ctx.variable , which is an object of the guild from where the command was invoked. And a Guild object itself have a method called get_member(user_id) which basically takes user ID and returns guild's member discord.Member object if it's found. If there is no member in guild with specified user_id it will return None so you better check for None

So, lets summarize:

async def ban(ctx, member_id: int, *, reason=None):
    member = ctx.guild.get_member(member_id) # Here we take guild object and asks it to provide us a member object
    if member is not None: # Checking that we found member with such user id
        await member.ban() # And now we are banning

At the end, I would strongly recomend to discover d.py's documentation which can be found here .

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