Is there a way to ignore the argument if it is not of a certain type/make an optional argument?

Viewed 50

So, for example, I have this code(in a cog):

@commands.command()
async def send_message(self, ctx, user : discord.Member = None,*, text = None)
if user and text:
  await ctx.send(user.mention + text)
elif not user and text:
  await ctx.send(text)

this code is supposed to send the message and mention a user if one is mentioned, but if there is no member object in the first argument of the message, it just shows an error and doesn't set text to all the other words in the message. Is there a way for the user argument to be completely ignored if the correct object type is not there?

2 Answers

Use isinstance() to test the type of the argument.

if text:
    if isinstance(user, discord.Member):
        await ctx.send(user.mention + text)
    else:
        await ctx.send(text)

As mentioned above, isinstance is the right way to check the object type. But type can also be used if you are aware of the subclasses.

if text is not None:
    if type(user) is discord.Member:
        await ctx.send(user.mention + text)
    else:
        await ctx.send(text)
Related