我目前正在使用Python开发Discord机器人。为了保存数据,我创建了一个.tmp文件,用于存储json格式的数据文本。
我必须对其进行编码,以便立即写入文件中(我还在文件中进行了一些值检查)。
由于已编码,因此无法使用以下代码编辑json:
emojiU = '\N{THUMBS UP SIGN}'
emojiD = '\N{THUMBS DOWN SIGN}'
cnd_Member = [member for member in ctx.guild.members if str(data['roles_id']['AmongUs']) in str(member.roles) and (str(member.status) == "online" or str(member.status) == "idle") and member.id != ctx.author.id]
tmpfile = open("my_file.tmp", "wb+", 0) #List that store connected user with a specific role
for i, member in enumerate(cnd_Member): # for connected member with the specific role
DM = discord.utils.get(client.get_all_members(), id=member.id)
Sstring = "***" + Sender + "***" + ' veux jouer à ***' + game + '***.\n :thumbsup: si vous êtes chaud ou :thumbsdown: si vous ne l\'êtes pas'
msg = await DM.send(embed=createEbd(des=Sstring, img=imgLink)) #send DM to the member
if i == 0:
save = '{{"{}":{{"msgId":{}, "reaction":"None"}}, '.format(member.id, msg.id)
elif i == len(list(cnd_Member))-1:
save = '"{}":{{"msgId":{}, "reaction":"None"}}}}'.format(member.id, msg.id)
else :
save = '"{}":{{"msgId":{}, "reaction":"None"}}, '.format(member.id, msg.id)
await msg.add_reaction(emojiU ) #Bot add reaction to the DM message
await msg.add_reaction(emojiD) #Bot add reaction to the DM message
tmpfile.write(save.encode("utf-8")) #creating the json file with data
@client.event
async def on_reaction_add(reaction, user):
if user.id != client.user.id :
if reaction.emoji == emojiU:
tmpfile.seek(0)
rd = tmpfile.read() # Getting the content of file
binf = json.loads(rd.decode('utf-8'))
binf["{}".format(user.id)]["msgId"] = thxObj.id #Updating the json with new value
binf["{}".format(user.id)]["reaction"] = "True" #Updating the json with new value
json.dump(binf, tmpfile) #writing to file fail because it's not encoded
if reaction.emoji == emojiD:
tmpfile.seek(0)
rd = tmpfile.read() # Getting the content of file
binf = json.loads(rd.decode('utf-8'))
binf["{}".format(user.id)]["msgId"] = thxObj.id #Updating the json with new value
binf["{}".format(user.id)]["reaction"] = "False" #Updating the json with new value
json.dump(binf, tmpfile) #writing to file fail because it's not encoded
使用json.dumps然后对其进行编码,并使用tmpfile.write将其写入文件,但它仅附加数据,而不编辑tmpfile中的现有json。
感谢帮助
答案 0 :(得分:0)
我找到了应对方法。
我将所有数据存储在JSON格式的文件中,当用户添加反应时,它将编辑该文件。 当我需要发布表时,它会读取JSON文件。
已编码或未编码,我只需要编辑json.loads
并重写文件即可使用