【问题标题】:discord.py how to accept optional argumentsdiscord.py 如何接受可选参数
【发布时间】:2023-08-10 17:40:01
【问题描述】:

我制作了一个系统,该系统使用 JSON 文件来创建一个使用 discord.py 的带有不和谐机器人的货币系统 我希望用户能够通过 +balance 向他们展示他们拥有多少,或者通过 +balance 来查看其他人的余额。我试着做一个尝试:抓住成员的平衡,除非成员没有争论,但我不知道这是什么错误。如果没有参数表明他们想要的成员是 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')

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    要在未传递可选变量时为函数提供默认行为,您可以为其提供默认值 None 以及该变量为 None 时的行为。

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

    【讨论】: