Skip to content

Commit

Permalink
Remove "requires" command field, overhaul Lavalink connection, fix me…
Browse files Browse the repository at this point in the history
…ssage objects not being properly sent
  • Loading branch information
TheEssem committed Oct 11, 2022
1 parent a274acd commit e5fd71b
Show file tree
Hide file tree
Showing 10 changed files with 51 additions and 84 deletions.
14 changes: 5 additions & 9 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import { paths } from "./utils/collections.js";
// database stuff
import database from "./utils/database.js";
// lavalink stuff
import { checkStatus, reload, connect, status, connected } from "./utils/soundplayer.js";
import { reload, connect, connected } from "./utils/soundplayer.js";
// events
import { endBroadcast, startBroadcast } from "./utils/misc.js";
import { parseThreshold } from "./utils/tempimages.js";
Expand Down Expand Up @@ -106,12 +106,11 @@ esmBot ${esmBotVersion} (${process.env.GIT_REV})
}

// register commands and their info
const soundStatus = await checkStatus();
logger.log("info", "Attempting to load commands...");
for await (const commandFile of getFiles(resolve(dirname(fileURLToPath(import.meta.url)), "./commands/"))) {
logger.log("main", `Loading command from ${commandFile}...`);
try {
await load(null, commandFile, soundStatus);
await load(null, commandFile);
} catch (e) {
logger.error(`Failed to register command from ${commandFile}: ${e}`);
}
Expand Down Expand Up @@ -175,13 +174,10 @@ esmBot ${esmBotVersion} (${process.env.GIT_REV})
switch (packet.data?.type) {
case "reload":
var path = paths.get(packet.data.message);
await load(client, path, await checkStatus(), true);
await load(client, path, true);
break;
case "soundreload":
var soundStatus = await checkStatus();
if (!soundStatus) {
reload();
}
await reload(client);
break;
case "imagereload":
await reloadImageConnections();
Expand Down Expand Up @@ -212,7 +208,7 @@ esmBot ${esmBotVersion} (${process.env.GIT_REV})
}

// connect to lavalink
if (!status && !connected) connect(client);
if (!connected) connect(client);

client.connect();
}
Expand Down
1 change: 0 additions & 1 deletion classes/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ class Command {
static aliases = [];
static arguments = [];
static flags = [];
static requires = [];
static slashAllowed = true;
static directAllowed = true;
static adminOnly = false;
Expand Down
1 change: 0 additions & 1 deletion classes/musicCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ class MusicCommand extends Command {
}
}

static requires = ["sound"];
static slashAllowed = false;
static directAllowed = false;
}
Expand Down
3 changes: 1 addition & 2 deletions classes/soundboardCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ import { play } from "../utils/soundplayer.js";
// only exists to sort the various soundboard commands
class SoundboardCommand extends Command {
async run() {
return await play(this.client, this.constructor.file, { channel: this.channel, author: this.author, member: this.member, type: this.type, interaction: this.interaction });
return play(this.client, this.constructor.file, { channel: this.channel, author: this.author, member: this.member, type: this.type, interaction: this.interaction });
}

static requires = ["sound"];
static slashAllowed = false;
static directAllowed = false;
}
Expand Down
23 changes: 11 additions & 12 deletions commands/general/soundreload.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Command from "../../classes/command.js";
import { checkStatus, reload } from "../../utils/soundplayer.js";
import { reload } from "../../utils/soundplayer.js";

class SoundReloadCommand extends Command {
async run() {
Expand All @@ -9,17 +9,16 @@ class SoundReloadCommand extends Command {
return "Only the bot owner can reload Lavalink!";
}
await this.acknowledge();
const soundStatus = await checkStatus();
if (!soundStatus) {
const length = reload();
if (process.env.PM2_USAGE) {
process.send({
type: "process:msg",
data: {
type: "soundreload"
}
});
}
const length = await reload();
if (process.env.PM2_USAGE) {
process.send({
type: "process:msg",
data: {
type: "soundreload"
}
});
}
if (length) {
return `Successfully connected to ${length} Lavalink node(s).`;
} else {
return "I couldn't connect to any Lavalink nodes!";
Expand Down
1 change: 0 additions & 1 deletion commands/music/music.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ class MusicAIOCommand extends Command {
}

static description = "Handles music playback";
static requires = ["sound"];
static aliases = ["m"];
static directAllowed = false;
}
Expand Down
1 change: 0 additions & 1 deletion commands/soundboard/soundboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ class SoundboardAIOCommand extends Command {
}

static description = "Plays a sound effect";
static requires = ["sound"];
static aliases = ["sound", "sb"];
static directAllowed = false;
}
Expand Down
48 changes: 25 additions & 23 deletions events/messageCreate.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,33 +122,35 @@ export default async (client, message) => {
await client.rest.channels.createMessage(message.channelID, Object.assign({
content: result
}, reference));
} else if (typeof result === "object" && result.embeds) {
await client.rest.channels.createMessage(message.channelID, Object.assign(result, reference));
} else if (typeof result === "object" && result.contents) {
let fileSize = 8388119;
if (message.guildID) {
switch (message.guild.premiumTier) {
case 2:
fileSize = 52428308;
break;
case 3:
fileSize = 104856616;
break;
} else if (typeof result === "object") {
if (result.contents && result.name) {
let fileSize = 8388119;
if (message.guildID) {
switch (message.guild.premiumTier) {
case 2:
fileSize = 52428308;
break;
case 3:
fileSize = 104856616;
break;
}
}
}
if (result.contents.length > fileSize) {
if (process.env.TEMPDIR && process.env.TEMPDIR !== "") {
await upload(client, result, message);
if (result.contents.length > fileSize) {
if (process.env.TEMPDIR && process.env.TEMPDIR !== "") {
await upload(client, result, message);
} else {
await client.rest.channels.createMessage(message.channelID, {
content: "The resulting image was more than 8MB in size, so I can't upload it."
});
}
} else {
await client.rest.channels.createMessage(message.channelID, {
content: "The resulting image was more than 8MB in size, so I can't upload it."
});
await client.rest.channels.createMessage(message.channelID, Object.assign({
content: result.text ? result.text : undefined,
files: [result]
}, reference));
}
} else {
await client.rest.channels.createMessage(message.channelID, Object.assign({
content: result.text ? result.text : undefined,
files: [result]
}, reference));
await client.rest.channels.createMessage(message.channelID, Object.assign(result, reference));
}
}
} catch (error) {
Expand Down
6 changes: 1 addition & 5 deletions utils/handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,9 @@ const { blacklist } = JSON.parse(readFileSync(new URL("../config/commands.json",
let queryValue = 0;

// load command into memory
export async function load(client, command, soundStatus, slashReload = false) {
export async function load(client, command, slashReload = false) {
const { default: props } = await import(`${command}?v=${queryValue}`);
queryValue++;
if (props.requires.includes("sound") && soundStatus) {
log("warn", `Failed to connect to some Lavalink nodes, skipped loading command ${command}...`);
return;
}
const commandArray = command.split("/");
let commandName = commandArray[commandArray.length - 1].split(".")[0];
const category = commandArray[commandArray.length - 2];
Expand Down
37 changes: 8 additions & 29 deletions utils/soundplayer.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as logger from "./logger.js";
import { request } from "undici";
import fs from "fs";
import format from "format-duration";
import { Shoukaku, Connectors } from "shoukaku";
Expand All @@ -10,27 +9,9 @@ export const queues = new Map();
export const skipVotes = new Map();

export let manager;
export let nodes;
export let status = false;
export let nodes = JSON.parse(fs.readFileSync(new URL("../config/servers.json", import.meta.url), { encoding: "utf8" })).lava;
export let connected = false;

export async function checkStatus() {
const json = await fs.promises.readFile(new URL("../config/servers.json", import.meta.url), { encoding: "utf8" });
nodes = JSON.parse(json).lava;
const newNodes = [];
for (const node of nodes) {
try {
const response = await request(`http://${node.url}/version`, { headers: { authorization: node.auth } }).then(res => res.body.text());
if (response) newNodes.push(node);
} catch (e) {
logger.error(`Failed to get status of Lavalink node ${node.url}: ${e}`);
}
}
nodes = newNodes;
status = newNodes.length === 0 ? true : false;
return status;
}

export function connect(client) {
manager = new Shoukaku(new Connectors.OceanicJS(client), nodes, { moveOnDisconnect: true, resume: true, reconnectInterval: 500, reconnectTries: 1 });
manager.on("error", (node, error) => {
Expand All @@ -42,8 +23,11 @@ export function connect(client) {
});
}

export function reload() {
export async function reload(client) {
if (!manager) connect(client);
const activeNodes = manager.nodes;
const json = await fs.promises.readFile(new URL("../config/servers.json", import.meta.url), { encoding: "utf8" });
nodes = JSON.parse(json).lava;
const names = nodes.map((a) => a.name);
for (const name in activeNodes) {
if (!names.includes(name)) {
Expand All @@ -55,25 +39,20 @@ export function reload() {
manager.addNode(node);
}
}
if (!manager.nodes.size) connected = false;
return manager.nodes.size;
}

export async function play(client, sound, options, music = false) {
if (!connected) return { content: "I'm not connected to any audio servers!", flags: 64 };
if (!manager) return { content: "The sound commands are still starting up!", flags: 64 };
if (!options.channel.guild) return { content: "This command only works in servers!", flags: 64 };
if (!options.member.voiceState) return { content: "You need to be in a voice channel first!", flags: 64 };
if (!options.channel.guild.permissionsOf(client.user.id.toString()).has("CONNECT")) return { content: "I can't join this voice channel!", flags: 64 };
const voiceChannel = options.channel.guild.channels.get(options.member.voiceState.channelID);
if (!voiceChannel.permissionsOf(client.user.id.toString()).has("CONNECT")) return { content: "I don't have permission to join this voice channel!", flags: 64 };
if (!music && manager.players.has(options.channel.guildID)) return { content: "I can't play a sound effect while other audio is playing!", flags: 64 };
let node = manager.getNode();
if (!node) {
const status = await checkStatus();
if (!status) {
connect(client);
node = manager.getNode();
}
}
const node = manager.getNode();
if (!music && !nodes.filter(obj => obj.name === node.name)[0].local) {
sound = sound.replace(/\.\//, "https://raw.githubusercontent.com/esmBot/esmBot/master/");
}
Expand Down

0 comments on commit e5fd71b

Please sign in to comment.