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(",");
if (!owners.includes(this.author.id)) return "Only the bot owner can broadcast messages!";
const message = this.options.message ?? this.args.join(" ");
if (message && message.trim()) {
if (message?.trim()) {
this.ipc.broadcast("playbroadcast", message);
this.ipc.register("broadcastSuccess", () => {
this.ipc.unregister("broadcastSuccess");

View File

@ -13,7 +13,7 @@ class ChannelCommand extends Command {
if (this.args[0].toLowerCase() === "disable") {
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(">", "");
if (guildDB.disabled.includes(id)) return "I'm already disabled in this channel!";
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\`.`;
} else if (this.args[0].toLowerCase() === "enable") {
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(">", "");
if (!guildDB.disabled.includes(id)) return "I'm not disabled in that channel!";
channel = this.channel.guild.channels.get(id);

View File

@ -18,12 +18,12 @@ class CommandCommand extends Command {
if (this.args[0].toLowerCase() === "disable") {
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);
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 (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);
return `The command \`${command}\` has been re-enabled.`;

View File

@ -29,7 +29,7 @@ class InfoCommand extends Command {
},
{
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:",

View File

@ -29,12 +29,12 @@ class StatsCommand extends Command {
},
{
"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
},
{
"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
},
{
@ -72,7 +72,7 @@ class StatsCommand extends Command {
},
{
"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
}
]

View File

@ -6,7 +6,7 @@ class RedditCommand extends ImageCommand {
params(url) {
const newArgs = this.options.text ?? this.args.filter(item => !item.includes(url)).join(" ");
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) => {
if (!oldChannel) return;
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) {
connection.player.setPaused(true);
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);
}
if (cmdInfo && cmdInfo.slashAllowed) commandArray.push({
if (cmdInfo?.slashAllowed) commandArray.push({
name,
type: 1,
description: cmdInfo.description,

View File

@ -14,7 +14,7 @@ const optionalReplace = (token) => {
// clean(text) to clean message of any private info or mentions
export async function clean(text) {
if (text && text.constructor && text.constructor.name == "Promise")
if (text?.constructor?.name == "Promise")
text = await text;
if (typeof text !== "string")
text = util.inspect(text, { depth: 1 });
@ -26,7 +26,7 @@ export async function clean(text) {
const { parsed } = config();
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) {
text = text.replaceAll(server, optionalReplace(server));
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) {
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({
addr: address,
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!";
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!";
const player = 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!";
const playerMeta = players.get(options.channel.guild.id);
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();
if (!node) {
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]];
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,
channelId: voiceChannel.id,
shardId: voiceChannel.guild.shard.id,
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!`;
} 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;
}
}
@ -135,11 +144,11 @@ export async function nextSong(client, options, connection, track, info, music,
},
fields: [{
name: " Title:",
value: info.title && info.title.trim() !== "" ? info.title : "(blank)"
value: info.title?.trim() !== "" ? info.title : "(blank)"
},
{
name: "🎤 Artist:",
value: info.title && info.author.trim() !== "" ? info.author : "(blank)"
value: info.author?.trim() !== "" ? info.author : "(blank)"
},
{
name: "💬 Channel:",
@ -147,7 +156,7 @@ export async function nextSong(client, options, connection, track, info, music,
},
{
name: "🌐 Node:",
value: connection.node ? connection.node.name : "Unknown"
value: connection.node?.name ?? "Unknown"
},
{
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);
}
let newQueue;
if (player && player.shuffle) {
if (player?.shuffle) {
if (player.loop) {
queue.push(queue.shift());
} 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]);
newQueue = queue;
} else if (player && player.loop) {
} else if (player?.loop) {
queue.push(queue.shift());
newQueue = queue;
} else {
@ -246,14 +255,14 @@ export async function nextSong(client, options, connection, track, info, music,
}
try {
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 {
// no-op
}
} else {
try {
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 {
// no-op
}