video-optimizer-bot / src /bot /telegramFiles.js
Hugging Face Deployer
Deploy bot to Hugging Face Spaces
03b405b
Raw History Blame Contribute Delete
1.27 kB
const fs = require("node:fs");
const fsp = require("node:fs/promises");
const path = require("node:path");
const { paths } = require("../config/paths");
const { config } = require("../config/env");
async function downloadTelegramFile(ctx, fileId, jobId, originalName = "telegram-video.mp4", onProgress = () => {}) {
const file = await ctx.api.getFile(fileId);
const url = `https://api.telegram.org/file/bot${config.telegram.token}/${file.file_path}`;
const response = await fetch(url);
if (!response.ok) throw new Error(`Telegram file download failed: ${response.status}`);
await fsp.mkdir(paths.downloads, { recursive: true });
const ext = path.extname(originalName) || path.extname(file.file_path) || ".mp4";
const output = path.join(paths.downloads, `${jobId}${ext}`);
const total = Number(response.headers.get("content-length") || file.file_size || 0);
let done = 0;
const writer = fs.createWriteStream(output);
for await (const chunk of response.body) {
done += chunk.length;
writer.write(chunk);
if (total) onProgress(Math.round(done / total * 100));
}
await new Promise((resolve, reject) => {
writer.end(resolve);
writer.on("error", reject);
});
return output;
}
module.exports = { downloadTelegramFile };