我正在构建一个机器人,它应该将每个 member
和相应的 guild
存储在 JSON 中。这在代码中没有问题,但我无法正确处理一件事。
代码如下:
async def on_member_join(self, member):
with open("src/member.json", "r", encoding='utf-8') as f:
mlist = json.load(f)
guild = str(member.id)
#try:
#mlist[str(member.guild.id)] = guild
#except KeyError:
#print("KEY ERROR")
#mlist[str(member.guild.id)] = guild
if guild in mlist:
return print("IN LIST")
else:
mlist[str(member.guild.id)] = guild
print("NOT IN LIST")
with open('src/member.json', 'w', encoding='utf-8') as f:
json.dump(mlist, f, indent=2)
当我使用我的帐户进入服务器时,条目已创建,但当我再次进入服务器时,我的 print("NOT IN LIST")
仍然出现。
这是我的 JSON 的样子:
{
"731855252277690XXX": "704712637988077XXX" # GuildID : UserID
}
这里有人看到我的错误吗?
我已经尝试了以下方法:
if guild not in raidlist
try
和except
语句str
并将 member.id
或 guild.id
转换为其他内容答案 0 :(得分:0)
您现在正在做的是将每个公会和用户存储为单个键值对。也就是说每个公会只能存放一名成员。我们可以做的是使用列表:
async def on_member_join(self, member):
with open("src/member.json", "r", encoding='utf-8') as f:
mlist = json.load(f)
# changed to member id so it's less confusing
memberid = str(member.id)
guildid = str(member.guild.id)
if guildid in mlist:
if memberid in mlist[guildid]: # the member has already been recorded
return
mlist[guildid].append(memberid) # add the member to that guild's list
else:
mlist[guildid] = [memberid] # making a list with 1 element
with open('src/member.json', 'w', encoding='utf-8') as f:
json.dump(mlist, f, indent=2)
您应该在运行此代码之前清除 JSON,因为它与您之前的格式不兼容。
这样 json 将如下所示:
{
'GUILDID': ['MEMBERID1', 'MEMBERID2]
}