Discord.py 如果get前缀出现错误,则自动创建文件

Discord.py 如果get前缀出现错误,则自动创建文件,discord.py,Discord.py,hello when it error我希望它自动为发生错误的服务器创建文件夹 def get_prefix(client, message): with open(f'Data/{message.guild.id}/settings.json', 'r') as f: prefixes = json.load(f) return prefixes['prefix'] client = commands.Bot(command_prefix=get_p

hello when it error我希望它自动为发生错误的服务器创建文件夹

def get_prefix(client, message):
    with open(f'Data/{message.guild.id}/settings.json', 'r') as f:
        prefixes = json.load(f)
    
    return prefixes['prefix']

client = commands.Bot(command_prefix=get_prefix, case_insensitive=True)

通过使用
try
except
我们可以在出现任何错误时运行代码块 当公会已经拥有
设置.json
时,它会返回前缀!否则它将为该公会创建一个新的settings.json!。 注意:将一些值设置为
数据
dict!将一些值存储到创建的settings.json中

def get_prefix(client, message):
    try:
        with open(f'Data/{message.guild.id}/settings.json', 'r') as f:
            prefixes = json.load(f)
        return prefixes['prefix']
    except:
        data = {'prefix':'!'}#data is dict to save something on it
        with open(f'Data/{message.guild.id}/settings.json', 'w') as f:
            json.dump(data, f)
        return data['prefix']
client = commands.Bot(command_prefix=get_prefix, case_insensitive=True)