N
N
NbUser1432021-01-26 18:00:45
Python
NbUser143, 2021-01-26 18:00:45

How to ban by username and id?

Hello!
I wrote a command that, according to the idea, should ban a participant by username or his id, but something does not work.
Tell me what's wrong, please.

@commands.command()
async def ban(self, ctx, member, *, reason=None):
        if len(member) == 18 and member.isdigit() == True: # бан по id участника
            id = int(member)
            user = await self.client.fetch_user(id)
            await user.ban(reason = reason)
        else: # бан по username участника
            await member.ban(reason = reason)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Nevzorov, 2021-01-27
@NbUser143

Use converters :

import typing

...

@commands.command()
async def ban(self, ctx, member: typing.Union[discord.Member, int], *, reason=None):
# https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#typing-union
    if isinstance(member, int):
        member = discord.Object(member)
    try:
        await ctx.guild.ban(member, reason=reason)  # https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.ban
    except NotFound:
        await ctx.send(f"Не найдено пользователя с ID {member.id}")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question