Added descriptions to the command parameters, granular error handling and new parameters

This commit is contained in:
2025-02-06 12:36:57 +01:00
parent c8e9ba1d9e
commit 3a9608d863
+38 -29
View File
@@ -19,7 +19,18 @@ class Post_Command(Base_Cog):
super().__init__(logging.getLogger("cmds.post")) super().__init__(logging.getLogger("cmds.post"))
@app_commands.command(name = "post", description = "Post an embed in the Current Channel with a link to the content") @app_commands.command(name = "post", description = "Post an embed in the Current Channel with a link to the content")
async def post(self, ctx:discord.Interaction, url:str, custom_note:str = None): @app_commands.describe(url = "URL to the post", custom_note = "Describe the post with your own note", use_title = "Display the title of the post", quality = "Specifies the quality of the converted image, closer to 100 is better")
@app_commands.choices(quality = [
app_commands.Choice(name = "Poor (60)", value = 60),
app_commands.Choice(name = "Fair (70)", value = 70),
app_commands.Choice(name = "Good (80)", value = 80),
app_commands.Choice(name = "Very Good (85)", value = 85),
app_commands.Choice(name = "Excellent (90)", value = 90),
app_commands.Choice(name = "Superior (95)", value = 95),
app_commands.Choice(name = "Perfect (100)", value = 100)
])
async def post(self, ctx:discord.Interaction, url:str, custom_note:str = None, use_title:bool = True, quality:app_commands.Choice[int] = 95):
try:
domain_info = urlparse(url) domain_info = urlparse(url)
portal = Portal.instance() portal = Portal.instance()
toplevel_domain = '.'.join(domain_info.netloc.split('.')[-2:]) toplevel_domain = '.'.join(domain_info.netloc.split('.')[-2:])
@@ -45,6 +56,11 @@ class Post_Command(Base_Cog):
progress_temp = progress_title + f"\n`0` of `{image_count}` have already been loaded" progress_temp = progress_title + f"\n`0` of `{image_count}` have already been loaded"
await ctx.response.send_message(progress_temp, ephemeral = True) await ctx.response.send_message(progress_temp, ephemeral = True)
if isinstance(quality, app_commands.Choice):
quality_value = quality.value
else:
quality_value = quality
# Download and convert each image # Download and convert each image
image_files:list[discord.File] = [] image_files:list[discord.File] = []
begin_conversion = datetime.now().timestamp() begin_conversion = datetime.now().timestamp()
@@ -52,12 +68,12 @@ class Post_Command(Base_Cog):
index = 0 index = 0
for image_url in image_urls: for image_url in image_urls:
async with session.get(image_url) as response: async with session.get(image_url) as response:
response.raise_for_status() # Fehlerbehandlung für HTTP-Status response.raise_for_status()
image_data = await response.read() # Bilddaten im RAM laden image_data = await response.read()
original_image = Image.open(BytesIO(image_data)) # Originalbild laden original_image = Image.open(BytesIO(image_data))
webp_buffer = BytesIO() # Puffer für WebP-Bild webp_buffer = BytesIO()
original_image.save(webp_buffer, format="WEBP", lossless=True) # WebP speichern original_image.save(webp_buffer, format = "WEBP", quality = quality_value)
webp_buffer.seek(0) webp_buffer.seek(0)
image_file = discord.File(webp_buffer, filename = f"image_{index}.webp") image_file = discord.File(webp_buffer, filename = f"image_{index}.webp")
image_files.append(image_file) image_files.append(image_file)
@@ -70,6 +86,9 @@ class Post_Command(Base_Cog):
author = subm.author.name if subm.author else "Author not found" author = subm.author.name if subm.author else "Author not found"
content = f":copyright: [{author}]({url})" content = f":copyright: [{author}]({url})"
if use_title:
content += f"\n# {subm.title}"
if custom_note: if custom_note:
content += f"\n> {custom_note}" content += f"\n> {custom_note}"
@@ -82,29 +101,6 @@ class Post_Command(Base_Cog):
self._logger.info(f"Successfully processed the command executed by {ctx.user.name} ({ctx.user.id}) after {get_elapsed_time_milliseconds(datetime.now().timestamp() - begin_process)} (ID of message: {message.id})") self._logger.info(f"Successfully processed the command executed by {ctx.user.name} ({ctx.user.id}) after {get_elapsed_time_milliseconds(datetime.now().timestamp() - begin_process)} (ID of message: {message.id})")
# embed = discord.Embed(url = "https://discord.com/humans.txt", color = int(portal.platforms_config["REDDIT"]["embed_color"], 16))
# embed.set_author(name = subm.title)
# embeds.append(embed)
# embed.add_field(
# name = "Author",
# value = f"[u/{subm.author}](https://www.reddit.com/user/{subm.author})",
# inline = True)
# embed.add_field(
# name = "Subreddit",
# value = f"[r/{subm.subreddit.display_name}]({url})",
# inline = True)
# if subm.selftext:
# embed.add_field(
# name = "Discription",
# value = subm.selftext,
# inline = False)
# for image_url in image_urls:
# embed = discord.Embed(url = "https://discord.com/humans.txt")
# embed.set_image(url = image_url)
# embeds.append(embed)
# No domain for seperation found # No domain for seperation found
case _: case _:
if toplevel_domain == "": if toplevel_domain == "":
@@ -116,6 +112,19 @@ class Post_Command(Base_Cog):
color = 0xED4337) color = 0xED4337)
await ctx.response.send_message(embed = embed, ephemeral = True) await ctx.response.send_message(embed = embed, ephemeral = True)
except Exception as error:
self._logger.error(f"Could not complete command by {ctx.user.name} ({ctx.user.id})")
self._logger.exception(error, stack_info = True)
await ctx.delete_original_response()
await ctx.followup.send(
embed = discord.Embed(
title = "Error while processing",
description = f"While we processed your request, the following exception occured: `{error}`",
color = 0xED4337
),
ephemeral = True
)
async def setup(bot:commands.Bot): async def setup(bot:commands.Bot):