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

时间:2020-07-04 16:30:39

标签: python python-3.x discord discord.py discord.py-rewrite

标题似乎有点通用,所以让我解释一下。我的机器人使用前缀m!,而我的实现方式是将以下行添加到我的代码中:

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

有效。现在,我决定更改前缀系统的工作方式,因为我希望服务器能够更改bot的前缀。我创建了一个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}")

现在,所有此代码均有效。但是,仅对于服务器,该机器人在我实现此目标之后才加入。这意味着对于之前添加的所有服务器,该漫游器实际上都已损坏,因为它们在JSON文件中没有任何条目。 我如何使机器人在这些服务器上工作?

1 个答案:

答案 0 :(得分:3)

您可以将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!")