[英]discord.py : Sort message ID in a JSON file by user
我目前正在制作一种票务系统。 我想通过反应来做到这一点。
当用户点击反应时,会向特定频道发送一条消息。 此消息 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)
代码看起来像:
@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
我希望我正确理解了您的问题,如果没有,我很乐意在澄清后编辑我的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.