pythonstringdiscorddiscord.pymonospace

How can i correctly format string widths inside of a discord Embed?


I’m working on a Discord bot using the discord.py library and encountered an issue where the printed console output is correct, but the output in the Discord embed is not displaying as expected - the String width is not correct.

Here is the relevant part of my code:

if in_database:
    searched_strings: list[str] = ["PLACEHOLDER_MONDAY", "PLACEHOLDER_TUESDAY", "PLACEHOLDER_WEDNESDAY",
                                   "PLACEHOLDER_THURSDAY", "PLACEHOLDER_FRIDAY", "PLACEHOLDER_SATURDAY",
                                   "PLACEHOLDER_SUNDAY"]
    days: list[str] = await translate_m(interaction.guild_id, searched_strings)
    for row in in_database:
        day: str = f"- **{days[row[0] - 1]}**:".ljust(50, ' ')
        work_hours += day + f"`{row[1]}`\n"

    print(work_hours)
    translations[2] = translations[2].replace("[work_hours]", work_hours)

embed: Embed = Embed(description="\n".join(translations[:-1]), color=0xEA2027)
await channel.send(embed=embed)

The correct console output: correct console output

The incorrectly formatted discord embed:

enter image description here

So my question is, how can I fix that? I heard about using a Codebox in discord to use it, but I'm not a fan of the idea to put all content here inside a Codebox - it's just ugly.


Solution

  • Based on this question, you could format the opening hours in a table-like style using Embed Fields:

    day_values = []
    hour_values = []
    if in_database:
        searched_strings: list[str] = ["PLACEHOLDER_MONDAY", "PLACEHOLDER_TUESDAY", "PLACEHOLDER_WEDNESDAY",
                                       "PLACEHOLDER_THURSDAY", "PLACEHOLDER_FRIDAY", "PLACEHOLDER_SATURDAY",
                                       "PLACEHOLDER_SUNDAY"]
        days: list[str] = await translate_m(interaction.guild_id, searched_strings)
        for row in in_database:
            day_values.append(f"**{days[row[0] - 1]}**")
            hour_values.append(f"`{row[1]}`")
    
    # I don't know what other stuff you have in `translations` and whether it makes sense 
    # (from a readability perspective) to simply omit the opening hours in the description 
    # but add it as fields
    embed: Embed = Embed(description="\n".join(translations[:-1]), color=0xEA2027)
    embed.add_field(name="Day", value="\n".join(day_values), inline=True)
    embed.add_field(name="Time", value="\n".join(hour_values), inline=True)
    await channel.send(embed=embed)