mirror of
https://github.com/darksaid98/cadence-discord-bot.git
synced 2026-12-03 06:28:53 +00:00
fix!: New folder structure and organize files
This commit is contained in:
1 parent
d92bd329dc
commit
39ff5ecb5d
83 files changed
+244
-246
No files matched your search
@@ -0,0 +1,274 @@
|
||||
import config from 'config';
|
||||
import { GuildQueue, GuildQueueHistory, PlayerTimestamp, Track } from 'discord-player';
|
||||
import {
|
||||
ApplicationCommandOptionChoiceData,
|
||||
AutocompleteInteraction,
|
||||
ChatInputCommandInteraction,
|
||||
EmbedAuthorOptions,
|
||||
EmbedFooterData,
|
||||
GuildMember,
|
||||
Interaction,
|
||||
Message,
|
||||
MessageComponentInteraction,
|
||||
SlashCommandBuilder,
|
||||
SlashCommandSubcommandsOnlyBuilder
|
||||
} from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../services/logger';
|
||||
import { BotOptions, EmbedOptions, PlayerOptions } from '../../types/configTypes';
|
||||
import {
|
||||
BaseAutocompleteParams,
|
||||
BaseAutocompleteReturnType,
|
||||
BaseComponentParams,
|
||||
BaseComponentReturnType,
|
||||
BaseInteractionParams,
|
||||
BaseSlashCommandParams,
|
||||
BaseSlashCommandReturnType
|
||||
} from '../../types/interactionTypes';
|
||||
import { Validator, ValidatorParams } from '../../types/utilTypes';
|
||||
import { TFunction } from 'i18next';
|
||||
|
||||
abstract class BaseInteraction {
|
||||
embedOptions: EmbedOptions;
|
||||
botOptions: BotOptions;
|
||||
playerOptions: PlayerOptions;
|
||||
|
||||
constructor() {
|
||||
this.embedOptions = config.get('embedOptions');
|
||||
this.botOptions = config.get('botOptions');
|
||||
this.playerOptions = config.get('playerOptions');
|
||||
}
|
||||
|
||||
protected getLoggerBase(
|
||||
module: string,
|
||||
name: string,
|
||||
executionId: string,
|
||||
interaction: Interaction | MessageComponentInteraction
|
||||
): Logger {
|
||||
return loggerModule.child({
|
||||
module: module,
|
||||
name: name,
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
}
|
||||
|
||||
protected validators: Validator[] = [];
|
||||
|
||||
protected async runValidators(args: ValidatorParams, validators?: Validator[]): Promise<void> {
|
||||
for (const validator of validators ? validators : this.validators) {
|
||||
await validator(args);
|
||||
}
|
||||
}
|
||||
|
||||
protected getFormattedDuration(track: Track): string {
|
||||
let durationFormat =
|
||||
Number(track.raw.duration) === 0 || track.duration === '0:00' ? '' : `**\`${track.duration}\`**`;
|
||||
|
||||
if (track.raw.live) {
|
||||
durationFormat = `**${this.embedOptions.icons.liveTrack} \`LIVE\`**`;
|
||||
}
|
||||
|
||||
return durationFormat;
|
||||
}
|
||||
|
||||
protected getFormattedTrackUrl(track: Track, translator: TFunction): string {
|
||||
const trackTitle = track.title ?? translator('musicPlayerCommon.unavailableTrackTitle');
|
||||
const trackUrl = track.url ?? track.raw.url;
|
||||
if (!trackTitle || !trackUrl) {
|
||||
return translator('musicPlayerCommon.unavailableTrackUrl');
|
||||
}
|
||||
return `**[${trackTitle}](${trackUrl})**`;
|
||||
}
|
||||
|
||||
protected getDisplayTrackDurationAndUrl(track: Track, translator: TFunction): string {
|
||||
const formattedDuration = this.getFormattedDuration(track);
|
||||
const formattedUrl = this.getFormattedTrackUrl(track, translator);
|
||||
|
||||
return `${formattedDuration} ${formattedUrl}`;
|
||||
}
|
||||
|
||||
protected getTrackThumbnailUrl(track: Track): string {
|
||||
let thumbnailUrl = '';
|
||||
|
||||
if (track.source === 'youtube') {
|
||||
if (track.raw.thumbnail) {
|
||||
// @ts-ignore -- discord-player bug with thumbnail for youtube?
|
||||
thumbnailUrl = track.raw.thumbnail.url;
|
||||
} else if (track.thumbnail && !track.thumbnail.endsWith('maxresdefault.jpg')) {
|
||||
// @ts-ignore -- discord-player bug with thumbnail for youtube?
|
||||
thumbnailUrl = track.thumbnail.url;
|
||||
} else {
|
||||
thumbnailUrl = this.embedOptions.info.fallbackThumbnailUrl;
|
||||
}
|
||||
} else {
|
||||
if (track.raw.thumbnail) {
|
||||
thumbnailUrl = track.raw.thumbnail;
|
||||
} else if (track.thumbnail) {
|
||||
thumbnailUrl = track.thumbnail;
|
||||
} else {
|
||||
thumbnailUrl = this.embedOptions.info.fallbackThumbnailUrl;
|
||||
}
|
||||
}
|
||||
|
||||
return thumbnailUrl;
|
||||
}
|
||||
|
||||
protected getFooterDisplayPageInfo(
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue | GuildQueueHistory,
|
||||
translator: TFunction
|
||||
): EmbedFooterData {
|
||||
const pageIndex: number = (interaction.options.getInteger('page') || 1) - 1;
|
||||
const totalPages: number = Math.ceil(queue.tracks.data.length / 10) || 1;
|
||||
return {
|
||||
text: translator('musicPlayerCommon.footerPageNumber', {
|
||||
page: pageIndex + 1,
|
||||
pageCount: totalPages,
|
||||
count: queue.tracks.data.length
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
protected getDisplayTrackRequestedBy = (track: Track, translator: TFunction): string => {
|
||||
return track.requestedBy
|
||||
? `<@${track.requestedBy.id}>`
|
||||
: translator('musicPlayerCommon.unavailableRequestedBy');
|
||||
};
|
||||
|
||||
protected getDisplayQueueProgressBar(queue: GuildQueue, translator: TFunction): string {
|
||||
const timestamp: PlayerTimestamp = queue.node.getTimestamp()!;
|
||||
let progressBar: string = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
|
||||
queue: false,
|
||||
length: this.playerOptions.progressBar.length ?? 12,
|
||||
timecodes: this.playerOptions.progressBar.timecodes ?? false,
|
||||
indicator: this.playerOptions.progressBar.indicator ?? '🔘',
|
||||
leftChar: this.playerOptions.progressBar.leftChar ?? '▬',
|
||||
rightChar: this.playerOptions.progressBar.rightChar ?? '▬'
|
||||
})} **\`${timestamp.total.label}\`**`;
|
||||
|
||||
if (Number(queue.currentTrack?.raw.duration) === 0 || queue.currentTrack?.duration === '0:00') {
|
||||
progressBar = translator('musicPlayerCommon.unavailableDuration');
|
||||
}
|
||||
|
||||
if (queue.currentTrack?.raw.live) {
|
||||
progressBar = translator('musicPlayerCommon.playingLive', {
|
||||
icon: this.embedOptions.icons.liveTrack
|
||||
});
|
||||
}
|
||||
|
||||
return progressBar;
|
||||
}
|
||||
|
||||
abstract execute(
|
||||
params: BaseInteractionParams
|
||||
): Promise<Message<boolean> | ApplicationCommandOptionChoiceData | void>;
|
||||
}
|
||||
|
||||
abstract class BaseInteractionWithEmbedResponse extends BaseInteraction {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
protected getEmbedUserAuthor(
|
||||
interaction: MessageComponentInteraction | ChatInputCommandInteraction
|
||||
): EmbedAuthorOptions {
|
||||
let authorName: string = '';
|
||||
if (interaction.member instanceof GuildMember) {
|
||||
authorName = interaction.member.nickname || interaction.user.username;
|
||||
} else {
|
||||
authorName = interaction.user.username;
|
||||
}
|
||||
|
||||
return {
|
||||
name: authorName,
|
||||
iconURL: interaction.user.avatarURL() || this.embedOptions.info.fallbackIconUrl
|
||||
};
|
||||
}
|
||||
|
||||
protected getEmbedQueueAuthor(
|
||||
interaction: MessageComponentInteraction | ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
): EmbedAuthorOptions {
|
||||
const bitrate = queue.channel ? queue.channel.bitrate / 1000 : 0;
|
||||
return {
|
||||
name: translator('musicPlayerCommon.voiceChannelInfo', {
|
||||
channel: queue.channel!.name,
|
||||
bitrate
|
||||
}),
|
||||
iconURL: interaction.guild!.iconURL() || this.embedOptions.info.fallbackIconUrl
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class BaseSlashCommandInteraction extends BaseInteractionWithEmbedResponse {
|
||||
data: Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'> | SlashCommandSubcommandsOnlyBuilder;
|
||||
isSystemCommand: boolean;
|
||||
isNew: boolean;
|
||||
isBeta: boolean;
|
||||
name: string;
|
||||
|
||||
constructor(
|
||||
data: Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'> | SlashCommandSubcommandsOnlyBuilder,
|
||||
isSystemCommand: boolean = false,
|
||||
isNew: boolean = false,
|
||||
isBeta: boolean = false
|
||||
) {
|
||||
super();
|
||||
this.data = data.setDMPermission(false).setNSFW(false);
|
||||
this.isSystemCommand = isSystemCommand;
|
||||
this.isNew = isNew;
|
||||
this.isBeta = isBeta;
|
||||
this.name = data.name;
|
||||
}
|
||||
|
||||
protected getLogger(name: string, executionId: string, interaction: ChatInputCommandInteraction): Logger {
|
||||
return super.getLoggerBase('slashCommandInteraction', name, executionId, interaction);
|
||||
}
|
||||
|
||||
abstract execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType;
|
||||
}
|
||||
|
||||
export abstract class BaseComponentInteraction extends BaseInteractionWithEmbedResponse {
|
||||
name: string;
|
||||
|
||||
constructor(name: string) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
protected getLogger(name: string, executionId: string, interaction: MessageComponentInteraction): Logger {
|
||||
return super.getLoggerBase('componentInteraction', name, executionId, interaction);
|
||||
}
|
||||
|
||||
abstract execute(params: BaseComponentParams): BaseComponentReturnType;
|
||||
}
|
||||
|
||||
export abstract class BaseAutocompleteInteraction extends BaseInteraction {
|
||||
name: string;
|
||||
|
||||
constructor(name: string) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
protected getLogger(name: string, executionId: string, interaction: AutocompleteInteraction): Logger {
|
||||
return super.getLoggerBase('autocompleteInteraction', name, executionId, interaction);
|
||||
}
|
||||
|
||||
abstract execute(params: BaseAutocompleteParams): BaseAutocompleteReturnType;
|
||||
}
|
||||
|
||||
export class CustomError extends Error {
|
||||
type?: string;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
export class InteractionValidationError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message);
|
||||
this.name = 'InteractionValidationError';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import Discord, { Client } from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../services/logger';
|
||||
|
||||
export const createClient = async ({ executionId }: { executionId: string }): Promise<Client> => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilFactory',
|
||||
name: 'createClient',
|
||||
executionId: executionId,
|
||||
shardId: 'client'
|
||||
});
|
||||
|
||||
try {
|
||||
logger.debug('Creating discord.js client...');
|
||||
|
||||
const client: Client = new Discord.Client({
|
||||
intents: [Discord.GatewayIntentBits.Guilds, Discord.GatewayIntentBits.GuildVoiceStates],
|
||||
makeCache: Discord.Options.cacheWithLimits({
|
||||
...Discord.Options.DefaultMakeCacheSettings,
|
||||
MessageManager: 25,
|
||||
ThreadManager: 25,
|
||||
PresenceManager: 0,
|
||||
ReactionManager: 0,
|
||||
GuildMemberManager: {
|
||||
maxSize: 50,
|
||||
keepOverLimit: (member) => member.id === client.user?.id
|
||||
}
|
||||
}),
|
||||
sweepers: {
|
||||
...Discord.Options.DefaultSweeperSettings,
|
||||
messages: {
|
||||
interval: 3600,
|
||||
lifetime: 1800
|
||||
},
|
||||
users: {
|
||||
interval: 3600,
|
||||
filter: () => (user) => user.id !== client.user?.id
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return client;
|
||||
} catch (error) {
|
||||
logger.error(error, 'Failed to create discord.js client');
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import config from 'config';
|
||||
import { IPRotationConfig, Player } from 'discord-player';
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../services/logger';
|
||||
import { CreatePlayerParams } from '../../types/playerTypes';
|
||||
|
||||
export const createPlayer = async ({ client, executionId }: CreatePlayerParams): Promise<Player> => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilFactory',
|
||||
name: 'createPlayer',
|
||||
executionId: executionId,
|
||||
shardId: client.shard?.ids[0]
|
||||
});
|
||||
|
||||
const ipRotationConfig = config.get<IPRotationConfig>('ipRotationConfig');
|
||||
|
||||
try {
|
||||
logger.debug('Creating discord-player player...');
|
||||
|
||||
const player: Player = new Player(client, {
|
||||
useLegacyFFmpeg: false,
|
||||
skipFFmpeg: false,
|
||||
ipconfig: ipRotationConfig,
|
||||
ytdlOptions: {
|
||||
quality: 'highestaudio',
|
||||
highWaterMark: 1 << 25,
|
||||
requestOptions: {
|
||||
headers: {
|
||||
cookie: process.env.YT_COOKIE || ''
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// make player accessible from anywhere in the application
|
||||
// primarily to be able to use it in broadcastEval and other sharding methods
|
||||
// @ts-ignore
|
||||
global.player = player;
|
||||
|
||||
await player.extractors.loadDefault();
|
||||
logger.trace(`discord-player loaded dependencies:\n${player.scanDeps()}`);
|
||||
|
||||
return player;
|
||||
} catch (error) {
|
||||
logger.error(error, 'Failed to create discord-player player');
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,115 @@
|
||||
import { usePrismaClient } from './prismaClient';
|
||||
import loggerModule from './logger';
|
||||
import { Logger } from 'pino';
|
||||
import { Interaction, MessageComponentInteraction } from 'discord.js';
|
||||
|
||||
const prisma = usePrismaClient();
|
||||
|
||||
function getLogger(executionId: string, interaction?: Interaction | MessageComponentInteraction): Logger {
|
||||
return loggerModule.child({
|
||||
module: 'databaseService',
|
||||
name: 'guildDatabaseService',
|
||||
executionId: executionId,
|
||||
shardId: interaction?.guild?.shardId ?? 'N/A'
|
||||
});
|
||||
}
|
||||
|
||||
export type GuildConfig = {
|
||||
defaultVolume?: number;
|
||||
locale?: string;
|
||||
actionPermissions?: Record<string, string[]>;
|
||||
};
|
||||
|
||||
const guildDatabaseClient = {
|
||||
async getGuildConfig(
|
||||
guildId: string,
|
||||
executionId: string,
|
||||
interaction?: Interaction | MessageComponentInteraction
|
||||
) {
|
||||
const logger = getLogger(executionId, interaction);
|
||||
logger.debug(`Getting config for guild ${guildId} from database.`);
|
||||
const config = await prisma.guildConfig.findUnique({
|
||||
where: { guildId: guildId }
|
||||
});
|
||||
|
||||
if (!config) {
|
||||
logger.debug(`No config found for guild ${guildId}.`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const response = {
|
||||
...config,
|
||||
actionPermissions: deserializeActionPermissions(config.actionPermissions ?? '')
|
||||
};
|
||||
|
||||
return response;
|
||||
},
|
||||
|
||||
async createOrUpdateGuildConfig(
|
||||
executionId: string,
|
||||
guildId: string,
|
||||
configData: GuildConfig,
|
||||
interaction?: Interaction | MessageComponentInteraction
|
||||
) {
|
||||
const logger = getLogger(executionId, interaction);
|
||||
logger.debug(`Creating or updating guild config for guild ${guildId} in database.`);
|
||||
|
||||
const validConfig = validateGuildConfig(logger, configData);
|
||||
return await prisma.guildConfig.upsert({
|
||||
where: { guildId: guildId },
|
||||
update: {
|
||||
...validConfig
|
||||
},
|
||||
create: {
|
||||
guildId: guildId,
|
||||
...validConfig
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
async deleteGuildConfig(
|
||||
executionId: string,
|
||||
guildId: string,
|
||||
interaction?: Interaction | MessageComponentInteraction
|
||||
) {
|
||||
const logger = getLogger(executionId, interaction);
|
||||
logger.debug(`Deleting guild ${guildId} and config from database.`);
|
||||
|
||||
return await prisma.guildConfig.delete({
|
||||
where: { guildId: guildId }
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export function validateGuildConfig(logger: Logger, configData: GuildConfig) {
|
||||
if (configData.defaultVolume && (configData.defaultVolume < 0 || configData.defaultVolume > 100)) {
|
||||
logger.debug(`defaultVolume ${configData.defaultVolume} is not between 0 and 100`);
|
||||
throw new Error('defaultVolume must be between 0 and 100');
|
||||
}
|
||||
|
||||
// get available locale from i18next?
|
||||
if (configData.locale && !['en-US', 'no', 'ro', 'en-ES'].includes(configData.locale)) {
|
||||
logger.debug(`locale ${configData.locale} is not in list of available locales`);
|
||||
throw new Error(`locale ${configData.locale} is not in list of available locales`);
|
||||
}
|
||||
|
||||
// TODO: validate actionPermissions
|
||||
|
||||
const validConfig = {
|
||||
defaultVolume: configData.defaultVolume,
|
||||
locale: configData.locale,
|
||||
actionPermissions: serializeActionPermissions(configData.actionPermissions ?? {})
|
||||
};
|
||||
|
||||
return validConfig;
|
||||
}
|
||||
|
||||
function serializeActionPermissions(permissions: Record<string, string[]>): string {
|
||||
return JSON.stringify(permissions);
|
||||
}
|
||||
|
||||
function deserializeActionPermissions(serializedPermissions: string): Record<string, string[]> {
|
||||
return JSON.parse(serializedPermissions);
|
||||
}
|
||||
|
||||
export default guildDatabaseClient;
|
||||
@@ -0,0 +1,107 @@
|
||||
/* eslint-disable no-console */
|
||||
import config from 'config';
|
||||
import pino, { DestinationStream, Logger, LoggerOptions } from 'pino';
|
||||
import { CustomLoggerOptions } from '../../types/configTypes';
|
||||
import { TargetOptions } from '../../types/serviceTypes';
|
||||
|
||||
// Retrieve logger options from config
|
||||
const loggerOptions: CustomLoggerOptions = config.get('loggerOptions');
|
||||
|
||||
const targets: TargetOptions[] = [
|
||||
{
|
||||
// This target is used for logging everything above specified minimumLogLevel
|
||||
target: 'pino/file',
|
||||
level: loggerOptions.minimumLogLevel,
|
||||
options: {
|
||||
destination: './logs/app-all.log',
|
||||
mkdir: true,
|
||||
sync: false
|
||||
}
|
||||
},
|
||||
{
|
||||
// This target is used for logging errors separately
|
||||
target: 'pino/file',
|
||||
level: 'error',
|
||||
options: {
|
||||
destination: './logs/app-error.log',
|
||||
mkdir: true,
|
||||
sync: false
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
// Add console logging with pino-pretty if available
|
||||
let pinoPrettyAvailable = false;
|
||||
let pinoLokiAvailable = false;
|
||||
|
||||
try {
|
||||
require.resolve('pino-pretty');
|
||||
pinoPrettyAvailable = true;
|
||||
} catch (e) {
|
||||
console.log('pino-pretty not available. Falling back to default console logging.');
|
||||
console.log('install pino-pretty for better console logging: npm i pino-pretty');
|
||||
}
|
||||
|
||||
try {
|
||||
require.resolve('pino-loki');
|
||||
pinoLokiAvailable = true;
|
||||
} catch (e) {
|
||||
console.log('pino-loki not available. Sending logs to Grafana Loki will be skipped.');
|
||||
}
|
||||
|
||||
if (pinoPrettyAvailable) {
|
||||
targets.push({
|
||||
target: 'pino-pretty',
|
||||
level: loggerOptions.minimumLogLevelConsole,
|
||||
options: {
|
||||
colorize: true,
|
||||
ignore: 'environment,source,module,action,name,context,executionId,executionTime,shardId,guildId,interactionType'
|
||||
}
|
||||
});
|
||||
} else {
|
||||
targets.push({
|
||||
// This target is used for logging to the console
|
||||
target: 'pino/file',
|
||||
level: loggerOptions.minimumLogLevelConsole,
|
||||
options: {
|
||||
colorize: true,
|
||||
sync: false
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Check for Loki credentials and add Loki as a target if present and pino-loki is installed
|
||||
if (pinoLokiAvailable && process.env.LOKI_AUTH_PASSWORD && process.env.LOKI_AUTH_USERNAME) {
|
||||
targets.push({
|
||||
target: 'pino-loki',
|
||||
level: loggerOptions.minimumLogLevel,
|
||||
options: {
|
||||
sync: false,
|
||||
batching: false,
|
||||
interval: 5,
|
||||
|
||||
// Loki host and credentials are retrieved from environment variables
|
||||
host: process.env.LOKI_HOST || 'http://localhost:3100',
|
||||
basicAuth: {
|
||||
username: process.env.LOKI_AUTH_USERNAME || '',
|
||||
password: process.env.LOKI_AUTH_PASSWORD || ''
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const transport: DestinationStream = pino.transport({ targets });
|
||||
|
||||
// Default properties for the logger, these will be added to every log entry
|
||||
const defaultProperties: object = {
|
||||
environment: process.env.NODE_ENV || 'development'
|
||||
};
|
||||
|
||||
const logLevelConfig: LoggerOptions = {
|
||||
level: loggerOptions.minimumLogLevel,
|
||||
timestamp: () => `,"timestamp":"${new Date(Date.now()).toISOString()}"`,
|
||||
base: defaultProperties
|
||||
};
|
||||
|
||||
const logger: Logger = pino(logLevelConfig, transport);
|
||||
export default logger;
|
||||
@@ -0,0 +1,10 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
let prisma: PrismaClient | undefined;
|
||||
|
||||
export const usePrismaClient = () => {
|
||||
if (!prisma) {
|
||||
prisma = new PrismaClient();
|
||||
}
|
||||
return prisma;
|
||||
};
|
||||
File renamed without changes.
@@ -1,6 +1,6 @@
|
||||
import { QueueRepeatMode } from 'discord-player';
|
||||
import { TFunction } from 'i18next';
|
||||
import { EmbedOptions } from '../types/configTypes';
|
||||
import { EmbedOptions } from '../../types/configTypes';
|
||||
|
||||
export function formatDuration(durationMs: number): string {
|
||||
const durationDate: Date = new Date(0);
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
@@ -13,8 +13,10 @@ 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',
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import osu from 'node-os-utils';
|
||||
import { ExtendedClient } from '../types/clientTypes';
|
||||
import { fetchTotalGuildStatistics, fetchTotalPlayerStatistics } from '../utils/shardUtils';
|
||||
import { getUptimeFormatted } from '../utils/system/getUptimeFormatted';
|
||||
import { ExtendedClient } from '../../types/clientTypes';
|
||||
import { fetchTotalGuildStatistics, fetchTotalPlayerStatistics } from './shardUtils';
|
||||
import { getUptimeFormatted } from './getUptimeFormatted';
|
||||
import { TFunction } from 'i18next';
|
||||
|
||||
export async function getBotStatistics(
|
||||
@@ -0,0 +1,137 @@
|
||||
import config from 'config';
|
||||
import {
|
||||
EmbedBuilder,
|
||||
GuildMember,
|
||||
InteractionType,
|
||||
TextBasedChannel,
|
||||
TextChannel,
|
||||
VoiceBasedChannel,
|
||||
VoiceChannel
|
||||
} from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { InteractionValidationError } from '../classes/interactions';
|
||||
import loggerModule from '../services/logger';
|
||||
import { EmbedOptions } from '../../types/configTypes';
|
||||
import { ValidatorParams } from '../../types/utilTypes';
|
||||
import { useServerTranslator } from '../utils/localeUtil';
|
||||
|
||||
const embedOptions: EmbedOptions = config.get('embedOptions');
|
||||
export const checkVoicePermissionJoinAndTalk = async ({ interaction, executionId }: ValidatorParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilValidation',
|
||||
name: 'cannotJoinVoiceOrTalk',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const channel: VoiceBasedChannel | null =
|
||||
interaction.member instanceof GuildMember ? interaction.member.voice.channel : null;
|
||||
const interactionIdentifier =
|
||||
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
|
||||
|
||||
if (channel instanceof VoiceChannel && (!channel.joinable || !channel.speakable)) {
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('validation.cannotJoinVoiceOrTalk', {
|
||||
icon: embedOptions.icons.warning,
|
||||
channel: `<#${channel.id}>`
|
||||
})
|
||||
)
|
||||
.setColor(embedOptions.colors.warning)
|
||||
.setFooter({
|
||||
text:
|
||||
interaction.member instanceof GuildMember
|
||||
? interaction.member.nickname || interaction.user.username
|
||||
: interaction.user.username,
|
||||
iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl
|
||||
})
|
||||
]
|
||||
});
|
||||
|
||||
logger.debug(
|
||||
`User tried to use command '${interactionIdentifier}' but the bot had no permission to join/speak in the voice channel.`
|
||||
);
|
||||
throw new InteractionValidationError('Bot cannot join or speak in voice channel.');
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
|
||||
export const checkChannelPermissionViewable = async ({ interaction, executionId }: ValidatorParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilValidation',
|
||||
name: 'cannotSendMessageInChannel',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const channel: TextBasedChannel | null = interaction.channel;
|
||||
|
||||
const interactionIdentifier =
|
||||
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
|
||||
|
||||
// only checks if channel is viewable, as bot will have permission to send interaction replies if channel is viewable
|
||||
if (channel instanceof TextChannel && !channel.viewable) {
|
||||
logger.info(
|
||||
`User tried to use interaction '${interactionIdentifier}' but the bot has permission to send reply in text channel.`
|
||||
);
|
||||
|
||||
try {
|
||||
// we can still send ephemeral replies in channels we can't view, so sending message to user instead
|
||||
if (!interaction.deferred && !interaction.replied) {
|
||||
logger.debug('Interaction was not deferred or replied to yet. Deferring reply as ephemeral.');
|
||||
await interaction.deferReply({ ephemeral: true });
|
||||
|
||||
logger.debug(
|
||||
'Sending ephemeral message in channel about insufficient permissions to send message in channel.'
|
||||
);
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('validation.cannotSendMessageInChannel', {
|
||||
icon: embedOptions.icons.warning,
|
||||
channel: `<#${channel.id}>`
|
||||
})
|
||||
)
|
||||
.setColor(embedOptions.colors.warning)
|
||||
.setFooter({
|
||||
text:
|
||||
interaction.member instanceof GuildMember
|
||||
? interaction.member.nickname || interaction.user.username
|
||||
: interaction.user.username,
|
||||
iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl
|
||||
})
|
||||
]
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message == 'The reply to this interaction has already been sent or deferred.') {
|
||||
logger.warn(
|
||||
'Error while sending ephemereal message about insufficient permissions to send message in channel.'
|
||||
);
|
||||
logger.debug(error);
|
||||
} else {
|
||||
logger.error(
|
||||
error,
|
||||
'Failed to send ephemeral reply to user in channel that bot cannot view/send message in.'
|
||||
);
|
||||
}
|
||||
} else {
|
||||
logger.debug('Throwing error');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InteractionValidationError('Bot cannot send message in channel.');
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
@@ -0,0 +1,174 @@
|
||||
import config from 'config';
|
||||
import { EmbedBuilder, GuildMember, InteractionType } from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { InteractionValidationError } from '../classes/interactions';
|
||||
import loggerModule from '../services/logger';
|
||||
import { EmbedOptions } from '../../types/configTypes';
|
||||
import { ValidatorParams } from '../../types/utilTypes';
|
||||
import { useServerTranslator } from '../utils/localeUtil';
|
||||
import { formatSlashCommand } from '../utils/formattingUtils';
|
||||
|
||||
const embedOptions: EmbedOptions = config.get('embedOptions');
|
||||
export const checkQueueExists = async ({ interaction, queue, executionId }: ValidatorParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilValidation',
|
||||
name: 'queueDoesNotExist',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const interactionIdentifier =
|
||||
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
|
||||
|
||||
if (!queue) {
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('validation.queueDoesNotExist', {
|
||||
icon: embedOptions.icons.warning,
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
})
|
||||
)
|
||||
.setColor(embedOptions.colors.warning)
|
||||
.setFooter({
|
||||
text:
|
||||
interaction.member instanceof GuildMember
|
||||
? interaction.member.nickname || interaction.user.username
|
||||
: interaction.user.username,
|
||||
iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl
|
||||
})
|
||||
]
|
||||
});
|
||||
|
||||
logger.debug(`User tried to use command '${interactionIdentifier}' but there was no queue.`);
|
||||
throw new InteractionValidationError('Queue does not exist.');
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
|
||||
export const checkHistoryExists = async ({ interaction, history, executionId }: ValidatorParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilValidation',
|
||||
name: 'historyDoesNotExist',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const interactionIdentifier =
|
||||
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
|
||||
|
||||
if (!history) {
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('validation.historyDoesNotExist', {
|
||||
icon: embedOptions.icons.warning,
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
})
|
||||
)
|
||||
.setColor(embedOptions.colors.warning)
|
||||
.setFooter({
|
||||
text:
|
||||
interaction.member instanceof GuildMember
|
||||
? interaction.member.nickname || interaction.user.username
|
||||
: interaction.user.username,
|
||||
iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl
|
||||
})
|
||||
]
|
||||
});
|
||||
|
||||
logger.debug(`User tried to use command '${interactionIdentifier}' but there was no history.`);
|
||||
throw new InteractionValidationError('History does not exist.');
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
|
||||
export const checkQueueCurrentTrack = async ({ interaction, queue, executionId }: ValidatorParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilValidation',
|
||||
name: 'queueNoCurrentTrack',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const interactionIdentifier =
|
||||
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
|
||||
|
||||
if (queue && !queue.currentTrack) {
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('validation.queueNoCurrentTrack', {
|
||||
icon: embedOptions.icons.warning,
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
})
|
||||
)
|
||||
.setColor(embedOptions.colors.warning)
|
||||
.setFooter({
|
||||
text:
|
||||
interaction.member instanceof GuildMember
|
||||
? interaction.member.nickname || interaction.user.username
|
||||
: interaction.user.username,
|
||||
iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl
|
||||
})
|
||||
]
|
||||
});
|
||||
|
||||
logger.debug(`User tried to use command '${interactionIdentifier}' but there was no current track.`);
|
||||
throw new InteractionValidationError('Queue has no current track.');
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
|
||||
export const checkQueueEmpty = async ({ interaction, queue, executionId }: ValidatorParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilValidation',
|
||||
name: 'queueIsEmpty',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const interactionIdentifier =
|
||||
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
|
||||
|
||||
if (queue && queue.tracks.data.length === 0) {
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('validation.queueIsEmpty', {
|
||||
icon: embedOptions.icons.warning,
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
})
|
||||
)
|
||||
.setColor(embedOptions.colors.warning)
|
||||
.setFooter({
|
||||
text:
|
||||
interaction.member instanceof GuildMember
|
||||
? interaction.member.nickname || interaction.user.username
|
||||
: interaction.user.username,
|
||||
iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl
|
||||
})
|
||||
]
|
||||
});
|
||||
|
||||
logger.debug(`User tried to use command '${interactionIdentifier}' but there was no tracks in the queue.`);
|
||||
throw new InteractionValidationError('Queue is empty.');
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../services/logger';
|
||||
import { TransformQueryParams } from '../../types/utilTypes';
|
||||
|
||||
export const transformQuery = ({ query, executionId }: TransformQueryParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilValidation',
|
||||
name: 'transformQuery',
|
||||
executionId: executionId
|
||||
});
|
||||
|
||||
if (query.startsWith('https://open.spotify.com/')) {
|
||||
try {
|
||||
// regex to check for country-based Spotify url
|
||||
const regex: RegExp = new RegExp(
|
||||
'https://open.spotify.com/((?:[a-z]{2,4}-[a-z]{2,4}/)|(?:[a-z]{2,4}/))(track|playlist)/([a-zA-Z0-9]+)'
|
||||
);
|
||||
const isCountryBased: boolean = regex.test(query);
|
||||
|
||||
// if country-based, transform to normal Spotify url
|
||||
if (isCountryBased) {
|
||||
logger.debug(`Transforming country-based Spotify url to normal Spotify url from query '${query}'.`);
|
||||
const matches: RegExpMatchArray | null = query.match(regex);
|
||||
if (matches) {
|
||||
const type: string = matches[2];
|
||||
const trackId: string = matches[3];
|
||||
query = `https://open.spotify.com/${type}/${trackId}`;
|
||||
}
|
||||
}
|
||||
|
||||
// if /track/id is in url TWICE, remove the second one, e.g. https://open.spotify.com/track/123/track/123
|
||||
const trackIdRegex: RegExp = new RegExp('https://open.spotify.com/track/([a-zA-Z0-9]+)');
|
||||
const trackIdMatches: RegExpMatchArray | null = query.match(trackIdRegex);
|
||||
if (trackIdMatches) {
|
||||
logger.debug(`Transforming Spotify url to remove duplicate track id from query '${query}'.`);
|
||||
const trackId: string = trackIdMatches[1];
|
||||
query = `https://open.spotify.com/track/${trackId}`;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error, 'Error while validating or transforming Spotify url.');
|
||||
}
|
||||
}
|
||||
|
||||
return query;
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
import config from 'config';
|
||||
import { EmbedBuilder, InteractionType } from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { InteractionValidationError } from '../classes/interactions';
|
||||
import loggerModule from '../services/logger';
|
||||
import { EmbedOptions, SystemOptions } from '../../types/configTypes';
|
||||
import { ValidatorParams } from '../../types/utilTypes';
|
||||
import { useServerTranslator } from '../utils/localeUtil';
|
||||
import { formatSlashCommand } from '../utils/formattingUtils';
|
||||
|
||||
const embedOptions: EmbedOptions = config.get('embedOptions');
|
||||
const systemOptions: SystemOptions = config.get('systemOptions');
|
||||
export const checkValidGuildId = async ({ interaction, executionId }: ValidatorParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilValidation',
|
||||
name: 'notValidGuildId',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const interactionIdentifier =
|
||||
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
|
||||
|
||||
if (interaction.guildId && !systemOptions.systemGuildIds.includes(interaction.guildId)) {
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('validation.notValidGuildId', {
|
||||
icon: embedOptions.icons.warning,
|
||||
command: formatSlashCommand(interactionIdentifier, translator)
|
||||
})
|
||||
)
|
||||
.setColor(embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
|
||||
logger.debug(
|
||||
`User tried to use command '${interactionIdentifier}' but system command cannot be executed in the specified guild.`
|
||||
);
|
||||
throw new InteractionValidationError('System command cannot be executed in the specified guild.');
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
import config from 'config';
|
||||
import { EmbedBuilder, GuildMember, InteractionType } from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { InteractionValidationError } from '../classes/interactions';
|
||||
import loggerModule from '../services/logger';
|
||||
import { EmbedOptions } from '../../types/configTypes';
|
||||
import { ValidatorParams } from '../../types/utilTypes';
|
||||
import { useServerTranslator } from '../utils/localeUtil';
|
||||
|
||||
const embedOptions: EmbedOptions = config.get('embedOptions');
|
||||
export const checkInVoiceChannel = async ({ interaction, executionId }: ValidatorParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'validator',
|
||||
name: 'notInVoiceChannel',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const interactionIdentifier =
|
||||
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
|
||||
|
||||
if (interaction.member instanceof GuildMember && !interaction.member.voice.channel) {
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('validation.notInVoiceChannel', {
|
||||
icon: embedOptions.icons.warning
|
||||
})
|
||||
)
|
||||
.setColor(embedOptions.colors.warning)
|
||||
.setFooter({
|
||||
text: interaction.member.nickname || interaction.user.username,
|
||||
iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl
|
||||
})
|
||||
]
|
||||
});
|
||||
|
||||
logger.debug(`User tried to use command '${interactionIdentifier}' but was not in a voice channel.`);
|
||||
throw new InteractionValidationError('User not in voice channel.');
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
|
||||
export const checkSameVoiceChannel = async ({ interaction, queue, executionId }: ValidatorParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilValidation',
|
||||
name: 'notInSameVoiceChannel',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const interactionIdentifier =
|
||||
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
|
||||
|
||||
if (!queue || !queue.dispatcher) {
|
||||
// If there is no queue or bot is not in voice channel, then there is no need to check if user is in same voice channel.
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
interaction.member instanceof GuildMember &&
|
||||
interaction.member.voice.channel?.id !== queue.dispatcher.channel.id
|
||||
) {
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('validation.notInSameVoiceChannel', {
|
||||
icon: embedOptions.icons.warning,
|
||||
channel: `<#${queue.dispatcher.channel.id}>`
|
||||
})
|
||||
)
|
||||
.setColor(embedOptions.colors.warning)
|
||||
.setFooter({
|
||||
text: interaction.member.nickname || interaction.user.username,
|
||||
iconURL: interaction.user.avatarURL() || embedOptions.info.fallbackIconUrl
|
||||
})
|
||||
]
|
||||
});
|
||||
|
||||
logger.debug(`User tried to use command '${interactionIdentifier}' but was not in the same voice channel.`);
|
||||
throw new InteractionValidationError('User not in same voice channel.');
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
Reference in new issue
Block a user