首页 > 解决方案 > 为不同的不和谐服务器创建自定义前缀

问题描述

我试图让机器人有一个前缀,你可以为你想要的每台服务器使用,但是当你使用命令时,它会在控制台中弹出

return prefixes[str(message.guild.id)] #recieve the prefix for the guild id given
KeyError: '882434407212925000'

这是我使用的代码和它说它失败的行

def get_prefix(client, message): ##first we define get_prefix
    with open("prefixes.js", "r") as f: ##we open and read the prefixes.json, assuming it's in the same file
        prefixes = json.load(f) #load the json as prefixes
    return prefixes[str(message.guild.id)] #recieve the prefix for the guild id given

标签: discord.pycommand

解决方案


错误的文件类型

首先,您尝试输入的文件是一个 .js (JavaScript) 文件,它不是一种数据库形式。您很可能正在寻找可以存储数据的 .json(JavaScript 对象表示法)文件。

公会ID找不到

您的代码不起作用的另一个原因是您返回的数据集不存在。换句话说,公会不在前缀文件中。

例子

def get_prefix(client, message):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    try:
        return prefixes[str(message.guild.id)]
    except:
        prefixes[str(message.guild.id)] = 'put default prefix here'}
        with open('prefixes.json', 'w') as f:
            json.dump(prefixes, f)
        return prefixes(message.guild.id)]

将“将默认前缀放在此处”替换为您的机器人前缀。

解释

在上面的示例中,我在您的代码中添加了一个 try except,以便在发生错误时(无法在数据集中找到公会)将其添加到数据集中并返回机器人的默认前缀作为占位符。


推荐阅读