1
votes

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')
1

1 Answers

3
votes

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