Discord.py how to pass ctx as a default argument

Viewed 1839

I'm writing a profile command using Discord.py which prints out information about the specified user.

I would like to pass the message author as the default argument, so if the user just writes the command and nothing else, the bot will send their profile.

@bot.command()
async def profile(ctx, *, user: discord.Member = ctx.message.author):

The above code doesn't work. It errors out with the following error:

Traceback (most recent call last):
  File "bot.py", line 50, in <module>
    async def profile(ctx, *, user: discord.Member = ctx.message.author.name):
NameError: name 'ctx' is not defined

Can anybody tell me what I am doing wrong and how to make my code work?

EDIT:

I sort of bypassed the problem with:

@bot.command()
async def profile(ctx, *, user: discord.Member=None):
        if(user == None):
                user = ctx.message.author

My question still remains, is there any way to pass ctx as a default argument?

2 Answers

you can use this -

user = ctx.author if not user else user

instead of -

if(user == None):
                user = ctx.message.author

The short answer is that you can't do that, as you would be altering the signature of the function. Commands are called expecting this signature:

async def my_command(ctx, *args, **kwargs):

ctx is not a given value, just the name of the first parameter. You can't make assumptions about what is going to be used for.

What you can do, is assume the number of parameters, following the example that's in the discord.py documentation, you can do something like this:

async def profile(ctx, *, user:discord.Member):
    member = user or ctx.message.author

In this code, you can assume member is always a Member, except in a private channel, when it would be a User.

Related