How to get userid from a string in discord.py

Viewed 389

I want to ban users. Theirs username+discriminator are write in a .txt file line per line.
Exemple:

user#0123
user2#0123
user3#0123

But the function ban() work with the ID of the user.
So, I need to know how to "transphorm" the username+discriminator to user.id

My code start with that:

    file = r'C:\Users\baron_btjit4i\Desktop\Autrebot\files\blacklist.txt'
    @commands.has_permissions(ban_members = True)
    @commands.command()
    async def banlist(self, ctx):
        with open(file, encoding='utf-8') as file_in:       

            for line in file_in:
                await ctx.guild.ban(line, reason='blacklist')

Thanks !

2 Answers

You can use discord.py MemberConverter to convert the string user into the user object. Docs of memberconverter

It will give you the member object and the properties of it is here mentioned in docs

Resulting code can be something like -

from discord.ext import commands

@commands.has_permissions(ban_members=True)
@commands.command()
async def banlist(self, ctx):
    with open(file, encoding='utf-8') as file_in:       
    for line in file_in:
        try:
            member = await commands.MemberConverter().convert(ctx, line)
            await ctx.guild.ban(member.id, reason='blacklist')
        except commands.errors.MemberNotFound:
            #  member not found here, handle it

To "transphorm" the username + discriminator to user.id you must use class discord.ext.commands.MemberConverter (not to be confused with UserConverter). The other user answered very well (@Priyam)

Related