galactic-bot/util/Util.js

66 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-04-08 18:08:46 +02:00
const path = require('path');
const fs = require('fs');
2020-04-09 16:30:52 +02:00
const fetch = require('node-fetch');
const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
2020-04-08 18:08:46 +02:00
class Util {
constructor() {
throw new Error("Class may not be instantiated.");
}
static readdirRecursive(directory) {
const result = [];
(function read(directory) {
const files = fs.readdirSync(directory);
for(const file of files) {
const filePath = path.join(directory, file);
if(fs.statSync(filePath).isDirectory()) {
read(filePath);
} else {
result.push(filePath);
}
}
}(directory));
return result;
}
2020-04-09 16:30:52 +02:00
static delayFor(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
static mergeDefault(def, given) {
if (!given) return def;
for (const key in def) {
if (!has(given, key) || given[key] === undefined) {
given[key] = def[key];
} else if (given[key] === Object(given[key])) {
given[key] = Util.mergeDefault(def[key], given[key]);
}
}
return given;
}
static fetchRecommendedShards(token, guildsPerShard = 1000) {
if(!token) throw new Error("[util] Token missing.");
return fetch("https://discordapp.com/api/v7/gateway/bot", {
method: 'GET',
headers: { Authorization: `Bot ${token.replace(/^Bot\s*/i, '')}` },
}).then(res => {
if (res.ok) return res.json();
throw res;
}).then(data => data.shards * (1000 / guildsPerShard));
}
2020-04-08 18:08:46 +02:00
}
module.exports = Util;