我正在用python编写一个discord bot,我有一个命令,可以抓取discord服务器上的每个用户,并将他们放在JSON文件中,我将其设置为JSON文件中已经存在一个人,然后它将他们第二次添加到他们的节中,但我在制作它时遇到了问题。这是我用来将所有内容放在JSON中的代码:
import discord
from discord import app_commands
from discord.ext import commands
import json
from datetime import date
@commands.command()
async def forceScrape(ctx):
schizo = 1133822869177126942 #my discord id
debugchannel = bot.get_channel(1134732572816068628) #debug channel
if ctx.message.author.id == schizo: #check if the user is me
with open("users.json", "r") as f:
users = json.load(f) #load json file
for members in ctx.guild.members:
currentDate = date.today() #getting current date
usersid = members.id #getting every memebers' ids
names = members.name #getting every members' name
if str(usersid) in users:
users[usersid] = [{f"{users[str(usersid)]}\n" + f"{currentDate}":names}] #updating users[usersid] to add new datas
await debugchannel.send(f"ID: {usersid} NAME: {names} || was updated") #send a message in the debug channel
else:
users[usersid] = [{f"{currentDate}":names}] #add new datas in users[usersid]
await debugchannel.send(f"ID: {usersid} NAME: {names} || was added") #send a message in debug channel
with open("users.json", "w") as f:
json.dump(users, f, indent=4) #put everything in users.json
await debugchannel.send("Users have been scraped to users.json")
else:
await ctx.reply("You do not have permissions to execute that command")
当它向已经存在的用户添加新数据时,它是这样的:
{
"1133822869177126942": [
{
"[{'2023-07-30': 'schizophrenic'}]\n2023-07-30": "schizophrenic"
}
]
}
我试着让它看起来像这样:
{
"1133822869177126942": [
{
"2023-07-30": "schizophrenic"
},
{
"2023-07-30": "schizophrenic"
}
]
}
我寻找了多种方法来实现这一点,但找不到任何可行的方法,所以这是我的最后手段。
我尽可能详细地介绍了代码,使您更容易理解。
提前谢谢。