mirror of
https://github.com/darksaid98/cadence-discord-bot.git
synced 2026-12-03 14:38:49 +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,95 @@
|
||||
import config from 'config';
|
||||
import { REST, RESTPostAPIChatInputApplicationCommandsJSONBody, RouteLike, Routes } from 'discord.js';
|
||||
import 'dotenv/config';
|
||||
import { randomUUID as uuidv4 } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Logger } from 'pino';
|
||||
import { BaseSlashCommandInteraction } from '../common/classes/interactions';
|
||||
import loggerModule from '../common/services/logger';
|
||||
import { SystemOptions } from '../types/configTypes';
|
||||
|
||||
const systemOptions: SystemOptions = config.get('systemOptions');
|
||||
|
||||
const executionId: string = uuidv4();
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'deploy',
|
||||
name: 'deploySlashCommands',
|
||||
executionId: executionId
|
||||
});
|
||||
|
||||
const userSlashCommands: RESTPostAPIChatInputApplicationCommandsJSONBody[] = [];
|
||||
const systemSlashCommands: RESTPostAPIChatInputApplicationCommandsJSONBody[] = [];
|
||||
|
||||
if (!process.env.DISCORD_BOT_TOKEN) {
|
||||
throw new Error('DISCORD_BOT_TOKEN environment variable is not set.');
|
||||
}
|
||||
|
||||
if (!process.env.DISCORD_APPLICATION_ID) {
|
||||
throw new Error('DISCORD_APPLICATION_ID environment variable is not set.');
|
||||
}
|
||||
|
||||
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) {
|
||||
logger.error(
|
||||
'Missing required environment variables for deployment.\nPlease provide valid DISCORD_APPLICATION_ID and DISCORD_BOT_TOKEN in .env file.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const commandFiles: string[] = fs
|
||||
.readdirSync(path.resolve('./dist/interactions/slashcommands'))
|
||||
.filter((file) => file.endsWith('.js'));
|
||||
|
||||
for (const file of commandFiles) {
|
||||
const { default: command } = await import(`../interactions/slashcommands/${file}`);
|
||||
const slashCommand = command as BaseSlashCommandInteraction;
|
||||
slashCommand.isSystemCommand
|
||||
? systemSlashCommands.push(slashCommand.data.toJSON())
|
||||
: userSlashCommands.push(slashCommand.data.toJSON());
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(
|
||||
`Bot user slash commands found: ${userSlashCommands.map((command) => `/${command.name}`).join(', ')}`
|
||||
);
|
||||
|
||||
logger.info('Started refreshing user slash commands.');
|
||||
await refreshCommands(Routes.applicationCommands(process.env.DISCORD_APPLICATION_ID!), userSlashCommands);
|
||||
logger.info('Successfully refreshed user slash commands.');
|
||||
} catch (error) {
|
||||
logger.error(error, 'Failed to refresh user slash commands.');
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(
|
||||
`Bot system slash commands found: ${systemSlashCommands
|
||||
.map((systemCommand) => `/${systemCommand.name}`)
|
||||
.join(', ')}`
|
||||
);
|
||||
|
||||
logger.info('Started refreshing system slash commands.');
|
||||
const systemGuildIds: string[] = systemOptions.systemGuildIds;
|
||||
await Promise.all(
|
||||
systemGuildIds.map((systemGuildId: string) => {
|
||||
logger.debug(`Refreshing system slash command for guild id '${systemGuildId}'.`);
|
||||
refreshCommands(
|
||||
Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID!, systemGuildId),
|
||||
systemSlashCommands
|
||||
);
|
||||
})
|
||||
);
|
||||
logger.info('Successfully refreshed system slash commands.');
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
error,
|
||||
"Failed to refresh system slash commands. Make sure the bot is in the system guilds specified in 'systemOptions'."
|
||||
);
|
||||
}
|
||||
})();
|
||||
|
||||
async function refreshCommands(route: RouteLike, commands: object[]) {
|
||||
await rest.put(route, { body: commands });
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { Client } from 'discord.js';
|
||||
import { ClientRequest, ClientRequestArgs, IncomingMessage } from 'node:http';
|
||||
import https from 'node:https';
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../common/services/logger';
|
||||
import { PostBotStatsParams, PostBotStatsSite } from '../types/utilTypes';
|
||||
import { fetchTotalGuildStatistics } from '../common/utils/shardUtils';
|
||||
|
||||
export const postBotStats = async ({ client, executionId }: PostBotStatsParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilOther',
|
||||
name: 'postBotStats',
|
||||
executionId: executionId,
|
||||
shardId: client.shard?.ids[0]
|
||||
});
|
||||
|
||||
const shardId: number = client.shard!.ids[0];
|
||||
|
||||
if (shardId !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
logger.debug('Not posting bot stats because NODE_ENV is not production.');
|
||||
return;
|
||||
}
|
||||
|
||||
const shardCount: number = client.shard!.count;
|
||||
const { guildCount, memberCount } = await fetchGuildAndMemberCounts(client, logger);
|
||||
|
||||
const botSites: PostBotStatsSite[] = createSites(shardId, shardCount, guildCount, memberCount);
|
||||
|
||||
try {
|
||||
const enabledSites = botSites.filter((site) => site.enabled);
|
||||
|
||||
if (enabledSites.length === 0) {
|
||||
logger.debug('No sites are enabled. Not posting bot stats.');
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`Starting to post bot stats with guild count ${guildCount} and member count ${memberCount} for ${enabledSites.length} sites...`
|
||||
);
|
||||
|
||||
await postStatsToSites(enabledSites, logger);
|
||||
} catch (error) {
|
||||
logger.error(error, 'Failed to post bot stats to sites.');
|
||||
}
|
||||
};
|
||||
|
||||
async function fetchGuildAndMemberCounts(client: Client, logger: Logger) {
|
||||
let guildCount = 0;
|
||||
let memberCount = 0;
|
||||
|
||||
try {
|
||||
logger.debug('Gathering data about guild and member count from shards...');
|
||||
const { totalGuildCount, totalMemberCount } = await fetchTotalGuildStatistics(client);
|
||||
guildCount = totalGuildCount;
|
||||
memberCount = totalMemberCount;
|
||||
} catch (error) {
|
||||
logger.error(error, 'Failed to gather data about guild and member count from shards.');
|
||||
}
|
||||
|
||||
return { guildCount, memberCount };
|
||||
}
|
||||
|
||||
async function postStatsToSites(enabledSites: PostBotStatsSite[], logger: Logger) {
|
||||
const statusPromises = enabledSites.map((site) => {
|
||||
return new Promise<number | null>((resolve, reject) => {
|
||||
const options: ClientRequestArgs = {
|
||||
protocol: 'https:',
|
||||
hostname: site.hostname,
|
||||
port: 443,
|
||||
path: site.path,
|
||||
method: site.method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: site.token
|
||||
}
|
||||
};
|
||||
|
||||
const request: ClientRequest = https.request(options, (res) => {
|
||||
const statusCode = handleResponse(res, site, logger);
|
||||
resolve(statusCode);
|
||||
});
|
||||
|
||||
request.on('error', (error) => {
|
||||
logger.error(error, `Request to ${site.hostname} failed.`);
|
||||
reject(error);
|
||||
});
|
||||
|
||||
request.write(JSON.stringify(site.body));
|
||||
request.end();
|
||||
});
|
||||
});
|
||||
|
||||
const statusCodes = await Promise.all(statusPromises);
|
||||
logger.info(`Successfully posted bot stats with status codes ${statusCodes.join(', ')}.`);
|
||||
}
|
||||
|
||||
function handleResponse(res: IncomingMessage, site: PostBotStatsSite, logger: Logger): number | null {
|
||||
if (typeof res.statusCode === 'number') {
|
||||
res.statusCode === 200
|
||||
? logger.debug(`Request to ${site.hostname}: statusCode: ${res.statusCode}`)
|
||||
: logger.warn(`Request to ${site.hostname}: statusCode: ${res.statusCode}`);
|
||||
return res.statusCode;
|
||||
} else {
|
||||
logger.error(`Request to ${site.hostname}: statusCode is undefined or not a number (${res.statusCode}).`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function createSites(shardId: number, shardCount: number, guildCount: number, memberCount: number): PostBotStatsSite[] {
|
||||
/* eslint-disable camelcase */
|
||||
return [
|
||||
{
|
||||
enabled: process.env.BOTLIST_TOP_GG_API_TOKEN ? true : false,
|
||||
hostname: 'top.gg',
|
||||
path: `/api/bots/${process.env.DISCORD_APPLICATION_ID}/stats`,
|
||||
method: 'POST',
|
||||
body: {
|
||||
shard_id: shardId,
|
||||
shard_count: shardCount,
|
||||
server_count: guildCount
|
||||
},
|
||||
token: process.env.BOTLIST_TOP_GG_API_TOKEN ?? ''
|
||||
},
|
||||
{
|
||||
enabled: process.env.BOTLIST_DISCORD_BOT_LIST_COM_API_TOKEN ? true : false,
|
||||
hostname: 'discordbotlist.com',
|
||||
path: `/api/v1/bots/${process.env.DISCORD_APPLICATION_ID}/stats`,
|
||||
method: 'POST',
|
||||
body: {
|
||||
shard_id: shardId,
|
||||
users: memberCount,
|
||||
guilds: guildCount
|
||||
},
|
||||
token: process.env.BOTLIST_DISCORD_BOT_LIST_COM_API_TOKEN ?? ''
|
||||
},
|
||||
{
|
||||
enabled: process.env.BOTLIST_DISCORDS_COM_API_TOKEN ? true : false,
|
||||
hostname: 'discords.com',
|
||||
path: `/bots/api/bot/${process.env.DISCORD_APPLICATION_ID}`,
|
||||
method: 'POST',
|
||||
body: {
|
||||
server_count: guildCount
|
||||
},
|
||||
token: process.env.BOTLIST_DISCORDS_COM_API_TOKEN ?? ''
|
||||
},
|
||||
{
|
||||
enabled: process.env.BOTLIST_DISCORD_BOTS_GG_API_TOKEN ? true : false,
|
||||
hostname: 'discord.bots.gg',
|
||||
path: `/api/v1/bots/${process.env.DISCORD_APPLICATION_ID}/stats`,
|
||||
method: 'POST',
|
||||
body: {
|
||||
shardId: shardId,
|
||||
shardCount: shardCount,
|
||||
guildCount: guildCount
|
||||
},
|
||||
token: process.env.BOTLIST_DISCORD_BOTS_GG_API_TOKEN ?? ''
|
||||
},
|
||||
{
|
||||
enabled: process.env.BOTLIST_BOTLIST_ME_API_TOKEN ? true : false,
|
||||
hostname: 'api.botlist.me',
|
||||
path: `/api/v1/bots/${process.env.DISCORD_APPLICATION_ID}/stats`,
|
||||
method: 'POST',
|
||||
body: {
|
||||
shard_count: shardCount,
|
||||
server_count: guildCount
|
||||
},
|
||||
token: process.env.BOTLIST_BOTLIST_ME_API_TOKEN ?? ''
|
||||
},
|
||||
{
|
||||
enabled: process.env.BOTLIST_DISCORDLIST_GG_API_TOKEN ? true : false,
|
||||
hostname: 'api.discordlist.gg',
|
||||
path: `/v0/bots/${process.env.DISCORD_APPLICATION_ID}/guilds`,
|
||||
method: 'POST',
|
||||
body: {
|
||||
count: guildCount
|
||||
},
|
||||
token: `Bearer ${process.env.BOTLIST_DISCORDLIST_GG_API_TOKEN}`
|
||||
},
|
||||
{
|
||||
enabled: process.env.BOTLIST_DISCORD_BOTLIST_EU_API_TOKEN ? true : false,
|
||||
hostname: 'api.discord-botlist.eu',
|
||||
path: '/v1/update',
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
serverCount: guildCount
|
||||
},
|
||||
token: `Bearer ${process.env.BOTLIST_DISCORD_BOTLIST_EU_API_TOKEN}`
|
||||
}
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Collection } from 'discord.js';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../common/services/logger';
|
||||
import { ExtendedClient } from '../types/clientTypes';
|
||||
import { RegisterClientInteractionsParams } from '../types/utilTypes';
|
||||
|
||||
export const registerClientInteractions = async ({ client, executionId }: RegisterClientInteractionsParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'register',
|
||||
name: 'registerClientInteractions',
|
||||
executionId: executionId,
|
||||
shardId: client.shard?.ids[0]
|
||||
});
|
||||
|
||||
await registerSlashCommandInteractions(logger, client);
|
||||
await registerAutocompleteInteractions(logger, client);
|
||||
await registerComponentInteractions(logger, client);
|
||||
|
||||
logger.debug('Registering all client interactions complete.');
|
||||
};
|
||||
|
||||
async function registerSlashCommandInteractions(logger: Logger, client: ExtendedClient): Promise<void> {
|
||||
logger.debug('Registering client slash command interactions...');
|
||||
client.slashCommandInteractions = new Collection();
|
||||
|
||||
const basePath = './dist/interactions/slashcommands';
|
||||
|
||||
logger.trace('Registering client commands...');
|
||||
|
||||
const files: string[] = fs.readdirSync(path.resolve(`${basePath}`)).filter((file) => file.endsWith('.js'));
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const filePath = path.resolve(`${basePath}/${file}`);
|
||||
|
||||
// delete require cache for file
|
||||
delete require.cache[filePath];
|
||||
|
||||
// import and register to client collection
|
||||
const { default: slashCommandInteraction } = await import(filePath);
|
||||
client.slashCommandInteractions.delete(slashCommandInteraction.name);
|
||||
client.slashCommandInteractions.set(slashCommandInteraction.name, slashCommandInteraction);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(`Error registering slash command interaction '${file}': ${error.message}`);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.trace('Registering client slash command interactions complete.');
|
||||
}
|
||||
|
||||
async function registerAutocompleteInteractions(logger: Logger, client: ExtendedClient): Promise<void> {
|
||||
logger.debug('Registering client autocomplete interactions...');
|
||||
client.autocompleteInteractions = new Collection();
|
||||
|
||||
const baseFolderPath = './dist/interactions/autocomplete';
|
||||
const files: string[] = fs.readdirSync(path.resolve(`${baseFolderPath}`)).filter((file) => file.endsWith('.js'));
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const filePath = path.resolve(`${baseFolderPath}/${file}`);
|
||||
|
||||
// delete require cache for file
|
||||
delete require.cache[filePath];
|
||||
|
||||
// import and register to client collection
|
||||
const { default: autocompleteInteraction } = await import(filePath);
|
||||
client.autocompleteInteractions.delete(autocompleteInteraction.name);
|
||||
client.autocompleteInteractions.set(autocompleteInteraction.name, autocompleteInteraction);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(`Error registering autocomplete interaction '${file}': ${error.message}`);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.trace('Registering client autocomplete interactions complete.');
|
||||
}
|
||||
|
||||
async function registerComponentInteractions(logger: Logger, client: ExtendedClient): Promise<void> {
|
||||
logger.debug('Registering client component interactions...');
|
||||
client.componentInteractions = new Collection();
|
||||
|
||||
const baseFolderPath = './dist/interactions/components';
|
||||
const files: string[] = fs.readdirSync(path.resolve(`${baseFolderPath}`)).filter((file) => file.endsWith('.js'));
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const filePath = path.resolve(`${baseFolderPath}/${file}`);
|
||||
|
||||
// delete require cache for file
|
||||
delete require.cache[filePath];
|
||||
|
||||
// import and register to client collection
|
||||
const { default: componentInteraction } = await import(filePath);
|
||||
client.componentInteractions.delete(componentInteraction.name);
|
||||
client.componentInteractions.set(componentInteraction.name, componentInteraction);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(`Error registering component interaction '${file}': ${error.message}`);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.trace('Registering client component interactions complete.');
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import config from 'config';
|
||||
import { GuildQueueEvents, Player, PlayerEvents } from 'discord-player';
|
||||
import { Client } from 'discord.js';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../common/services/logger';
|
||||
import { CustomLoggerOptions } from '../types/configTypes';
|
||||
import { ClientEventArguments, PlayerEventArguments, ProcessEventArguments } from '../types/eventTypes';
|
||||
import { CustomEvent, RegisterEventListenersParams } from '../types/utilTypes';
|
||||
|
||||
const loggerOptions: CustomLoggerOptions = config.get('loggerOptions');
|
||||
|
||||
const registerClientEventListeners = (client: Client, event: CustomEvent) => {
|
||||
if (event.once) {
|
||||
client.once(event.name, (...args: ClientEventArguments) => event.execute(...args));
|
||||
} else {
|
||||
if (!event.isDebug || process.env.MINIMUM_LOG_LEVEL === 'debug') {
|
||||
client.on(event.name, (...args: ClientEventArguments) => event.execute(...args));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const registerInteractionEventListeners = (client: Client, event: CustomEvent) => {
|
||||
client.on(event.name, (...args: ClientEventArguments) => event.execute(...args, { client }));
|
||||
};
|
||||
|
||||
const registerProcessEventListeners = (event: CustomEvent) => {
|
||||
process.on(event.name, (...args: ProcessEventArguments) => event.execute(...args));
|
||||
};
|
||||
|
||||
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) =>
|
||||
event.execute(...args)
|
||||
);
|
||||
} else {
|
||||
player.on(event.name as keyof PlayerEvents, (...args: PlayerEventArguments) => event.execute(...args));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const registerEventListeners = async ({ client, player, executionId }: RegisterEventListenersParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'register',
|
||||
name: 'registerEventListeners',
|
||||
executionId: executionId,
|
||||
shardId: client.shard?.ids[0]
|
||||
});
|
||||
|
||||
logger.debug('Registering event listeners...');
|
||||
|
||||
const eventFolders: string[] = fs.readdirSync(path.resolve('./dist/events'));
|
||||
for (const folder of eventFolders) {
|
||||
logger.trace(`Registering event listener for folder '${folder}'...`);
|
||||
|
||||
const eventFiles: string[] = fs
|
||||
.readdirSync(path.resolve(`./dist/events/${folder}`))
|
||||
.filter((file) => file.endsWith('.js'));
|
||||
|
||||
for (const file of eventFiles) {
|
||||
const event = await import(`../events/${folder}/${file}`);
|
||||
switch (folder) {
|
||||
case 'client':
|
||||
registerClientEventListeners(client, event);
|
||||
break;
|
||||
|
||||
case 'interactions':
|
||||
registerInteractionEventListeners(client, event);
|
||||
break;
|
||||
|
||||
case 'process':
|
||||
registerProcessEventListeners(event);
|
||||
break;
|
||||
|
||||
case 'player':
|
||||
registerPlayerEventListeners(player, event, loggerOptions);
|
||||
break;
|
||||
|
||||
default:
|
||||
logger.error(`Unknown event folder '${folder}' while trying to register events.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.trace('Registering event listeners complete.');
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
import config from 'config';
|
||||
import { Channel, Client } from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../common/services/logger';
|
||||
import { LoadTestOptions } from '../types/configTypes';
|
||||
import { StartLoadTestParams } from '../types/utilTypes';
|
||||
|
||||
const loadTestOptions: LoadTestOptions = config.get('loadTestOptions');
|
||||
|
||||
export const startLoadTest = async ({ client, executionId }: StartLoadTestParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
module: 'utilOther',
|
||||
name: 'startLoadTest',
|
||||
executionId: executionId,
|
||||
shardId: client.shard?.ids[0]
|
||||
});
|
||||
|
||||
if (!loadTestOptions.enabled) {
|
||||
logger.debug('Load test is disabled in options, cancelling.');
|
||||
return;
|
||||
}
|
||||
|
||||
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: Channel | undefined = shardClient.channels.cache.get(channelId);
|
||||
if (channel) {
|
||||
/* eslint-disable no-undef */
|
||||
// @ts-ignore
|
||||
await player.play(channel.id, track, {
|
||||
nodeOptions: {
|
||||
leaveOnEmpty: false,
|
||||
leaveOnEnd: false,
|
||||
leaveOnStop: false,
|
||||
metadata: {
|
||||
channel: channel,
|
||||
client: shardClient
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
{ context: { channelId: each, track: track } }
|
||||
);
|
||||
});
|
||||
|
||||
logger.info('Load test started across shards in specified channels.');
|
||||
};
|
||||
Reference in new issue
Block a user