mirror of
https://github.com/ahmadk953/poixpixel-discord-bot.git
synced 2025-04-02 09:44:14 +00:00
Added code coments, refactored db.ts and redis.ts, and added two new commands
This commit is contained in:
parent
b3fbd2358b
commit
890ca26c78
30 changed files with 1899 additions and 462 deletions
2
.github/workflows/npm-build-and-compile.yml
vendored
2
.github/workflows/npm-build-and-compile.yml
vendored
|
@ -12,7 +12,7 @@ jobs:
|
||||||
|
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
node-version: [21.x]
|
node-version: [23.x]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
|
@ -20,4 +20,8 @@ Compile: ``yarn compile``
|
||||||
|
|
||||||
Start: ``yarn target``
|
Start: ``yarn target``
|
||||||
|
|
||||||
Build & Start: ``yarn start``
|
Build & Start (dev): ``yarn start:dev``
|
||||||
|
|
||||||
|
Build & Start (prod): ``yarn start:prod``
|
||||||
|
|
||||||
|
Restart (works only when the bot is started with ``yarn start:prod``): ``yarn restart``
|
||||||
|
|
|
@ -2,8 +2,16 @@
|
||||||
"token": "DISCORD_BOT_API_KEY",
|
"token": "DISCORD_BOT_API_KEY",
|
||||||
"clientId": "DISCORD_BOT_ID",
|
"clientId": "DISCORD_BOT_ID",
|
||||||
"guildId": "DISCORD_SERVER_ID",
|
"guildId": "DISCORD_SERVER_ID",
|
||||||
"dbConnectionString": "POSTGRESQL_CONNECTION_STRING",
|
"database": {
|
||||||
"redisConnectionString": "REDIS_CONNECTION_STRING",
|
"dbConnectionString": "POSTGRESQL_CONNECTION_STRING",
|
||||||
|
"maxRetryAttempts": "MAX_RETRY_ATTEMPTS",
|
||||||
|
"retryDelay": "RETRY_DELAY_IN_MS"
|
||||||
|
},
|
||||||
|
"redis": {
|
||||||
|
"redisConnectionString": "REDIS_CONNECTION_STRING",
|
||||||
|
"retryAttempts": "RETRY_ATTEMPTS",
|
||||||
|
"initialRetryDelay": "INITIAL_RETRY_DELAY_IN_MS"
|
||||||
|
},
|
||||||
"channels": {
|
"channels": {
|
||||||
"welcome": "WELCOME_CHANNEL_ID",
|
"welcome": "WELCOME_CHANNEL_ID",
|
||||||
"logs": "LOG_CHANNEL_ID",
|
"logs": "LOG_CHANNEL_ID",
|
||||||
|
@ -45,5 +53,10 @@
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"factPingRole": "FACT_OF_THE_DAY_ROLE_ID"
|
"factPingRole": "FACT_OF_THE_DAY_ROLE_ID"
|
||||||
|
},
|
||||||
|
"leveling": {
|
||||||
|
"xpCooldown": "XP_COOLDOWN_IN_SECONDS",
|
||||||
|
"minXpAwarded": "MINIMUM_XP_AWARDED",
|
||||||
|
"maxXpAwarded": "MAXIMUM_XP_AWARDED"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,7 +9,9 @@
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"compile": "npx tsc",
|
"compile": "npx tsc",
|
||||||
"target": "node ./target/discord-bot.js",
|
"target": "node ./target/discord-bot.js",
|
||||||
"start": "yarn run compile && yarn run target",
|
"start:dev": "yarn run compile && yarn run target",
|
||||||
|
"start:prod": "yarn compile && pm2 start ./target/discord-bot.js --name poixpixel-discord-bot",
|
||||||
|
"restart": "pm2 restart poixpixel-discord-bot",
|
||||||
"lint": "npx eslint ./src && npx tsc --noEmit",
|
"lint": "npx eslint ./src && npx tsc --noEmit",
|
||||||
"format": "prettier --check --ignore-path .prettierignore .",
|
"format": "prettier --check --ignore-path .prettierignore .",
|
||||||
"format:fix": "prettier --write --ignore-path .prettierignore ."
|
"format:fix": "prettier --write --ignore-path .prettierignore ."
|
||||||
|
|
|
@ -19,7 +19,7 @@ const command: Command = {
|
||||||
execute: async (interaction) => {
|
execute: async (interaction) => {
|
||||||
let members = await getAllMembers();
|
let members = await getAllMembers();
|
||||||
members = members.sort((a, b) =>
|
members = members.sort((a, b) =>
|
||||||
a.discordUsername.localeCompare(b.discordUsername),
|
(a.discordUsername ?? '').localeCompare(b.discordUsername ?? ''),
|
||||||
);
|
);
|
||||||
|
|
||||||
const ITEMS_PER_PAGE = 15;
|
const ITEMS_PER_PAGE = 15;
|
||||||
|
|
203
src/commands/util/reconnect.ts
Normal file
203
src/commands/util/reconnect.ts
Normal file
|
@ -0,0 +1,203 @@
|
||||||
|
import {
|
||||||
|
CommandInteraction,
|
||||||
|
PermissionsBitField,
|
||||||
|
SlashCommandBuilder,
|
||||||
|
} from 'discord.js';
|
||||||
|
|
||||||
|
import { SubcommandCommand } from '../../types/CommandTypes.js';
|
||||||
|
import { loadConfig } from '../../util/configLoader.js';
|
||||||
|
import {
|
||||||
|
initializeDatabaseConnection,
|
||||||
|
ensureDbInitialized,
|
||||||
|
} from '../../db/db.js';
|
||||||
|
import { isRedisConnected } from '../../db/redis.js';
|
||||||
|
import {
|
||||||
|
NotificationType,
|
||||||
|
notifyManagers,
|
||||||
|
} from '../../util/notificationHandler.js';
|
||||||
|
|
||||||
|
const command: SubcommandCommand = {
|
||||||
|
data: new SlashCommandBuilder()
|
||||||
|
.setName('reconnect')
|
||||||
|
.setDescription('(Manager Only) Force reconnection to database or Redis')
|
||||||
|
.addSubcommand((subcommand) =>
|
||||||
|
subcommand
|
||||||
|
.setName('database')
|
||||||
|
.setDescription('(Manager Only) Force reconnection to the database'),
|
||||||
|
)
|
||||||
|
.addSubcommand((subcommand) =>
|
||||||
|
subcommand
|
||||||
|
.setName('redis')
|
||||||
|
.setDescription('(Manager Only) Force reconnection to Redis cache'),
|
||||||
|
)
|
||||||
|
.addSubcommand((subcommand) =>
|
||||||
|
subcommand
|
||||||
|
.setName('status')
|
||||||
|
.setDescription(
|
||||||
|
'(Manager Only) Check connection status of database and Redis',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
execute: async (interaction) => {
|
||||||
|
if (!interaction.isChatInputCommand()) return;
|
||||||
|
|
||||||
|
const config = loadConfig();
|
||||||
|
const managerRoleId = config.roles.staffRoles.find(
|
||||||
|
(role) => role.name === 'Manager',
|
||||||
|
)?.roleId;
|
||||||
|
|
||||||
|
const member = await interaction.guild?.members.fetch(interaction.user.id);
|
||||||
|
const hasManagerRole = member?.roles.cache.has(managerRoleId || '');
|
||||||
|
|
||||||
|
if (
|
||||||
|
!hasManagerRole &&
|
||||||
|
!interaction.memberPermissions?.has(
|
||||||
|
PermissionsBitField.Flags.Administrator,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
await interaction.reply({
|
||||||
|
content:
|
||||||
|
'You do not have permission to use this command. This command is restricted to users with the Manager role.',
|
||||||
|
flags: ['Ephemeral'],
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const subcommand = interaction.options.getSubcommand();
|
||||||
|
|
||||||
|
await interaction.deferReply({ flags: ['Ephemeral'] });
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (subcommand === 'database') {
|
||||||
|
await handleDatabaseReconnect(interaction);
|
||||||
|
} else if (subcommand === 'redis') {
|
||||||
|
await handleRedisReconnect(interaction);
|
||||||
|
} else if (subcommand === 'status') {
|
||||||
|
await handleStatusCheck(interaction);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error in reconnect command (${subcommand}):`, error);
|
||||||
|
await interaction.editReply({
|
||||||
|
content: `An error occurred while processing the reconnect command: \`${error}\``,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle database reconnection
|
||||||
|
*/
|
||||||
|
async function handleDatabaseReconnect(interaction: CommandInteraction) {
|
||||||
|
await interaction.editReply('Attempting to reconnect to the database...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const success = await initializeDatabaseConnection();
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
await interaction.editReply(
|
||||||
|
'✅ **Database reconnection successful!** All database functions should now be operational.',
|
||||||
|
);
|
||||||
|
|
||||||
|
notifyManagers(
|
||||||
|
interaction.client,
|
||||||
|
NotificationType.DATABASE_CONNECTION_RESTORED,
|
||||||
|
`Database connection manually restored by ${interaction.user.tag}`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await interaction.editReply(
|
||||||
|
'❌ **Database reconnection failed.** Check the logs for more details.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error reconnecting to database:', error);
|
||||||
|
await interaction.editReply(
|
||||||
|
`❌ **Database reconnection failed with error:** \`${error}\``,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle Redis reconnection
|
||||||
|
*/
|
||||||
|
async function handleRedisReconnect(interaction: CommandInteraction) {
|
||||||
|
await interaction.editReply('Attempting to reconnect to Redis...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const redisModule = await import('../../db/redis.js');
|
||||||
|
|
||||||
|
await redisModule.ensureRedisConnection();
|
||||||
|
|
||||||
|
const isConnected = redisModule.isRedisConnected();
|
||||||
|
|
||||||
|
if (isConnected) {
|
||||||
|
await interaction.editReply(
|
||||||
|
'✅ **Redis reconnection successful!** Cache functionality is now available.',
|
||||||
|
);
|
||||||
|
|
||||||
|
notifyManagers(
|
||||||
|
interaction.client,
|
||||||
|
NotificationType.REDIS_CONNECTION_RESTORED,
|
||||||
|
`Redis connection manually restored by ${interaction.user.tag}`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await interaction.editReply(
|
||||||
|
'❌ **Redis reconnection failed.** The bot will continue to function without caching capabilities.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error reconnecting to Redis:', error);
|
||||||
|
await interaction.editReply(
|
||||||
|
`❌ **Redis reconnection failed with error:** \`${error}\``,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle status check for both services
|
||||||
|
*/
|
||||||
|
async function handleStatusCheck(interaction: any) {
|
||||||
|
await interaction.editReply('Checking connection status...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const dbStatus = await (async () => {
|
||||||
|
try {
|
||||||
|
await ensureDbInitialized();
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
const redisStatus = isRedisConnected();
|
||||||
|
|
||||||
|
const statusEmbed = {
|
||||||
|
title: '🔌 Service Connection Status',
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: 'Database',
|
||||||
|
value: dbStatus ? '✅ Connected' : '❌ Disconnected',
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Redis Cache',
|
||||||
|
value: redisStatus
|
||||||
|
? '✅ Connected'
|
||||||
|
: '⚠️ Disconnected (caching disabled)',
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
color:
|
||||||
|
dbStatus && redisStatus ? 0x00ff00 : dbStatus ? 0xffaa00 : 0xff0000,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
await interaction.editReply({ content: '', embeds: [statusEmbed] });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error checking connection status:', error);
|
||||||
|
await interaction.editReply(
|
||||||
|
`❌ **Error checking connection status:** \`${error}\``,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default command;
|
93
src/commands/util/restart.ts
Normal file
93
src/commands/util/restart.ts
Normal file
|
@ -0,0 +1,93 @@
|
||||||
|
import { PermissionsBitField, SlashCommandBuilder } from 'discord.js';
|
||||||
|
import { exec } from 'child_process';
|
||||||
|
import { promisify } from 'util';
|
||||||
|
|
||||||
|
import { Command } from '../../types/CommandTypes.js';
|
||||||
|
import { loadConfig } from '../../util/configLoader.js';
|
||||||
|
import {
|
||||||
|
NotificationType,
|
||||||
|
notifyManagers,
|
||||||
|
} from '../../util/notificationHandler.js';
|
||||||
|
import { isRedisConnected } from '../../db/redis.js';
|
||||||
|
import { ensureDatabaseConnection } from '../../db/db.js';
|
||||||
|
|
||||||
|
const execAsync = promisify(exec);
|
||||||
|
|
||||||
|
const command: Command = {
|
||||||
|
data: new SlashCommandBuilder()
|
||||||
|
.setName('restart')
|
||||||
|
.setDescription('(Manager Only) Restart the bot'),
|
||||||
|
execute: async (interaction) => {
|
||||||
|
const config = loadConfig();
|
||||||
|
const managerRoleId = config.roles.staffRoles.find(
|
||||||
|
(role) => role.name === 'Manager',
|
||||||
|
)?.roleId;
|
||||||
|
|
||||||
|
const member = await interaction.guild?.members.fetch(interaction.user.id);
|
||||||
|
const hasManagerRole = member?.roles.cache.has(managerRoleId || '');
|
||||||
|
|
||||||
|
if (
|
||||||
|
!hasManagerRole &&
|
||||||
|
!interaction.memberPermissions?.has(
|
||||||
|
PermissionsBitField.Flags.Administrator,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
await interaction.reply({
|
||||||
|
content:
|
||||||
|
'You do not have permission to restart the bot. This command is restricted to users with the Manager role.',
|
||||||
|
flags: ['Ephemeral'],
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await interaction.reply({
|
||||||
|
content: 'Restarting the bot... This may take a few moments.',
|
||||||
|
flags: ['Ephemeral'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const dbConnected = await ensureDatabaseConnection();
|
||||||
|
const redisConnected = isRedisConnected();
|
||||||
|
let statusInfo = '';
|
||||||
|
|
||||||
|
if (!dbConnected) {
|
||||||
|
statusInfo += '⚠️ Database is currently disconnected\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!redisConnected) {
|
||||||
|
statusInfo += '⚠️ Redis caching is currently unavailable\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dbConnected && redisConnected) {
|
||||||
|
statusInfo = '✅ All services are operational\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
await notifyManagers(
|
||||||
|
interaction.client,
|
||||||
|
NotificationType.BOT_RESTARTING,
|
||||||
|
`Restart initiated by ${interaction.user.tag}\n\nCurrent service status:\n${statusInfo}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
console.log(
|
||||||
|
`Bot restart initiated by ${interaction.user.tag} (${interaction.user.id})`,
|
||||||
|
);
|
||||||
|
|
||||||
|
await execAsync('yarn restart');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to restart the bot:', error);
|
||||||
|
try {
|
||||||
|
await interaction.followUp({
|
||||||
|
content:
|
||||||
|
'Failed to restart the bot. Check the console for details.',
|
||||||
|
flags: ['Ephemeral'],
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// If this fails too, we can't do much
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default command;
|
1010
src/db/db.ts
1010
src/db/db.ts
File diff suppressed because it is too large
Load diff
307
src/db/redis.ts
307
src/db/redis.ts
|
@ -1,9 +1,31 @@
|
||||||
import Redis from 'ioredis';
|
import Redis from 'ioredis';
|
||||||
|
import { Client } from 'discord.js';
|
||||||
|
|
||||||
import { loadConfig } from '../util/configLoader.js';
|
import { loadConfig } from '../util/configLoader.js';
|
||||||
|
import {
|
||||||
|
logManagerNotification,
|
||||||
|
NotificationType,
|
||||||
|
notifyManagers,
|
||||||
|
} from '../util/notificationHandler.js';
|
||||||
|
|
||||||
const config = loadConfig();
|
const config = loadConfig();
|
||||||
const redis = new Redis(config.redisConnectionString);
|
|
||||||
|
|
||||||
|
// Redis connection state
|
||||||
|
let isRedisAvailable = false;
|
||||||
|
let redis: Redis;
|
||||||
|
let connectionAttempts = 0;
|
||||||
|
const MAX_RETRY_ATTEMPTS = config.redis.retryAttempts;
|
||||||
|
const INITIAL_RETRY_DELAY = config.redis.initialRetryDelay;
|
||||||
|
let hasNotifiedDisconnect = false;
|
||||||
|
let discordClient: Client | null = null;
|
||||||
|
|
||||||
|
// ========================
|
||||||
|
// Redis Utility Classes and Helper Functions
|
||||||
|
// ========================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom error class for Redis errors
|
||||||
|
*/
|
||||||
class RedisError extends Error {
|
class RedisError extends Error {
|
||||||
constructor(
|
constructor(
|
||||||
message: string,
|
message: string,
|
||||||
|
@ -14,77 +36,271 @@ class RedisError extends Error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
redis.on('error', (error: Error) => {
|
/**
|
||||||
console.error('Redis connection error:', error);
|
* Redis error handler
|
||||||
throw new RedisError('Failed to connect to Redis instance: ', error);
|
* @param errorMessage - The error message to log
|
||||||
});
|
* @param error - The error object
|
||||||
|
*/
|
||||||
|
const handleRedisError = (errorMessage: string, error: Error): null => {
|
||||||
|
console.error(`${errorMessage}:`, error);
|
||||||
|
throw new RedisError(errorMessage, error);
|
||||||
|
};
|
||||||
|
|
||||||
redis.on('connect', () => {
|
/**
|
||||||
console.log('Successfully connected to Redis');
|
* Sets the Discord client for sending notifications
|
||||||
});
|
* @param client - The Discord client
|
||||||
|
*/
|
||||||
|
export function setDiscordClient(client: Client): void {
|
||||||
|
discordClient = client;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes the Redis connection with retry logic
|
||||||
|
*/
|
||||||
|
async function initializeRedisConnection() {
|
||||||
|
try {
|
||||||
|
if (redis && redis.status !== 'end' && redis.status !== 'close') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
redis = new Redis(config.redis.redisConnectionString, {
|
||||||
|
retryStrategy(times) {
|
||||||
|
connectionAttempts = times;
|
||||||
|
if (times >= MAX_RETRY_ATTEMPTS) {
|
||||||
|
const message = `Failed to connect to Redis after ${times} attempts. Caching will be disabled.`;
|
||||||
|
console.warn(message);
|
||||||
|
|
||||||
|
if (!hasNotifiedDisconnect && discordClient) {
|
||||||
|
logManagerNotification(NotificationType.REDIS_CONNECTION_LOST);
|
||||||
|
notifyManagers(
|
||||||
|
discordClient,
|
||||||
|
NotificationType.REDIS_CONNECTION_LOST,
|
||||||
|
`Connection attempts exhausted after ${times} tries. Caching is now disabled.`,
|
||||||
|
);
|
||||||
|
hasNotifiedDisconnect = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const delay = Math.min(INITIAL_RETRY_DELAY * Math.pow(2, times), 30000);
|
||||||
|
console.log(
|
||||||
|
`Retrying Redis connection in ${delay}ms... (Attempt ${times + 1}/${MAX_RETRY_ATTEMPTS})`,
|
||||||
|
);
|
||||||
|
return delay;
|
||||||
|
},
|
||||||
|
maxRetriesPerRequest: 3,
|
||||||
|
enableOfflineQueue: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// ========================
|
||||||
|
// Redis Events
|
||||||
|
// ========================
|
||||||
|
redis.on('error', (error: Error) => {
|
||||||
|
console.error('Redis Connection Error:', error);
|
||||||
|
isRedisAvailable = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
redis.on('connect', () => {
|
||||||
|
console.info('Successfully connected to Redis');
|
||||||
|
isRedisAvailable = true;
|
||||||
|
connectionAttempts = 0;
|
||||||
|
|
||||||
|
if (hasNotifiedDisconnect && discordClient) {
|
||||||
|
logManagerNotification(NotificationType.REDIS_CONNECTION_RESTORED);
|
||||||
|
notifyManagers(
|
||||||
|
discordClient,
|
||||||
|
NotificationType.REDIS_CONNECTION_RESTORED,
|
||||||
|
);
|
||||||
|
hasNotifiedDisconnect = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
redis.on('close', () => {
|
||||||
|
console.warn('Redis connection closed');
|
||||||
|
isRedisAvailable = false;
|
||||||
|
|
||||||
|
// Try to reconnect after some time if we've not exceeded max attempts
|
||||||
|
if (connectionAttempts < MAX_RETRY_ATTEMPTS) {
|
||||||
|
const delay = Math.min(
|
||||||
|
INITIAL_RETRY_DELAY * Math.pow(2, connectionAttempts),
|
||||||
|
30000,
|
||||||
|
);
|
||||||
|
setTimeout(initializeRedisConnection, delay);
|
||||||
|
} else if (!hasNotifiedDisconnect && discordClient) {
|
||||||
|
logManagerNotification(NotificationType.REDIS_CONNECTION_LOST);
|
||||||
|
notifyManagers(
|
||||||
|
discordClient,
|
||||||
|
NotificationType.REDIS_CONNECTION_LOST,
|
||||||
|
'Connection closed and max retry attempts reached.',
|
||||||
|
);
|
||||||
|
hasNotifiedDisconnect = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
redis.on('reconnecting', () => {
|
||||||
|
console.info('Attempting to reconnect to Redis...');
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to initialize Redis:', error);
|
||||||
|
isRedisAvailable = false;
|
||||||
|
|
||||||
|
if (!hasNotifiedDisconnect && discordClient) {
|
||||||
|
logManagerNotification(
|
||||||
|
NotificationType.REDIS_CONNECTION_LOST,
|
||||||
|
`Error: ${error}`,
|
||||||
|
);
|
||||||
|
notifyManagers(
|
||||||
|
discordClient,
|
||||||
|
NotificationType.REDIS_CONNECTION_LOST,
|
||||||
|
`Initialization error: ${error}`,
|
||||||
|
);
|
||||||
|
hasNotifiedDisconnect = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize Redis connection
|
||||||
|
initializeRedisConnection();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if Redis is currently available, and attempt to reconnect if not
|
||||||
|
* @returns - True if Redis is connected and available
|
||||||
|
*/
|
||||||
|
export async function ensureRedisConnection(): Promise<boolean> {
|
||||||
|
if (!isRedisAvailable) {
|
||||||
|
await initializeRedisConnection();
|
||||||
|
}
|
||||||
|
return isRedisAvailable;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================
|
||||||
|
// Redis Functions
|
||||||
|
// ========================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Function to set a key in Redis
|
||||||
|
* @param key - The key to set
|
||||||
|
* @param value - The value to set
|
||||||
|
* @param ttl - The time to live for the key
|
||||||
|
* @returns - 'OK' if successful
|
||||||
|
*/
|
||||||
export async function set(
|
export async function set(
|
||||||
key: string,
|
key: string,
|
||||||
value: string,
|
value: string,
|
||||||
ttl?: number,
|
ttl?: number,
|
||||||
): Promise<'OK'> {
|
): Promise<'OK' | null> {
|
||||||
try {
|
if (!(await ensureRedisConnection())) {
|
||||||
await redis.set(key, value);
|
console.warn('Redis unavailable, skipping set operation');
|
||||||
if (ttl) await redis.expire(key, ttl);
|
return null;
|
||||||
} catch (error) {
|
}
|
||||||
console.error('Redis set error: ', error);
|
|
||||||
throw new RedisError(`Failed to set key: ${key}, `, error as Error);
|
try {
|
||||||
|
await redis.set(`bot:${key}`, value);
|
||||||
|
if (ttl) await redis.expire(`bot:${key}`, ttl);
|
||||||
|
return 'OK';
|
||||||
|
} catch (error) {
|
||||||
|
return handleRedisError(`Failed to set key: ${key}`, error as Error);
|
||||||
}
|
}
|
||||||
return Promise.resolve('OK');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Function to set a key in Redis with a JSON value
|
||||||
|
* @param key - The key to set
|
||||||
|
* @param value - The value to set
|
||||||
|
* @param ttl - The time to live for the key
|
||||||
|
* @returns - 'OK' if successful
|
||||||
|
*/
|
||||||
export async function setJson<T>(
|
export async function setJson<T>(
|
||||||
key: string,
|
key: string,
|
||||||
value: T,
|
value: T,
|
||||||
ttl?: number,
|
ttl?: number,
|
||||||
): Promise<'OK'> {
|
): Promise<'OK' | null> {
|
||||||
return await set(key, JSON.stringify(value), ttl);
|
return await set(key, JSON.stringify(value), ttl);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function incr(key: string): Promise<number> {
|
/**
|
||||||
|
* Increments a key in Redis
|
||||||
|
* @param key - The key to increment
|
||||||
|
* @returns - The new value of the key, or null if Redis is unavailable
|
||||||
|
*/
|
||||||
|
export async function incr(key: string): Promise<number | null> {
|
||||||
|
if (!(await ensureRedisConnection())) {
|
||||||
|
console.warn('Redis unavailable, skipping increment operation');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await redis.incr(key);
|
return await redis.incr(`bot:${key}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Redis increment error: ', error);
|
return handleRedisError(`Failed to increment key: ${key}`, error as Error);
|
||||||
throw new RedisError(`Failed to increment key: ${key}, `, error as Error);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function exists(key: string): Promise<boolean> {
|
/**
|
||||||
|
* Checks if a key exists in Redis
|
||||||
|
* @param key - The key to check
|
||||||
|
* @returns - True if the key exists, false otherwise, or null if Redis is unavailable
|
||||||
|
*/
|
||||||
|
export async function exists(key: string): Promise<boolean | null> {
|
||||||
|
if (!(await ensureRedisConnection())) {
|
||||||
|
console.warn('Redis unavailable, skipping exists operation');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return (await redis.exists(key)) === 1;
|
return (await redis.exists(`bot:${key}`)) === 1;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Redis exists error: ', error);
|
return handleRedisError(
|
||||||
throw new RedisError(
|
`Failed to check if key exists: ${key}`,
|
||||||
`Failed to check if key exists: ${key}, `,
|
|
||||||
error as Error,
|
error as Error,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the value of a key in Redis
|
||||||
|
* @param key - The key to get
|
||||||
|
* @returns - The value of the key, or null if the key does not exist or Redis is unavailable
|
||||||
|
*/
|
||||||
export async function get(key: string): Promise<string | null> {
|
export async function get(key: string): Promise<string | null> {
|
||||||
|
if (!(await ensureRedisConnection())) {
|
||||||
|
console.warn('Redis unavailable, skipping get operation');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await redis.get(key);
|
return await redis.get(`bot:${key}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Redis get error: ', error);
|
return handleRedisError(`Failed to get key: ${key}`, error as Error);
|
||||||
throw new RedisError(`Failed to get key: ${key}, `, error as Error);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function mget(...keys: string[]): Promise<(string | null)[]> {
|
/**
|
||||||
|
* Gets the values of multiple keys in Redis
|
||||||
|
* @param keys - The keys to get
|
||||||
|
* @returns - The values of the keys, or null if Redis is unavailable
|
||||||
|
*/
|
||||||
|
export async function mget(
|
||||||
|
...keys: string[]
|
||||||
|
): Promise<(string | null)[] | null> {
|
||||||
|
if (!(await ensureRedisConnection())) {
|
||||||
|
console.warn('Redis unavailable, skipping mget operation');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await redis.mget(keys);
|
return await redis.mget(...keys.map((key) => `bot:${key}`));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Redis mget error: ', error);
|
return handleRedisError('Failed to get keys', error as Error);
|
||||||
throw new RedisError(`Failed to get keys: ${keys}, `, error as Error);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the value of a key in Redis and parses it as a JSON object
|
||||||
|
* @param key - The key to get
|
||||||
|
* @returns - The parsed JSON value of the key, or null if the key does not exist or Redis is unavailable
|
||||||
|
*/
|
||||||
export async function getJson<T>(key: string): Promise<T | null> {
|
export async function getJson<T>(key: string): Promise<T | null> {
|
||||||
const value = await get(key);
|
const value = await get(key);
|
||||||
if (!value) return null;
|
if (!value) return null;
|
||||||
|
@ -95,11 +311,28 @@ export async function getJson<T>(key: string): Promise<T | null> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function del(key: string): Promise<number> {
|
/**
|
||||||
|
* Deletes a key in Redis
|
||||||
|
* @param key - The key to delete
|
||||||
|
* @returns - The number of keys that were deleted, or null if Redis is unavailable
|
||||||
|
*/
|
||||||
|
export async function del(key: string): Promise<number | null> {
|
||||||
|
if (!(await ensureRedisConnection())) {
|
||||||
|
console.warn('Redis unavailable, skipping delete operation');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await redis.del(key);
|
return await redis.del(`bot:${key}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Redis del error: ', error);
|
return handleRedisError(`Failed to delete key: ${key}`, error as Error);
|
||||||
throw new RedisError(`Failed to delete key: ${key}, `, error as Error);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if Redis is currently available
|
||||||
|
* @returns - True if Redis is connected and available
|
||||||
|
*/
|
||||||
|
export function isRedisConnected(): boolean {
|
||||||
|
return isRedisAvailable;
|
||||||
|
}
|
||||||
|
|
|
@ -75,6 +75,7 @@ export const memberRelations = relations(memberTable, ({ many, one }) => ({
|
||||||
fields: [memberTable.discordId],
|
fields: [memberTable.discordId],
|
||||||
references: [levelTable.discordId],
|
references: [levelTable.discordId],
|
||||||
}),
|
}),
|
||||||
|
facts: many(factTable),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
export const levelRelations = relations(levelTable, ({ one }) => ({
|
export const levelRelations = relations(levelTable, ({ one }) => ({
|
||||||
|
|
|
@ -63,7 +63,7 @@ export default {
|
||||||
if (!interaction.memberPermissions?.has('ModerateMembers')) {
|
if (!interaction.memberPermissions?.has('ModerateMembers')) {
|
||||||
await interaction.reply({
|
await interaction.reply({
|
||||||
content: 'You do not have permission to approve facts.',
|
content: 'You do not have permission to approve facts.',
|
||||||
ephemeral: true,
|
flags: ['Ephemeral'],
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -79,7 +79,7 @@ export default {
|
||||||
if (!interaction.memberPermissions?.has('ModerateMembers')) {
|
if (!interaction.memberPermissions?.has('ModerateMembers')) {
|
||||||
await interaction.reply({
|
await interaction.reply({
|
||||||
content: 'You do not have permission to reject facts.',
|
content: 'You do not have permission to reject facts.',
|
||||||
ephemeral: true,
|
flags: ['Ephemeral'],
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
import { Events, Guild, GuildMember, PartialGuildMember } from 'discord.js';
|
import {
|
||||||
|
Collection,
|
||||||
|
Events,
|
||||||
|
Guild,
|
||||||
|
GuildMember,
|
||||||
|
PartialGuildMember,
|
||||||
|
} from 'discord.js';
|
||||||
|
|
||||||
import { updateMember, setMembers } from '../db/db.js';
|
import { updateMember, setMembers } from '../db/db.js';
|
||||||
import { generateMemberBanner } from '../util/helpers.js';
|
import { generateMemberBanner } from '../util/helpers.js';
|
||||||
|
@ -19,12 +25,9 @@ export const memberJoin: Event<typeof Events.GuildMemberAdd> = {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await setMembers([
|
const memberCollection = new Collection<string, GuildMember>();
|
||||||
{
|
memberCollection.set(member.user.id, member);
|
||||||
discordId: member.user.id,
|
await setMembers(memberCollection);
|
||||||
discordUsername: member.user.username,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (!member.user.bot) {
|
if (!member.user.bot) {
|
||||||
const attachment = await generateMemberBanner({
|
const attachment = await generateMemberBanner({
|
||||||
|
|
|
@ -84,7 +84,7 @@ export const messageCreate: Event<typeof Events.MessageCreate> = {
|
||||||
advancementsChannelId,
|
advancementsChannelId,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!advancementsChannel || !advancementsChannel.isTextBased()) {
|
if (!advancementsChannel?.isTextBased()) {
|
||||||
console.error(
|
console.error(
|
||||||
'Advancements channel not found or is not a text channel',
|
'Advancements channel not found or is not a text channel',
|
||||||
);
|
);
|
||||||
|
|
|
@ -1,16 +1,28 @@
|
||||||
import { Client, Events } from 'discord.js';
|
import { Client, Events } from 'discord.js';
|
||||||
|
|
||||||
import { setMembers } from '../db/db.js';
|
import { ensureDbInitialized, setMembers } from '../db/db.js';
|
||||||
import { loadConfig } from '../util/configLoader.js';
|
import { loadConfig } from '../util/configLoader.js';
|
||||||
import { Event } from '../types/EventTypes.js';
|
import { Event } from '../types/EventTypes.js';
|
||||||
import { scheduleFactOfTheDay } from '../util/factManager.js';
|
import { scheduleFactOfTheDay } from '../util/factManager.js';
|
||||||
|
|
||||||
|
import {
|
||||||
|
ensureRedisConnection,
|
||||||
|
setDiscordClient as setRedisDiscordClient,
|
||||||
|
} from '../db/redis.js';
|
||||||
|
import { setDiscordClient as setDbDiscordClient } from '../db/db.js';
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: Events.ClientReady,
|
name: Events.ClientReady,
|
||||||
once: true,
|
once: true,
|
||||||
execute: async (client: Client) => {
|
execute: async (client: Client) => {
|
||||||
const config = loadConfig();
|
const config = loadConfig();
|
||||||
try {
|
try {
|
||||||
|
setRedisDiscordClient(client);
|
||||||
|
setDbDiscordClient(client);
|
||||||
|
|
||||||
|
await ensureDbInitialized();
|
||||||
|
await ensureRedisConnection();
|
||||||
|
|
||||||
const guild = client.guilds.cache.find(
|
const guild = client.guilds.cache.find(
|
||||||
(guilds) => guilds.id === config.guildId,
|
(guilds) => guilds.id === config.guildId,
|
||||||
);
|
);
|
||||||
|
@ -25,7 +37,7 @@ export default {
|
||||||
|
|
||||||
await scheduleFactOfTheDay(client);
|
await scheduleFactOfTheDay(client);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to initialize members in database:', error);
|
console.error('Failed to initialize the bot:', error);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Ready! Logged in as ${client.user?.tag}`);
|
console.log(`Ready! Logged in as ${client.user?.tag}`);
|
||||||
|
|
|
@ -4,6 +4,9 @@ import { Config } from '../types/ConfigTypes.js';
|
||||||
import { deployCommands } from '../util/deployCommand.js';
|
import { deployCommands } from '../util/deployCommand.js';
|
||||||
import { registerEvents } from '../util/eventLoader.js';
|
import { registerEvents } from '../util/eventLoader.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extended client class that extends the default Client class
|
||||||
|
*/
|
||||||
export class ExtendedClient extends Client {
|
export class ExtendedClient extends Client {
|
||||||
public commands: Collection<string, Command>;
|
public commands: Collection<string, Command>;
|
||||||
private config: Config;
|
private config: Config;
|
||||||
|
|
|
@ -5,16 +5,25 @@ import {
|
||||||
SlashCommandSubcommandsOnlyBuilder,
|
SlashCommandSubcommandsOnlyBuilder,
|
||||||
} from 'discord.js';
|
} from 'discord.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command interface for normal commands
|
||||||
|
*/
|
||||||
export interface Command {
|
export interface Command {
|
||||||
data: Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>;
|
data: Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>;
|
||||||
execute: (interaction: CommandInteraction) => Promise<void>;
|
execute: (interaction: CommandInteraction) => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command interface for options commands
|
||||||
|
*/
|
||||||
export interface OptionsCommand {
|
export interface OptionsCommand {
|
||||||
data: SlashCommandOptionsOnlyBuilder;
|
data: SlashCommandOptionsOnlyBuilder;
|
||||||
execute: (interaction: CommandInteraction) => Promise<void>;
|
execute: (interaction: CommandInteraction) => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command interface for subcommand commands
|
||||||
|
*/
|
||||||
export interface SubcommandCommand {
|
export interface SubcommandCommand {
|
||||||
data: SlashCommandSubcommandsOnlyBuilder;
|
data: SlashCommandSubcommandsOnlyBuilder;
|
||||||
execute: (interaction: CommandInteraction) => Promise<void>;
|
execute: (interaction: CommandInteraction) => Promise<void>;
|
||||||
|
|
|
@ -1,9 +1,20 @@
|
||||||
|
/**
|
||||||
|
* Config interface for the bot
|
||||||
|
*/
|
||||||
export interface Config {
|
export interface Config {
|
||||||
token: string;
|
token: string;
|
||||||
clientId: string;
|
clientId: string;
|
||||||
guildId: string;
|
guildId: string;
|
||||||
dbConnectionString: string;
|
database: {
|
||||||
redisConnectionString: string;
|
dbConnectionString: string;
|
||||||
|
maxRetryAttempts: number;
|
||||||
|
retryDelay: number;
|
||||||
|
};
|
||||||
|
redis: {
|
||||||
|
redisConnectionString: string;
|
||||||
|
retryAttempts: number;
|
||||||
|
initialRetryDelay: number;
|
||||||
|
};
|
||||||
channels: {
|
channels: {
|
||||||
welcome: string;
|
welcome: string;
|
||||||
logs: string;
|
logs: string;
|
||||||
|
@ -24,4 +35,9 @@ export interface Config {
|
||||||
}[];
|
}[];
|
||||||
factPingRole: string;
|
factPingRole: string;
|
||||||
};
|
};
|
||||||
|
leveling: {
|
||||||
|
xpCooldown: number;
|
||||||
|
minXpAwarded: number;
|
||||||
|
maxXpAwarded: number;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,8 @@
|
||||||
import { ClientEvents } from 'discord.js';
|
import { ClientEvents } from 'discord.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event interface for events
|
||||||
|
*/
|
||||||
export interface Event<K extends keyof ClientEvents> {
|
export interface Event<K extends keyof ClientEvents> {
|
||||||
name: K;
|
name: K;
|
||||||
once?: boolean;
|
once?: boolean;
|
||||||
|
|
|
@ -2,6 +2,10 @@ import { Config } from '../types/ConfigTypes.js';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads the config file from the root directory
|
||||||
|
* @returns - The loaded config object
|
||||||
|
*/
|
||||||
export function loadConfig(): Config {
|
export function loadConfig(): Config {
|
||||||
try {
|
try {
|
||||||
const configPath = path.join(process.cwd(), './config.json');
|
const configPath = path.join(process.cwd(), './config.json');
|
||||||
|
|
|
@ -16,6 +16,10 @@ const MILESTONE_REACTIONS = {
|
||||||
multiples100: '🎉',
|
multiples100: '🎉',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes the counting data if it doesn't exist
|
||||||
|
* @returns - The initialized counting data
|
||||||
|
*/
|
||||||
export async function initializeCountingData(): Promise<CountingData> {
|
export async function initializeCountingData(): Promise<CountingData> {
|
||||||
const exists = await getJson<CountingData>('counting');
|
const exists = await getJson<CountingData>('counting');
|
||||||
if (exists) return exists;
|
if (exists) return exists;
|
||||||
|
@ -31,6 +35,10 @@ export async function initializeCountingData(): Promise<CountingData> {
|
||||||
return initialData;
|
return initialData;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the current counting data
|
||||||
|
* @returns - The current counting data
|
||||||
|
*/
|
||||||
export async function getCountingData(): Promise<CountingData> {
|
export async function getCountingData(): Promise<CountingData> {
|
||||||
const data = await getJson<CountingData>('counting');
|
const data = await getJson<CountingData>('counting');
|
||||||
if (!data) {
|
if (!data) {
|
||||||
|
@ -39,6 +47,10 @@ export async function getCountingData(): Promise<CountingData> {
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the counting data with new data
|
||||||
|
* @param data - The data to update the counting data with
|
||||||
|
*/
|
||||||
export async function updateCountingData(
|
export async function updateCountingData(
|
||||||
data: Partial<CountingData>,
|
data: Partial<CountingData>,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
|
@ -47,6 +59,10 @@ export async function updateCountingData(
|
||||||
await setJson<CountingData>('counting', updatedData);
|
await setJson<CountingData>('counting', updatedData);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resets the counting data to the initial state
|
||||||
|
* @returns - The current count
|
||||||
|
*/
|
||||||
export async function resetCounting(): Promise<void> {
|
export async function resetCounting(): Promise<void> {
|
||||||
await updateCountingData({
|
await updateCountingData({
|
||||||
currentCount: 0,
|
currentCount: 0,
|
||||||
|
@ -55,6 +71,11 @@ export async function resetCounting(): Promise<void> {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processes a counting message to determine if it is valid
|
||||||
|
* @param message - The message to process
|
||||||
|
* @returns - An object with information about the message
|
||||||
|
*/
|
||||||
export async function processCountingMessage(message: Message): Promise<{
|
export async function processCountingMessage(message: Message): Promise<{
|
||||||
isValid: boolean;
|
isValid: boolean;
|
||||||
expectedCount?: number;
|
expectedCount?: number;
|
||||||
|
@ -125,6 +146,11 @@ export async function processCountingMessage(message: Message): Promise<{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds counting reactions to a message based on the milestone type
|
||||||
|
* @param message - The message to add counting reactions to
|
||||||
|
* @param milestoneType - The type of milestone to add reactions for
|
||||||
|
*/
|
||||||
export async function addCountingReactions(
|
export async function addCountingReactions(
|
||||||
message: Message,
|
message: Message,
|
||||||
milestoneType: keyof typeof MILESTONE_REACTIONS,
|
milestoneType: keyof typeof MILESTONE_REACTIONS,
|
||||||
|
@ -140,11 +166,19 @@ export async function addCountingReactions(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the current counting status
|
||||||
|
* @returns - A string with the current counting status
|
||||||
|
*/
|
||||||
export async function getCountingStatus(): Promise<string> {
|
export async function getCountingStatus(): Promise<string> {
|
||||||
const data = await getCountingData();
|
const data = await getCountingData();
|
||||||
return `Current count: ${data.currentCount}\nHighest count ever: ${data.highestCount}\nTotal correct counts: ${data.totalCorrect}`;
|
return `Current count: ${data.currentCount}\nHighest count ever: ${data.highestCount}\nTotal correct counts: ${data.totalCorrect}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the current count to a specific number
|
||||||
|
* @param count - The number to set as the current count
|
||||||
|
*/
|
||||||
export async function setCount(count: number): Promise<void> {
|
export async function setCount(count: number): Promise<void> {
|
||||||
if (!Number.isInteger(count) || count < 0) {
|
if (!Number.isInteger(count) || count < 0) {
|
||||||
throw new Error('Count must be a non-negative integer.');
|
throw new Error('Count must be a non-negative integer.');
|
||||||
|
|
|
@ -11,6 +11,11 @@ const commandsPath = path.join(__dirname, 'target', 'commands');
|
||||||
|
|
||||||
const rest = new REST({ version: '10' }).setToken(token);
|
const rest = new REST({ version: '10' }).setToken(token);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets all files in the command directory and its subdirectories
|
||||||
|
* @param directory - The directory to get files from
|
||||||
|
* @returns - An array of file paths
|
||||||
|
*/
|
||||||
const getFilesRecursively = (directory: string): string[] => {
|
const getFilesRecursively = (directory: string): string[] => {
|
||||||
const files: string[] = [];
|
const files: string[] = [];
|
||||||
const filesInDirectory = fs.readdirSync(directory);
|
const filesInDirectory = fs.readdirSync(directory);
|
||||||
|
@ -30,15 +35,21 @@ const getFilesRecursively = (directory: string): string[] => {
|
||||||
|
|
||||||
const commandFiles = getFilesRecursively(commandsPath);
|
const commandFiles = getFilesRecursively(commandsPath);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers all commands in the command directory with the Discord API
|
||||||
|
* @returns - An array of valid command objects
|
||||||
|
*/
|
||||||
export const deployCommands = async () => {
|
export const deployCommands = async () => {
|
||||||
try {
|
try {
|
||||||
console.log(
|
console.log(
|
||||||
`Started refreshing ${commandFiles.length} application (/) commands...`,
|
`Started refreshing ${commandFiles.length} application (/) commands...`,
|
||||||
);
|
);
|
||||||
|
|
||||||
const existingCommands = (await rest.get(
|
console.log('Undeploying all existing commands...');
|
||||||
Routes.applicationGuildCommands(clientId, guildId),
|
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
|
||||||
)) as any[];
|
body: [],
|
||||||
|
});
|
||||||
|
console.log('Successfully undeployed all commands');
|
||||||
|
|
||||||
const commands = commandFiles.map(async (file) => {
|
const commands = commandFiles.map(async (file) => {
|
||||||
const commandModule = await import(`file://${file}`);
|
const commandModule = await import(`file://${file}`);
|
||||||
|
@ -64,18 +75,6 @@ export const deployCommands = async () => {
|
||||||
|
|
||||||
const apiCommands = validCommands.map((command) => command.data.toJSON());
|
const apiCommands = validCommands.map((command) => command.data.toJSON());
|
||||||
|
|
||||||
const commandsToRemove = existingCommands.filter(
|
|
||||||
(existingCmd) =>
|
|
||||||
!apiCommands.some((newCmd) => newCmd.name === existingCmd.name),
|
|
||||||
);
|
|
||||||
|
|
||||||
for (const cmdToRemove of commandsToRemove) {
|
|
||||||
await rest.delete(
|
|
||||||
Routes.applicationGuildCommand(clientId, guildId, cmdToRemove.id),
|
|
||||||
);
|
|
||||||
console.log(`Removed command: ${cmdToRemove.name}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data: any = await rest.put(
|
const data: any = await rest.put(
|
||||||
Routes.applicationGuildCommands(clientId, guildId),
|
Routes.applicationGuildCommands(clientId, guildId),
|
||||||
{ body: apiCommands },
|
{ body: apiCommands },
|
||||||
|
|
|
@ -7,6 +7,10 @@ import { dirname } from 'path';
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
const __dirname = dirname(__filename);
|
const __dirname = dirname(__filename);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers all event handlers in the events directory
|
||||||
|
* @param client - The Discord client
|
||||||
|
*/
|
||||||
export async function registerEvents(client: Client): Promise<void> {
|
export async function registerEvents(client: Client): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const eventsPath = join(__dirname, '..', 'events');
|
const eventsPath = join(__dirname, '..', 'events');
|
||||||
|
|
|
@ -3,8 +3,22 @@ import { EmbedBuilder, Client } from 'discord.js';
|
||||||
import { getRandomUnusedFact, markFactAsUsed } from '../db/db.js';
|
import { getRandomUnusedFact, markFactAsUsed } from '../db/db.js';
|
||||||
import { loadConfig } from './configLoader.js';
|
import { loadConfig } from './configLoader.js';
|
||||||
|
|
||||||
export async function scheduleFactOfTheDay(client: Client) {
|
let isFactScheduled = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedule the fact of the day to be posted daily
|
||||||
|
* @param client - The Discord client
|
||||||
|
*/
|
||||||
|
export async function scheduleFactOfTheDay(client: Client): Promise<void> {
|
||||||
|
if (isFactScheduled) {
|
||||||
|
console.log(
|
||||||
|
'Fact of the day already scheduled, skipping duplicate schedule',
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
isFactScheduled = true;
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const tomorrow = new Date();
|
const tomorrow = new Date();
|
||||||
tomorrow.setDate(now.getDate() + 1);
|
tomorrow.setDate(now.getDate() + 1);
|
||||||
|
@ -14,6 +28,7 @@ export async function scheduleFactOfTheDay(client: Client) {
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
postFactOfTheDay(client);
|
postFactOfTheDay(client);
|
||||||
|
isFactScheduled = false;
|
||||||
scheduleFactOfTheDay(client);
|
scheduleFactOfTheDay(client);
|
||||||
}, timeUntilMidnight);
|
}, timeUntilMidnight);
|
||||||
|
|
||||||
|
@ -22,11 +37,16 @@ export async function scheduleFactOfTheDay(client: Client) {
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error scheduling fact of the day:', error);
|
console.error('Error scheduling fact of the day:', error);
|
||||||
|
isFactScheduled = false;
|
||||||
setTimeout(() => scheduleFactOfTheDay(client), 60 * 60 * 1000);
|
setTimeout(() => scheduleFactOfTheDay(client), 60 * 60 * 1000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function postFactOfTheDay(client: Client) {
|
/**
|
||||||
|
* Post the fact of the day to the configured channel
|
||||||
|
* @param client - The Discord client
|
||||||
|
*/
|
||||||
|
export async function postFactOfTheDay(client: Client): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const config = loadConfig();
|
const config = loadConfig();
|
||||||
const guild = client.guilds.cache.get(config.guildId);
|
const guild = client.guilds.cache.get(config.guildId);
|
||||||
|
|
|
@ -5,11 +5,16 @@ import { AttachmentBuilder, Client, GuildMember, Guild } from 'discord.js';
|
||||||
import { and, eq } from 'drizzle-orm';
|
import { and, eq } from 'drizzle-orm';
|
||||||
|
|
||||||
import { moderationTable } from '../db/schema.js';
|
import { moderationTable } from '../db/schema.js';
|
||||||
import { db, updateMember } from '../db/db.js';
|
import { db, handleDbError, updateMember } from '../db/db.js';
|
||||||
import logAction from './logging/logAction.js';
|
import logAction from './logging/logAction.js';
|
||||||
|
|
||||||
const __dirname = path.resolve();
|
const __dirname = path.resolve();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turns a duration string into milliseconds
|
||||||
|
* @param duration - The duration to parse
|
||||||
|
* @returns - The parsed duration in milliseconds
|
||||||
|
*/
|
||||||
export function parseDuration(duration: string): number {
|
export function parseDuration(duration: string): number {
|
||||||
const regex = /^(\d+)(s|m|h|d)$/;
|
const regex = /^(\d+)(s|m|h|d)$/;
|
||||||
const match = duration.match(regex);
|
const match = duration.match(regex);
|
||||||
|
@ -30,17 +35,27 @@ export function parseDuration(duration: string): number {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Member banner types
|
||||||
|
*/
|
||||||
interface generateMemberBannerTypes {
|
interface generateMemberBannerTypes {
|
||||||
member: GuildMember;
|
member: GuildMember;
|
||||||
width: number;
|
width: number;
|
||||||
height: number;
|
height: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a welcome banner for a member
|
||||||
|
* @param member - The member to generate a banner for
|
||||||
|
* @param width - The width of the banner
|
||||||
|
* @param height - The height of the banner
|
||||||
|
* @returns - The generated banner
|
||||||
|
*/
|
||||||
export async function generateMemberBanner({
|
export async function generateMemberBanner({
|
||||||
member,
|
member,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
}: generateMemberBannerTypes) {
|
}: generateMemberBannerTypes): Promise<AttachmentBuilder> {
|
||||||
const welcomeBackground = path.join(__dirname, 'assets', 'welcome-bg.png');
|
const welcomeBackground = path.join(__dirname, 'assets', 'welcome-bg.png');
|
||||||
const canvas = Canvas.createCanvas(width, height);
|
const canvas = Canvas.createCanvas(width, height);
|
||||||
const context = canvas.getContext('2d');
|
const context = canvas.getContext('2d');
|
||||||
|
@ -92,12 +107,19 @@ export async function generateMemberBanner({
|
||||||
return attachment;
|
return attachment;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedules an unban for a user
|
||||||
|
* @param client - The client to use
|
||||||
|
* @param guildId - The guild ID to unban the user from
|
||||||
|
* @param userId - The user ID to unban
|
||||||
|
* @param expiresAt - The date to unban the user at
|
||||||
|
*/
|
||||||
export async function scheduleUnban(
|
export async function scheduleUnban(
|
||||||
client: Client,
|
client: Client,
|
||||||
guildId: string,
|
guildId: string,
|
||||||
userId: string,
|
userId: string,
|
||||||
expiresAt: Date,
|
expiresAt: Date,
|
||||||
) {
|
): Promise<void> {
|
||||||
const timeUntilUnban = expiresAt.getTime() - Date.now();
|
const timeUntilUnban = expiresAt.getTime() - Date.now();
|
||||||
if (timeUntilUnban > 0) {
|
if (timeUntilUnban > 0) {
|
||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
|
@ -106,12 +128,19 @@ export async function scheduleUnban(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Executes an unban for a user
|
||||||
|
* @param client - The client to use
|
||||||
|
* @param guildId - The guild ID to unban the user from
|
||||||
|
* @param userId - The user ID to unban
|
||||||
|
* @param reason - The reason for the unban
|
||||||
|
*/
|
||||||
export async function executeUnban(
|
export async function executeUnban(
|
||||||
client: Client,
|
client: Client,
|
||||||
guildId: string,
|
guildId: string,
|
||||||
userId: string,
|
userId: string,
|
||||||
reason?: string,
|
reason?: string,
|
||||||
) {
|
): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const guild = await client.guilds.fetch(guildId);
|
const guild = await client.guilds.fetch(guildId);
|
||||||
await guild.members.unban(userId, reason ?? 'Temporary ban expired');
|
await guild.members.unban(userId, reason ?? 'Temporary ban expired');
|
||||||
|
@ -140,26 +169,96 @@ export async function executeUnban(
|
||||||
reason: reason ?? 'Temporary ban expired',
|
reason: reason ?? 'Temporary ban expired',
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Failed to unban user ${userId}:`, error);
|
handleDbError(`Failed to unban user ${userId}`, error as Error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadActiveBans(client: Client, guild: Guild) {
|
/**
|
||||||
const activeBans = await db
|
* Loads all active bans and schedules unban events
|
||||||
.select()
|
* @param client - The client to use
|
||||||
.from(moderationTable)
|
* @param guild - The guild to load bans for
|
||||||
.where(
|
*/
|
||||||
and(eq(moderationTable.action, 'ban'), eq(moderationTable.active, true)),
|
export async function loadActiveBans(
|
||||||
);
|
client: Client,
|
||||||
|
guild: Guild,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const activeBans = await db
|
||||||
|
.select()
|
||||||
|
.from(moderationTable)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(moderationTable.action, 'ban'),
|
||||||
|
eq(moderationTable.active, true),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
for (const ban of activeBans) {
|
for (const ban of activeBans) {
|
||||||
if (!ban.expiresAt) continue;
|
if (!ban.expiresAt) continue;
|
||||||
|
|
||||||
const timeUntilUnban = ban.expiresAt.getTime() - Date.now();
|
const timeUntilUnban = ban.expiresAt.getTime() - Date.now();
|
||||||
if (timeUntilUnban <= 0) {
|
if (timeUntilUnban <= 0) {
|
||||||
await executeUnban(client, guild.id, ban.discordId);
|
await executeUnban(client, guild.id, ban.discordId);
|
||||||
} else {
|
} else {
|
||||||
await scheduleUnban(client, guild.id, ban.discordId, ban.expiresAt);
|
await scheduleUnban(client, guild.id, ban.discordId, ban.expiresAt);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
handleDbError('Failed to load active bans', error as Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Types for the roundRect function
|
||||||
|
*/
|
||||||
|
interface roundRectTypes {
|
||||||
|
ctx: Canvas.SKRSContext2D;
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
fill: boolean;
|
||||||
|
radius?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a rounded rectangle
|
||||||
|
* @param ctx - The canvas context to use
|
||||||
|
* @param x - The x position of the rectangle
|
||||||
|
* @param y - The y position of the rectangle
|
||||||
|
* @param width - The width of the rectangle
|
||||||
|
* @param height - The height of the rectangle
|
||||||
|
* @param radius - The radius of the corners
|
||||||
|
* @param fill - Whether to fill the rectangle
|
||||||
|
*/
|
||||||
|
export function roundRect({
|
||||||
|
ctx,
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
radius,
|
||||||
|
fill,
|
||||||
|
}: roundRectTypes): void {
|
||||||
|
if (typeof radius === 'undefined') {
|
||||||
|
radius = 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(x + radius, y);
|
||||||
|
ctx.lineTo(x + width - radius, y);
|
||||||
|
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
|
||||||
|
ctx.lineTo(x + width, y + height - radius);
|
||||||
|
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
|
||||||
|
ctx.lineTo(x + radius, y + height);
|
||||||
|
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
|
||||||
|
ctx.lineTo(x, y + radius);
|
||||||
|
ctx.quadraticCurveTo(x, y, x + radius, y);
|
||||||
|
ctx.closePath();
|
||||||
|
|
||||||
|
if (fill) {
|
||||||
|
ctx.fill();
|
||||||
|
} else {
|
||||||
|
ctx.stroke();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +1,41 @@
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { GuildMember, Message, AttachmentBuilder, Guild } from 'discord.js';
|
|
||||||
import Canvas, { GlobalFonts } from '@napi-rs/canvas';
|
import Canvas, { GlobalFonts } from '@napi-rs/canvas';
|
||||||
|
import { GuildMember, Message, AttachmentBuilder, Guild } from 'discord.js';
|
||||||
|
|
||||||
import { addXpToUser, db, getUserLevel, getUserRank } from '../db/db.js';
|
import {
|
||||||
|
addXpToUser,
|
||||||
|
db,
|
||||||
|
getUserLevel,
|
||||||
|
getUserRank,
|
||||||
|
handleDbError,
|
||||||
|
} from '../db/db.js';
|
||||||
import * as schema from '../db/schema.js';
|
import * as schema from '../db/schema.js';
|
||||||
import { loadConfig } from './configLoader.js';
|
import { loadConfig } from './configLoader.js';
|
||||||
|
import { roundRect } from './helpers.js';
|
||||||
|
|
||||||
const config = loadConfig();
|
const config = loadConfig();
|
||||||
|
|
||||||
const XP_COOLDOWN = 60 * 1000;
|
const XP_COOLDOWN = config.leveling.xpCooldown * 1000;
|
||||||
const MIN_XP = 15;
|
const MIN_XP = config.leveling.minXpAwarded;
|
||||||
const MAX_XP = 25;
|
const MAX_XP = config.leveling.maxXpAwarded;
|
||||||
|
|
||||||
const __dirname = path.resolve();
|
const __dirname = path.resolve();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the amount of XP required to reach the given level
|
||||||
|
* @param level - The level to calculate the XP for
|
||||||
|
* @returns - The amount of XP required to reach the given level
|
||||||
|
*/
|
||||||
export const calculateXpForLevel = (level: number): number => {
|
export const calculateXpForLevel = (level: number): number => {
|
||||||
if (level === 0) return 0;
|
if (level === 0) return 0;
|
||||||
return (5 / 6) * level * (2 * level * level + 27 * level + 91);
|
return (5 / 6) * level * (2 * level * level + 27 * level + 91);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the level that corresponds to the given amount of XP
|
||||||
|
* @param xp - The amount of XP to calculate the level for
|
||||||
|
* @returns - The level that corresponds to the given amount of XP
|
||||||
|
*/
|
||||||
export const calculateLevelFromXp = (xp: number): number => {
|
export const calculateLevelFromXp = (xp: number): number => {
|
||||||
if (xp < calculateXpForLevel(1)) return 0;
|
if (xp < calculateXpForLevel(1)) return 0;
|
||||||
|
|
||||||
|
@ -30,6 +47,12 @@ export const calculateLevelFromXp = (xp: number): number => {
|
||||||
return level;
|
return level;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the amount of XP required to reach the next level
|
||||||
|
* @param level - The level to calculate the XP for
|
||||||
|
* @param currentXp - The current amount of XP
|
||||||
|
* @returns - The amount of XP required to reach the next level
|
||||||
|
*/
|
||||||
export const getXpToNextLevel = (level: number, currentXp: number): number => {
|
export const getXpToNextLevel = (level: number, currentXp: number): number => {
|
||||||
if (level === 0) return calculateXpForLevel(1) - currentXp;
|
if (level === 0) return calculateXpForLevel(1) - currentXp;
|
||||||
|
|
||||||
|
@ -37,14 +60,26 @@ export const getXpToNextLevel = (level: number, currentXp: number): number => {
|
||||||
return nextLevelXp - currentXp;
|
return nextLevelXp - currentXp;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recalculates the levels for all users in the database
|
||||||
|
*/
|
||||||
export async function recalculateUserLevels() {
|
export async function recalculateUserLevels() {
|
||||||
const users = await db.select().from(schema.levelTable);
|
try {
|
||||||
|
const users = await db.select().from(schema.levelTable);
|
||||||
|
|
||||||
for (const user of users) {
|
for (const user of users) {
|
||||||
await addXpToUser(user.discordId, 0);
|
await addXpToUser(user.discordId, 0);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
handleDbError('Failed to recalculate user levels', error as Error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processes a message for XP
|
||||||
|
* @param message - The message to process for XP
|
||||||
|
* @returns - The result of processing the message
|
||||||
|
*/
|
||||||
export async function processMessage(message: Message) {
|
export async function processMessage(message: Message) {
|
||||||
if (message.author.bot || !message.guild) return;
|
if (message.author.bot || !message.guild) return;
|
||||||
|
|
||||||
|
@ -71,38 +106,12 @@ export async function processMessage(message: Message) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function roundRect(
|
/**
|
||||||
ctx: Canvas.SKRSContext2D,
|
* Generates a rank card for the given member
|
||||||
x: number,
|
* @param member - The member to generate a rank card for
|
||||||
y: number,
|
* @param userData - The user's level data
|
||||||
width: number,
|
* @returns - The rank card as an attachment
|
||||||
height: number,
|
*/
|
||||||
radius: number,
|
|
||||||
fill: boolean,
|
|
||||||
) {
|
|
||||||
if (typeof radius === 'undefined') {
|
|
||||||
radius = 5;
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.beginPath();
|
|
||||||
ctx.moveTo(x + radius, y);
|
|
||||||
ctx.lineTo(x + width - radius, y);
|
|
||||||
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
|
|
||||||
ctx.lineTo(x + width, y + height - radius);
|
|
||||||
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
|
|
||||||
ctx.lineTo(x + radius, y + height);
|
|
||||||
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
|
|
||||||
ctx.lineTo(x, y + radius);
|
|
||||||
ctx.quadraticCurveTo(x, y, x + radius, y);
|
|
||||||
ctx.closePath();
|
|
||||||
|
|
||||||
if (fill) {
|
|
||||||
ctx.fill();
|
|
||||||
} else {
|
|
||||||
ctx.stroke();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function generateRankCard(
|
export async function generateRankCard(
|
||||||
member: GuildMember,
|
member: GuildMember,
|
||||||
userData: schema.levelTableTypes,
|
userData: schema.levelTableTypes,
|
||||||
|
@ -125,7 +134,15 @@ export async function generateRankCard(
|
||||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||||
|
|
||||||
context.fillStyle = '#2C2F33';
|
context.fillStyle = '#2C2F33';
|
||||||
roundRect(context, 22, 22, 890, 238, 20, true);
|
roundRect({
|
||||||
|
ctx: context,
|
||||||
|
x: 22,
|
||||||
|
y: 22,
|
||||||
|
width: 890,
|
||||||
|
height: 238,
|
||||||
|
radius: 20,
|
||||||
|
fill: true,
|
||||||
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const avatar = await Canvas.loadImage(
|
const avatar = await Canvas.loadImage(
|
||||||
|
@ -183,19 +200,27 @@ export async function generateRankCard(
|
||||||
);
|
);
|
||||||
|
|
||||||
context.fillStyle = '#484b4E';
|
context.fillStyle = '#484b4E';
|
||||||
roundRect(context, barX, barY, barWidth, barHeight, barHeight / 2, true);
|
roundRect({
|
||||||
|
ctx: context,
|
||||||
|
x: barX,
|
||||||
|
y: barY,
|
||||||
|
width: barWidth,
|
||||||
|
height: barHeight,
|
||||||
|
radius: barHeight / 2,
|
||||||
|
fill: true,
|
||||||
|
});
|
||||||
|
|
||||||
if (progress > 0) {
|
if (progress > 0) {
|
||||||
context.fillStyle = '#5865F2';
|
context.fillStyle = '#5865F2';
|
||||||
roundRect(
|
roundRect({
|
||||||
context,
|
ctx: context,
|
||||||
barX,
|
x: barX,
|
||||||
barY,
|
y: barY,
|
||||||
barWidth * progress,
|
width: barWidth * progress,
|
||||||
barHeight,
|
height: barHeight,
|
||||||
barHeight / 2,
|
radius: barHeight / 2,
|
||||||
true,
|
fill: true,
|
||||||
);
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
context.textAlign = 'center';
|
context.textAlign = 'center';
|
||||||
|
@ -212,6 +237,13 @@ export async function generateRankCard(
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Assigns level roles to a user based on their new level
|
||||||
|
* @param guild - The guild to assign roles in
|
||||||
|
* @param userId - The userId of the user to assign roles to
|
||||||
|
* @param newLevel - The new level of the user
|
||||||
|
* @returns - The highest role that was assigned
|
||||||
|
*/
|
||||||
export async function checkAndAssignLevelRoles(
|
export async function checkAndAssignLevelRoles(
|
||||||
guild: Guild,
|
guild: Guild,
|
||||||
userId: string,
|
userId: string,
|
||||||
|
|
|
@ -1,6 +1,9 @@
|
||||||
import { ChannelType } from 'discord.js';
|
import { ChannelType } from 'discord.js';
|
||||||
import { LogActionType } from './types';
|
import { LogActionType } from './types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Colors for different actions
|
||||||
|
*/
|
||||||
export const ACTION_COLORS: Record<string, number> = {
|
export const ACTION_COLORS: Record<string, number> = {
|
||||||
// Danger actions - Red
|
// Danger actions - Red
|
||||||
ban: 0xff0000,
|
ban: 0xff0000,
|
||||||
|
@ -31,6 +34,9 @@ export const ACTION_COLORS: Record<string, number> = {
|
||||||
default: 0x0099ff,
|
default: 0x0099ff,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Emojis for different actions
|
||||||
|
*/
|
||||||
export const ACTION_EMOJIS: Record<LogActionType, string> = {
|
export const ACTION_EMOJIS: Record<LogActionType, string> = {
|
||||||
roleCreate: '⭐',
|
roleCreate: '⭐',
|
||||||
roleDelete: '🗑️',
|
roleDelete: '🗑️',
|
||||||
|
@ -54,6 +60,9 @@ export const ACTION_EMOJIS: Record<LogActionType, string> = {
|
||||||
roleRemove: '➖',
|
roleRemove: '➖',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Types of channels
|
||||||
|
*/
|
||||||
export const CHANNEL_TYPES: Record<number, string> = {
|
export const CHANNEL_TYPES: Record<number, string> = {
|
||||||
[ChannelType.GuildText]: 'Text Channel',
|
[ChannelType.GuildText]: 'Text Channel',
|
||||||
[ChannelType.GuildVoice]: 'Voice Channel',
|
[ChannelType.GuildVoice]: 'Voice Channel',
|
||||||
|
|
|
@ -1,5 +1,4 @@
|
||||||
import {
|
import {
|
||||||
TextChannel,
|
|
||||||
ButtonStyle,
|
ButtonStyle,
|
||||||
ButtonBuilder,
|
ButtonBuilder,
|
||||||
ActionRowBuilder,
|
ActionRowBuilder,
|
||||||
|
@ -25,7 +24,13 @@ import {
|
||||||
} from './utils.js';
|
} from './utils.js';
|
||||||
import { loadConfig } from '../configLoader.js';
|
import { loadConfig } from '../configLoader.js';
|
||||||
|
|
||||||
export default async function logAction(payload: LogActionPayload) {
|
/**
|
||||||
|
* Logs an action to the log channel
|
||||||
|
* @param payload - The payload to log
|
||||||
|
*/
|
||||||
|
export default async function logAction(
|
||||||
|
payload: LogActionPayload,
|
||||||
|
): Promise<void> {
|
||||||
const config = loadConfig();
|
const config = loadConfig();
|
||||||
const logChannel = payload.guild.channels.cache.get(config.channels.logs);
|
const logChannel = payload.guild.channels.cache.get(config.channels.logs);
|
||||||
if (!logChannel?.isTextBased()) {
|
if (!logChannel?.isTextBased()) {
|
||||||
|
|
|
@ -7,6 +7,9 @@ import {
|
||||||
PermissionsBitField,
|
PermissionsBitField,
|
||||||
} from 'discord.js';
|
} from 'discord.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moderation log action types
|
||||||
|
*/
|
||||||
export type ModerationActionType =
|
export type ModerationActionType =
|
||||||
| 'ban'
|
| 'ban'
|
||||||
| 'kick'
|
| 'kick'
|
||||||
|
@ -14,23 +17,38 @@ export type ModerationActionType =
|
||||||
| 'unban'
|
| 'unban'
|
||||||
| 'unmute'
|
| 'unmute'
|
||||||
| 'warn';
|
| 'warn';
|
||||||
|
/**
|
||||||
|
* Message log action types
|
||||||
|
*/
|
||||||
export type MessageActionType = 'messageDelete' | 'messageEdit';
|
export type MessageActionType = 'messageDelete' | 'messageEdit';
|
||||||
|
/**
|
||||||
|
* Member log action types
|
||||||
|
*/
|
||||||
export type MemberActionType =
|
export type MemberActionType =
|
||||||
| 'memberJoin'
|
| 'memberJoin'
|
||||||
| 'memberLeave'
|
| 'memberLeave'
|
||||||
| 'memberUsernameUpdate'
|
| 'memberUsernameUpdate'
|
||||||
| 'memberNicknameUpdate';
|
| 'memberNicknameUpdate';
|
||||||
|
/**
|
||||||
|
* Role log action types
|
||||||
|
*/
|
||||||
export type RoleActionType =
|
export type RoleActionType =
|
||||||
| 'roleAdd'
|
| 'roleAdd'
|
||||||
| 'roleRemove'
|
| 'roleRemove'
|
||||||
| 'roleCreate'
|
| 'roleCreate'
|
||||||
| 'roleDelete'
|
| 'roleDelete'
|
||||||
| 'roleUpdate';
|
| 'roleUpdate';
|
||||||
|
/**
|
||||||
|
* Channel log action types
|
||||||
|
*/
|
||||||
export type ChannelActionType =
|
export type ChannelActionType =
|
||||||
| 'channelCreate'
|
| 'channelCreate'
|
||||||
| 'channelDelete'
|
| 'channelDelete'
|
||||||
| 'channelUpdate';
|
| 'channelUpdate';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* All log action types
|
||||||
|
*/
|
||||||
export type LogActionType =
|
export type LogActionType =
|
||||||
| ModerationActionType
|
| ModerationActionType
|
||||||
| MessageActionType
|
| MessageActionType
|
||||||
|
@ -38,6 +56,9 @@ export type LogActionType =
|
||||||
| RoleActionType
|
| RoleActionType
|
||||||
| ChannelActionType;
|
| ChannelActionType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Properties of a role
|
||||||
|
*/
|
||||||
export type RoleProperties = {
|
export type RoleProperties = {
|
||||||
name: string;
|
name: string;
|
||||||
color: string;
|
color: string;
|
||||||
|
@ -45,6 +66,9 @@ export type RoleProperties = {
|
||||||
mentionable: boolean;
|
mentionable: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base log action properties
|
||||||
|
*/
|
||||||
export interface BaseLogAction {
|
export interface BaseLogAction {
|
||||||
guild: Guild;
|
guild: Guild;
|
||||||
action: LogActionType;
|
action: LogActionType;
|
||||||
|
@ -53,6 +77,9 @@ export interface BaseLogAction {
|
||||||
duration?: string;
|
duration?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log action properties for moderation actions
|
||||||
|
*/
|
||||||
export interface ModerationLogAction extends BaseLogAction {
|
export interface ModerationLogAction extends BaseLogAction {
|
||||||
action: ModerationActionType;
|
action: ModerationActionType;
|
||||||
target: GuildMember;
|
target: GuildMember;
|
||||||
|
@ -61,6 +88,9 @@ export interface ModerationLogAction extends BaseLogAction {
|
||||||
duration?: string;
|
duration?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log action properties for message actions
|
||||||
|
*/
|
||||||
export interface MessageLogAction extends BaseLogAction {
|
export interface MessageLogAction extends BaseLogAction {
|
||||||
action: MessageActionType;
|
action: MessageActionType;
|
||||||
message: Message<true>;
|
message: Message<true>;
|
||||||
|
@ -68,11 +98,17 @@ export interface MessageLogAction extends BaseLogAction {
|
||||||
newContent?: string;
|
newContent?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log action properties for member actions
|
||||||
|
*/
|
||||||
export interface MemberLogAction extends BaseLogAction {
|
export interface MemberLogAction extends BaseLogAction {
|
||||||
action: 'memberJoin' | 'memberLeave';
|
action: 'memberJoin' | 'memberLeave';
|
||||||
member: GuildMember;
|
member: GuildMember;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log action properties for member username or nickname updates
|
||||||
|
*/
|
||||||
export interface MemberUpdateAction extends BaseLogAction {
|
export interface MemberUpdateAction extends BaseLogAction {
|
||||||
action: 'memberUsernameUpdate' | 'memberNicknameUpdate';
|
action: 'memberUsernameUpdate' | 'memberNicknameUpdate';
|
||||||
member: GuildMember;
|
member: GuildMember;
|
||||||
|
@ -80,6 +116,9 @@ export interface MemberUpdateAction extends BaseLogAction {
|
||||||
newValue: string;
|
newValue: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log action properties for role actions
|
||||||
|
*/
|
||||||
export interface RoleLogAction extends BaseLogAction {
|
export interface RoleLogAction extends BaseLogAction {
|
||||||
action: 'roleAdd' | 'roleRemove';
|
action: 'roleAdd' | 'roleRemove';
|
||||||
member: GuildMember;
|
member: GuildMember;
|
||||||
|
@ -87,6 +126,9 @@ export interface RoleLogAction extends BaseLogAction {
|
||||||
moderator?: GuildMember;
|
moderator?: GuildMember;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log action properties for role updates
|
||||||
|
*/
|
||||||
export interface RoleUpdateAction extends BaseLogAction {
|
export interface RoleUpdateAction extends BaseLogAction {
|
||||||
action: 'roleUpdate';
|
action: 'roleUpdate';
|
||||||
role: Role;
|
role: Role;
|
||||||
|
@ -97,12 +139,18 @@ export interface RoleUpdateAction extends BaseLogAction {
|
||||||
moderator?: GuildMember;
|
moderator?: GuildMember;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log action properties for role creation or deletion
|
||||||
|
*/
|
||||||
export interface RoleCreateDeleteAction extends BaseLogAction {
|
export interface RoleCreateDeleteAction extends BaseLogAction {
|
||||||
action: 'roleCreate' | 'roleDelete';
|
action: 'roleCreate' | 'roleDelete';
|
||||||
role: Role;
|
role: Role;
|
||||||
moderator?: GuildMember;
|
moderator?: GuildMember;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log action properties for channel actions
|
||||||
|
*/
|
||||||
export interface ChannelLogAction extends BaseLogAction {
|
export interface ChannelLogAction extends BaseLogAction {
|
||||||
action: ChannelActionType;
|
action: ChannelActionType;
|
||||||
channel: GuildChannel;
|
channel: GuildChannel;
|
||||||
|
@ -123,6 +171,9 @@ export interface ChannelLogAction extends BaseLogAction {
|
||||||
moderator?: GuildMember;
|
moderator?: GuildMember;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Payload for a log action
|
||||||
|
*/
|
||||||
export type LogActionPayload =
|
export type LogActionPayload =
|
||||||
| ModerationLogAction
|
| ModerationLogAction
|
||||||
| MessageLogAction
|
| MessageLogAction
|
||||||
|
|
|
@ -5,9 +5,15 @@ import {
|
||||||
EmbedField,
|
EmbedField,
|
||||||
PermissionsBitField,
|
PermissionsBitField,
|
||||||
} from 'discord.js';
|
} from 'discord.js';
|
||||||
|
|
||||||
import { LogActionPayload, LogActionType, RoleProperties } from './types.js';
|
import { LogActionPayload, LogActionType, RoleProperties } from './types.js';
|
||||||
import { ACTION_EMOJIS } from './constants.js';
|
import { ACTION_EMOJIS } from './constants.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats a permission name to be more readable
|
||||||
|
* @param perm - The permission to format
|
||||||
|
* @returns - The formatted permission name
|
||||||
|
*/
|
||||||
export const formatPermissionName = (perm: string): string => {
|
export const formatPermissionName = (perm: string): string => {
|
||||||
return perm
|
return perm
|
||||||
.split('_')
|
.split('_')
|
||||||
|
@ -15,6 +21,12 @@ export const formatPermissionName = (perm: string): string => {
|
||||||
.join(' ');
|
.join(' ');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a field for a user
|
||||||
|
* @param user - The user to create a field for
|
||||||
|
* @param label - The label for the field
|
||||||
|
* @returns - The created field
|
||||||
|
*/
|
||||||
export const createUserField = (
|
export const createUserField = (
|
||||||
user: User | GuildMember,
|
user: User | GuildMember,
|
||||||
label = 'User',
|
label = 'User',
|
||||||
|
@ -24,6 +36,12 @@ export const createUserField = (
|
||||||
inline: true,
|
inline: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a field for a moderator
|
||||||
|
* @param moderator - The moderator to create a field for
|
||||||
|
* @param label - The label for the field
|
||||||
|
* @returns - The created field
|
||||||
|
*/
|
||||||
export const createModeratorField = (
|
export const createModeratorField = (
|
||||||
moderator?: GuildMember,
|
moderator?: GuildMember,
|
||||||
label = 'Moderator',
|
label = 'Moderator',
|
||||||
|
@ -36,12 +54,23 @@ export const createModeratorField = (
|
||||||
}
|
}
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a field for a channel
|
||||||
|
* @param channel - The channel to create a field for
|
||||||
|
* @returns - The created field
|
||||||
|
*/
|
||||||
export const createChannelField = (channel: GuildChannel): EmbedField => ({
|
export const createChannelField = (channel: GuildChannel): EmbedField => ({
|
||||||
name: 'Channel',
|
name: 'Channel',
|
||||||
value: `<#${channel.id}>`,
|
value: `<#${channel.id}>`,
|
||||||
inline: true,
|
inline: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a field for changed permissions
|
||||||
|
* @param oldPerms - The old permissions
|
||||||
|
* @param newPerms - The new permissions
|
||||||
|
* @returns - The created fields
|
||||||
|
*/
|
||||||
export const createPermissionChangeFields = (
|
export const createPermissionChangeFields = (
|
||||||
oldPerms: Readonly<PermissionsBitField>,
|
oldPerms: Readonly<PermissionsBitField>,
|
||||||
newPerms: Readonly<PermissionsBitField>,
|
newPerms: Readonly<PermissionsBitField>,
|
||||||
|
@ -84,6 +113,11 @@ export const createPermissionChangeFields = (
|
||||||
return fields;
|
return fields;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the names of the permissions in a bitfield
|
||||||
|
* @param permissions - The permissions to get the names of
|
||||||
|
* @returns - The names of the permissions
|
||||||
|
*/
|
||||||
export const getPermissionNames = (
|
export const getPermissionNames = (
|
||||||
permissions: Readonly<PermissionsBitField>,
|
permissions: Readonly<PermissionsBitField>,
|
||||||
): string[] => {
|
): string[] => {
|
||||||
|
@ -98,6 +132,12 @@ export const getPermissionNames = (
|
||||||
return names;
|
return names;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compares two bitfields and returns the names of the permissions that are in the first bitfield but not the second
|
||||||
|
* @param a - The first bitfield
|
||||||
|
* @param b - The second bitfield
|
||||||
|
* @returns - The names of the permissions that are in the first bitfield but not the second
|
||||||
|
*/
|
||||||
export const getPermissionDifference = (
|
export const getPermissionDifference = (
|
||||||
a: Readonly<PermissionsBitField>,
|
a: Readonly<PermissionsBitField>,
|
||||||
b: Readonly<PermissionsBitField>,
|
b: Readonly<PermissionsBitField>,
|
||||||
|
@ -114,6 +154,12 @@ export const getPermissionDifference = (
|
||||||
return names;
|
return names;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a field for a role
|
||||||
|
* @param oldRole - The old role
|
||||||
|
* @param newRole - The new role
|
||||||
|
* @returns - The fields for the role changes
|
||||||
|
*/
|
||||||
export const createRoleChangeFields = (
|
export const createRoleChangeFields = (
|
||||||
oldRole: Partial<RoleProperties>,
|
oldRole: Partial<RoleProperties>,
|
||||||
newRole: Partial<RoleProperties>,
|
newRole: Partial<RoleProperties>,
|
||||||
|
@ -153,6 +199,11 @@ export const createRoleChangeFields = (
|
||||||
return fields;
|
return fields;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the ID of the item that was logged
|
||||||
|
* @param payload - The payload to get the log item ID from
|
||||||
|
* @returns - The ID of the log item
|
||||||
|
*/
|
||||||
export const getLogItemId = (payload: LogActionPayload): string => {
|
export const getLogItemId = (payload: LogActionPayload): string => {
|
||||||
switch (payload.action) {
|
switch (payload.action) {
|
||||||
case 'roleCreate':
|
case 'roleCreate':
|
||||||
|
@ -188,6 +239,11 @@ export const getLogItemId = (payload: LogActionPayload): string => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the emoji for an action
|
||||||
|
* @param action - The action to get an emoji for
|
||||||
|
* @returns - The emoji for the action
|
||||||
|
*/
|
||||||
export const getEmojiForAction = (action: LogActionType): string => {
|
export const getEmojiForAction = (action: LogActionType): string => {
|
||||||
return ACTION_EMOJIS[action] || '📝';
|
return ACTION_EMOJIS[action] || '📝';
|
||||||
};
|
};
|
||||||
|
|
151
src/util/notificationHandler.ts
Normal file
151
src/util/notificationHandler.ts
Normal file
|
@ -0,0 +1,151 @@
|
||||||
|
import { Client, Guild, GuildMember } from 'discord.js';
|
||||||
|
import { loadConfig } from './configLoader.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Types of notifications that can be sent
|
||||||
|
*/
|
||||||
|
export enum NotificationType {
|
||||||
|
// Redis notifications
|
||||||
|
REDIS_CONNECTION_LOST = 'REDIS_CONNECTION_LOST',
|
||||||
|
REDIS_CONNECTION_RESTORED = 'REDIS_CONNECTION_RESTORED',
|
||||||
|
|
||||||
|
// Database notifications
|
||||||
|
DATABASE_CONNECTION_LOST = 'DATABASE_CONNECTION_LOST',
|
||||||
|
DATABASE_CONNECTION_RESTORED = 'DATABASE_CONNECTION_RESTORED',
|
||||||
|
|
||||||
|
// Bot notifications
|
||||||
|
BOT_RESTARTING = 'BOT_RESTARTING',
|
||||||
|
BOT_ERROR = 'BOT_ERROR',
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maps notification types to their messages
|
||||||
|
*/
|
||||||
|
const NOTIFICATION_MESSAGES = {
|
||||||
|
[NotificationType.REDIS_CONNECTION_LOST]:
|
||||||
|
'⚠️ **Redis Connection Lost**\n\nThe bot has lost connection to Redis after multiple retry attempts. Caching functionality is disabled until the connection is restored.',
|
||||||
|
[NotificationType.REDIS_CONNECTION_RESTORED]:
|
||||||
|
'✅ **Redis Connection Restored**\n\nThe bot has successfully reconnected to Redis. All caching functionality has been restored.',
|
||||||
|
|
||||||
|
[NotificationType.DATABASE_CONNECTION_LOST]:
|
||||||
|
'🚨 **Database Connection Lost**\n\nThe bot has lost connection to the database after multiple retry attempts. The bot cannot function properly without database access and will shut down.',
|
||||||
|
[NotificationType.DATABASE_CONNECTION_RESTORED]:
|
||||||
|
'✅ **Database Connection Restored**\n\nThe bot has successfully reconnected to the database.',
|
||||||
|
|
||||||
|
[NotificationType.BOT_RESTARTING]:
|
||||||
|
'🔄 **Bot Restarting**\n\nThe bot is being restarted. Services will be temporarily unavailable.',
|
||||||
|
[NotificationType.BOT_ERROR]:
|
||||||
|
'🚨 **Critical Bot Error**\n\nThe bot has encountered a critical error and may not function correctly.',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a Discord-friendly timestamp string
|
||||||
|
* @returns Formatted Discord timestamp string
|
||||||
|
*/
|
||||||
|
function createDiscordTimestamp(): string {
|
||||||
|
const timestamp = Math.floor(Date.now() / 1000);
|
||||||
|
return `<t:${timestamp}:F> (<t:${timestamp}:R>)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets all managers with the Manager role
|
||||||
|
* @param guild - The guild to search in
|
||||||
|
* @returns Array of members with the Manager role
|
||||||
|
*/
|
||||||
|
async function getManagers(guild: Guild): Promise<GuildMember[]> {
|
||||||
|
const config = loadConfig();
|
||||||
|
const managerRoleId = config.roles?.staffRoles?.find(
|
||||||
|
(role) => role.name === 'Manager',
|
||||||
|
)?.roleId;
|
||||||
|
|
||||||
|
if (!managerRoleId) {
|
||||||
|
console.warn('Manager role not found in config');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await guild.members.fetch();
|
||||||
|
|
||||||
|
return Array.from(
|
||||||
|
guild.members.cache
|
||||||
|
.filter(
|
||||||
|
(member) => member.roles.cache.has(managerRoleId) && !member.user.bot,
|
||||||
|
)
|
||||||
|
.values(),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching managers:', error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends a notification to users with the Manager role
|
||||||
|
* @param client - Discord client instance
|
||||||
|
* @param type - Type of notification to send
|
||||||
|
* @param customMessage - Optional custom message to append
|
||||||
|
*/
|
||||||
|
export async function notifyManagers(
|
||||||
|
client: Client,
|
||||||
|
type: NotificationType,
|
||||||
|
customMessage?: string,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const config = loadConfig();
|
||||||
|
const guild = client.guilds.cache.get(config.guildId);
|
||||||
|
|
||||||
|
if (!guild) {
|
||||||
|
console.error(`Guild with ID ${config.guildId} not found`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const managers = await getManagers(guild);
|
||||||
|
|
||||||
|
if (managers.length === 0) {
|
||||||
|
console.warn('No managers found to notify');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseMessage = NOTIFICATION_MESSAGES[type];
|
||||||
|
const timestamp = createDiscordTimestamp();
|
||||||
|
const fullMessage = customMessage
|
||||||
|
? `${baseMessage}\n\n${customMessage}`
|
||||||
|
: baseMessage;
|
||||||
|
|
||||||
|
let successCount = 0;
|
||||||
|
for (const manager of managers) {
|
||||||
|
try {
|
||||||
|
await manager.send({
|
||||||
|
content: `${fullMessage}\n\nTimestamp: ${timestamp}`,
|
||||||
|
});
|
||||||
|
successCount++;
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
`Failed to send DM to manager ${manager.user.tag}:`,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`Sent ${type} notification to ${successCount}/${managers.length} managers`,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error sending manager notifications:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log a manager-level notification to the console
|
||||||
|
* @param type - Type of notification
|
||||||
|
* @param details - Additional details
|
||||||
|
*/
|
||||||
|
export function logManagerNotification(
|
||||||
|
type: NotificationType,
|
||||||
|
details?: string,
|
||||||
|
): void {
|
||||||
|
const baseMessage = NOTIFICATION_MESSAGES[type].split('\n')[0];
|
||||||
|
console.warn(
|
||||||
|
`MANAGER NOTIFICATION: ${baseMessage}${details ? ` | ${details}` : ''}`,
|
||||||
|
);
|
||||||
|
}
|
Loading…
Add table
Reference in a new issue