JaBa/base/JaBa.js

317 lines
11 KiB
JavaScript
Raw Normal View History

2021-12-16 23:42:58 +05:00
const { MessageEmbed, Util, Client, Collection } = require("discord.js"),
{ GiveawaysManager } = require("discord-giveaways"),
2021-12-26 00:04:26 +05:00
{ SoundCloudPlugin } = require("@distube/soundcloud"),
{ SpotifyPlugin } = require("@distube/spotify"),
2021-12-16 23:42:58 +05:00
{ Client: Joker } = require("blague.xyz");
2021-12-10 21:39:54 +05:00
const util = require("util"),
AmeClient = require("amethyste-api"),
path = require("path"),
2021-12-26 00:04:26 +05:00
DisTube = require("distube"),
2021-12-10 21:39:54 +05:00
moment = require("moment");
moment.relativeTimeThreshold("s", 60);
moment.relativeTimeThreshold("ss", 5);
moment.relativeTimeThreshold("m", 60);
moment.relativeTimeThreshold("h", 60);
moment.relativeTimeThreshold("d", 24);
moment.relativeTimeThreshold("M", 12);
2021-12-22 16:50:28 +05:00
// Creates JaBa class
class JaBa extends Client {
2021-12-26 19:29:37 +05:00
constructor(options) {
2021-12-10 21:39:54 +05:00
super(options);
this.config = require("../config"); // Load the config file
this.customEmojis = require("../emojis.json"); // load the bot's emojis
this.languages = require("../languages/language-meta.json"); // Load the bot's languages
this.commands = new Collection(); // Creates new commands collection
this.aliases = new Collection(); // Creates new command aliases collection
this.logger = require("../helpers/logger"); // Load the logger file
this.wait = util.promisify(setTimeout); // client.wait(1000) - Wait 1 second
this.functions = require("../helpers/functions"); // Load the functions file
this.guildsData = require("../base/Guild"); // Guild mongoose model
this.usersData = require("../base/User"); // User mongoose model
this.membersData = require("../base/Member"); // Member mongoose model
this.logs = require("../base/Log"); // Log mongoose model
this.dashboard = require("../dashboard/app"); // Dashboard app
this.queues = new Collection(); // This collection will be used for the music
this.states = {}; // Used for the dashboard
this.knownGuilds = [];
this.databaseCache = {};
this.databaseCache.users = new Collection();
this.databaseCache.guilds = new Collection();
this.databaseCache.members = new Collection();
this.databaseCache.usersReminds = new Collection(); // members with active reminds
this.databaseCache.mutedUsers = new Collection(); // members who are currently muted
2021-12-16 23:42:58 +05:00
if (this.config.apiKeys.amethyste) this.AmeAPI = new AmeClient(this.config.apiKeys.amethyste);
2021-12-26 19:29:37 +05:00
if (this.config.apiKeys.blagueXYZ) this.joker = new Joker(this.config.apiKeys.blagueXYZ, {
defaultLanguage: "en"
});
2021-12-10 21:39:54 +05:00
2021-12-26 00:04:26 +05:00
this.player = new DisTube.default(this, {
searchSongs: 10,
searchCooldown: 30,
leaveOnEmpty: true,
emptyCooldown: 0,
leaveOnFinish: true,
leaveOnStop: true,
2021-12-26 19:29:37 +05:00
plugins: [new SoundCloudPlugin(), new SpotifyPlugin()],
2021-12-10 21:39:54 +05:00
});
this.player
2021-12-26 00:04:26 +05:00
.on("playSong", (queue, song) => queue.textChannel.send(this.translate("music/play:NOW_PLAYING", { songName: song.name })))
.on("addSong", (queue, song) => queue.textChannel.send(this.translate("music/play:ADDED_QUEUE", { songName: song.name })))
.on("addList", (queue, playlist) => queue.textChannel.send(this.translate("music/play:ADDED_QUEUE_COUNT", { songCount: playlist.songs.length })))
.on("searchResult", (message, result) => {
let i = 0
2021-12-10 21:39:54 +05:00
const embed = new MessageEmbed()
2021-12-26 00:04:26 +05:00
.setDescription(Util.escapeSpoiler(result.map(song => `**${++i} -** ${song.name}`).join("\n")))
.setFooter(this.translate("music/play:RESULTS_FOOTER"))
2021-12-10 21:39:54 +05:00
.setColor(this.config.embed.color);
message.channel.send(embed);
})
2021-12-26 00:04:26 +05:00
.on("searchDone", () => {})
.on("searchCancel", message => message.error("misc:TIMES_UP"))
2021-12-26 19:29:37 +05:00
.on("searchInvalidAnswer", message => message.error("misc:INVALID_NUMBER_RANGE", { min: 1, max: 10 }))
2021-12-26 00:04:26 +05:00
.on("searchNoResult", message => message.error("music/play:NO_RESULT"))
.on("error", (textChannel, e) => {
console.error(e);
2021-12-26 19:29:37 +05:00
textChannel.send(this.translate("music/play:ERR_OCCURRED", {
error: e
}));
2021-12-10 21:39:54 +05:00
})
2021-12-26 00:04:26 +05:00
.on("finish", queue => queue.textChannel.send(this.translate("music/play:QUEUE_ENDED")))
.on("disconnect", queue => queue.textChannel.send(this.translate("music/play:STOP_DISCONNECTED")))
.on("empty", queue => queue.textChannel.send(this.translate("music/play:STOP_EMPTY")));
2021-12-10 21:39:54 +05:00
this.giveawaysManager = new GiveawaysManager(this, {
storage: "./giveaways.json",
updateCountdownEvery: 10000,
default: {
botsCanWin: false,
// exemptPermissions: [ "MANAGE_MESSAGES", "ADMINISTRATOR" ],
2021-12-16 23:42:58 +05:00
embedColor: this.config.embed.color,
2021-12-10 21:39:54 +05:00
reaction: "🎉"
}
});
};
get defaultLanguage() {
2021-12-26 00:04:26 +05:00
return this.languages.find(language => language.default).name;
2021-12-10 21:39:54 +05:00
};
translate(key, args, locale) {
if (!locale) locale = this.defaultLanguage;
const language = this.translations.get(locale);
if (!language) throw "Invalid language set in data.";
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return language(key, args);
};
printDate(date, format, locale) {
if (!locale) locale = this.defaultLanguage;
const languageData = this.languages.find((language) => language.name === locale || language.aliases.includes(locale));
if (!format) format = languageData.defaultMomentFormat;
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return moment(new Date(date))
.locale(languageData.moment)
.format(format);
};
convertTime(time, type, noPrefix, locale) {
if (!type) time = "to";
if (!locale) locale = this.defaultLanguage;
const languageData = this.languages.find((language) => language.name === locale || language.aliases.includes(locale));
2021-12-16 23:42:58 +05:00
const m = moment(time).locale(languageData.moment);
2021-12-10 21:39:54 +05:00
return (type === "to" ? m.toNow(noPrefix) : m.fromNow(noPrefix));
};
// This function is used to load a command and add it to the collection
loadCommand(commandPath, commandName) {
try {
2021-12-26 19:29:37 +05:00
const props = new(require(`.${commandPath}${path.sep}${commandName}`))(this);
2021-12-10 21:39:54 +05:00
this.logger.log(`Loading Command: ${props.help.name}. 👌`, "log");
props.conf.location = commandPath;
2021-12-16 23:42:58 +05:00
if (props.init) props.init(this);
2021-12-10 21:39:54 +05:00
this.commands.set(props.help.name, props);
props.help.aliases.forEach((alias) => {
this.aliases.set(alias, props.help.name);
});
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return false;
} catch (e) {
return `Unable to load command ${commandName}: ${e}`;
};
};
// This function is used to unload a command (you need to load them again)
2021-12-26 19:29:37 +05:00
async unloadCommand(commandPath, commandName) {
2021-12-10 21:39:54 +05:00
let command;
2021-12-16 23:42:58 +05:00
if (this.commands.has(commandName)) command = this.commands.get(commandName);
else if (this.aliases.has(commandName)) command = this.commands.get(this.aliases.get(commandName));
if (!command) return `The command \`${commandName}\` doesn't seem to exist, nor is it an alias. Try again!`;
if (command.shutdown) await command.shutdown(this);
2021-12-10 21:39:54 +05:00
delete require.cache[require.resolve(`.${commandPath}${path.sep}${commandName}.js`)];
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return false;
};
// This function is used to find a user data or create it
async findOrCreateUser({ id: userID }, isLean) {
2021-12-16 23:42:58 +05:00
if (this.databaseCache.users.get(userID)) return isLean ? this.databaseCache.users.get(userID).toJSON() : this.databaseCache.users.get(userID);
else {
2021-12-26 19:29:37 +05:00
let userData = (isLean ? await this.usersData.findOne({
id: userID
}).lean() : await this.usersData.findOne({
id: userID
}));
2021-12-10 21:39:54 +05:00
if (userData) {
if (!isLean) this.databaseCache.users.set(userID, userData);
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return userData;
} else {
2021-12-26 19:29:37 +05:00
userData = new this.usersData({
id: userID
});
2021-12-10 21:39:54 +05:00
await userData.save();
this.databaseCache.users.set(userID, userData);
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return isLean ? userData.toJSON() : userData;
};
};
};
// This function is used to find a member data or create it
async findOrCreateMember({ id: memberID, guildID }, isLean) {
2021-12-16 23:42:58 +05:00
if (this.databaseCache.members.get(`${memberID}${guildID}`)) return isLean ? this.databaseCache.members.get(`${memberID}${guildID}`).toJSON() : this.databaseCache.members.get(`${memberID}${guildID}`);
else {
2021-12-26 19:29:37 +05:00
let memberData = (isLean ? await this.membersData.findOne({
guildID,
id: memberID
}).lean() : await this.membersData.findOne({
guildID,
id: memberID
}));
2021-12-10 21:39:54 +05:00
if (memberData) {
if (!isLean) this.databaseCache.members.set(`${memberID}${guildID}`, memberData);
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return memberData;
} else {
2021-12-26 19:29:37 +05:00
memberData = new this.membersData({
id: memberID,
guildID: guildID
});
2021-12-10 21:39:54 +05:00
await memberData.save();
2021-12-26 19:29:37 +05:00
const guild = await this.findOrCreateGuild({
id: guildID
});
2021-12-10 21:39:54 +05:00
if (guild) {
guild.members.push(memberData._id);
await guild.save();
};
this.databaseCache.members.set(`${memberID}${guildID}`, memberData);
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return isLean ? memberData.toJSON() : memberData;
};
};
};
// This function is used to find a guild data or create it
async findOrCreateGuild({ id: guildID }, isLean) {
2021-12-16 23:42:58 +05:00
if (this.databaseCache.guilds.get(guildID)) return isLean ? this.databaseCache.guilds.get(guildID).toJSON() : this.databaseCache.guilds.get(guildID);
else {
2021-12-26 19:29:37 +05:00
let guildData = (isLean ? await this.guildsData.findOne({
id: guildID
}).populate("members").lean() : await this.guildsData.findOne({
id: guildID
}).populate("members"));
2021-12-10 21:39:54 +05:00
if (guildData) {
if (!isLean) this.databaseCache.guilds.set(guildID, guildData);
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return guildData;
} else {
2021-12-26 19:29:37 +05:00
guildData = new this.guildsData({
id: guildID
});
2021-12-10 21:39:54 +05:00
await guildData.save();
this.databaseCache.guilds.set(guildID, guildData);
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return isLean ? guildData.toJSON() : guildData;
};
};
};
// This function is used to resolve a user from a string
async resolveUser(search) {
let user = null;
if (!search || typeof search !== "string") return;
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
// Try ID search
if (search.match(/^<@!?(\d+)>$/)) {
const id = search.match(/^<@!?(\d+)>$/)[1];
user = this.users.fetch(id).catch(() => {});
if (user) return user;
};
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
// Try username search
if (search.match(/^!?(\w+)#(\d+)$/)) {
const username = search.match(/^!?(\w+)#(\d+)$/)[0];
const discriminator = search.match(/^!?(\w+)#(\d+)$/)[1];
user = this.users.find((u) => u.username === username && u.discriminator === discriminator);
if (user) return user;
};
user = await this.users.fetch(search).catch(() => {});
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return user;
};
async resolveMember(search, guild) {
let member = null;
if (!search || typeof search !== "string") return;
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
// Try ID search
if (search.match(/^<@!?(\d+)>$/)) {
const id = search.match(/^<@!?(\d+)>$/)[1];
member = await guild.members.fetch(id).catch(() => {});
if (member) return member;
};
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
// Try username search
if (search.match(/^!?(\w+)#(\d+)$/)) {
guild = await guild.fetch();
member = guild.members.cache.find((m) => m.user.tag === search);
if (member) return member;
};
member = await guild.members.fetch(search).catch(() => {});
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return member;
};
async resolveRole(search, guild) {
let role = null;
if (!search || typeof search !== "string") return;
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
// Try ID search
if (search.match(/^<@&!?(\d+)>$/)) {
const id = search.match(/^<@&!?(\d+)>$/)[1];
role = guild.roles.cache.get(id);
if (role) return role;
};
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
// Try name search
role = guild.roles.cache.find((r) => search === r.name);
if (role) return role;
role = guild.roles.cache.get(search);
2021-12-16 23:42:58 +05:00
2021-12-10 21:39:54 +05:00
return role;
};
};
2021-12-22 16:50:28 +05:00
module.exports = JaBa;