discord.py how to accept optional arguments

10,611

To give a function a default behavior when an optional variable is not passed, you can give it a default value of None and a behavior when that variable is None.

@bot.command(pass_context=True)
async def balance(ctx, member: discord.Member=None):
    if member is None:
        member = ctx.message.author

    # do stuff
Share:
10,611
Sammy
Author by

Sammy

Updated on June 05, 2022

Comments

  • Sammy
    Sammy about 2 years

    I have made a system that uses JSON files to create a currency system with a discord bot using discord.py I want users to be able to do +balance to show them how much they have, or +balance in order to check someone else's balance. I tried doing a try: to grab the members' balance and excepting if there was no argument for the member, but I don't know what kind of error it is for that. How do I make it so that the bot will assume if there is no argument that the member they want is ctx.message.author?

    if exists('balances.json'):
        with open('balances.json', 'r') as file:
            balances = json.load(file)
            print(balances)
    def save():
        with open('balances.json', 'w+') as f:
            json.dump(balances, f)
    
    
    
    #Allows users to check their balance
    @bot.command(pass_context=True)
    async def balance(ctx, member: discord.Member):
        global balances
        if str(member.id) not in balances.keys():
            await ctx.channel.send(f'{member.name} not registered')
            return
        if str(member.id) in balances.keys():
            requestedUserBalance = balances[str(member.id)]
            await ctx.channel.send(f'{member.name} has {requestedUserBalance} LotusTokens')