JSON文件每次写入新信息时都会清除

时间:2018-07-06 16:26:42

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

因此,基本上我有一个JSON文件,该文件保存了来自我的不和谐服务器的每条消息,它适用于第一条消息,但是当第二条消息保存到“ data.txt”文件中时,原始消息将被删除/已覆盖,并从文件中消失。如何使所有邮件保存为单独的项目...

  @bot.event
    async def on_message(message):
        contents = message.content
        data = [contents]
        for word in contents:
            with open('data.txt', 'w') as outfile:
                data.append(json.dump(str(data), outfile))

            await bot.process_commands(message)

1 个答案:

答案 0 :(得分:1)

这就是我要做的。这会将机器人看到的每条消息作为字符串文字放在自己的行上。无论您有什么消费者,都应在此文件上逐行致电ast.literal_eval来重新构造消息。

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return 
    with open('data.txt', 'a') as f:
        print(repr(message.content), file=f)
    await bot/process_commands(message)