This repository has been archived on 2025-01-28. You can view files and clone it, but cannot push or open issues or pull requests.
natsuko/cogs/file_ext.py

59 lines
2.3 KiB
Python
Raw Normal View History

2023-05-03 19:53:01 +03:00
import discord
from discord.ext import commands
from discord import app_commands
from os.path import splitext
from os.path import join as joinpath
from os import mkdir, rmdir, remove
from cairosvg import svg2png
2023-05-07 01:55:55 +03:00
dir = "tmp"
2023-05-03 19:53:01 +03:00
class FileExt(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
if message.attachments:
files = []
2023-05-07 01:55:55 +03:00
mkdir(joinpath(dir, str(message.id)))
2023-05-03 19:53:01 +03:00
if list(filter(lambda x: splitext(x.filename)[1] in ('.mkv', '.svg'), message.attachments)):
m = await message.reply("Конвертация...")
# MKV
for at in filter(lambda x: x.filename.endswith('.mkv'), message.attachments):
2023-05-07 01:55:55 +03:00
await at.save(fp=joinpath(dir, str(message.id), at.filename))
2023-05-03 19:53:01 +03:00
import ffmpeg
(
ffmpeg
2023-05-07 01:55:55 +03:00
.input(joinpath(dir, str(message.id), at.filename))
.output(joinpath(dir, str(message.id), splitext(at.filename)[0]+'.mp4'))
2023-05-03 19:53:01 +03:00
.run()
)
2023-05-07 01:55:55 +03:00
remove(joinpath(dir, str(message.id), at.filename))
with open(joinpath(dir, str(message.id), splitext(at.filename)[0]+'.mp4'), 'rb') as f:
2023-05-03 19:53:01 +03:00
files.append( discord.File(f, spoiler=at.is_spoiler(), filename=splitext(at.filename)[0]+'.mp4') )
2023-05-07 01:55:55 +03:00
remove(joinpath(dir, str(message.id), splitext(at.filename)[0]+'.mp4'))
2023-05-03 19:53:01 +03:00
# SVG
for at in filter(lambda x: x.filename.endswith('.svg'), message.attachments):
code = await at.read()
code = code.decode("utf-8")
2023-05-07 01:55:55 +03:00
svg2png(bytestring=code, write_to=joinpath(dir, str(message.id), splitext(at.filename)[0]+'.png'))
2023-05-03 19:53:01 +03:00
2023-05-07 01:55:55 +03:00
with open(joinpath(dir, str(message.id), splitext(at.filename)[0]+'.png'), 'rb') as f:
2023-05-03 19:53:01 +03:00
files.append( discord.File(f, spoiler=at.is_spoiler(), filename=splitext(at.filename)[0]+'.png') )
2023-05-07 01:55:55 +03:00
remove(joinpath(dir, str(message.id), splitext(at.filename)[0]+'.png'))
2023-05-03 19:53:01 +03:00
if files:
await message.reply(files=files)
await m.delete()
2023-05-07 01:55:55 +03:00
rmdir(joinpath(dir, str(message.id)))
2023-05-03 19:53:01 +03:00
async def setup(bot):
await bot.add_cog(FileExt(bot))