首页 > 解决方案 > 将服务器 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}")

标签: pythondiscorddiscord.py

解决方案


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'

参考:


推荐阅读