在成员上删除删除json内容

2024-09-30 02:29:34 发布

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

我没有收到任何错误,我正在通过踢私有服务器中的成员进行测试。问题是,我希望这段代码在json成员离开服务器时将其从json中删除。它们将被踢出,并且不会从json中删除键/值。相反,当它们重新连接时,json文件的全部内容将被删除。甚至连{}都没有留下。 感谢您的帮助

@client.event
async def on_member_remove(member):
    with open ("MFpointsupdate.json", "r") as f:
        users = json.load(f)     
    
    await remove_member_from_json(users, member)
    
    with open("MFpointsupdate.json", "w") as f:
        json.dump(users, f,indent = 4)       
    
async def remove_member_from_json(users, user):
    
        member = await client.get_user_info(member.id)
        if member in users:
            del users[f"{user.id}"]["points"]

意图已正确启用(我认为):

intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix="<", intents = intents)

Tags: clientjsonasyncdefaswith成员open
1条回答
网友
1楼 · 发布于 2024-09-30 02:29:34

我不知道是什么导致json被完全删除,还有什么代码访问您的json文件。我最好的猜测是,不知何故,在on_member_join()事件中,您的用户数据是空的,而该文件只是被无内容覆盖

不管怎么说,这正是你想要的:

import json
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix="<", intents = intents)

@client.event
async def on_member_remove(member):
    with open ("MFpointsupdate.json", "r") as f:
        users = json.load(f)     
    
    await remove_member_from_json(users, member)
    
    with open("MFpointsupdate.json", "w") as f:
        json.dump(users, f,indent = 4)       
    
async def remove_member_from_json(users, user):
    if str(user.id) in users:
        del users[str(user.id)]

client.run(TOKEN)

相关问题 更多 >

    热门问题