3
0
Fork 0
mirror of https://github.com/ZeppelinBot/Zeppelin.git synced 2025-05-17 23:25:02 +00:00

Post: add support for !posting files

This commit is contained in:
Dragory 2019-01-15 03:04:47 +02:00
parent 5a3af84a48
commit 3110d15509
4 changed files with 93 additions and 8 deletions

View file

@ -1,9 +1,15 @@
import at = require("lodash.at");
import at from "lodash.at";
import { Emoji, Guild, GuildAuditLogEntry, TextableChannel } from "eris";
import url from "url";
import tlds from "tlds";
import emojiRegex from "emoji-regex";
import fs from "fs";
const fsp = fs.promises;
import https from "https";
import tmp from "tmp";
/**
* Turns a "delay string" such as "1h30m" to milliseconds
* @param {String} str
@ -287,6 +293,41 @@ export async function createChunkedMessage(channel: TextableChannel, messageText
}
}
/**
* Downloads the file from the given URL to a temporary file, with retry support
*/
export function downloadFile(attachmentUrl: string, retries = 3): Promise<{ path: string; deleteFn: () => void }> {
return new Promise(resolve => {
tmp.file((err, path, fd, deleteFn) => {
if (err) throw err;
const writeStream = fs.createWriteStream(path);
https
.get(attachmentUrl, res => {
res.pipe(writeStream);
writeStream.on("finish", () => {
writeStream.end();
resolve({
path,
deleteFn
});
});
})
.on("error", httpsErr => {
fsp.unlink(path);
if (retries === 0) {
throw httpsErr;
} else {
console.warn("File download failed, retrying. Error given:", httpsErr.message);
resolve(downloadFile(attachmentUrl, retries - 1));
}
});
});
});
}
export function noop() {
// IT'S LITERALLY NOTHING
}