【问题标题】:on_member_remove deleting json contentson_member_remove 删除 json 内容
【发布时间】:2021-05-11 13:08:09
【问题描述】:

我没有收到任何错误,我正在通过踢私人服务器中的成员进行测试。问题是我希望这段代码在他们离开服务器时从我的 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"]

Intent 已正确启用(我认为):

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

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

【问题讨论】:

    标签: python json discord discord.py


    【解决方案1】:

    我不知道是什么导致 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)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      相关资源
      最近更新 更多