Search code examples
pythondiscorddiscord.pyconverters

Banning user outside + inside server


I'm trying my best to make a command that bans people inside and outside a server. Is this possible?

@client.command(aliases=["banmember", "banuser"])
async def ban(ctx, member: discord.Member, *, reason=None):
    await ctx.message.delete()
    if reason is None:
        reason = ""

        if reason is not None:
            reason = reason
            try:
                await member.ban(reason=reason)
            except:
                user = await commands.converter.UserConverter().convert(ctx, user)
                banneduser = await client.fetch_user(user.id)
                await ctx.guild.ban(banneduser, reason=reason)

It does not look possible, as if i used UserConverter it wouldn't ban members inside the server, if i used Members it wouldn't ban people outside the server. How can I do both?


Solution

  • You can use use typing-union which allows for the command to take in any of the specific types instead of a singular type..

    Here is a simple example to send the name to verify it is working for both.

    import typing
    
    @bot.command()
    async def union(ctx, member: typing.Union[discord.Member, discord.User]):
        await ctx.send(member.name)