1
Fork 0
mirror of https://github.com/wlinator/luminara.git synced 2024-10-03 00:23:13 +00:00
Lumi/lib/formatter.py

79 lines
2.3 KiB
Python
Raw Normal View History

2024-03-29 17:15:42 +00:00
import textwrap
2024-03-29 17:17:51 +00:00
import discord
2024-07-07 11:55:12 +00:00
from discord.ext import commands
2024-03-29 17:17:51 +00:00
2024-06-20 10:34:03 +00:00
from services.config_service import GuildConfig
2024-07-07 11:55:12 +00:00
def template(text: str, username: str, level: int | None = None) -> str:
2024-03-07 19:26:11 +00:00
"""
Replaces placeholders in the given text with actual values.
Args:
text (str): The template text containing placeholders.
2024-07-07 11:55:12 +00:00
username (str): The username to replace the "{user}" placeholder.
level (int | None, optional): The level to replace the "{level}" placeholder. Defaults to None.
2024-03-07 19:26:11 +00:00
Returns:
2024-07-07 11:55:12 +00:00
str: The formatted text with placeholders replaced by actual values.
2024-03-07 19:26:11 +00:00
"""
2024-07-07 11:55:12 +00:00
replacements: dict[str, str] = {
2024-03-07 19:26:11 +00:00
"{user}": username,
"{level}": str(level) if level else "",
2024-03-07 19:26:11 +00:00
}
for placeholder, value in replacements.items():
text = text.replace(placeholder, value)
return text
2024-07-07 11:55:12 +00:00
def shorten(text: str, width: int = 200) -> str:
"""
Shortens the input text to the specified width by adding a placeholder at the end if the text exceeds the width.
Args:
text (str): The text to be shortened.
width (int): The maximum width of the shortened text (default is 200).
Returns:
str: The shortened text.
Examples:
shortened_text = shorten("Lorem ipsum dolor sit amet", 10)
"""
2024-03-29 17:15:42 +00:00
return textwrap.shorten(text, width=width, placeholder="...")
2024-07-07 11:55:12 +00:00
def get_prefix(ctx: commands.Context) -> str:
"""
2024-07-07 11:55:12 +00:00
Attempts to retrieve the prefix for the given guild context.
Args:
ctx (discord.ext.commands.Context): The context of the command invocation.
Returns:
str: The prefix for the guild. Defaults to "." if the guild or prefix is not found.
"""
try:
2024-07-07 11:55:12 +00:00
return GuildConfig.get_prefix(ctx.guild.id if ctx.guild else 0)
except (AttributeError, TypeError):
return "."
2024-07-07 11:55:12 +00:00
def get_invoked_name(ctx: commands.Context) -> str | None:
"""
2024-07-07 11:55:12 +00:00
Attempts to get the alias of the command used. If the user used a SlashCommand, return the command name.
Args:
ctx (discord.ext.commands.Context): The context of the command invocation.
Returns:
str: The alias or name of the invoked command.
"""
try:
return ctx.invoked_with
except (discord.ApplicationCommandInvokeError, AttributeError):
return ctx.command.name if ctx.command else None