Improved pagination, empty value checks, and bigints

This commit is contained in:
Essem 2022-01-14 23:26:38 -06:00
parent 72efad0928
commit e1cfbff5a8
No known key found for this signature in database
GPG key ID: 7D497397CC3A2A8C
17 changed files with 51 additions and 41 deletions

View file

@ -53,8 +53,8 @@ const jobs = new JobCache();
const queue = [];
// Array of IDs
const MAX_JOBS = process.env.JOBS && process.env.JOBS !== "" ? parseInt(process.env.JOBS) : cpus().length * 4; // Completely arbitrary, should usually be some multiple of your amount of cores
const PASS = process.env.PASS && process.env.PASS !== "" ? process.env.PASS : undefined;
const MAX_JOBS = process.env.JOBS ? parseInt(process.env.JOBS) : cpus().length * 4; // Completely arbitrary, should usually be some multiple of your amount of cores
const PASS = process.env.PASS ? process.env.PASS : undefined;
let jobAmount = 0;
const acceptJob = (id, sock) => {

2
app.js
View file

@ -27,7 +27,7 @@ import { promisify } from "util";
const exec = promisify(baseExec);
// dbl posting
import { Api } from "@top-gg/sdk";
const dbl = process.env.NODE_ENV === "production" && process.env.DBL !== "" ? new Api(process.env.DBL) : null;
const dbl = process.env.NODE_ENV === "production" && process.env.DBL ? new Api(process.env.DBL) : null;
if (isMaster) {
const esmBotVersion = JSON.parse(readFileSync(new URL("./package.json", import.meta.url))).version;

View file

@ -67,7 +67,7 @@ class ImageCommand extends Command {
magickParams.path = image.path;
magickParams.params.type = image.type;
magickParams.url = image.url; // technically not required but can be useful for text filtering
magickParams.params.delay = image.delay ? image.delay : 0;
magickParams.params.delay = image.delay ?? 0;
if (this.constructor.requiresGIF) magickParams.onlyGIF = true;
} catch (e) {
runningCommands.delete(this.message.author.id);

View file

@ -7,8 +7,8 @@ class RetroCommand extends ImageCommand {
if (!line2 && line1.length > 15) {
const [split1, split2, split3] = wrap(line1, { width: 15, indent: "" }).split("\n");
line1 = split1;
line2 = split2 ? split2 : "";
line3 = split3 ? split3 : "";
line2 = split2 ?? "";
line3 = split3 ?? "";
} else {
if (!line2) {
line2 = "";
@ -29,4 +29,4 @@ class RetroCommand extends ImageCommand {
static command = "retro";
}
export default RetroCommand;
export default RetroCommand;

View file

@ -7,7 +7,7 @@ class AvatarCommand extends Command {
} else if (await this.ipc.fetchUser(this.args[0])) {
const user = await this.ipc.fetchUser(this.args[0]);
return user.avatar ? this.client._formatImage(`/avatars/${user.id}/${user.avatar}`, null, 1024) : `https://cdn.discordapp.com/embed/avatars/${user.discriminator % 5}.png`; // hacky "solution"
} else if (this.args[0] && this.args[0].match(/^<?[@#]?[&!]?\d+>?$/) && this.args[0] >= 21154535154122752) {
} else if (this.args[0] && this.args[0].match(/^<?[@#]?[&!]?\d+>?$/) && this.args[0] >= 21154535154122752n) {
try {
const user = await this.client.getRESTUser(this.args[0]);
return user.avatar ? this.client._formatImage(`/avatars/${user.id}/${user.avatar}`, null, 1024) : `https://cdn.discordapp.com/embed/avatars/${user.discriminator % 5}.png`; // repeat of hacky "solution" from above

View file

@ -26,7 +26,7 @@ class ChannelCommand extends Command {
return `I have been disabled in this channel. To re-enable me, just run \`${guildDB.prefix}channel enable\`.`;
} else if (this.args[0].toLowerCase() === "enable") {
let channel;
if (this.args[1] && this.args[1].match(/^<?[@#]?[&!]?\d+>?$/) && this.args[1] >= 21154535154122752) {
if (this.args[1] && this.args[1].match(/^<?[@#]?[&!]?\d+>?$/) && this.args[1] >= 21154535154122752n) {
const id = this.args[1].replaceAll("@", "").replaceAll("#", "").replaceAll("!", "").replaceAll("&", "").replaceAll("<", "").replaceAll(">", "");
if (!guildDB.disabled.includes(id)) return "I'm not disabled in that channel!";
channel = this.message.channel.guild.channels.get(id);
@ -44,4 +44,4 @@ class ChannelCommand extends Command {
static arguments = ["[enable/disable]", "{id}"];
}
export default ChannelCommand;
export default ChannelCommand;

View file

@ -11,11 +11,11 @@ class CommandCommand extends Command {
if (this.args[0] !== "disable" && this.args[0] !== "enable") return "That's not a valid option!";
const guildDB = await db.getGuild(this.message.channel.guild.id);
const disabled = guildDB.disabled_commands ? guildDB.disabled_commands : guildDB.disabledCommands;
const disabled = guildDB.disabled_commands ?? guildDB.disabledCommands;
if (this.args[0].toLowerCase() === "disable") {
if (!collections.commands.has(this.args[1].toLowerCase()) && !collections.aliases.has(this.args[1].toLowerCase())) return "That isn't a command!";
const command = collections.aliases.has(this.args[1].toLowerCase()) ? collections.aliases.get(this.args[1].toLowerCase()) : this.args[1].toLowerCase();
const command = collections.aliases.get(this.args[1].toLowerCase()) ?? this.args[1].toLowerCase();
if (command === "command") return "You can't disable that command!";
if (disabled && disabled.includes(command)) return "That command is already disabled!";
@ -23,7 +23,7 @@ class CommandCommand extends Command {
return `The command has been disabled. To re-enable it, just run \`${guildDB.prefix}command enable ${command}\`.`;
} else if (this.args[0].toLowerCase() === "enable") {
if (!collections.commands.has(this.args[1].toLowerCase()) && !collections.aliases.has(this.args[1].toLowerCase())) return "That isn't a command!";
const command = collections.aliases.has(this.args[1].toLowerCase()) ? collections.aliases.get(this.args[1].toLowerCase()) : this.args[1].toLowerCase();
const command = collections.aliases.get(this.args[1].toLowerCase()) ?? this.args[1].toLowerCase();
if (disabled && !disabled.includes(command)) return "That command isn't disabled!";
await db.enableCommand(this.message.channel.guild.id, command);
@ -36,4 +36,4 @@ class CommandCommand extends Command {
static arguments = ["[enable/disable]", "[command]"];
}
export default CommandCommand;
export default CommandCommand;

View file

@ -9,10 +9,8 @@ const tips = ["You can change the bot's prefix using the prefix command.", "Imag
class HelpCommand extends Command {
async run() {
const { prefix } = this.message.channel.guild ? await database.getGuild(this.message.channel.guild.id) : "N/A";
const commands = collections.commands;
const aliases = collections.aliases;
if (this.args.length !== 0 && (commands.has(this.args[0].toLowerCase()) || aliases.has(this.args[0].toLowerCase()))) {
const command = aliases.has(this.args[0].toLowerCase()) ? collections.aliases.get(this.args[0].toLowerCase()) : this.args[0].toLowerCase();
if (this.args.length !== 0 && (collections.commands.has(this.args[0].toLowerCase()) || collections.aliases.has(this.args[0].toLowerCase()))) {
const command = collections.aliases.get(this.args[0].toLowerCase()) ?? this.args[0].toLowerCase();
const info = collections.info.get(command);
const counts = await database.getCounts();
const embed = {
@ -104,4 +102,4 @@ class HelpCommand extends Command {
static arguments = ["{command}"];
}
export default HelpCommand;
export default HelpCommand;

View file

@ -3,7 +3,7 @@ import Command from "../../classes/command.js";
class SnowflakeCommand extends Command {
async run() {
if (!this.args[0]) return "You need to provide a snowflake ID!";
if (!this.args[0].match(/^<?[@#]?[&!]?\d+>?$/) && this.args[0] < 21154535154122752) return "That's not a valid snowflake!";
if (!this.args[0].match(/^<?[@#]?[&!]?\d+>?$/) && this.args[0] < 21154535154122752n) return "That's not a valid snowflake!";
return `<t:${Math.floor(((this.args[0].replaceAll("@", "").replaceAll("#", "").replaceAll("!", "").replaceAll("&", "").replaceAll("<", "").replaceAll(">", "") / 4194304) + 1420070400000) / 1000)}:F>`;
}
@ -12,4 +12,4 @@ class SnowflakeCommand extends Command {
static arguments = ["[id]"];
}
export default SnowflakeCommand;
export default SnowflakeCommand;

View file

@ -6,7 +6,7 @@ class UserInfoCommand extends Command {
let user;
if (getUser) {
user = getUser;
} else if (this.args[0].match(/^<?[@#]?[&!]?\d+>?$/) && this.args[0] >= 21154535154122752) {
} else if (this.args[0].match(/^<?[@#]?[&!]?\d+>?$/) && this.args[0] >= 21154535154122752n) {
try {
user = await this.client.getRESTUser(this.args[0]);
} catch {
@ -17,7 +17,7 @@ class UserInfoCommand extends Command {
const member = this.client.users.find(element => {
return userRegex.test(element.username);
});
user = member ? member : this.message.author;
user = member ?? this.message.author;
} else {
user = this.message.author;
}
@ -36,7 +36,7 @@ class UserInfoCommand extends Command {
},
{
name: "📛 **Nickname:**",
value: member ? (member.nick ? member.nick : "None") : "N/A"
value: member ? (member.nick ?? "None") : "N/A"
},
{
name: "🤖 **Bot:**",

View file

@ -42,4 +42,4 @@ class NowPlayingCommand extends MusicCommand {
static aliases = ["playing", "np"];
}
export default NowPlayingCommand;
export default NowPlayingCommand;

View file

@ -13,7 +13,7 @@ class RemoveCommand extends MusicCommand {
const removed = this.queue.splice(pos, 1);
const track = await Rest.decode(this.connection.player.node, removed[0]);
queues.set(this.message.channel.guild.id, this.queue);
return `🔊 The song \`${track.title !== "" ? track.title : "(blank)"}\` has been removed from the queue.`;
return `🔊 The song \`${track.title ? track.title : "(blank)"}\` has been removed from the queue.`;
}
static description = "Removes a song from the queue";

View file

@ -8,7 +8,7 @@ class SkipCommand extends MusicCommand {
if (!this.message.channel.guild.members.get(this.client.user.id).voiceState.channelID) return "I'm not in a voice channel!";
const player = this.connection;
if (player.host !== this.message.author.id && !this.message.member.permissions.has("manageChannels")) {
const votes = skipVotes.has(this.message.channel.guild.id) ? skipVotes.get(this.message.channel.guild.id) : { count: 0, ids: [], max: Math.min(3, player.voiceChannel.voiceMembers.filter((i) => i.id !== this.client.user.id && !i.bot).length) };
const votes = skipVotes.get(this.message.channel.guild.id) ?? { count: 0, ids: [], max: Math.min(3, player.voiceChannel.voiceMembers.filter((i) => i.id !== this.client.user.id && !i.bot).length) };
if (votes.ids.includes(this.message.author.id)) return "You've already voted to skip!";
const newObject = {
count: votes.count + 1,

View file

@ -72,16 +72,16 @@ export default async (client, cluster, worker, ipc, message) => {
const disabledCmds = disabledCmdCache.get(message.channel.guild.id);
if (disabledCmds) {
if (disabledCmds.includes(aliased ? aliased : command)) return;
if (disabledCmds.includes(aliased ?? command)) return;
} else {
guildDB = await database.getGuild(message.channel.guild.id);
disabledCmdCache.set(message.channel.guild.id, guildDB.disabled_commands ? guildDB.disabled_commands : guildDB.disabledCommands);
if ((guildDB.disabled_commands ? guildDB.disabled_commands : guildDB.disabledCommands).includes(aliased ? aliased : command)) return;
disabledCmdCache.set(message.channel.guild.id, guildDB.disabled_commands ?? guildDB.disabledCommands);
if ((guildDB.disabled_commands ?? guildDB.disabledCommands).includes(aliased ?? command)) return;
}
}
// check if command exists and if it's enabled
const cmd = aliased ? commands.get(aliased) : commands.get(command);
const cmd = commands.get(aliased ?? command);
if (!cmd) return;
// actually run the command
@ -98,7 +98,7 @@ export default async (client, cluster, worker, ipc, message) => {
}
};
try {
await database.addCount(aliases.has(command) ? aliases.get(command) : command);
await database.addCount(aliases.get(command) ?? command);
const startTime = new Date();
// eslint-disable-next-line no-unused-vars
const commandClass = new cmd(client, cluster, worker, ipc, message, parsed._, message.content.substring(prefix.length).trim().replace(command, "").trim(), (({ _, ...o }) => o)(parsed)); // we also provide the message content as a parameter for cases where we need more accuracy
@ -128,7 +128,7 @@ export default async (client, cluster, worker, ipc, message) => {
if (process.env.TEMPDIR !== "") {
const filename = `${Math.random().toString(36).substring(2, 15)}.${result.name.split(".")[1]}`;
await promises.writeFile(`${process.env.TEMPDIR}/${filename}`, result.file);
const imageURL = `${process.env.TMP_DOMAIN == "" ? "https://tmp.projectlounge.pw" : process.env.TMP_DOMAIN}/${filename}`;
const imageURL = `${process.env.TMP_DOMAIN !== "" ? process.env.TMP_DOMAIN : "https://tmp.projectlounge.pw"}/${filename}`;
await client.createMessage(message.channel.id, Object.assign({
embeds: [{
color: 16711680,

View file

@ -135,7 +135,7 @@ class ImageConnection {
async getOutput(jobid) {
const req = await fetch(`${this.httpurl}?id=${jobid}`, {
headers: {
"Authentication": this.auth && this.auth !== "" ? this.auth : undefined
"Authentication": this.auth ? this.auth : undefined
}
});
const contentType = req.headers.get("Content-Type");

View file

@ -59,6 +59,7 @@ const getImage = async (image, image2, video, extraReturnTypes, gifv = false) =>
}
}
const json = await data.json();
if (json.error) throw Error(json.error);
payload.path = json.results[0].media[0].gif.url;
} else {
const delay = (await execPromise(`ffprobe -v 0 -of csv=p=0 -select_streams v:0 -show_entries stream=r_frame_rate ${image}`)).stdout.replace("\n", "");
@ -121,7 +122,7 @@ const checkImages = async (message, extraReturnTypes, video, sticker) => {
}
}
// if the return value exists then return it
return type ? type : false;
return type ?? false;
};
// this checks for the latest message containing an image and returns the url of the image

View file

@ -77,17 +77,22 @@ export default async (client, message, pages, timeout = 120000) => {
if (member === message.author.id) {
switch (interaction) {
case "back":
await fetch(`https://discord.com/api/v8/interactions/${id}/${token}/callback`, ackOptions);
await fetch(`https://discord.com/api/v9/interactions/${id}/${token}/callback`, ackOptions);
page = page > 0 ? --page : pages.length - 1;
currentPage = await currentPage.edit(Object.assign(pages[page], options));
break;
case "forward":
await fetch(`https://discord.com/api/v8/interactions/${id}/${token}/callback`, ackOptions);
await fetch(`https://discord.com/api/v9/interactions/${id}/${token}/callback`, ackOptions);
page = page + 1 < pages.length ? ++page : 0;
currentPage = await currentPage.edit(Object.assign(pages[page], options));
break;
case "jump":
await fetch(`https://discord.com/api/v8/interactions/${id}/${token}/callback`, ackOptions);
await fetch(`https://discord.com/api/v9/interactions/${id}/${token}/callback`, ackOptions);
const newComponents = JSON.parse(JSON.stringify(components));
for (const index of newComponents.components[0].components.keys()) {
newComponents.components[0].components[index].disabled = true;
}
currentPage = await currentPage.edit(newComponents);
client.createMessage(message.channel.id, Object.assign({ content: "What page do you want to jump to?" }, {
messageReference: {
channelID: currentPage.channel.id,
@ -107,14 +112,14 @@ export default async (client, message, pages, timeout = 120000) => {
if (await client.getMessage(askMessage.channel.id, askMessage.id).catch(() => undefined)) await askMessage.delete();
if (manageMessages) await response.delete();
page = Number(response.content) - 1;
currentPage = await currentPage.edit(Object.assign(pages[page], options));
currentPage = await currentPage.edit(Object.assign(pages[page], options, components));
});
}).catch(error => {
throw error;
});
break;
case "delete":
await fetch(`https://discord.com/api/v8/interactions/${id}/${token}/callback`, ackOptions);
await fetch(`https://discord.com/api/v9/interactions/${id}/${token}/callback`, ackOptions);
interactionCollector.emit("end");
if (await client.getMessage(currentPage.channel.id, currentPage.id).catch(() => undefined)) await currentPage.delete();
return;
@ -123,8 +128,14 @@ export default async (client, message, pages, timeout = 120000) => {
}
}
});
interactionCollector.once("end", () => {
interactionCollector.once("end", async () => {
interactionCollector.removeAllListeners("interaction");
if (await client.getMessage(currentPage.channel.id, currentPage.id).catch(() => undefined)) {
for (const index of components.components[0].components.keys()) {
components.components[0].components[index].disabled = true;
}
await currentPage.edit(components);
}
});
}
};