【问题标题】:Discord.py json files keep resetting after restarting botDiscord.py json 文件在重新启动机器人后不断重置
【发布时间】:2021-07-23 05:42:55
【问题描述】:

所以基本上我制作了一个可以通过命令更改其前缀的机器人,它只会将该自定义前缀设置为您所在的服务器。但是当我重新运行程序时,它会将前缀重置为默认值。例如,如果我将前缀设置为 !从-,如果我重新运行机器人,它会将其设置回!。这是我的代码:

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!")

【问题讨论】:

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


    【解决方案1】:

    按照您的编码,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_prefixes
    

    【讨论】:

    • 它现在可以在您重新运行机器人时工作,但在您设置前缀后不起作用:/
    • custom_prefixes[str(ctx.guild.id)] = prefixes.split() or default_prefixes
    最近更新 更多