Simplify events

This commit is contained in:
Christer Warén 2023-06-06 03:41:04 +03:00
parent 348ac90cba
commit 87cf4b62c8
10 changed files with 232 additions and 257 deletions

View File

@ -6,7 +6,7 @@ import Streamer from "./client/classes/Streamer";
import Statistics from "./client/classes/Statistics"; import Statistics from "./client/classes/Statistics";
import { command } from "./client/commands"; import { command } from "./client/commands";
import config from "./config"; import config from "./config";
import { events } from "./client/events" import events from "./client/events"
import { funcs } from "./client/funcs"; import { funcs } from "./client/funcs";
import { messages } from "./client/messages"; import { messages } from "./client/messages";
@ -20,7 +20,6 @@ GatewayIntents.add(
export default class RadioClient extends Client { export default class RadioClient extends Client {
readonly commands: Collection<string, command>; readonly commands: Collection<string, command>;
readonly events = events;
readonly funcs = funcs; readonly funcs = funcs;
readonly config = config; readonly config = config;
readonly messages = messages; readonly messages = messages;
@ -52,47 +51,7 @@ export default class RadioClient extends Client {
this.funcs.logger("Maintenance Mode", "Enabled"); this.funcs.logger("Maintenance Mode", "Enabled");
this.config.maintenanceMode = true; this.config.maintenanceMode = true;
this.on("ready", () => { events(this);
this.events.ready.execute(this);
});
this.on("messageDelete", msg => {
this.events.messageDelete.execute(this, msg);
});
this.on("interactionCreate", interaction => {
this.events.interactionCreate.execute(this, interaction);
});
this.on("voiceStateUpdate", (oldState, newState) => {
this.events.voiceStateUpdate.execute(this, oldState, newState);
});
this.on("error", error => {
this.funcs.logger("Discord Client", "Error");
console.error(error);
console.log('');
});
process.on('SIGINT', () => {
this.events.SIGINT.execute(this);
});
process.on('SIGTERM', () => {
this.events.SIGTERM.execute(this);
});
process.on('uncaughtException', (error) => {
this.events.uncaughtException.execute(this, error);
});
process.on('exit', () => {
this.funcs.logger("Bot", "Stopping");
});
process.on('warning', (warning) => {
this.events.warning.execute(this, warning);
});
this.login(this.config.token).catch((err) => { this.login(this.config.token).catch((err) => {
this.funcs.logger("Discord Client", "Login Error"); this.funcs.logger("Discord Client", "Login Error");

View File

@ -1,3 +1,4 @@
import RadioClient from "../Client"
import interactionCreate from "./events/interactionCreate" import interactionCreate from "./events/interactionCreate"
import messageDelete from "./events/messageDelete" import messageDelete from "./events/messageDelete"
import ready from "./events/ready" import ready from "./events/ready"
@ -7,6 +8,46 @@ import uncaughtException from "./events/uncaughtException"
import voiceStateUpdate from "./events/voiceStateUpdate" import voiceStateUpdate from "./events/voiceStateUpdate"
import warning from "./events/warning" import warning from "./events/warning"
export const events = { export default function events(client: RadioClient) {
interactionCreate, messageDelete, ready, SIGINT, SIGTERM, uncaughtException, voiceStateUpdate, warning client.on("ready", () => {
ready(client);
});
client.on("messageDelete", msg => {
messageDelete(client, msg);
});
client.on("interactionCreate", interaction => {
interactionCreate(client, interaction);
});
client.on("voiceStateUpdate", (oldState, newState) => {
voiceStateUpdate(client, oldState, newState);
});
client.on("error", error => {
client.funcs.logger("Discord Client", "Error");
console.error(error);
console.log('');
});
process.on('SIGINT', () => {
SIGINT(client);
});
process.on('SIGTERM', () => {
SIGTERM(client);
});
process.on('uncaughtException', (error) => {
uncaughtException(client, error);
});
process.on('exit', () => {
client.funcs.logger("Bot", "Stopping");
});
process.on('warning', (error) => {
warning(client, error);
});
} }

View File

@ -1,17 +1,14 @@
import RadioClient from "../../Client"; import RadioClient from "../../Client";
export default { export default function SIGINT(client: RadioClient) {
name: 'SIGINT', client.user?.setStatus('dnd');
execute(client: RadioClient) {
client.user?.setStatus('dnd');
client.streamer?.leave(client); client.streamer?.leave(client);
client.radio?.save(client); client.radio?.save(client);
setInterval(() => { setInterval(() => {
if(client.radio?.size == 0){ if(client.radio?.size == 0){
process.exit(); process.exit();
} }
}, 500); }, 500);
}
} }

View File

@ -1,8 +1,5 @@
import RadioClient from "../../Client"; import RadioClient from "../../Client";
export default { export default function SIGTERM(client: RadioClient) {
name: 'SIGTERM', process.emit('SIGINT');
execute(client: RadioClient) {
process.emit('SIGINT');
}
} }

View File

@ -1,53 +1,52 @@
import { PermissionFlagsBits } from "discord.js"; import { Interaction, PermissionFlagsBits } from "discord.js";
import RadioClient from "../../Client"; import RadioClient from "../../Client";
export default { export default function interactionCreate(client: RadioClient, interaction: Interaction) {
name: 'interactionCreate', if(!(interaction.isButton()) && !(interaction.isChatInputCommand()) && !(interaction.isStringSelectMenu())) return;
async execute(client: RadioClient, interaction: any) {
if(client.config.maintenanceMode){ if(client.config.maintenanceMode){
return interaction.reply({ return interaction.reply({
content: client.messages.emojis["error"] + client.messages.maintenance, content: client.messages.emojis["error"] + client.messages.maintenance,
ephemeral: true
});
}
const permissions = interaction.channel.permissionsFor(interaction.client.user);
if (!permissions.has(PermissionFlagsBits.ViewChannel)) return;
if (!permissions.has(PermissionFlagsBits.EmbedLinks)) return interaction.reply({
content: client.messages.emojis["error"] + client.messages.noPermsEmbed,
ephemeral: true ephemeral: true
}); });
}
if(interaction.isChatInputCommand()){ //@ts-ignore
const commandName = interaction.commandName; const permissions = interaction.channel?.permissionsFor(interaction.client.user);
const command = client.commands.get(commandName); if (!permissions.has(PermissionFlagsBits.ViewChannel)) return;
if (!command) return;
try { if (!permissions.has(PermissionFlagsBits.EmbedLinks)) return interaction.reply({
command.execute(interaction, client); content: client.messages.emojis["error"] + client.messages.noPermsEmbed,
} catch (error) { ephemeral: true
interaction.reply({ });
content: client.messages.emojis["error"] + client.messages.runningCommandFailed,
ephemeral: true
});
console.error(error);
}
} else if (interaction.isStringSelectMenu() || interaction.isButton()){
const commandName = interaction.customId;
const command = client.commands.get(commandName);
if (!command) return;
try { if(interaction.isChatInputCommand()){
command.execute(interaction, client, command); const commandName = interaction.commandName;
} catch (error) { const command = client.commands.get(commandName);
interaction.reply({ if (!command) return;
content: client.messages.emojis["error"] + client.messages.runningCommandFailed,
ephemeral: true try {
}); command.execute(interaction, client);
console.error(error); } catch (error) {
} interaction.reply({
content: client.messages.emojis["error"] + client.messages.runningCommandFailed,
ephemeral: true
});
console.error(error);
}
} else if (interaction.isStringSelectMenu() || interaction.isButton()){
const commandName = interaction.customId;
const command = client.commands.get(commandName);
if (!command) return;
try {
command.execute(interaction, client, command);
} catch (error) {
interaction.reply({
content: client.messages.emojis["error"] + client.messages.runningCommandFailed,
ephemeral: true
});
console.error(error);
} }
} }
} }

View File

@ -1,14 +1,11 @@
import { Message, PartialMessage } from "discord.js"; import { Message, PartialMessage } from "discord.js";
import RadioClient from "../../Client"; import RadioClient from "../../Client";
export default { export default function messageDelete(client: RadioClient, msg: Message | PartialMessage){
name: 'messageDelete', if(!msg.author?.bot || !msg.guild) return;
async execute(client: RadioClient, msg: Message | PartialMessage) { const radio = client.radio?.get(msg.guild.id);
if(!msg.author?.bot || !msg.guild) return; if(!radio) return;
const radio = client.radio?.get(msg.guild.id); if(!radio.message) return;
if(!radio) return; if(msg.id != radio.message.id) return;
if(!radio.message) return; radio.message = null;
if(msg.id != radio.message.id) return;
radio.message = null;
}
} }

View File

@ -6,82 +6,77 @@ import Streamer from "../classes/Streamer";
import Statistics from "../classes/Statistics"; import Statistics from "../classes/Statistics";
import commands from "../commands"; import commands from "../commands";
export default { export default async function ready(client: RadioClient) {
name: 'ready', client.funcs.logger("Bot", "Ready");
async execute(client: RadioClient) {
client.funcs.logger("Bot", "Ready"); /*DATASTORE*/
client.funcs.logger('Datastore', 'Initialize');
client.datastore = new Datastore();
/*DATASTORE*/ client.datastore.map.forEach((datastore: { guild: { id: string; name: string; }; }) => {
client.funcs.logger('Datastore', 'Initialize'); client.funcs.logger('Datastore', datastore.guild.id + " / " + datastore.guild.name);
client.datastore = new Datastore(); });
client.datastore.map.forEach((datastore: { guild: { id: string; name: string; }; }) => { client.funcs.logger('Datastore', 'Ready');
client.funcs.logger('Datastore', datastore.guild.id + " / " + datastore.guild.name);
});
client.funcs.logger('Datastore', 'Ready'); /*DEVELOPERS*/
client.developers = "";
/*DEVELOPERS*/ let user : any= "";
client.developers = ""; for (let i = 0; i < client.config.devId.length; i++) {
let user : any= ""; user = await client.users.fetch(client.config.devId[i]);
for (let i = 0; i < client.config.devId.length; i++) { client.funcs.logger('Developers', user.tag);
user = await client.users.fetch(client.config.devId[i]); if (i == client.config.devId.length - 1) {
client.funcs.logger('Developers', user.tag); client.developers += user.tag;
if (i == client.config.devId.length - 1) { } else {
client.developers += user.tag; client.developers += user.tag + " & ";
} else {
client.developers += user.tag + " & ";
}
} }
/*STATIONS*/
client.stations = new Stations();
await client.stations.fetch({
url: client.config.stationslistUrl,
show: true
});
client.streamer = new Streamer();
client.streamer.init(client);
if(!client.stations) {
client.user?.setStatus('dnd');
}
/*GUILDS*/
client.funcs.logger('Guilds', 'Started fetching list');
let guilds = await client.guilds.fetch();
guilds.forEach((guild: { id: string; name: string; }) => {
client.funcs.logger('Guilds', guild.id + " / " + guild.name);
});
client.funcs.logger('Guilds', 'Successfully fetched list');
/*STATISTICS*/
client.statistics = new Statistics();
client.statistics.calculateGlobal(client);
/*COMMANDS*/
commands.execute(client);
/*RADIO*/
client.radio = new Radio();
setTimeout(function () {
/*RESTORE RADIOS*/
client.radio?.restore(client, guilds);
}, 5000);
setTimeout(function () {
if(client.stations) {
/*MAINTENANCE MODE*/
client.funcs.logger("Maintenance Mode", "Disabled");
client.config.maintenanceMode = false;
}
}, 10000);
} }
/*STATIONS*/
client.stations = new Stations();
await client.stations.fetch({
url: client.config.stationslistUrl,
show: true
});
client.streamer = new Streamer();
client.streamer.init(client);
if(!client.stations) {
client.user?.setStatus('dnd');
}
/*GUILDS*/
client.funcs.logger('Guilds', 'Started fetching list');
let guilds = await client.guilds.fetch();
guilds.forEach((guild: { id: string; name: string; }) => {
client.funcs.logger('Guilds', guild.id + " / " + guild.name);
});
client.funcs.logger('Guilds', 'Successfully fetched list');
/*STATISTICS*/
client.statistics = new Statistics();
client.statistics.calculateGlobal(client);
/*COMMANDS*/
commands.execute(client);
/*RADIO*/
client.radio = new Radio();
setTimeout(function () {
/*RESTORE RADIOS*/
client.radio?.restore(client, guilds);
}, 5000);
setTimeout(function () {
if(client.stations) {
/*MAINTENANCE MODE*/
client.funcs.logger("Maintenance Mode", "Disabled");
client.config.maintenanceMode = false;
}
}, 10000);
} }

View File

@ -1,13 +1,10 @@
import RadioClient from "../../Client"; import RadioClient from "../../Client";
export default { export default function uncaughtException(client: RadioClient, error: Error) {
name: 'uncaughtException', client.funcs.logger("Error");
execute(client: RadioClient, error: any) { console.log(error.stack);
client.funcs.logger("Error"); console.log('');
console.log(error.stack);
console.log('');
if(error.name == "DiscordAPIError" && error.message == "Unknown interaction") return; if(error.name == "DiscordAPIError" && error.message == "Unknown interaction") return;
process.emit('SIGINT'); process.emit('SIGINT');
}
} }

View File

@ -5,65 +5,61 @@ const {
joinVoiceChannel joinVoiceChannel
} = require("@discordjs/voice"); } = require("@discordjs/voice");
export default { export default async function voiceStateUpdate(client: RadioClient, oldState: VoiceState, newState: VoiceState) {
name: "voiceStateUpdate", if (oldState.channel === null) return;
async execute(client: RadioClient, oldState: VoiceState, newState: VoiceState) { let change = false;
if (oldState.channel === null) return; const radio = client.radio?.get(newState.guild.id);
let change = false; if (!radio) return;
const radio = client.radio?.get(newState.guild.id);
if (!radio) return;
if (newState.member?.id === client.user?.id && oldState.member?.id === client.user?.id) { if (newState.member?.id === client.user?.id && oldState.member?.id === client.user?.id) {
if (newState.channel === null) { if (newState.channel === null) {
client.statistics?.update(client, newState.guild, radio);
radio.connection?.destroy();
radio.message?.delete();
client.funcs.logger('Radio', newState.guild.id + " / " + 'Stop');
return client.radio?.delete(newState.guild.id);
}
const newPermissions = newState.channel.permissionsFor(newState.client.user);
if (!newPermissions?.has(PermissionFlagsBits.Connect) || !newPermissions?.has(PermissionFlagsBits.Speak) || !newPermissions?.has(PermissionFlagsBits.ViewChannel)) {
try {
setTimeout(
async () => (
radio.connection = joinVoiceChannel({
channelId: oldState.channel?.id,
guildId: oldState.channel?.guild.id,
adapterCreator: oldState.channel?.guild.voiceAdapterCreator
})
),
1000
);
} catch (error) {
client.statistics?.update(client, newState.guild, radio); client.statistics?.update(client, newState.guild, radio);
radio.connection?.destroy(); radio.connection?.destroy();
radio.message?.delete(); radio.message?.delete();
client.funcs.logger('Radio', newState.guild.id + " / " + 'Stop'); client.funcs.logger('Radio', newState.guild.id + " / " + 'Stop');
return client.radio?.delete(newState.guild.id); client.radio?.delete(oldState.guild.id);
} }
return;
}
if (newState.channel !== radio.voiceChannel) {
change = true;
radio.voiceChannel = newState.channel;
radio.connection = getVoiceConnection(newState.channel.guild.id);
const newPermissions = newState.channel.permissionsFor(newState.client.user);
if (!newPermissions?.has(PermissionFlagsBits.Connect) || !newPermissions?.has(PermissionFlagsBits.Speak) || !newPermissions?.has(PermissionFlagsBits.ViewChannel)) {
try {
setTimeout(
async () => (
radio.connection = joinVoiceChannel({
channelId: oldState.channel?.id,
guildId: oldState.channel?.guild.id,
adapterCreator: oldState.channel?.guild.voiceAdapterCreator
})
//radio.connection = await oldState.channel.join()
),
1000
);
} catch (error) {
client.statistics?.update(client, newState.guild, radio);
radio.connection?.destroy();
radio.message?.delete();
client.funcs.logger('Radio', newState.guild.id + " / " + 'Stop');
client.radio?.delete(oldState.guild.id);
}
return;
}
if (newState.channel !== radio.voiceChannel) {
change = true;
radio.voiceChannel = newState.channel;
radio.connection = getVoiceConnection(newState.channel.guild.id);
//radio.connection = await newState.channel.join();
}
} }
if ((oldState.channel.members.filter(member => !member.user.bot).size === 0 && oldState.channel === radio.voiceChannel) || change) { }
setTimeout(() => { if ((oldState.channel.members.filter(member => !member.user.bot).size === 0 && oldState.channel === radio.voiceChannel) || change) {
if (!radio || !radio.connection || !radio.connection === null) return; setTimeout(() => {
if (radio.voiceChannel.members.filter((member: { user: { bot: any; }; }) => !member.user.bot).size === 0) { if (!radio || !radio.connection || !radio.connection === null) return;
client.statistics?.update(client, newState.guild, radio); if (radio.voiceChannel.members.filter((member: { user: { bot: any; }; }) => !member.user.bot).size === 0) {
radio.connection?.destroy(); client.statistics?.update(client, newState.guild, radio);
radio.message?.delete(); radio.connection?.destroy();
client.funcs.logger('Radio', newState.guild.id + " / " + 'Stop'); radio.message?.delete();
client.radio?.delete(newState.guild.id); client.funcs.logger('Radio', newState.guild.id + " / " + 'Stop');
} client.radio?.delete(newState.guild.id);
}, 5000); }
} }, 5000);
}, }
}; };

View File

@ -1,14 +1,11 @@
import RadioClient from "../../Client"; import RadioClient from "../../Client";
export default { export default function warning(client: RadioClient, warning: Error) {
name: 'warning', if(warning.name == "ExperimentalWarning" && warning.message.startsWith("stream/web")) return;
execute(client: RadioClient, warning: Error) {
if(warning.name == "ExperimentalWarning" && warning.message.startsWith("stream/web")) return;
client.funcs.logger("Warning"); client.funcs.logger("Warning");
console.warn(warning.name); console.warn(warning.name);
console.warn(warning.message); console.warn(warning.message);
console.warn(warning.stack); console.warn(warning.stack);
console.log(''); console.log('');
}
} }