fix!: New folder structure and organize files

This commit is contained in:
Marius Begby committed 2024-01-30 16:29:17 +01:00
1 parent d92bd329dc
commit 39ff5ecb5d
83 files changed
+244 -246

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
import { Track } from 'discord-player';
import { TFunction } from 'i18next';
export function shouldUseLastQuery(query: string, lastQuery?: string, timestamp?: number): boolean {
return Boolean(
lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - (timestamp ?? 0) < 500
);
}
export function isQueryTooShort(query: string): boolean {
return query.length < 3;
}
export function getTrackName(track: Track, translator: TFunction): string {
const name = translator('autocomplete.trackName', {
title: track.title,
author: track.author
});
return name.length > 100 ? name.slice(0, 100) : name;
}
+75
View File
@@ -0,0 +1,75 @@
import { QueueRepeatMode } from 'discord-player';
import { TFunction } from 'i18next';
import { EmbedOptions } from '../../types/configTypes';
export function formatDuration(durationMs: number): string {
const durationDate: Date = new Date(0);
durationDate.setMilliseconds(durationMs);
const durationDays: number = durationDate.getUTCDate() - 1;
const durationHours: number = durationDate.getUTCHours();
const durationMinutes: number = durationDate.getUTCMinutes();
const durationSeconds: number = durationDate.getUTCSeconds();
if (durationDays >= 1) {
return `${durationDays}d ${durationHours}h`;
} else if (durationHours >= 1) {
return `${durationHours}h ${durationMinutes}m`;
} else if (durationMinutes >= 1) {
return `${durationMinutes}m ${durationSeconds}s`;
} else {
return `${durationSeconds}s`;
}
}
export function formatSlashCommand(commandName: string, translator: TFunction): string {
const translatedName = translator(`commands.${commandName}.metadata.name`, {
defaultValue: commandName
});
return `**\`/${translatedName}\`**`;
}
export function formatRepeatMode(repeatMode: QueueRepeatMode, translator: TFunction): string {
switch (repeatMode) {
case QueueRepeatMode.AUTOPLAY:
return translator('musicPlayerCommon.queueRepeatMode.autoplay');
case QueueRepeatMode.OFF:
return translator('musicPlayerCommon.queueRepeatMode.off');
case QueueRepeatMode.TRACK:
return translator('musicPlayerCommon.queueRepeatMode.track');
case QueueRepeatMode.QUEUE:
return translator('musicPlayerCommon.queueRepeatMode.queue');
}
}
export function formatRepeatModeDetailed(
repeatMode: QueueRepeatMode,
embedOptions: EmbedOptions,
translator: TFunction,
state: string = 'info'
) {
let icon: string;
switch (repeatMode) {
case QueueRepeatMode.TRACK:
icon = state === 'info' ? embedOptions.icons.loop : embedOptions.icons.looping;
break;
case QueueRepeatMode.QUEUE:
icon = state === 'info' ? embedOptions.icons.loop : embedOptions.icons.looping;
break;
case QueueRepeatMode.AUTOPLAY:
icon = state === 'info' ? embedOptions.icons.autoplay : embedOptions.icons.autoplaying;
break;
default:
return '';
}
return (
'\n' +
translator('musicPlayerCommon.loopingInfo', {
icon,
loopMode: formatRepeatMode(repeatMode, translator),
loopCommand: formatSlashCommand('loop', translator)
})
);
}
+20
View File
@@ -0,0 +1,20 @@
import { Logger } from 'pino';
import loggerModule from '../services/logger';
import { GetUptimeFormattedParams } from '../../types/utilTypes';
import { formatDuration } from './formattingUtils';
export const getUptimeFormatted = ({ executionId }: GetUptimeFormattedParams): string => {
const logger: Logger = loggerModule.child({
module: 'utilSystem',
name: 'getUptimeFormatted',
executionId: executionId
});
try {
const uptimeInSeconds: number = parseFloat(process.uptime().toFixed(0));
return formatDuration(uptimeInSeconds * 1000);
} catch (error) {
logger.error('Error retrieving or transforming uptime to formatted string.', error);
throw error;
}
};
+191
View File
@@ -0,0 +1,191 @@
import assert from 'assert';
import {
APIApplicationCommandOption,
ApplicationCommandOptionType,
BaseInteraction,
Locale,
LocaleString,
SlashCommandBuilder,
SlashCommandSubcommandBuilder,
SlashCommandSubcommandsOnlyBuilder
} from 'discord.js';
import { lstatSync, readdirSync } from 'fs';
import i18n from 'i18next';
import i18nextFsBackend, { FsBackendOptions } from 'i18next-fs-backend';
import { join } from 'path';
export const translatorInstance = i18n.createInstance();
const localeDir = join(__dirname, '..', '..', 'locales');
translatorInstance.use(i18nextFsBackend).init<FsBackendOptions>({
initImmediate: false,
fallbackLng: 'en',
preload: readdirSync(localeDir).filter((fileName) => {
const joinedPath = join(localeDir, fileName);
const isDirectory = lstatSync(joinedPath).isDirectory();
return isDirectory;
}),
ns: 'bot',
defaultNS: 'bot',
backend: {
loadPath: join(localeDir, '{{lng}}', '{{ns}}.json'),
addPath: join(localeDir, '{{lng}}', '{{ns}}.missing.json')
},
interpolation: {
escapeValue: false
}
});
export function useServerTranslator(interaction: BaseInteraction) {
return translatorInstance.getFixedT(interaction.guildLocale ?? 'en-US');
}
export function useUserTranslator(interaction: BaseInteraction) {
return translatorInstance.getFixedT(interaction.locale ?? 'en-US');
}
export function useLanguageTranslator(language: LocaleString) {
return translatorInstance.getFixedT(language ?? 'en-US');
}
export const DISCORD_LOCALES = Object.values(Locale);
export type SubcommandMetadata = {
name?: string;
description?: string;
options?: Record<
string,
{
name?: string;
description?: string;
choices?: Record<string, string>;
}
>;
};
export type CommandMetadata =
| SubcommandMetadata
| (SubcommandMetadata & {
options?: Record<string, SubcommandMetadata>;
});
type DeepMutable<T> = { -readonly [P in keyof T]: DeepMutable<T[P]> };
export function localizeCommand(
command:
| SlashCommandSubcommandBuilder
| SlashCommandSubcommandsOnlyBuilder
| Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>,
resourcePath?: string
) {
const jsonCommand = command as DeepMutable<typeof command>;
const logCommandName = resourcePath ?? `/${command.name}`;
assert(jsonCommand.name, `Command ${logCommandName} must have a name using setName.`);
const metadataKey = resourcePath ?? `commands.${jsonCommand.name}.metadata`;
const englishData = translatorInstance.getResource('en', 'bot', metadataKey) as CommandMetadata | undefined;
assert(englishData, `Command ${logCommandName} must have English localization data.`);
// Localizing the top-level command...
assert(englishData.description, `Command ${logCommandName} is missing an English description.`);
jsonCommand.description = englishData.description;
/* eslint-disable camelcase */
jsonCommand.name_localizations = {};
/* eslint-disable camelcase */
jsonCommand.description_localizations = {};
for (const locale of DISCORD_LOCALES) {
const localeData = translatorInstance.getResource(locale, 'bot', metadataKey) as CommandMetadata | undefined;
if (locale.startsWith('en') || !localeData) {
continue;
}
if (localeData.name) {
jsonCommand.name_localizations[locale] = localeData.name;
}
if (localeData.description) {
jsonCommand.description_localizations[locale] = localeData.description;
}
}
// Localizing the command options...
if (jsonCommand.options.length > 0) {
assert(englishData.options, `Command ${logCommandName} must have option localizations.`);
for (const unwritableOption of jsonCommand.options) {
const option = unwritableOption as never as APIApplicationCommandOption;
// Subcommands are stored in options - they have an 'options' field that always exists (even if empty) on subcommands
if ('options' in option && Array.isArray(option.options)) {
localizeCommand(
unwritableOption as SlashCommandSubcommandBuilder,
`commands.${command.name}.metadata.options.${option.name}`
);
continue;
}
assert(option.name, `Option in ${logCommandName} must have a name using setName.`);
const englishOptionData = englishData.options[option.name];
assert(
englishOptionData.description,
`Option ${option.name} in command ${logCommandName} is missing an English description.`
);
option.description = englishOptionData.description;
option.name_localizations = {};
option.description_localizations = {};
if (
(option.type === ApplicationCommandOptionType.String ||
option.type === ApplicationCommandOptionType.Integer) &&
option.choices
) {
assert(
englishOptionData.choices,
`Option ${option.name} in ${logCommandName} must have choice localizations.`
);
for (const choice of option.choices) {
choice.name_localizations = {};
assert(
choice.value !== undefined && choice.value !== null,
`Choice in option ${option.name} in ${logCommandName} must have a value.`
);
const stringifiedValue = choice.value.toString();
assert(
englishOptionData.choices[stringifiedValue],
`Choice ${choice.value} of option ${option.name} in ${logCommandName} must have an English localization.`
);
choice.name = englishOptionData.choices[stringifiedValue];
}
}
for (const locale of DISCORD_LOCALES) {
const localeOptionData = (
translatorInstance.getResource(locale, 'bot', metadataKey) as CommandMetadata | undefined
)?.options?.[option.name];
if (locale.startsWith('en') || !localeOptionData) {
continue;
}
if (localeOptionData.name) {
option.name_localizations[locale] = localeOptionData.name;
}
if (localeOptionData.description) {
option.description_localizations[locale] = localeOptionData.description;
}
if (
localeOptionData.choices &&
(option.type === ApplicationCommandOptionType.String ||
option.type === ApplicationCommandOptionType.Integer) &&
option.choices
) {
for (const choice of option.choices) {
const localizedChoice = localeOptionData.choices[choice.value];
if (!localizedChoice) {
continue;
}
choice.name_localizations![locale] = localizedChoice;
}
}
}
}
}
return jsonCommand as SlashCommandBuilder;
}
+93
View File
@@ -0,0 +1,93 @@
import { GuildQueueStatisticsMetadata } from 'discord-player';
import { Client, Guild } from 'discord.js';
import { PlayerStatistics, ShardPlayerStatistics } from '../../types/utilTypes';
async function fetchGuildsPerShard(client?: Client): Promise<Map<string, Guild>[]> {
if (!client || !client.shard) {
throw new Error('Client is undefined or not sharded.');
}
try {
return (await client.shard.fetchClientValues('guilds.cache')) as Map<string, Guild>[];
} catch (error) {
throw new Error('Failed to fetch client values from shards.');
}
}
function calculateTotalCountForShard(guildListMap: Map<string, Guild>) {
const guildList: Guild[] = [...guildListMap.values()];
const totalGuildCount: number = guildList.length;
const totalMemberCount: number = guildList.reduce((acc: number, guild: Guild) => acc + guild.memberCount, 0);
return { totalGuildCount, totalMemberCount };
}
function calculateTotalCountForAllShards(guildListPerShard: Map<string, Guild>[]) {
return guildListPerShard.reduce(
(totals, guildList) => {
const { totalGuildCount, totalMemberCount } = calculateTotalCountForShard(guildList);
totals.totalGuildCount += totalGuildCount;
totals.totalMemberCount += totalMemberCount;
return totals;
},
{ totalGuildCount: 0, totalMemberCount: 0 }
);
}
export async function fetchTotalGuildStatistics(client?: Client) {
const guildsPerShard: Map<string, Guild>[] = await fetchGuildsPerShard(client);
const { totalGuildCount, totalMemberCount } = calculateTotalCountForAllShards(guildsPerShard);
return { totalGuildCount, totalMemberCount };
}
async function fetchPlayerStatisticsPerShard(client?: Client): Promise<PlayerStatistics[]> {
if (!client || !client.shard) {
throw new Error('Client is undefined or not sharded.');
}
try {
const playerStatisticsPerShard: PlayerStatistics[] = await client.shard.broadcastEval(() => {
/* eslint-disable no-undef */
return player.generateStatistics();
});
return playerStatisticsPerShard;
} catch (error) {
throw new Error('Failed to fetch player statistics from shards.');
}
}
function calculateTotalPlayerStatisticsForShard(result: PlayerStatistics): ShardPlayerStatistics {
const totalVoiceConnections = result.queues.length;
let totalTracksInQueues = 0;
let totalListeners = 0;
result.queues.map((queue: GuildQueueStatisticsMetadata) => {
totalTracksInQueues += queue.status.playing ? queue.tracksCount + 1 : queue.tracksCount;
totalListeners += queue.listeners;
});
return { totalVoiceConnections, totalTracksInQueues, totalListeners };
}
function calculateTotalPlayerStatisticsForAllShards(results: PlayerStatistics[]): ShardPlayerStatistics {
return results.reduce(
(totals: ShardPlayerStatistics, result: PlayerStatistics) => {
const { totalVoiceConnections, totalTracksInQueues, totalListeners } =
calculateTotalPlayerStatisticsForShard(result);
totals.totalVoiceConnections += totalVoiceConnections;
totals.totalTracksInQueues += totalTracksInQueues;
totals.totalListeners += totalListeners;
return totals;
},
{ totalVoiceConnections: 0, totalTracksInQueues: 0, totalListeners: 0 }
);
}
export async function fetchTotalPlayerStatistics(client?: Client): Promise<ShardPlayerStatistics> {
const results: PlayerStatistics[] = await fetchPlayerStatisticsPerShard(client);
return calculateTotalPlayerStatisticsForAllShards(results);
}
+79
View File
@@ -0,0 +1,79 @@
import osu from 'node-os-utils';
import { ExtendedClient } from '../../types/clientTypes';
import { fetchTotalGuildStatistics, fetchTotalPlayerStatistics } from './shardUtils';
import { getUptimeFormatted } from './getUptimeFormatted';
import { TFunction } from 'i18next';
export async function getBotStatistics(
client: ExtendedClient,
version: string,
translator: TFunction
): Promise<string> {
const releaseVersion: string = version;
const { totalGuildCount, totalMemberCount } = await fetchTotalGuildStatistics(client);
return (
translator('statistics.botStatus.joinedServers', {
count: totalGuildCount
}) +
'\n' +
translator('statistics.botStatus.totalMembers', {
count: totalMemberCount
}) +
'\n' +
translator('statistics.botStatus.releaseVersion', {
version: `v${releaseVersion}`
})
);
}
export async function getPlayerStatistics(client: ExtendedClient, translator: TFunction): Promise<string> {
const { totalVoiceConnections, totalTracksInQueues, totalListeners } = await fetchTotalPlayerStatistics(client);
return (
translator('statistics.queueStatus.voiceConnections', {
count: totalVoiceConnections
}) +
'\n' +
translator('statistics.queueStatus.tracksInQueues', {
count: totalTracksInQueues
}) +
'\n' +
translator('statistics.queueStatus.usersListening', {
count: totalListeners
})
);
}
export async function getSystemStatus(executionId: string, extended: boolean, translator: TFunction): Promise<string> {
const uptimeString: string = getUptimeFormatted({ executionId });
const usedMemoryInMB: number = Math.ceil((await osu.mem.info()).usedMemMb);
const cpuUsage: number = await osu.cpu.usage();
if (!extended) {
return (
translator('statistics.systemStatus.uptime', { value: uptimeString }) +
'\n' +
translator('statistics.systemStatus.cpu', { value: cpuUsage }) +
'\n' +
translator('statistics.systemStatus.memory', { value: usedMemoryInMB })
);
}
const totalMemoryInMb: number = Math.ceil((await osu.mem.info()).totalMemMb);
const cpuCores: number = osu.cpu.count();
const platform: string = osu.os.platform();
return (
translator('statistics.systemStatus.platform', { value: platform }) +
'\n' +
translator('statistics.systemStatus.uptime', { value: uptimeString }) +
'\n' +
translator('statistics.systemStatus.cpuDetailed', { usage: cpuUsage, cores: cpuCores }) +
'\n' +
translator('statistics.systemStatus.memoryDetailed', { used: usedMemoryInMB, total: totalMemoryInMb })
);
}
export function getDiscordStatus(client: ExtendedClient, translator: TFunction): string {
return translator('statistics.discordStatus.apiLatency', { value: client.ws.ping });
}