这个标题看上去有点笼统,所以让我解释一下。我的机器人使用前缀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)本质上,当bot加入服务器时,它将被添加到JSON文件中。
{
"<id goes here>": "m!"
}当服务器使用我添加的set前缀命令时,JSON将使用它们的新前缀进行更新。
顺便提一下,set前缀命令是什么样子的
@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文件中没有条目。,我怎样才能让机器人在这些服务器上工作呢?
发布于 2020-07-04 17:41:22
您可以更新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!")https://stackoverflow.com/questions/62731666
复制相似问题