#how to send file with webhook api

7 messages · Page 1 of 1 (latest)

severe jasper
#
import { fetch } from "bun";
import { CronJobParams } from "cron";
import FormData from "form-data";
import { createReadStream, existsSync } from "node:fs";
import { basename } from "node:path";

export class Webhook {
    private webhookPath: string;
    private crontab: CronJobParams["cronTime"];

    public constructor(webhookPath: string, crontab: CronJobParams["cronTime"]) {
        this.webhookPath = webhookPath;
        this.crontab = crontab;
    }

    public async sendWebhook(filePath: string): Promise<boolean> {
        if (!existsSync(filePath)) {
            throw new Error(`File ${filePath} does not exist`);
        }

        console.log(`[${new Date().toString().split(" ", 5).join(" ")}] Sending webhook`);

        const content = this.crontab ? `Auto Backup crontab \`${this.crontab}\`` : `Manual Backup`;
        const fileName = basename(filePath);
        const fileBuffer = createReadStream(filePath);

        const form = new FormData();
        form.append("payload_json", JSON.stringify({ content: content }));
        form.append("file", fileBuffer, { filename: fileName });

        const response = await fetch(this.webhookPath, {
            method: "POST",
            headers: {
                "Content-Type": `multipart/form-data; boundary=${form.getBoundary()}`
            },
            body: form,
        })

        console.log(`[${new Date().toString().split(" ", 5).join(" ")}] Webhook response: ${response.status}`);

        if (response.status === 200) {
            return true;
        } else {
            console.error(await response.text());
            return false;
        }
    }
}

bun 1.2.8

errant flameBOT
#
  • Consider reading #how-to-get-help to improve your question!
  • Explain what exactly your issue is.
  • Post the full error stack trace, not just the top part!
  • Show your code!
  • Issue solved? Press the button!
  • Marked as resolved by OP
willow robin
#

createReadStream returns a ReadStream, not a Buffer

#

What you want is readFile

severe jasper
willow robin
#

Then you‘re still using it wrong. readFile is either promise based or callback based. There’s also the Sync variant.

raw lake
#

Show the updated code with what Qjuh suggested