User: sempurnakan kode ini selalu mengalami error' saat mengconvert mp4 ke webp import fs from "fs";
import path from "path";
import axios from "axios";
import { execSync } from "child_process";
import fetch from "node-fetch";

let cooldown = new Map();

let handler = async (a, { conn: r, args: e }) => {
    const t = a.sender;
    let o;

    if (e.length) {
        o = e.join(" ");
    } else {
        if (!a.quoted || !a.quoted.text) return r.reply(a.chat, "Input atau reply text!", a);
        o = a.quoted.text;
    }

    if (!o) return r.reply(a.chat, "Contoh penggunaan: !bratvideo hello world", a);
    if (o.length > 250) return r.reply(a.chat, "Max 250 karakter!", a);

    if (cooldown.has(t)) {
        const elapsed = (Date.now() - cooldown.get(t)) / 1000;
        if (elapsed < 10) return r.reply(a.chat, `[❗] Tunggu ${Math.ceil(10 - elapsed)} detik sebelum menggunakan perintah ini lagi.`);
    }

    cooldown.set(t, Date.now());
    r.sendReact(a.chat, "🕒", a.key);

    const n = o.split(" ");
    const tempDir = path.resolve("tmp");
    const files = (fs.existsSync(tempDir) || fs.mkdirSync(tempDir), []);

    try {
        // Mengambil data dari API
        for (let e = 0; e < n.length; e++) {
            const p = n.slice(0, e + 1).join(" ");
            const response = await axios.get("https://brat.caliphdev.com/api/brat?text=" + encodeURIComponent(p), { responseType: "arraybuffer" }).catch(err => err.response);
            if (response.status !== 200) throw new Error(`Gagal mengambil data dari API: ${response.statusText}`);
            
            const filePath = path.join(tempDir, `frame${e}.mp4`);
            fs.writeFileSync(filePath, response.data);
            files.push(filePath);
        }

        const fileListPath = path.join(tempDir, "filelist.txt");
        let fileListContent = "";
        for (let e = 0; e < files.length; e++) {
            fileListContent += `file '${files[e]}'\nduration 0.7\n`;
        }
        fileListContent += `file '${files[files.length - 1]}'\nduration 2\n`;
        fs.writeFileSync(fileListPath, fileListContent);

        const outputPath = path.join(tempDir, "output.mp4");
        execSync(`ffmpeg -y -f concat -safe 0 -i ${fileListPath} -vf "fps=30" -c:v libx264 -preset ultrafast -pix_fmt yuv420p ${outputPath}`);

        if (!fs.existsSync(outputPath)) throw new Error("Output video tidak ditemukan.");

        const videoBuffer = fs.readFileSync(outputPath);
        const m = await mp4ToWebp(videoBuffer, { pack: global.packname, author: global.author });

        r.sendFile(a.chat, m, "sticker.webp", o, a);
        
        // Menghapus file yang telah digunakan
        files.forEach(file => { if (fs.existsSync(file)) fs.unlinkSync(file); });
        if (fs.existsSync(fileListPath)) fs.unlinkSync(fileListPath);
        if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
    } catch (e) {
        r.reply(a.chat, `Maaf, terjadi kesalahan saat mengambil output.\n- ${e.message}`, a);
    }
};

async function mp4ToWebp(buffer, options) {
    options = options || { pack: "‎", author: "‎", crop: false };
    const data = {
        file: "data:video/mp4;base64," + buffer.toString("base64"),
        processOptions: {
            crop: options.crop,
            startTime: "00:00:00.0",
            endTime: "00:00:07.0",
            loop: 0
        },
        stickerMetadata: { ...options }
    };

    const response = await fetch("https://sticker-api.openwa.dev/convertMp4BufferToWebpDataUrl", {
        method: "POST",
        headers: {
            Accept: "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8"
        },
        body: JSON.stringify(data)
    });

    if (!response.ok) throw new Error("Gagal mengkonversi video ke webp.");

    const responseData = await response.text();
    return Buffer.from(responseData.split(";base64,")[1], "base64");
}

handler.help = handler.command = ["bratvideo"];
handler.tags = ["tools"];
export default handler;
User: sempurnakan kode ini selalu mengalami error' saat mengconvert mp4 ke webp import fs from "fs";
import path from "path";
import axios from "axios";
import { execSync } from "child_process";
import fetch from "node-fetch";

let cooldown = new Map();

let handler = async (a, { conn: r, args: e }) => {
    const t = a.sender;
    let o;

    if (e.length) {
        o = e.join(" ");
    } else {
        if (!a.quoted || !a.quoted.text) return r.reply(a.chat, "Input atau reply text!", a);
        o = a.quoted.text;
    }

    if (!o) return r.reply(a.chat, "Contoh penggunaan: !bratvideo hello world", a);
    if (o.length > 250) return r.reply(a.chat, "Max 250 karakter!", a);

    if (cooldown.has(t)) {
        const elapsed = (Date.now() - cooldown.get(t)) / 1000;
        if (elapsed < 10) return r.reply(a.chat, `[❗] Tunggu ${Math.ceil(10 - elapsed)} detik sebelum menggunakan perintah ini lagi.`);
    }

    cooldown.set(t, Date.now());
    r.sendReact(a.chat, "🕒", a.key);

    const n = o.split(" ");
    const tempDir = path.resolve("tmp");
    const files = (fs.existsSync(tempDir) || fs.mkdirSync(tempDir), []);

    try {
        // Mengambil data dari API
        for (let e = 0; e < n.length; e++) {
            const p = n.slice(0, e + 1).join(" ");
            const response = await axios.get("https://brat.caliphdev.com/api/brat?text=" + encodeURIComponent(p), { responseType: "arraybuffer" }).catch(err => err.response);
            if (response.status !== 200) throw new Error(`Gagal mengambil data dari API: ${response.statusText}`);
            
            const filePath = path.join(tempDir, `frame${e}.mp4`);
            fs.writeFileSync(filePath, response.data);
            files.push(filePath);
        }

        const fileListPath = path.join(tempDir, "filelist.txt");
        let fileListContent = "";
        for (let e = 0; e < files.length; e++) {
            fileListContent += `file '${files[e]}'\nduration 0.7\n`;
        }
        fileListContent += `file '${files[files.length - 1]}'\nduration 2\n`;
        fs.writeFileSync(fileListPath, fileListContent);

        const outputPath = path.join(tempDir, "output.mp4");
        execSync(`ffmpeg -y -f concat -safe 0 -i ${fileListPath} -vf "fps=30" -c:v libx264 -preset ultrafast -pix_fmt yuv420p ${outputPath}`);

        if (!fs.existsSync(outputPath)) throw new Error("Output video tidak ditemukan.");

        const videoBuffer = fs.readFileSync(outputPath);
        const m = await mp4ToWebp(videoBuffer, { pack: global.packname, author: global.author });

        r.sendFile(a.chat, m, "sticker.webp", o, a);
        
        // Menghapus file yang telah digunakan
        files.forEach(file => { if (fs.existsSync(file)) fs.unlinkSync(file); });
        if (fs.existsSync(fileListPath)) fs.unlinkSync(fileListPath);
        if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
    } catch (e) {
        r.reply(a.chat, `Maaf, terjadi kesalahan saat mengambil output.\n- ${e.message}`, a);
    }
};

async function mp4ToWebp(buffer, options) {
    options = options || { pack: "‎", author: "‎", crop: false };
    const data = {
        file: "data:video/mp4;base64," + buffer.toString("base64"),
        processOptions: {
            crop: options.crop,
            startTime: "00:00:00.0",
            endTime: "00:00:07.0",
            loop: 0
        },
        stickerMetadata: { ...options }
    };

    const response = await fetch("https://sticker-api.openwa.dev/convertMp4BufferToWebpDataUrl", {
        method: "POST",
        headers: {
            Accept: "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8"
        },
        body: JSON.stringify(data)
    });

    if (!response.ok) throw new Error("Gagal mengkonversi video ke webp.");

    const responseData = await response.text();
    return Buffer.from(responseData.split(";base64,")[1], "base64");
}

handler.help = handler.command = ["bratvideo"];
handler.tags = ["tools"];
export default handler;
Assistant: