Антонина

VideoEditBot

Kodari AI
KodariSep 25 at 1:42 pm 1
VideoEditBot
A Discord bot that automates video editing tasks. Users can submit video files through Discord, apply edits like trimming, cropping, adding text overlays, filters, and transitions, then receive the processed video back. The bot uses FFmpeg for processing, supports queue management for multiple requests, provides progress updates, and includes permission controls for server administrators. It handles format conversion, resolution scaling, and watermark insertion with a simple command interface.

Created VideoEditBot with /trim for trimming uploaded videos and /ping for a quick status check.

Install dependencies with pip install -r requirements.txt, copy .env.example to .env and add your Discord token, then run python main.py. FFmpeg must also be installed and available on PATH (or configured with FFMPEG_PATH).

Kodari can make mistakes. Review important code before using.
Files
.gitignore
main.py
requirements.txt
Code
3 179
main.py
import asyncio
import logging
import math
import os
import tempfile
from pathlib import Path

import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("video_edit_bot")

TOKEN = os.getenv("DISCORD_TOKEN")
FFMPEG_PATH = os.getenv("FFMPEG_PATH", "ffmpeg")
MAX_INPUT_BYTES = 25 * 1024 * 1024
SUPPORTED_VIDEO_EXTENSIONS = {
    ".avi",
    ".m4v",
    ".mkv",
    ".mov",
    ".mp4",
    ".mpeg",
    ".mpg",
    ".webm",
}


def parse_timestamp(value: str) -> float:
    parts = value.strip().split(":")
    if not 1 <= len(parts) <= 3:
        raise ValueError("Use seconds, MM:SS, or HH:MM:SS.")

    try:
        numbers = [float(part) for part in parts]
    except ValueError as exc:
        raise ValueError("Use seconds, MM:SS, or HH:MM:SS.") from exc

    if any(not math.isfinite(number) or number < 0 for number in numbers):
        raise ValueError("Timestamps must be finite, non-negative values.")
    if any(number >= 60 for number in numbers[1:]):
        raise ValueError("Minutes and seconds after a colon must be less than 60.")

    return sum(number * 60**index for index, number in enumerate(reversed(numbers)))


class VideoEditBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix=commands.when_mentioned, intents=discord.Intents.default())

    async def setup_hook(self) -> None:
        await self.tree.sync()
        logger.info("Slash commands synchronized")


bot = VideoEditBot()


@bot.tree.command(name="ping", description="Check whether VideoEditBot is online.")
async def ping(interaction: discord.Interaction) -> None:
    await interaction.response.send_message("Pong! VideoEditBot is online.", ephemeral=True)


@bot.tree.command(name="trim", description="Trim a video and return the edited clip.")
@app_commands.describe(
    video="Video file to trim (up to 25 MB)",
    start="Start time: seconds, MM:SS, or HH:MM:SS",
    end="End time: seconds, MM:SS, or HH:MM:SS",
)
async def trim(
    interaction: discord.Interaction,
    video: discord.Attachment,
    start: str,
    end: str,
) -> None:
    if video.size > MAX_INPUT_BYTES:
        await interaction.response.send_message("The video must be 25 MB or smaller.", ephemeral=True)
        return

    if Path(video.filename).suffix.lower() not in SUPPORTED_VIDEO_EXTENSIONS:
        await interaction.response.send_message(
            "Please attach a supported video file (MP4, MOV, MKV, WebM, AVI, M4V, or MPEG).",
            ephemeral=True,
        )
        return

    try:
        start_seconds = parse_timestamp(start)
        end_seconds = parse_timestamp(end)
    except ValueError as exc:
        await interaction.response.send_message(str(exc), ephemeral=True)
        return

    if end_seconds <= start_seconds:
        await interaction.response.send_message("The end time must be after the start time.", ephemeral=True)
        return

    await interaction.response.defer(thinking=True)

    try:
        with tempfile.TemporaryDirectory(prefix="video-edit-") as temporary_directory:
            input_path = Path(temporary_directory) / f"input{Path(video.filename).suffix.lower()}"
            output_path = Path(temporary_directory) / "trimmed.mp4"
            await video.save(input_path)

            process = await asyncio.create_subprocess_exec(
                FFMPEG_PATH,
                "-hide_banner",
                "-loglevel",
                "error",
                "-y",
                "-ss",
                str(start_seconds),
                "-i",
                str(input_path),
                "-t",
                str(end_seconds - start_seconds),
                "-c:v",
                "libx264",
                "-preset",
                "veryfast",
                "-crf",
                "23",
                "-c:a",
                "aac",
                "-movflags",
                "+faststart",
                str(output_path),
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )
            _, stderr = await process.communicate()

            if process.returncode != 0:
                logger.warning("ffmpeg failed: %s", stderr.decode(errors="replace")[-2000:])
                await interaction.followup.send(
                    "I couldn't trim that video. Check that the timestamps fit the clip and try again."
                )
                return

            try:
                await interaction.followup.send(
                    content=f"Trimmed clip: {start}–{end}",
                    file=discord.File(output_path, filename="trimmed.mp4"),
                )
            except discord.HTTPException:
                logger.exception("Could not upload the trimmed video")
                await interaction.followup.send(
                    "The clip was trimmed, but Discord couldn't upload it. The result may exceed the server's upload limit."
                )
    except FileNotFoundError:
        logger.exception("FFmpeg executable was not found")
        await interaction.followup.send("Video processing is unavailable because FFmpeg is not installed.")
    except (discord.HTTPException, OSError):
        logger.exception("Could not process the uploaded video")
        await interaction.followup.send("I couldn't download or process that video. Please try again.")


def main() -> None:
    if not TOKEN:
        raise RuntimeError("Set DISCORD_TOKEN in your .env file before starting the bot.")
    bot.run(TOKEN)


if __name__ == "__main__":
    main()