import discord from discord.ext import commands import logging import os import subprocess import mimetypes logger = logging.getLogger(__name__) def filetype(filename): mime_type, _ = mimetypes.guess_type(filename) if mime_type: if mime_type.startswith('video/'): return "Video" elif mime_type.startswith('audio/'): return "Audio" elif mime_type.startswith('image/'): return "Image" return "Unknown" class Conversion(commands.Cog): def __init__(self, bot): self.bot = bot @commands.slash_command(name="konwersja", description="konwertuj plik na inny format") @discord.option( "plik", description="plik do konwersji", required=True, type=discord.Attachment ) @discord.option( "format", description="format konwersji", required=True, type=str ) async def convert(self, ctx, plik, output_format, args): await ctx.defer() # Save files to the temp directory inside the bot's root directory bot_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) temp_dir = os.path.join(bot_dir, "temp") if not os.path.exists(temp_dir): os.makedirs(temp_dir) file_path = os.path.join(temp_dir, plik.filename) filename_noext = os.path.splitext(plik.filename)[0] await plik.save(file_path) input_path = file_path output_path = os.path.join(temp_dir, f"{filename_noext}.{output_format}") file_type = filetype(file_path) logger.info(f"Conversion started for: {file_type}") if file_type == "Video" or file_type == "Audio": # Execute ffmpeg command to compress video ffmpeg_command = f"ffmpeg -i {input_path} {args} {output_path}" elif file_type == "Image": img_command = f"magick {input_path} {args} {output_path}" ffmpeg_command = img_command else: await ctx.respond("Plik jest nieobsługiwany", ephemeral=True) logger.info("Unsupported file type") return try: subprocess.run(ffmpeg_command, check=True, shell=True) # Upload the compressed file await ctx.respond(file=discord.File(output_path)) logger.info(f"Conversion completed for: {file_type}") # Delete compressed file os.remove(input_path) os.remove(output_path) except subprocess.CalledProcessError as e: await ctx.respond(f"Conversion failed: {str(e)}", ephemeral=True) if os.path.exists(input_path): os.remove(input_path) if os.path.exists(output_path): os.remove(output_path) def setup(bot): bot.add_cog(Conversion(bot))