基本上,我制作了一个机器人,它可以通过命令改变它的前缀,它只会将这个自定义前缀设置为您所在的服务器。但是,当我重新运行程序时,它会将前缀重置为默认值。例如,如果我将前缀设置为!从-,如果我重新运行这个机器人,它会将它设置为!这是我的密码:
custom_prefixes = {}
with open('prefixes.json', 'r') as f:
json.load(f)
default_prefixes = ['-']
async def determine_prefix(bot, message):
guild = message.guild
#Only allow custom prefixs in guild
if guild:
return custom_prefixes.get(guild.id, default_prefixes)
else:
return default_prefixes
client = commands.Bot(command_prefix = determine_prefix)
@client.event
async def on_ready():
print("Bot loaded successfully")
@client.command()
@commands.guild_only()
async def setprefix(ctx, *, prefixes=""):
custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
with open('prefixes.json', 'w') as f:
json.dump(custom_prefixes, f)
await ctx.send("Prefixes set!")发布于 2021-07-23 07:08:21
在编写代码时,custom_prefixes始终是一个空字典。
您编写了json.load(f)来读取json文件,但没有为该文件内容分配任何变量:
with open('prefixes.json') as f:
custom_prefixes = json.load(f)在json文件中,键必须是字符串,不能是整数。在您的代码中,您将得到guild.id,它是一个整数,因此custom_prefixes.get(guild.id, default_prefixes)将始终返回default_prefixes
def determine_prefix(bot, message):
guild = message.guild
if guild:
return custom_prefixes.get(str(guild.id), default_prefixes)
# The else statement is unnecessary
return default_prefixeshttps://stackoverflow.com/questions/68494534
复制相似问题