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

问题描述 投票:0回答:3

嗨,我正在创建一个可以制作积分表/排行榜的机器人,下面是效果非常好的代码。

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)  

结果看起来像这样:

enter image description here

但是我想知道,我可以做一些事情来获得表格形式的结果,例如团队名称,位置点,总分,击杀分写在一行中,并在它们下面打印结果(我真的不知道,如果这使得你明白我想说什么。)

下图可以帮助您理解,

enter image description here

所以我希望结果采用以下格式。我想不出办法,如果你能回答这个问题,请回答,那将是一个非常大的帮助! 谢谢。

python discord discord.py
3个回答
16
投票

使用 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```")

table 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


9
投票

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

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

代码将输出如下内容:

image

我已将

inline
设置为
False
并将
>
字符添加到每个统计数据中。


0
投票

我被要求做同样的事情,最终编写了一个函数来从 pandas df 创建图像并返回一个对象。

def create_table_image(df):
    fig, ax = plt.subplots(figsize=(12, len(df) * 0.5 + 1))
    ax.axis('off')
    ax.axis('tight')

    table = ax.table(cellText=df.values, colLabels=df.columns, cellLoc='center', loc='center',
                     colColours=["#4682B4"] * df.shape[1], cellColours=[["#f0f0f0"] * df.shape[1]] * df.shape[0])

    table.auto_set_font_size(False)
    table.set_fontsize(10)
    table.scale(1.5, 1.5)

    for key, cell in table.get_celld().items():
        cell.set_text_props(ha='center', va='center')
        cell.set_fontsize(10)
        cell.set_width(1.0 / len(df.columns))

    plt.title('** Leader Board **', fontsize=35, fontweight='bold')

    buffer = BytesIO()
    plt.savefig(buffer, format='png', bbox_inches='tight', dpi=300)
    plt.close()
    
    buffer.seek(0)
    return buffer
    ```

© www.soinside.com 2019 - 2024. All rights reserved.