如何在discord.py中以表格形式显示数据?

6

嗨,我正在创建一个可以制作积分表/排行榜的机器人,以下是能正常工作的代码:

def check(ctx):
    return lambda m: m.author == ctx.author and m.channel == ctx.channel


async def get_input_of_type(func, ctx):
    while True:
        try:
            msg = await bot.wait_for('message', check=check(ctx))
            return func(msg.content)
        except ValueError:
            continue

@bot.command()
async def start(ctx):
    await ctx.send("How many total teams are there?")
    t = await get_input_of_type(int, ctx)
    embed = discord.Embed(title=f"__**{ctx.guild.name} Results:**__", color=0x03f8fc,timestamp= ctx.message.created_at)
    
    lst = []
    
    for i in range(t):
        await ctx.send(f"Enter team {i+1} name :")
        teamname = await get_input_of_type(str, ctx)
        await ctx.send("How many kills did they get?")
        firstnum = await get_input_of_type(int, ctx)
        await ctx.send("How much Position points did they score?")
        secondnum = await get_input_of_type(int, ctx)
        lst.append((teamname, firstnum, secondnum))  # append 
        
    lstSorted = sorted(lst, key = lambda x: int(x[1]) + int(x[2],),reverse=True) # sort   
    for teamname, firstnum, secondnum in lstSorted:  # process embed
        embed.add_field(name=f'**{teamname}**', value=f'Kills: {firstnum}\nPosition Pt: {secondnum}\nTotal Pt: {firstnum+secondnum}',inline=True)

    await ctx.send(embed=embed)  

结果大致如下:

输入图像描述

但是我想知道,是否可以做些什么来以表格形式获得结果,像队名、位置分数、总积分、击杀积分这样的一行写在一起,然后将结果打印在它们下面(如果这让你明白我想说什么,那就好了)。
下面的图片将帮助您理解,

输入图像描述

所以我希望结果以以下格式呈现。我无法想到一种方法来做到这一点,如果您能回答这个问题,请这样做,这将非常有帮助!谢谢。

检查 Discord 嵌入。 https://discordpy.readthedocs.io/en/latest/api.html#embed - Abhilash
3个回答

11
使用 table2ascii 工具,您可以轻松生成 ASCII 表格并将其放置在 Discord 的代码块中。
您还可以选择在嵌入式消息中使用该工具。
from table2ascii import table2ascii as t2a, PresetStyle

# In your command:
output = t2a(
    header=["Rank", "Team", "Kills", "Position Pts", "Total"],
    body=[[1, 'Team A', 2, 4, 6], [2, 'Team B', 3, 3, 6], [3, 'Team C', 4, 2, 6]],
    style=PresetStyle.thin_compact
)

await ctx.send(f"```\n{output}\n```")

表格1

您可以选择许多不同的样式。

from table2ascii import table2ascii as t2a, PresetStyle

# In your command:
output = t2a(
    header=["Rank", "Team", "Kills", "Position Pts", "Total"],
    body=[[1, 'Team A', 2, 4, 6], [2, 'Team B', 3, 3, 6], [3, 'Team C', 4, 2, 6]],
    first_col_heading=True
)

await ctx.send(f"```\n{output}\n```")

enter image description here


7

这可能是你能得到的最接近的:

embed.add_field(name=f'**{teamname}**', value=f'> Kills: {firstnum}\n> Position Pt: {secondnum}\n> Total Pt: {firstnum+secondnum}',inline=False)

代码将输出类似于以下内容:

image

我已将inline设置为False并在每个统计数据前添加了>字符。

3

好的,有一种方法可以实现这一点,但您将无法使用字段名称作为团队名称!此图片显示了它的外观!

@bot.command(name = 'test')
async def test(context: commands.Context):
    # Example dataset here! 
    DATASET = (
        # Rank, team, kills, positions, totals ... 
        (1, 'A', 2, 4, 6),
        (2, 'B', 3, 3, 6),
        (3, 'C', 4, 2, 6)
    ) # Assumes we have sorted this! 
    s = ['Rank     Team   Kills   PosPts.  Total']
    # This needs to be adjusted based on expected range of values or   calculated dynamically
    for data in DATASET:
        s.append('   '.join([str(item).center(5, ' ') for item in data]))
        # Joining up scores into a line
    d = '```'+'\n'.join(s) + '```'
    # Joining all lines togethor! 
    embed = discord.Embed(title = 'Quotient Results', description = d)
    await context.send(embed = embed)

那应该如预期所般运作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接