[英]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.