python - 将服务器 ID 的部分发送到它旁边
问题描述
当我使用 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}")
解决方案
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'
有了这些,我们就可以解决您的问题。
首先,我建议为函数和变量选择更合理的名称。这将有助于避免命名空间污染。
这是一些具有更好名称的工作代码的示例:
# 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'
参考:
- 字典练习- 可能值得一看,这样你就会对它们的工作方式感到满意。
- 命名空间污染
- PEP-8 - Python 的样式指南。我建议您通读这篇文章,或者至少浏览一下您可能不确定的任何内容。
json.load()
json.dump()
Context.guild
Guild.id
on_guild_join()
推荐阅读
- maven - 常见依赖安装覆盖失败
- powershell - 在 powershell/powercli 中使用 invoke-vmscript 时的多线程 foreach 循环
- vb.net - 迁移 VB 项目后的 Nuget Catch 22
- c# - 实体框架/基础存储库类 - 添加重复检查
- apache-spark - 通过 sparklyr 连接到另一个 Spark 集群时是否需要本地版本的 Spark?
- ios - 以与 iPhone 相同的方式截屏 iOS 模拟器(但不保存到桌面)
- html - 内容未居中对齐
- javascript - 获取yLabel值onclick图表js
- java - 双掷硬币
- wix - 未选择的功能正在安装