【问题标题】:discord.py : Sort message ID in a JSON file by userdiscord.py :按用户对 JSON 文件中的消息 ID 进行排序
【发布时间】:2020-09-19 23:17:01
【问题描述】:

我目前正在制作一种票务系统。我想通过反应来做到这一点。

当用户点击反应时,会向特定频道发送一条消息。此消息 ID 保存在 JSON 文件中,应分配给单击反应的用户。但是如果我将用户和消息分别保存在 JSON 文件中,我不知道该消息属于哪个用户。如何将消息 ID 分配给用户?

我的代码:

@client.event
async def on_raw_reaction_add(reaction):
    ticketmess = 716263100638035969
    ticketlog = client.get_channel(716265124771397662)
    user = client.get_user(reaction.user_id)


    if reaction.message_id == ticketmess and reaction.emoji.id == 680827797165572117:
        with open(r'./tickets.json', 'r')as f:
            ticketchannels = json.load(f)
        if not f"{reaction.user_id}" in ticketchannels:

            ticketmess = await ticketlog.send('Ein User braucht Hilfe!')

            with open(r'./tickets.json', 'r')as f:
                ticketmessages = json.load(f)

                ticketmessages[f"{reaction.user_id}"] = f'{user} in {ticketmess.id}'

                with open(r'./tickets.json', 'w') as f:
                    json.dump(ticketmessages, f, indent=4)

【问题讨论】:

    标签: python json discord.py


    【解决方案1】:

    代码如下所示:

    @client.event
    async def on_raw_reaction_add(reaction):
        ticketmsg = 716263100638035969
        ticketlog = client.get_channel(716265124771397662)
        user = client.get_user(reaction.user_id)
    
        if reaction.message_id == ticketmsg and reaction.emoji.id == 680827797165572117:
    
            # you already have loaded it in once, you don't need to read it again
            with open("tickets.json", "r") as fp:
                data = json.load(fp) 
    
            if f"{reaction.user_id}" not in data.keys():
                ticketmsg = await ticketlog.send("Ein User braucht Hilfe!")
    
                # you can just assign the message id to the user, no need for a string
                data[f"{reaction.user_id}"] = ticketmsg.id
    
                with open("tickets.json", "w+") as fp:
                    json.dump(data, fp, sort_keys=True, indent=4) # kwargs are for beautification
    

    您不需要f"{user} in {ticketmsg.id}",因为您可以从密钥中获取用户。此外,用户名可以更改,因此将其放入文件中将被证明不是很有用。
    如果您想获取用户名,只需从 json 中加载密钥并使用 client.get_user(ID_HERE)

    如果您想根据特定的消息 ID 搜索用户,您可以像这样遍历字典:

    my_dict = {"key": "value", "foo": "bar"}
    
    for k, v in my_dict.items():
        if v == "bar":
            print(k) # selecting the key based off of its value
    
    # output:
    # foo
    

    我希望我正确理解了您的问题,如果没有,我很乐意在澄清后编辑我的答案。

    【讨论】:

    • 感谢您的回答。我稍后会测试它,因为我现在没有时间。我会通知你,如果我有问题。 :)
    • 好的,不用担心,等你测试完我就在身边!
    • 我有一个问题。但是当我有“很多”代码要发送时,在这里写起来有点令人困惑。我们可以简短地介绍一下 Discord 吗? Discord:Puncher#1111
    • 是的,无论如何。我正要 brb,但我会加你。
    猜你喜欢
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 2015-10-29
    • 1970-01-01
    相关资源
    最近更新 更多