How to make data to be shown in tabular form in discord.py?

2024/9/20 9:26:38

Hi I am creating a bot that makes points table/leaderboard , below is the code which works really nice.

def check(ctx):return lambda m: m.author == ctx.author and m.channel == ctx.channelasync 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 embedembed.add_field(name=f'**{teamname}**', value=f'Kills: {firstnum}\nPosition Pt: {secondnum}\nTotal Pt: {firstnum+secondnum}',inline=True)await ctx.send(embed=embed)  

The result looks something like this:

enter image description here

But I want to know, can I do something to get the result in tabular form like The Team Name , positions points , total pts, kill pts written in a row and the results printed below them (I really don't if that made you understand what I am trying to say.)

Below image will help you understand ,

enter image description here

So I want the result to be in following format. I can't think of a way doing it , if you can answer this please do so, That would be a very great help! Thanks.

Answer

With table2ascii, you can easily generate ascii tables and put them in codeblocks on Discord.

You may also choose to use it in an Embed.

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

You can choose from many alternate styles.

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

https://en.xdnf.cn/q/72363.html

Related Q&A

Getting Python version using Go

Im trying to get my Python version using Go:import ("log""os/exec""strings" )func verifyPythonVersion() {_, err := exec.LookPath("python")if err != nil {log.Fata…

Python shutil.copytree() is there away to track the status of the copying

I have a lot of raster files (600+) in directories that I need copy into a new location (including their directory structure). Is there a way to track the status of the copying using shutil.copytree()?…

Py2exe error: [Errno 2] No such file or directory

C:\Users\Shalia\Desktop\accuadmin>python setup_py2exe.py py2exe running py2exe10 missing Modules------------------ ? PIL._imagingagg imported from PIL.ImageDraw ? PyQt4 …

pandas rolling window mean in the future

I would like to use the pandas.DataFrame.rolling method on a data frame with datetime to aggregate future values. It looks it can be done only in the past, is it correct?

When should I use type checking (if ever) in Python?

Im starting to learn Python and as a primarily Java developer the biggest issue I am having is understanding when and when not to use type checking. Most people seem to be saying that Python code shoul…

Kartograph python script generates SVG with incorrect lat/long coords

I have modified this question to reflect some progress on discovering the problem. I am using the following python code to generate an SVG of the continental USA. The shapefile is irrelevant, as the …

Python multiprocessing blocks indefinately in waiter.acquire()

Can someone explain why this code blocks and cannot complete?Ive followed a couple of examples for multiprocessing and Ive writting some very similar code that does not get blocked. But, obviously, I…

What is the best way to control Twisteds reactor so that it is nonblocking?

Instead of running reactor.run(), Id like to call something else (I dunno, like reactor.runOnce() or something) occasionally while maintaining my own main loop. Is there a best-practice for this with …

Accessing the content of a variable array with ctypes

I use ctypes to access a file reading C function in python. As the read data is huge and unknown in size I use **float in C . int read_file(const char *file,int *n_,int *m_,float **data_) {...}The func…

What is the stack in Python?

What do we call "stack" in Python? Is it the C stack of CPython? I read that Python stackframes are allocated in a heap. But I thought the goal of a stack was... to stack stackframes. What …