首页 > 解决方案 > 通过python json模块更新json文件无法通过discord命令工作

问题描述

我有一个用 python 编码的不和谐机器人。我希望能够将用户数据保存在 JSON 文件中,但由于某种原因,我编写的这段代码不起作用。这是给我问题的代码。

@client.command()
async def slash(ctx):

amount = random.randint(1,10)

with open("data.json", "r") as f:
    users = json.load(f)

await userupdateslash(users, ctx.author, amount)

with open("data.json", "w") as f:
    json.dump(users, f, indent=4)

f.close()

embed = discord.Embed(
        title = "Slash!",
        description = (f"{ctx.author} slashed through a stormtrooper and gained {amount}xp"),
        colour = discord.Colour.green()
)

embed.set_footer(text='Created by [VG] Xezo#6969')
embed.set_thumbnail(url='https://cdn.discordapp.com/app-icons/760648752435822613/c1d0d4451e8e3123373709d31b0bffba.png?size=128')
embed.set_author(name='Baby Yoda',
icon_url='https://cdn.discordapp.com/app-icons/760648752435822613/c1d0d4451e8e3123373709d31b0bffba.png?size=128')

await ctx.send(embed=embed)

async def userupdateslash(users, user, xp):
    if user.id in users:
        try:
            users[user.id]["xp"] += xp
        except Exception as error:
            raise(error)

标签: pythondiscord.py-rewrite

解决方案


我有一个工作代码, on_message如果用户在 data.json 上已经有一个插槽(xp),我实现了事件。

@client.event
async def on_message(message):
    if message.author.bot == False:
        with open('data.json', 'r') as f:
            users = json.load(f)

        await update_data_slash(users, message.author)
        await update_slash(users, message.author, 0)
        with open('data.json', 'w') as f:
            json.dump(users, f, sort_keys=True, ensure_ascii=False, indent=4)

    await client.process_commands(message)

async def update_data_slash(users, user):
    if not f'{user.id}' in users:
        users[f'{user.id}'] = {}
        users[f'{user.id}']['xp'] = 0

async def update_slash(users, user, xp):
    users[f'{user.id}']['xp'] += xp

@client.command()
async def slash(ctx):
    amount = random.randint(1, 10)

    with open('data.json', 'r') as f:
        users = json.load(f)

    users[f'{ctx.author.id}']['xp'] += amount

    with open('data.json', 'w') as f:
        json.dump(users, f, sort_keys=True, ensure_ascii=False, indent=4)

    embed = discord.Embed(
        title = "Slash!",
        description = (f"{ctx.author} slashed through a stormtrooper and gained {amount}xp"),
        colour = discord.Colour.green()
        
        ).set_footer(
        text='Created by [VG] Xezo#6969'
        
        ).set_thumbnail(
        url='https://cdn.discordapp.com/app-icons/760648752435822613/c1d0d4451e8e3123373709d31b0bffba.png?size=128'

        ).set_author(
        name='Baby Yoda',
        icon_url='https://cdn.discordapp.com/app-icons/760648752435822613/c1d0d4451e8e3123373709d31b0bffba.png?size=128'
        )

    await ctx.send(ctx.author.mention, embed=embed)

我还改进了一些事情,例如:它对用户 ID 和 exp 进行排序,我更改了嵌入格式,它会提到带有嵌入的用户(不是在嵌入中,而是在它之上)


推荐阅读