如何将json文件转移到discord.py的嵌入文件中?

时间:2020-05-19 20:13:19

标签: python json discord.py

我尝试过:

@bot.command()
@commands.has_any_role('KING')
async def list(ctx):

    with open(r'F:\DiscordBot\PyCharm\Knastwärter\knastusers.json', 'r')as read_file:
        users = json.load(read_file)

    embedlist = discord.Embed(title='__**Liste aller Häftlinge**__', description=
                              f'{users}')
    await ctx.send(embed=embedlist)

但是我明白了:

{'369910055665008652': 'Scuux#0001', '605948244282834944': 'test12312424#3354'}

但是我希望用户名和ID彼此之间排列,没有字符串和尾括号。

1 个答案:

答案 0 :(得分:1)

我认为您不会自己传输json文件,否则您的代码可能会显示如下:

@bot.command(name='file')
async def cmd_file(ctx):
    await ctx.send(file=discord.File('./a.json'))

您的问题是如何在json文件中传输信息,因此我认为您需要Embed.add_field才能实现:

@bot.command(name='list')
async def cmd_list(ctx):
    with open('./a.json', 'r') as read_file:
        users = json.load(read_file)

    embedlist = discord.Embed(title='Title', description='User List')

    join = lambda x: '\n'.join(x)
    embedlist.add_field(name='User Name', value=join(users.values()))
    embedlist.add_field(name='User ID', value=join(users.keys()))

    await ctx.send(embed=embedlist)

请注意,list是内置数据类型,应避免将函数命名为list。建议您在函数名称前添加前缀,并在name上使用bot.command参数。

结果:

Results

您可以根据自己的喜好进行调整,documentation of discord.py中有更多详细信息,包括许多美化嵌入的方法。