所以我正在嘗試制作一個將歌曲名稱添加給用戶的命令。我只是不明白我應該怎么做。我嘗試查看字典檔案,但在任何地方都找不到如何將變數附加到某個人。這是我當前的代碼,盡管我認為這是完全錯誤的:
@commands.command()
async def quote(self, ctx):
await ctx.send("add your quote")
msg = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
quote = msg.content
with open('quotes.json', 'r') as f:
quotes = json.load(f)
quotes.append(quote)
with open('quotes.json', 'w') as f:
json.dump(quotes, f)
await ctx.send("quote added!")
uj5u.com熱心網友回復:
您可以將其與字典一起使用并通過 ID 跟蹤它們。請注意這一點,因為 JSON 不允許您將整數用作任何內容的鍵。只允許使用字串。
@commands.command()
async def quote(self, ctx):
await ctx.send("add your quote")
msg = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
quote = msg.content
with open('quotes.json', 'r') as f:
quotes = json.load(f)
strid = str(msg.author.id) # this is necessary for json
if strid not in quotes.keys():
quotes[strid] = []
quotes[strid].append('My quote, or put whatever you need to add in here')
with open('quotes.json', 'w') as f:
json.dump(quotes, f)
await ctx.send("quote added!")
作為旁注,打開檔案并多次關閉它是一個壞主意。相反,您可以嘗試這樣的構造,然后您將不必打開檔案這么多:
client = commands.Bot(...)
with open('quotes.json', 'r'):
client.quotes_data = json.load(f)
@tasks.loop(minutes=3.0) # adjust this at your liking, or execute it manually
async def save_all():
with open('quotes.json', 'w'):
json.dump(client.quotes_data, f)
save_all.start()
uj5u.com熱心網友回復:
如果您嘗試這樣做,以便用戶可以以佇列型別的方式請求多首歌曲,我會創建一個字典,將鍵設為用戶(訊息的作者)的ID(ctx.author.id)并將值設定為空串列,然后將用戶請求的歌曲名稱附加到該串列中。
另一方面,如果您更喜歡每個用戶一首歌曲,只需將值設定為用戶 ID 鍵的歌曲即可。
這通常只使用字典的隨意鍵分配。
這是如何作業的示例(假設這是在您的命令中):
songs = {};
# This code if you'd like multiple songs per user.
songs[ctx.author.id] = [];
songs[ctx.author.id].append("SONG VALUE HERE");
# This code if you'd like one.
songs[ctx.author.id] = "SONG VALUE HERE";
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473204.html
上一篇:創建跨列標簽編碼器的字典
