(discord.py) 如何让我的 setprefix 命令正常工作?

(discord.py) How can I make my setprefix command work properly?

标题可能看起来有点笼统,所以让我解释一下。我的机器人使用前缀 m!,我实现这一点的方法是将这一行添加到我的代码中:

client = commands.Bot(command_prefix="m!")

成功了。现在我决定更改前缀系统的工作方式,因为我希望服务器能够更改机器人的前缀。我创建了一个 prefixes.json 文件并添加了以下代码:

def get_prefix(client, message):
    with open("prefixes.json", "r") as f:
        prefixes = json.load(f)
    return prefixes[str(message.guild.id)]

我也把client = commands.Bot(command_prefix="m!")改成这样:

client = commands.Bot(command_prefix=get_prefix)

并添加了这些,以便机器人在加入服务器时将服务器添加到具有默认前缀 m! 的 JSON 文件中。

@client.event
async def on_guild_join(guild):
    with open("prefixes.json", "r") as f:
        prefixes = json.load(f)

    prefixes[str(guild.id)] = "m!"
    with open("prefixes.json", "w") as f:
        json.dump(prefixes, f, indent=4)


@client.event
async def on_guild_remove(guild):
    with open("prefixes.json", "r") as f:
        prefixes = json.load(f)

    prefixes.pop(str(guild.id))
    with open("prefixes.json", "w") as f:
        json.dump(prefixes, f, indent=4)

基本上,当机器人加入服务器时,它会被添加到 JSON 文件

{
    "<id goes here>": "m!"
}

当服务器使用我添加的 setprefix 命令时,JSON 会更新为新前缀。

下面是 setprefix 命令的样子

@client.command()
async def setprefix(ctx, prefix):
    with open("prefixes.json", "r") as f:
        prefixes = json.load(f)
    prefixes[str(ctx.guild.id)] = prefix
    with open("prefixes.json", "w") as f:
        json.dump(prefixes, f, indent=4)
    await ctx.send(f"Prefix changed to: {prefix}")

现在,所有这些代码都有效。但仅适用于机器人在我实施后加入的服务器。这意味着 bot 对于之前添加的所有服务器基本上都是坏的,因为它们在 JSON 文件中没有条目。 我怎样才能使机器人在这些服务器上也能正常工作?

您可以将 get_prefix 更新为默认值:

def get_prefix(client, message):
    with open("prefixes.json", "r") as f:
        prefixes = json.load(f)
    return prefixes.get(str(message.guild.id), "m!")