使用test命令时,我想访问存储在字典中的值:
但是,我不断收到此错误:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '714235745140736080'
这是我的代码:
def test1(client, message):
with open('test.json', "r") as f:
test = json.load(f)
return (test[str(message.guild.id)])
@client.command()
async def test(ctx):
with open('test.json', 'r') as f:
test = json.load(f)
test1 = (test[str(ctx.guild.id)])
await ctx.send(f"{test1}")
答案 0 :(得分:1)
JSON文件的工作方式类似于Python中的字典。使用键和值创建字典时,可以将其保存到.json
中。然后,在加载文件时就可以访问这些值,就像您正常访问字典时一样:
# Creating a dictionary with some arbitrary values
>>> data = {"foo": "bar", "key": "value"}
# Opening a file and writing to it
>>> with open("db.json", "w+") as fp:
... json.dump(data, fp, sort_keys=True, indent=4) # Kwargs for beautification
# Loading in data from a file
>>> with open("db.json", "r") as fp:
... data = json.load(fp)
# Accessing the values
>>> data["foo"]
'bar'
>>> data["key"]
'value'
通过这种方式,我们可以解决您的问题。
首先,我建议为函数和变量选择更合理的名称。这将有助于避免namespace pollution。
下面是一些名称更好的工作代码的示例:
# Adding a default paramter type will mean that you won't need to convert throughout the function
def get_data(guild_id: str):
with open("guilds.json", "r") as f:
data = json.load(f)
return data[guild_id]
@client.command()
async def cmd(ctx):
value = get_data(ctx.guild.id)
await ctx.send(f"{value}")
要注意的一件事是您实际上并没有使用定义的功能。您只是稍后在脚本中重写了它的代码。函数的目的是防止您重复这样的代码。您想调用该函数(例如my_func()
)以对其进行处理。
我猜您已经有一种将值写入/更新文件的方法。如果没有,那么此答案中应该有足够的信息。
当您尝试访问字典中不存在的键时,将得到KeyError
。出于这个原因,我建议您在机器人加入新协会的情况下建议调查on_guild_join()
事件以更新文件。
我相信,导致您的错误的原因是试图访问类型实际上为str
而不是int
的键的值-它们是完全不同的。请考虑以下内容:
>>> data = {"123": "value"}
>>> data[123] # This will throw a KeyError
>>> data["123"] # This will return the value
'value'
参考:
json.load()
json.dump()
Context.guild
Guild.id
on_guild_join()