Skip to content

Instantly share code, notes, and snippets.

@dcdunkan
Last active March 27, 2023 10:07
Show Gist options
  • Save dcdunkan/6b5468b874f54527953d472c7d3e43b8 to your computer and use it in GitHub Desktop.
Save dcdunkan/6b5468b874f54527953d472c7d3e43b8 to your computer and use it in GitHub Desktop.
Slideshare downloader
import { Bot, InputFile } from "https://deno.land/x/[email protected]/mod.ts";
import { DOMParser } from "https://deno.land/x/[email protected]/deno-dom-wasm.ts";
import { StatusMessage } from "https://gist.githubusercontent.com/dcdunkan/235859eac749d36f4df7c00b99fbbc8f/raw/status.ts";
const bot = new Bot(Deno.env.get("BOT_TOKEN")!);
bot.command("start", async (ctx) => await ctx.reply("yeah!"));
bot.on("message:text").on("::url", async (ctx) => {
const url = ctx.message.text;
const status = new StatusMessage(ctx);
await status.send("Getting slides...");
const response = await fetch(url);
if (!response.ok) return await status.set("Failed to fetch :(");
const html = await response.text();
const doc = new DOMParser().parseFromString(html, "text/html")!;
const imageElements = doc.getElementsByClassName("slide-image");
await status.set(`Downloading ${imageElements.length} slides...`);
const files: string[] = [];
const tempDir = await Deno.makeTempDir({
dir: Deno.cwd(),
prefix: "slideshare-dl",
});
for (let i = 0; i < imageElements.length; i++) {
const src = imageElements[i].attributes.srcset.split(", ").at(-1) ??
imageElements[i].attributes.src;
const imgResponse = await fetch(src);
if (!response.ok) continue;
const img = await imgResponse.arrayBuffer();
const filename = `${tempDir}/slide-${i}.jpg`;
files.push(filename);
await Deno.writeFile(filename, new Uint8Array(img));
}
if (!files.length) return await status.set("Failed to fetch images :(");
await status.set("Creating PDF...");
const pdfName = `${tempDir}/${url.split("/").at(-1)}.pdf`;
const convertProcess = Deno.run({
cmd: ["convert", ...files, pdfName],
});
const processStatus = await convertProcess.status();
if (processStatus.success) {
await status.set("Sending file...");
await ctx.replyWithDocument(new InputFile(pdfName), { caption: url });
await status.set("Here we go!");
} else {
await status.clear();
await status.send("Failed to send PDF!");
}
await Deno.remove(tempDir, { recursive: true }); // remove temporary folder
});
bot.catch(console.error);
bot.start({
onStart: () => console.log("Bot is online"),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment