fix: more type annotation

This commit is contained in:
Marius Begby committed 2023-08-30 14:12:55 +02:00
1 parent 3ac692d8eb
commit 2560f0fe9a
65 files changed
+408 -343

No files matched your search

+8 -6
View File
@@ -8,12 +8,13 @@ import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../services/logger';
import { SystemOptions } from '../types/configTypes';
import { Logger } from 'pino';
const systemOptions: SystemOptions = config.get('systemOptions');
const executionId = uuidv4();
const executionId: string = uuidv4();
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'deploySlashCommands.js',
module: 'deploy',
name: 'deploySlashCommands',
@@ -24,7 +25,7 @@ const logger = loggerModule.child({
const slashCommands: SlashCommandBuilder[] = [];
const systemCommands: SlashCommandBuilder[] = [];
const commandFolders = fs.readdirSync(path.resolve('./dist/interactions/commands'));
const commandFolders: string[] = fs.readdirSync(path.resolve('./dist/interactions/commands'));
if (!process.env.DISCORD_BOT_TOKEN) {
throw new Error('DISCORD_BOT_TOKEN environment variable is not set.');
@@ -34,7 +35,7 @@ if (!process.env.DISCORD_APPLICATION_ID) {
throw new Error('DISCORD_APPLICATION_ID environment variable is not set.');
}
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN);
const rest: REST = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN);
(async () => {
if (!process.env.DISCORD_APPLICATION_ID || !process.env.DISCORD_BOT_TOKEN) {
@@ -45,11 +46,12 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN)
}
for (const folder of commandFolders) {
const commandFiles = fs
const commandFiles: string[] = fs
.readdirSync(path.resolve(`./dist/interactions/commands/${folder}`))
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
// TODO: create commandModule type
const commandModule = await import(`../interactions/commands/${folder}/${file}`);
const command = commandModule.default;
command.isSystemCommand
@@ -76,7 +78,7 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN)
);
logger.info('Started refreshing system slash commands.');
const systemGuildIds = systemOptions.systemGuildIds;
const systemGuildIds: string[] = systemOptions.systemGuildIds;
await Promise.all(
systemGuildIds.map((systemGuildId: string) => {
logger.debug(`Refreshing system slash command for guild id '${systemGuildId}'.`);
+2 -1
View File
@@ -1,9 +1,10 @@
import Discord, { Client } from 'discord.js';
import loggerModule from '../../services/logger';
import { Logger } from 'pino';
export const createClient = async ({ executionId }: { executionId: string }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'createClient.js',
module: 'utilFactory',
name: 'createClient',
+3 -2
View File
@@ -2,9 +2,10 @@ import { Player } from 'discord-player';
import loggerModule from '../../services/logger';
import { CreatePlayerParams } from '../../types/playerTypes';
import { Logger } from 'pino';
export const createPlayer = async ({ client, executionId }: CreatePlayerParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'createPlayer.js',
module: 'utilFactory',
name: 'createPlayer',
@@ -15,7 +16,7 @@ export const createPlayer = async ({ client, executionId }: CreatePlayerParams)
try {
logger.debug('Creating discord-player player...');
const player = new Player(client, {
const player: Player = new Player(client, {
useLegacyFFmpeg: false,
ytdlOptions: {
quality: 'highestaudio',
+2 -2
View File
@@ -2,10 +2,10 @@ import fs from 'node:fs';
import path from 'node:path';
/* eslint-disable @typescript-eslint/no-var-requires */
const cookies = require(path.resolve('./cookies.json'));
const cookies: { name: string; value: string }[] = require(path.resolve('./cookies.json'));
try {
const cookieString = cookies
const cookieString: string = cookies
.map(({ name, value }: { name: string; value: string }) => {
return `${name}=${value}`;
})
+10 -8
View File
@@ -3,9 +3,11 @@ import https from 'node:https';
import loggerModule from '../../services/logger';
import { PostBotStatsParams, PostBotStatsSite } from '../../types/utilTypes';
import { Logger } from 'pino';
import { ClientRequest, ClientRequestArgs } from 'node:http';
export const postBotStats = async ({ client, executionId }: PostBotStatsParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'postBotStats.js',
module: 'utilOther',
name: 'postBotStats',
@@ -18,16 +20,16 @@ export const postBotStats = async ({ client, executionId }: PostBotStatsParams)
return;
}
let guildCount = 0;
let memberCount = 0;
const shardCount = client.shard.count;
const shardId = client.shard.ids[0];
let guildCount: number = 0;
let memberCount: number = 0;
const shardCount: number = client.shard.count;
const shardId: number = client.shard.ids[0];
logger.debug('Gathering data about guild and member count from shards...');
await client.shard
.fetchClientValues('guilds.cache')
.then((results) => {
const guildCaches = results as Collection<string, Guild>[];
const guildCaches: Collection<string, Guild>[] = results as Collection<string, Guild>[];
guildCaches.map((guildCache) => {
if (guildCache) {
guildCount += guildCache.size;
@@ -132,7 +134,7 @@ export const postBotStats = async ({ client, executionId }: PostBotStatsParams)
return;
}
const options = {
const options: ClientRequestArgs = {
protocol: 'https:',
hostname: site.hostname,
port: 443,
@@ -144,7 +146,7 @@ export const postBotStats = async ({ client, executionId }: PostBotStatsParams)
}
};
const request = https.request(options, (res) => {
const request: ClientRequest = https.request(options, (res) => {
if (typeof res.statusCode === 'number') {
res.statusCode === 200
? logger.debug(`Request to ${site.hostname}: statusCode: ${res.statusCode}`)
+6 -5
View File
@@ -1,6 +1,7 @@
import config from 'config';
import { Client } from 'discord.js';
import { Channel, Client } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { LoadTestOptions } from '../../types/configTypes';
import { StartLoadTestParams } from '../../types/utilTypes';
@@ -8,7 +9,7 @@ import { StartLoadTestParams } from '../../types/utilTypes';
const loadTestOptions: LoadTestOptions = config.get('loadTestOptions');
export const startLoadTest = async ({ client, executionId }: StartLoadTestParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'startLoadTest.js',
module: 'utilOther',
name: 'startLoadTest',
@@ -21,15 +22,15 @@ export const startLoadTest = async ({ client, executionId }: StartLoadTestParams
return;
}
const channelIds = loadTestOptions.channelIdsToJoin;
const track = loadTestOptions.trackUrl;
const channelIds: string[] = loadTestOptions.channelIdsToJoin;
const track: string = loadTestOptions.trackUrl;
logger.info(`Starting load test in ${channelIds.length} specified channels.`);
channelIds.forEach((each) => {
client.shard?.broadcastEval(
async (shardClient: Client, { channelId, track }: { channelId: string; track: string }) => {
const channel = shardClient.channels.cache.get(channelId);
const channel: Channel | undefined = shardClient.channels.cache.get(channelId);
if (channel) {
/* eslint-disable no-undef */
// @ts-ignore
+4 -3
View File
@@ -4,9 +4,10 @@ import path from 'node:path';
import loggerModule from '../services/logger';
import { RegisterClientCommandsParams } from '../types/utilTypes';
import { Logger } from 'pino';
export const registerClientCommands = async ({ client, executionId }: RegisterClientCommandsParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'registerClientCommands.js',
module: 'register',
name: 'registerClientCommands',
@@ -17,10 +18,10 @@ export const registerClientCommands = async ({ client, executionId }: RegisterCl
logger.debug('Registering client commands...');
client.commands = new Collection();
const commandFolders = fs.readdirSync(path.resolve('./dist/interactions/commands'));
const commandFolders: string[] = fs.readdirSync(path.resolve('./dist/interactions/commands'));
for (const folder of commandFolders) {
logger.trace(`Registering client commands for folder '${folder}'...`);
const commandFiles = fs
const commandFiles: string[] = fs
.readdirSync(path.resolve(`./dist/interactions/commands/${folder}`))
.filter((file) => file.endsWith('.js'));
+7 -6
View File
@@ -5,11 +5,12 @@ import path from 'node:path';
import { GuildQueueEvents, Player, PlayerEvents } from 'discord-player';
import { Client } from 'discord.js';
import loggerModule from '../services/logger';
import { LoggerOptions } from '../types/configTypes';
import { CustomLoggerOptions } from '../types/configTypes';
import { ClientEventArguments, PlayerEventArguments, ProcessEventArguments } from '../types/eventTypes';
import { CustomEvent, RegisterEventListenersParams } from '../types/utilTypes';
import { Logger } from 'pino';
const loggerOptions: LoggerOptions = config.get('loggerOptions');
const loggerOptions: CustomLoggerOptions = config.get('loggerOptions');
const registerClientEventListeners = (client: Client, event: CustomEvent) => {
if (event.once) {
@@ -29,7 +30,7 @@ const registerProcessEventListeners = (event: CustomEvent) => {
process.on(event.name, (...args: ProcessEventArguments) => event.execute(...args));
};
const registerPlayerEventListeners = (player: Player, event: CustomEvent, loggerOptions: LoggerOptions) => {
const registerPlayerEventListeners = (player: Player, event: CustomEvent, loggerOptions: CustomLoggerOptions) => {
if (!event.isDebug || (loggerOptions.minimumLogLevel === 'debug' && loggerOptions.discordPlayerDebug)) {
if (event.isPlayerEvent) {
player.events.on(event.name as keyof GuildQueueEvents, (...args: PlayerEventArguments) =>
@@ -42,7 +43,7 @@ const registerPlayerEventListeners = (player: Player, event: CustomEvent, logger
};
export const registerEventListeners = async ({ client, player, executionId }: RegisterEventListenersParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'registerEventListeners.js',
module: 'register',
name: 'registerEventListeners',
@@ -52,11 +53,11 @@ export const registerEventListeners = async ({ client, player, executionId }: Re
logger.debug('Registering event listeners...');
const eventFolders = fs.readdirSync(path.resolve('./dist/events'));
const eventFolders: string[] = fs.readdirSync(path.resolve('./dist/events'));
for (const folder of eventFolders) {
logger.trace(`Registering event listener for folder '${folder}'...`);
const eventFiles = fs
const eventFiles: string[] = fs
.readdirSync(path.resolve(`./dist/events/${folder}`))
.filter((file) => file.endsWith('.js'));
+5 -4
View File
@@ -1,8 +1,9 @@
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { GetUptimeFormattedParams } from '../../types/utilTypes';
export const getUptimeFormatted = async ({ executionId }: GetUptimeFormattedParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'getUptimeFormatted.js',
module: 'utilSystem',
name: 'getUptimeFormatted',
@@ -10,10 +11,10 @@ export const getUptimeFormatted = async ({ executionId }: GetUptimeFormattedPara
});
try {
let uptimeFormattedString = '';
let uptimeFormattedString: string = '';
const uptimeInSeconds = parseFloat(process.uptime().toFixed(0));
const uptimeDate = new Date(0);
const uptimeInSeconds: number = parseFloat(process.uptime().toFixed(0));
const uptimeDate: Date = new Date(0);
uptimeDate.setSeconds(uptimeInSeconds);
uptimeFormattedString = `${
uptimeDate.getUTCDate() - 1
+15 -5
View File
@@ -1,13 +1,22 @@
import config from 'config';
import { EmbedBuilder, GuildMember, InteractionType, TextChannel, VoiceChannel } from 'discord.js';
import {
EmbedBuilder,
GuildMember,
InteractionType,
TextBasedChannel,
TextChannel,
VoiceBasedChannel,
VoiceChannel
} from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import { CannotJoinVoiceOrTalkParams, CannotSendMessageInChannelParams } from '../../types/utilTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: CannotJoinVoiceOrTalkParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'permissionValidator.js',
module: 'utilValidation',
name: 'cannotJoinVoiceOrTalk',
@@ -16,7 +25,8 @@ export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: Cannot
guildId: interaction.guild?.id
});
const channel = interaction.member instanceof GuildMember ? interaction.member.voice.channel : null;
const channel: VoiceBasedChannel | null =
interaction.member instanceof GuildMember ? interaction.member.voice.channel : null;
const interactionIdentifier =
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
@@ -41,7 +51,7 @@ export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: Cannot
};
export const cannotSendMessageInChannel = async ({ interaction, executionId }: CannotSendMessageInChannelParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'permissionValidator.js',
module: 'utilValidation',
name: 'cannotSendMessageInChannel',
@@ -50,7 +60,7 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }: C
guildId: interaction.guild?.id
});
const channel = interaction.channel;
const channel: TextBasedChannel | null = interaction.channel;
const interactionIdentifier =
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
+4 -3
View File
@@ -4,10 +4,11 @@ import { EmbedBuilder, InteractionType } from 'discord.js';
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import { QueueDoesNotExistParams, QueueIsEmptyParams, QueueNoCurrentTrackParams } from '../../types/utilTypes';
import { Logger } from 'pino';
const embedOptions: EmbedOptions = config.get('embedOptions');
export const queueDoesNotExist = async ({ interaction, queue, executionId }: QueueDoesNotExistParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueDoesNotExist',
@@ -38,7 +39,7 @@ export const queueDoesNotExist = async ({ interaction, queue, executionId }: Que
};
export const queueNoCurrentTrack = async ({ interaction, queue, executionId }: QueueNoCurrentTrackParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueNoCurrentTrack',
@@ -69,7 +70,7 @@ export const queueNoCurrentTrack = async ({ interaction, queue, executionId }: Q
};
export const queueIsEmpty = async ({ interaction, queue, executionId }: QueueIsEmptyParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueIsEmpty',
+6 -5
View File
@@ -1,8 +1,9 @@
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { TransformQueryParams } from '../../types/utilTypes';
export const transformQuery = async ({ query, executionId }: TransformQueryParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'searchQueryValidator.js',
module: 'utilValidation',
name: 'transformQuery',
@@ -15,15 +16,15 @@ export const transformQuery = async ({ query, executionId }: TransformQueryParam
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 = regex.test(query);
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 = query.match(regex);
const matches: RegExpMatchArray | null = query.match(regex);
if (matches) {
const type = matches[2];
const trackId = matches[3];
const type: string = matches[2];
const trackId: string = matches[3];
query = `https://open.spotify.com/${type}/${trackId}`;
}
}
@@ -4,11 +4,12 @@ import { EmbedBuilder, InteractionType } from 'discord.js';
import loggerModule from '../../services/logger';
import { EmbedOptions, SystemOptions } from '../../types/configTypes';
import { NotValidGuildIdParams } from '../../types/utilTypes';
import { Logger } from 'pino';
const embedOptions: EmbedOptions = config.get('embedOptions');
const systemOptions: SystemOptions = config.get('systemOptions');
export const notValidGuildId = async ({ interaction, executionId }: NotValidGuildIdParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'systemCommandValidator.js',
module: 'utilValidation',
name: 'notValidGuildId',
@@ -1,13 +1,14 @@
import config from 'config';
import { EmbedBuilder, GuildMember, InteractionType } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import { NotInSameVoiceChannelParams, NotInVoiceChannelParams } from '../../types/utilTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
export const notInVoiceChannel = async ({ interaction, executionId }: NotInVoiceChannelParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'voiceChannelValidator.js',
module: 'validator',
name: 'notInVoiceChannel',
@@ -38,7 +39,7 @@ export const notInVoiceChannel = async ({ interaction, executionId }: NotInVoice
};
export const notInSameVoiceChannel = async ({ interaction, queue, executionId }: NotInSameVoiceChannelParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'voiceChannelValidator.js',
module: 'utilValidation',
name: 'notInSameVoiceChannel',