【问题标题】:How to create a rank command with discord.py?如何使用 discord.py 创建排名命令?
【发布时间】:2021-09-22 11:42:40
【问题描述】:

最近我一直在尝试使用 discord.py(不使用 Cog,使用 bot.command)创建一个调平机器人。该代码实际上可以在每条消息之后更新级别,但 rank 命令不起作用。 我有一个类似json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)的消息错误

请问有人有办法解决吗?

这是我的完整代码(json 和 discord 库已经导入):

with open("users.json", "ab+") as ab:
    ab.close()
    f = open('users.json','r+')
    f.readline()
    if os.stat("users.json").st_size == 0:
      f.write("{}")
      f.close()
    else:
      pass
 
with open('users.json', 'r') as f:
  users = json.load(f)
 
@bot.event    
async def on_message(message):
    if message.author.bot == False:
        with open('users.json', 'r') as f:
            users = json.load(f)
        await add_experience(users, message.author)
        await level_up(users, message.author, message)
        with open('users.json', 'w') as f:
            json.dump(users, f)
            await bot.process_commands(message)
 
async def add_experience(users, user):
  if not f'{user.id}' in users:
        users[f'{user.id}'] = {}
        users[f'{user.id}']['experience'] = 0
        users[f'{user.id}']['level'] = 0
  users[f'{user.id}']['experience'] += 6
  print(f"{users[f'{user.id}']['level']}")
 
async def level_up(users, user, message):
  experience = users[f'{user.id}']["experience"]
  lvl_start = users[f'{user.id}']["level"]
  lvl_end = int(experience ** (1 / 4))
  if lvl_start < lvl_end:
    await message.channel.send(f':tada: {user.mention} has reached level {lvl_end}. Congrats! :tada:')
    users[f'{user.id}']["level"] = lvl_end
 
@bot.command()
async def level(ctx, member: discord.Member = None):
    if not member:
        id = ctx.message.author.id
        with open('users.json', 'r') as f:
            users = json.load(f)
        lvl = users[str(id)]['level']
        await ctx.send(f'You are at level {lvl}!')
    else:
        id = member.id
        with open('users.json', 'r') as f:
            users = json.load(f)
        lvl = users[str(id)]['level']
        await ctx.send(f'{member} is at level {lvl}!')

【问题讨论】:

    标签: python discord discord.py bots


    【解决方案1】:

    json 错误意味着你的 json 文件完全为空,你的 json 文件中至少需要{}

    【讨论】:

    • 我的 json 文档是这样的:{"my id": {"experience": 174, "level": 3}}
    • 我不这么认为
    【解决方案2】:

    在名为 users.json 的文件中 它必须看起来像这样:

    {
      
    }
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    • 我的 json 文档是这样的:{"my id": {"experience": 174, "level": 3}}
    • 那里一定是这样的...
    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2021-12-21
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    相关资源
    最近更新 更多