discord.py将消息对象分配给json文件

2024-04-19 01:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

在discord.py中,我让机器人发送消息。然后,我让机器人将该消息对象分配给json文件中的一个键。我的代码是

async def testmessage():
    with open('messages.json') as json_file:
        data = json.load(json_file)
    channel = bot.get_channel(779563485724934184)
    message1 = await channel.send('hi')
    print(data)
    data['message1'] = message1

    with open('messages.json', 'w') as json_file:
        json.dump(data, json_file)

    message3 = data['message1']
    await message3.edit(content='lol')

然而,当我这样做时,我得到了错误TypeError: Object of type Message is not JSON serializable 我如何解决这个问题


Tags: pyjson消息dataaswithchannel机器人
1条回答
网友
1楼 · 发布于 2024-04-19 01:29:32

您需要获取消息对象的字段,并创建一个字段名为键的dict。只取你需要的字段。 然后,将这个dict放到data['message1']字段中

不一致。消息在JSON中不可序列化

如果您想存储真正的消息对象,并且在读取存储的数据时能够检索到它,这在JSON中是不可能的,那么您应该对该对象进行pickle(即使这样,我也不确定是否一切都会好起来)

相关问题 更多 >