【问题标题】:Discord.py bot failing to send a message when the member is not in the JSON file当成员不在 JSON 文件中时,Discord.py 机器人无法发送消息
【发布时间】:2020-05-04 01:01:47
【问题描述】:
@bot.command()
async def coincount(ctx,*, member: discord.Member = None):
    member = ctx.author if not member else member
    member_id = str(member.id)
    with open('users.json', 'r') as f:
        users = json.load(f)

        coins = users[member_id]['coins']
        if member_id in users:
            if coins > 1:
                await ctx.send(f'{member.mention} has {coins} coins.')
            if coins == 1:
                await ctx.send(f'{member.mention} has {coins} coin.')
        else:
            await ctx.send(f'{member.mention} has no coins.')

没有回溯。如果成员在文件中,机器人会发送相应的消息,但如果不在,则不执行任何操作。

【问题讨论】:

    标签: python python-3.x discord discord.py


    【解决方案1】:

    如果会员 ID 不在您的 JSON 文件中,则 coins = users[member_id]['coins'] 将引发 KeyError
    您应该将它移到 if 语句中。

    由于您的on_command_error 中的error handling,它可能不会引发回溯。

    【讨论】:

      猜你喜欢
      • 2020-09-29
      • 1970-01-01
      • 2021-01-26
      • 2022-12-01
      • 2021-10-14
      • 2020-11-04
      • 2020-10-10
      • 2020-06-16
      • 2021-10-23
      相关资源
      最近更新 更多