【问题标题】:Why exactly will this discord python command only run once?为什么这个 discord python 命令只运行一次?
【发布时间】:2020-09-07 22:45:16
【问题描述】:

我一直试图让这段代码工作一段时间;

@bot.group()
async def donator(ctx):
    '''Commands for donators'''

@donator.command()
async def register(ctx, Steam_ID : str):
    '''Registers your donator status'''
    if SteamID(Steam_ID).is_valid():
        convert = SteamID(Steam_ID)
        Steam64ID = convert.as_64

        author = ctx.author

        with open('donators.json') as d:
            data = json.load(d)

        newstring = {
        f"{author.id}": {
                "steam": f"{Steam64ID}",
                "tier": "6"
            }
        }

        data.update(newstring)

        with open('donators.json', 'w') as d:
            json.dump(data, d, indent=2)

    else:
        ctx.send("Invalid Steam ID!\nThis command accepts any kind of Steam ID.")

当我运行它时,它会产生我想要的结果,一个具有正确信息的有效 json 文件被写入,没有错误。 如果我再次运行它,没有任何反应,绝对没有。这就是 json 最初的结构。

{
  "000000000000000000": {
    "steam": "00000000000000000",
    "tier": "0"
  }
}

运行python脚本后会是这个样子

{
  "000000000000000000": {
    "steam": "00000000000000000",
    "tier": "0"
  },
  "240912491624923137": {
    "steam": "76561197960265729",
    "tier": "6"
  }
}

如果我第二次运行它,什么都不会发生。什么都没写,json文件保持不变,没有错误。

【问题讨论】:

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


    【解决方案1】:

    您应该将 JSON 文件构建为字典列表。

    {"data": [{"id": 0, "name": "Hello"}, {"id": 1, "name": "Test"}]}
    

    【讨论】:

    • 感谢您的回复!我的问题与 JSON 结构无关,实际上我当前的结构工作得很好。问题是我试图在同一个帐户下添加多个条目,因此它只会更新已经存在的密钥而不是创建重复项。我的错误,哎呀!
    • 在这种情况下,无法创建副本。虽然您可以编辑现有索引。
    • 不,不,我不想重复,但是我没有想清楚,忘记了它是如何工作的哈哈!试图在我创建的明确不允许重复的系统上进行重复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 2020-11-28
    • 1970-01-01
    相关资源
    最近更新 更多