Improve voice connection checking, take advantage of optional chaining operators

This commit is contained in:
Essem 2022-07-23 16:02:04 -05:00
parent df43f9eb9d
commit 398ce07bd2
No known key found for this signature in database
GPG Key ID: 7D497397CC3A2A8C
11 changed files with 36 additions and 27 deletions

View File

@ -7,7 +7,7 @@ class BroadcastCommand extends Command {
const owners = process.env.OWNER.split(","); const owners = process.env.OWNER.split(",");
if (!owners.includes(this.author.id)) return "Only the bot owner can broadcast messages!"; if (!owners.includes(this.author.id)) return "Only the bot owner can broadcast messages!";
const message = this.options.message ?? this.args.join(" "); const message = this.options.message ?? this.args.join(" ");
if (message && message.trim()) { if (message?.trim()) {
this.ipc.broadcast("playbroadcast", message); this.ipc.broadcast("playbroadcast", message);
this.ipc.register("broadcastSuccess", () => { this.ipc.register("broadcastSuccess", () => {
this.ipc.unregister("broadcastSuccess"); this.ipc.unregister("broadcastSuccess");

View File

@ -13,7 +13,7 @@ class ChannelCommand extends Command {
if (this.args[0].toLowerCase() === "disable") { if (this.args[0].toLowerCase() === "disable") {
let channel; let channel;
if (this.args[1] && this.args[1].match(/^<?[@#]?[&!]?\d+>?$/) && this.args[1] >= 21154535154122752n) { if (this.args[1]?.match(/^<?[@#]?[&!]?\d+>?$/) && this.args[1] >= 21154535154122752n) {
const id = this.args[1].replaceAll("@", "").replaceAll("#", "").replaceAll("!", "").replaceAll("&", "").replaceAll("<", "").replaceAll(">", ""); const id = this.args[1].replaceAll("@", "").replaceAll("#", "").replaceAll("!", "").replaceAll("&", "").replaceAll("<", "").replaceAll(">", "");
if (guildDB.disabled.includes(id)) return "I'm already disabled in this channel!"; if (guildDB.disabled.includes(id)) return "I'm already disabled in this channel!";
channel = this.channel.guild.channels.get(id); channel = this.channel.guild.channels.get(id);
@ -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\`.`; 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") { } else if (this.args[0].toLowerCase() === "enable") {
let channel; let channel;
if (this.args[1] && this.args[1].match(/^<?[@#]?[&!]?\d+>?$/) && this.args[1] >= 21154535154122752n) { if (this.args[1]?.match(/^<?[@#]?[&!]?\d+>?$/) && this.args[1] >= 21154535154122752n) {
const id = this.args[1].replaceAll("@", "").replaceAll("#", "").replaceAll("!", "").replaceAll("&", "").replaceAll("<", "").replaceAll(">", ""); const id = this.args[1].replaceAll("@", "").replaceAll("#", "").replaceAll("!", "").replaceAll("&", "").replaceAll("<", "").replaceAll(">", "");
if (!guildDB.disabled.includes(id)) return "I'm not disabled in that channel!"; if (!guildDB.disabled.includes(id)) return "I'm not disabled in that channel!";
channel = this.channel.guild.channels.get(id); channel = this.channel.guild.channels.get(id);

View File

@ -18,12 +18,12 @@ class CommandCommand extends Command {
if (this.args[0].toLowerCase() === "disable") { if (this.args[0].toLowerCase() === "disable") {
if (command === "command") return "You can't disable that command!"; if (command === "command") return "You can't disable that command!";
if (disabled && disabled.includes(command)) return "That command is already disabled!"; if (disabled?.includes(command)) return "That command is already disabled!";
await db.disableCommand(this.channel.guild.id, command); await db.disableCommand(this.channel.guild.id, command);
return `The command has been disabled. To re-enable it, just run \`${guildDB.prefix}command enable ${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") { } else if (this.args[0].toLowerCase() === "enable") {
if (disabled && !disabled.includes(command)) return "That command isn't disabled!"; if (!disabled?.includes(command)) return "That command isn't disabled!";
await db.enableCommand(this.channel.guild.id, command); await db.enableCommand(this.channel.guild.id, command);
return `The command \`${command}\` has been re-enabled.`; return `The command \`${command}\` has been re-enabled.`;

View File

@ -29,7 +29,7 @@ class InfoCommand extends Command {
}, },
{ {
name: "💬 Total Servers:", name: "💬 Total Servers:",
value: stats && stats.guilds ? stats.guilds : `${this.client.guilds.size} (for this cluster only)` value: stats?.guilds ? stats.guilds : `${this.client.guilds.size} (for this cluster only)`
}, },
{ {
name: "✅ Official Server:", name: "✅ Official Server:",

View File

@ -29,12 +29,12 @@ class StatsCommand extends Command {
}, },
{ {
"name": "Cluster Memory Usage", "name": "Cluster Memory Usage",
"value": stats && stats.clusters[this.cluster] ? `${stats.clusters[this.cluster].ram.toFixed(2)} MB` : `${(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)} MB`, "value": stats?.clusters[this.cluster] ? `${stats.clusters[this.cluster].ram.toFixed(2)} MB` : `${(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)} MB`,
"inline": true "inline": true
}, },
{ {
"name": "Total Memory Usage", "name": "Total Memory Usage",
"value": stats && stats.totalRam ? `${stats.totalRam.toFixed(2)} MB` : "Unknown", "value": stats?.totalRam ? `${stats.totalRam.toFixed(2)} MB` : "Unknown",
"inline": true "inline": true
}, },
{ {
@ -72,7 +72,7 @@ class StatsCommand extends Command {
}, },
{ {
"name": "Servers", "name": "Servers",
"value": stats && stats.guilds ? stats.guilds : `${this.client.guilds.size} (for this cluster only)`, "value": stats?.guilds ? stats.guilds : `${this.client.guilds.size} (for this cluster only)`,
"inline": true "inline": true
} }
] ]

View File

@ -6,7 +6,7 @@ class RedditCommand extends ImageCommand {
params(url) { params(url) {
const newArgs = this.options.text ?? this.args.filter(item => !item.includes(url)).join(" "); const newArgs = this.options.text ?? this.args.filter(item => !item.includes(url)).join(" ");
return { return {
caption: newArgs && newArgs.trim() ? newArgs.replaceAll("\n", "").replaceAll(" ", "") : random(names) caption: newArgs?.trim() ? newArgs.replaceAll("\n", "").replaceAll(" ", "") : random(names)
}; };
} }

View File

@ -5,7 +5,7 @@ import { random } from "../utils/misc.js";
export default async (client, cluster, worker, ipc, member, oldChannel) => { export default async (client, cluster, worker, ipc, member, oldChannel) => {
if (!oldChannel) return; if (!oldChannel) return;
const connection = players.get(oldChannel.guild.id); const connection = players.get(oldChannel.guild.id);
if (connection && oldChannel.id === connection.voiceChannel.id) { if (oldChannel.id === connection?.voiceChannel.id) {
if (oldChannel.voiceMembers.filter((i) => i.id !== client.user.id && !i.bot).length === 0) { if (oldChannel.voiceMembers.filter((i) => i.id !== client.user.id && !i.bot).length === 0) {
connection.player.setPaused(true); connection.player.setPaused(true);
const waitMessage = await client.createMessage(connection.originalChannel.id, "🔊 Waiting 10 seconds for someone to return..."); const waitMessage = await client.createMessage(connection.originalChannel.id, "🔊 Waiting 10 seconds for someone to return...");

View File

@ -75,7 +75,7 @@ export async function update() {
}; };
info.set(name, cmdInfo); info.set(name, cmdInfo);
} }
if (cmdInfo && cmdInfo.slashAllowed) commandArray.push({ if (cmdInfo?.slashAllowed) commandArray.push({
name, name,
type: 1, type: 1,
description: cmdInfo.description, description: cmdInfo.description,

View File

@ -14,7 +14,7 @@ const optionalReplace = (token) => {
// clean(text) to clean message of any private info or mentions // clean(text) to clean message of any private info or mentions
export async function clean(text) { export async function clean(text) {
if (text && text.constructor && text.constructor.name == "Promise") if (text?.constructor?.name == "Promise")
text = await text; text = await text;
if (typeof text !== "string") if (typeof text !== "string")
text = util.inspect(text, { depth: 1 }); text = util.inspect(text, { depth: 1 });
@ -26,7 +26,7 @@ export async function clean(text) {
const { parsed } = config(); const { parsed } = config();
const imageServers = JSON.parse(fs.readFileSync(new URL("../servers.json", import.meta.url), { encoding: "utf8" })).image; const imageServers = JSON.parse(fs.readFileSync(new URL("../servers.json", import.meta.url), { encoding: "utf8" })).image;
if (imageServers && imageServers.length !== 0) { if (imageServers?.length !== 0) {
for (const { server, auth } of imageServers) { for (const { server, auth } of imageServers) {
text = text.replaceAll(server, optionalReplace(server)); text = text.replaceAll(server, optionalReplace(server));
text = text.replaceAll(auth, optionalReplace(auth)); text = text.replaceAll(auth, optionalReplace(auth));

View File

@ -153,7 +153,7 @@ class ImageWorker extends BaseServiceWorker {
if (connection.conn.readyState !== 0 && connection.conn.readyState !== 1) { if (connection.conn.readyState !== 0 && connection.conn.readyState !== 1) {
continue; continue;
} }
if (object.params.type && connection.formats[object.cmd] && !connection.formats[object.cmd].includes(object.params.type)) continue; if (object.params.type && !connection.formats[object.cmd]?.includes(object.params.type)) continue;
idealServers.push({ idealServers.push({
addr: address, addr: address,
load: connection.njobs / connection.max load: connection.njobs / connection.max

View File

@ -65,8 +65,8 @@ export async function play(client, sound, options, music = false) {
if (!options.channel.guild.permissionsOf(client.user.id).has("voiceConnect")) return "I can't join this voice channel!"; if (!options.channel.guild.permissionsOf(client.user.id).has("voiceConnect")) return "I can't join this voice channel!";
const voiceChannel = options.channel.guild.channels.get(options.member.voiceState.channelID); const voiceChannel = options.channel.guild.channels.get(options.member.voiceState.channelID);
if (!voiceChannel.permissionsOf(client.user.id).has("voiceConnect")) return "I don't have permission to join this voice channel!"; if (!voiceChannel.permissionsOf(client.user.id).has("voiceConnect")) return "I don't have permission to join this voice channel!";
const player = players.get(options.channel.guild.id); const playerMeta = players.get(options.channel.guild.id);
if (!music && manager.players.has(options.channel.guild.id) && (player && player.type === "music")) return "I can't play a sound effect while playing music!"; if (!music && manager.players.has(options.channel.guild.id) && (playerMeta?.type === "music")) return "I can't play a sound effect while playing music!";
let node = manager.getNode(); let node = manager.getNode();
if (!node) { if (!node) {
const status = await checkStatus(); const status = await checkStatus();
@ -94,17 +94,26 @@ export async function play(client, sound, options, music = false) {
const playlistTracks = response.playlistInfo.selectedTrack ? sortedTracks : [sortedTracks[0]]; const playlistTracks = response.playlistInfo.selectedTrack ? sortedTracks : [sortedTracks[0]];
queues.set(voiceChannel.guild.id, oldQueue ? [...oldQueue, ...playlistTracks] : playlistTracks); queues.set(voiceChannel.guild.id, oldQueue ? [...oldQueue, ...playlistTracks] : playlistTracks);
} }
const connection = player && player.player && player.player.connection.state !== 3 && player.player.connection.state !== 1 ? player.player : await node.joinChannel({ let player;
if (node.players.has(voiceChannel.guild.id)) {
player = node.players.get(voiceChannel.guild.id);
} else if (playerMeta?.player) {
const storedState = playerMeta?.player?.connection.state;
if (storedState && storedState === 1) {
player = playerMeta?.player;
}
}
const connection = player ?? await node.joinChannel({
guildId: voiceChannel.guild.id, guildId: voiceChannel.guild.id,
channelId: voiceChannel.id, channelId: voiceChannel.id,
shardId: voiceChannel.guild.shard.id, shardId: voiceChannel.guild.shard.id,
deaf: true deaf: true
}); });
if (oldQueue && oldQueue.length !== 0 && music) { if (oldQueue?.length && music) {
return `Your ${response.playlistInfo.name ? "playlist" : "tune"} \`${response.playlistInfo.name ? response.playlistInfo.name.trim() : (response.tracks[0].info.title !== "" ? response.tracks[0].info.title.trim() : "(blank)")}\` has been added to the queue!`; return `Your ${response.playlistInfo.name ? "playlist" : "tune"} \`${response.playlistInfo.name ? response.playlistInfo.name.trim() : (response.tracks[0].info.title !== "" ? response.tracks[0].info.title.trim() : "(blank)")}\` has been added to the queue!`;
} else { } else {
nextSong(client, options, connection, response.tracks[0].track, response.tracks[0].info, music, voiceChannel, player ? player.host : options.member.id, player ? player.loop : false, player ? player.shuffle : false); nextSong(client, options, connection, response.tracks[0].track, response.tracks[0].info, music, voiceChannel, playerMeta?.host ?? options.member.id, playerMeta?.loop ?? false, playerMeta?.shuffle ?? false);
return; return;
} }
} }
@ -135,11 +144,11 @@ export async function nextSong(client, options, connection, track, info, music,
}, },
fields: [{ fields: [{
name: " Title:", name: " Title:",
value: info.title && info.title.trim() !== "" ? info.title : "(blank)" value: info.title?.trim() !== "" ? info.title : "(blank)"
}, },
{ {
name: "🎤 Artist:", name: "🎤 Artist:",
value: info.title && info.author.trim() !== "" ? info.author : "(blank)" value: info.author?.trim() !== "" ? info.author : "(blank)"
}, },
{ {
name: "💬 Channel:", name: "💬 Channel:",
@ -147,7 +156,7 @@ export async function nextSong(client, options, connection, track, info, music,
}, },
{ {
name: "🌐 Node:", name: "🌐 Node:",
value: connection.node ? connection.node.name : "Unknown" value: connection.node?.name ?? "Unknown"
}, },
{ {
name: `${"▬".repeat(parts)}🔘${"▬".repeat(10 - parts)}`, name: `${"▬".repeat(parts)}🔘${"▬".repeat(10 - parts)}`,
@ -209,7 +218,7 @@ export async function nextSong(client, options, connection, track, info, music,
players.set(voiceChannel.guild.id, player); players.set(voiceChannel.guild.id, player);
} }
let newQueue; let newQueue;
if (player && player.shuffle) { if (player?.shuffle) {
if (player.loop) { if (player.loop) {
queue.push(queue.shift()); queue.push(queue.shift());
} else { } else {
@ -217,7 +226,7 @@ export async function nextSong(client, options, connection, track, info, music,
} }
queue.unshift(queue.splice(Math.floor(Math.random() * queue.length), 1)[0]); queue.unshift(queue.splice(Math.floor(Math.random() * queue.length), 1)[0]);
newQueue = queue; newQueue = queue;
} else if (player && player.loop) { } else if (player?.loop) {
queue.push(queue.shift()); queue.push(queue.shift());
newQueue = queue; newQueue = queue;
} else { } else {
@ -246,14 +255,14 @@ export async function nextSong(client, options, connection, track, info, music,
} }
try { try {
if (playingMessage.channel.messages.has(playingMessage.id)) await playingMessage.delete(); if (playingMessage.channel.messages.has(playingMessage.id)) await playingMessage.delete();
if (player && player.playMessage.channel.messages.has(player.playMessage.id)) await player.playMessage.delete(); if (player?.playMessage.channel.messages.has(player.playMessage.id)) await player.playMessage.delete();
} catch { } catch {
// no-op // no-op
} }
} else { } else {
try { try {
if (playingMessage.channel.messages.has(playingMessage.id)) await playingMessage.delete(); if (playingMessage.channel.messages.has(playingMessage.id)) await playingMessage.delete();
if (player && player.playMessage.channel.messages.has(player.playMessage.id)) await player.playMessage.delete(); if (player?.playMessage.channel.messages.has(player.playMessage.id)) await player.playMessage.delete();
} catch { } catch {
// no-op // no-op
} }