1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
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):
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} {output_path}"
elif file_type == "Image":
img_command = f"magick {input_path} {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))
|