Compare commits

..

3 Commits

Author SHA1 Message Date
Pax 7ea009714b misc fixes 2024-10-25 06:36:49 +04:00
Pax 373cb814c3 readd sctipts, and use outdir option in tsconfig 2024-10-25 06:14:19 +04:00
Pax f27ec17bed strings are always truthy fix 2024-10-25 06:05:13 +04:00
4 changed files with 220 additions and 170 deletions

View File

@ -1,70 +1,94 @@
import DiscordInteractionCommand from "../../util/DiscordInteractionCommand"; import DiscordInteractionCommand from '../../util/DiscordInteractionCommand';
import { MemberModel } from "../../database/Member"; import { MemberModel } from '../../database/Member';
import Partner, { PartnerCommissionType, PartnerDepartment, PartnerModel, PartnerRoleType } from "../../database/Partner"; import Partner, {
import { ChatInputCommandInteraction, EmbedBuilder, GuildMember } from "discord.js"; PartnerCommissionType,
import MemberUtil from "../../util/MemberUtil"; PartnerDepartment,
import EmojiConfig from "../../util/EmojiConfig" PartnerModel,
PartnerRoleType,
} from '../../database/Partner';
import {
ChatInputCommandInteraction,
EmbedBuilder,
GuildMember,
} from 'discord.js';
import MemberUtil from '../../util/MemberUtil';
import EmojiConfig from '../../util/EmojiConfig';
export default class Whois extends DiscordInteractionCommand { export default class Whois extends DiscordInteractionCommand {
constructor() { constructor() {
super("whois", "Retrieves information about a user."); super('whois', 'Retrieves information about a user.');
this.builder.addUserOption(option => option.setName("member").setDescription("The member to get information about.").setRequired(true)); this.builder.addUserOption((option) =>
option
.setName('member')
.setDescription('The member to get information about.')
.setRequired(true)
);
} }
public async execute(interaction: ChatInputCommandInteraction) { public async execute(interaction: ChatInputCommandInteraction) {
// defer our reply and perform database/external API operations/lookups // defer our reply and perform database/external API operations/lookups
await interaction.deferReply({ ephemeral: false }); await interaction.deferReply({ ephemeral: false });
const target = interaction.options.getUser("member", true); const target = interaction.options.getUser('member', true);
const guild = interaction.guild || interaction.client.guilds.cache.get(this.GUILD_ID); const guild =
interaction.guild || interaction.client.guilds.cache.get(this.GUILD_ID);
const guildMember = await guild?.members.fetch(target.id); const guildMember = await guild?.members.fetch(target.id);
const databaseMember = await MemberModel.findOne({ discordID: target.id }); const databaseMember = await MemberModel.findOne({ discordID: target.id });
const partner = await PartnerModel.findOne({ discordID: target.id }); const partner = await PartnerModel.findOne({ discordID: target.id });
// return an error if target was not located // return an error if target was not located
if (!guildMember) return interaction.editReply({ content: `Member target ${target.id} was not located.`}); if (!guildMember)
return interaction.editReply({
content: `Member target ${target.id} was not located.`,
});
// build our embed // build our embed
const embed = new EmbedBuilder(); const embed = new EmbedBuilder();
// if the role type is managerial, add a [k] to the end of the name // if the role type is managerial, add a [k] to the end of the name
// if the partner exists, set the iconURL to the organizational logo // if the partner exists, set the iconURL to the organizational logo
const formattedName = MemberUtil.formatName(guildMember, partner); const formattedName = MemberUtil.formatName(guildMember, partner);
embed.setAuthor({ name: formattedName.text, iconURL: formattedName.iconURL }); embed.setAuthor({
name: formattedName.text,
iconURL: formattedName.iconURL,
});
// set the thumbnail to the user's avatar // set the thumbnail to the user's avatar
embed.setThumbnail(guildMember.user.displayAvatarURL()); embed.setThumbnail(guildMember.user.displayAvatarURL());
// initialize the description string // initialize the description string
let embedDescription = ''; let embedDescription = '';
if (partner) { if (partner) {
// set the title to the partner's title if applicable // set the title to the partner's title if applicable
if (partner.title) embedDescription += `## __${EmojiConfig.LOC} ${partner.title}__\n`; if (partner.title)
embedDescription += "### Partner Information\n"; embedDescription += `## __${EmojiConfig.LOC} ${partner.title}__\n`;
if (partner.emailAddress) embedDescription += `**Email Address**: ${partner.emailAddress}\n`; embedDescription += '### Partner Information\n';
if (partner.emailAddress)
embedDescription += `**Email Address**: ${partner.emailAddress}\n`;
switch (partner.department) { switch (partner.department) {
case PartnerDepartment.ENGINEERING: case PartnerDepartment.ENGINEERING:
embedDescription += "**Department**: Dept. of Engineering\n"; embedDescription += '**Department**: Dept. of Engineering\n';
break; break;
case PartnerDepartment.OPERATIONS: case PartnerDepartment.OPERATIONS:
embedDescription += "**Department**: Dept. of Operations\n"; embedDescription += '**Department**: Dept. of Operations\n';
break; break;
case PartnerDepartment.INDEPENDENT_AGENCY: case PartnerDepartment.INDEPENDENT_AGENCY:
embedDescription += "**Department**: Independent Agency/Contractor\n"; embedDescription += '**Department**: Independent Agency/Contractor\n';
break; break;
} }
switch (partner.commissionType) { switch (partner.commissionType) {
case PartnerCommissionType.TENURE: case PartnerCommissionType.TENURE:
embedDescription += "**Commission Type**: Tenure\n"; embedDescription += '**Commission Type**: Tenure\n';
break; break;
case PartnerCommissionType.PROVISIONAL: case PartnerCommissionType.PROVISIONAL:
embedDescription += "**Commission Type**: Provisional\n"; embedDescription += '**Commission Type**: Provisional\n';
break; break;
case PartnerCommissionType.CONTRACTUAL: case PartnerCommissionType.CONTRACTUAL:
embedDescription += "**Commission Type**: Contractual/Independent/Collaborator\n"; embedDescription +=
'**Commission Type**: Contractual/Independent/Collaborator\n';
break; break;
case PartnerCommissionType.ACTING: case PartnerCommissionType.ACTING:
embedDescription += "**Commission Type**: Acting\n"; embedDescription += '**Commission Type**: Acting\n';
break; break;
case PartnerCommissionType.INTERIM: case PartnerCommissionType.INTERIM:
embedDescription += "**Commission Type**: Interim\n"; embedDescription += '**Commission Type**: Interim\n';
break; break;
case PartnerCommissionType.TRIAL: case PartnerCommissionType.TRIAL:
embedDescription += "**Commission Type**: Trial/Intern\n"; embedDescription += '**Commission Type**: Trial/Intern\n';
break; break;
} }
if (partner.directReport) { if (partner.directReport) {
@ -76,27 +100,39 @@ export default class Whois extends DiscordInteractionCommand {
embed.setColor(guildMember.displayColor); embed.setColor(guildMember.displayColor);
if (embedDescription?.length > 0) embed.setDescription(embedDescription); if (embedDescription?.length > 0) embed.setDescription(embedDescription);
// add status to embed // add status to embed
if (guildMember.presence?.status) { // TODO: this currently doesn't work for some reason if (guildMember.presence?.status) {
// TODO: this currently doesn't work for some reason
switch (guildMember.presence.status) { switch (guildMember.presence.status) {
case "online": case 'online':
embed.addFields({ name: "Status", value: "Online", inline: true }); embed.addFields({ name: 'Status', value: 'Online', inline: true });
break; break;
case "idle": case 'idle':
embed.addFields({ name: "Status", value: "Idle", inline: true }); embed.addFields({ name: 'Status', value: 'Idle', inline: true });
break; break;
case "dnd": case 'dnd':
embed.addFields({ name: "Status", value: "Do Not Disturb", inline: true }); embed.addFields({
name: 'Status',
value: 'Do Not Disturb',
inline: true,
});
break; break;
case "offline" || "invisible": case 'offline':
embed.addFields({ name: "Status", value: "Online", inline: true }); embed.addFields({ name: 'Status', value: 'Offline', inline: true });
break;
case 'invisible':
embed.addFields({ name: 'Status', value: 'invisible', inline: true });
break; break;
default: default:
// TODO: decide what placeholder we should use for values that fall "out of range" // TODO: decide what placeholder we should use for values that fall "out of range"
embed.addFields({ name: "Status", value: "", inline: true }); embed.addFields({ name: 'Status', value: '', inline: true });
break; break;
} }
} }
embed.setFooter({ text: `Discord ID: ${guildMember.id}${databaseMember ? `Internal ID: ${databaseMember?._id}` : ''}` }); embed.setFooter({
text: `Discord ID: ${guildMember.id}${
databaseMember ? `Internal ID: ${databaseMember?._id}` : ''
}`,
});
return await interaction.editReply({ embeds: [embed] }); return await interaction.editReply({ embeds: [embed] });
} }

View File

@ -1,13 +1,14 @@
import { Client, GatewayIntentBits, Partials, REST, Routes } from "discord.js"; import { Client, GatewayIntentBits, Partials, REST, Routes } from 'discord.js';
import { discordBotToken, discordClientID } from "./config.json" import { discordBotToken, discordClientID, MongoDbUrl } from './config.json';
import Collection from "./util/Collection"; import Collection from './util/Collection';
import DiscordInteractionCommand from "./util/DiscordInteractionCommand"; import DiscordInteractionCommand from './util/DiscordInteractionCommand';
import DiscordEvent from "./util/DiscordEvent"; import DiscordEvent from './util/DiscordEvent';
import * as DiscordInteractionCommandsIndex from "./discord/commands"; import * as DiscordInteractionCommandsIndex from './discord/commands';
import * as DiscordEventsIndex from "./discord/events"; import * as DiscordEventsIndex from './discord/events';
import mongoose from "mongoose"; import mongoose from 'mongoose';
export const DiscordInteractionCommands: Collection<DiscordInteractionCommand> = new Collection(); export const DiscordInteractionCommands: Collection<DiscordInteractionCommand> =
new Collection();
export const DiscordEvents: Collection<DiscordEvent> = new Collection(); export const DiscordEvents: Collection<DiscordEvent> = new Collection();
// Instantiates a new Discord client // Instantiates a new Discord client
@ -21,7 +22,12 @@ const discordClient = new Client({
GatewayIntentBits.GuildInvites, GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildModeration, GatewayIntentBits.GuildModeration,
], ],
partials: [ Partials.GuildMember, Partials.Message, Partials.User, Partials.Channel, ], partials: [
Partials.GuildMember,
Partials.Message,
Partials.User,
Partials.Channel,
],
}); });
const discordREST = new REST().setToken(discordBotToken); const discordREST = new REST().setToken(discordBotToken);
// const stripeClient = new Stripe(stripeToken, { typescript: true }); // const stripeClient = new Stripe(stripeToken, { typescript: true });
@ -29,11 +35,12 @@ const discordREST = new REST().setToken(discordBotToken);
export async function main() { export async function main() {
// Connect to the databases // Connect to the databases
try { try {
mongoose.connection.once("open", () => { //@ts-ignore
console.info("[Info - Database] Connected to MongoDB"); mongoose.connection.once('open', () => {
}) console.info('[Info - Database] Connected to MongoDB');
});
// TODO: Fetch the MongoDB URI from the config file // TODO: Fetch the MongoDB URI from the config file
await mongoose.connect("mongodb://localhost:27017/crra-main", {}); await mongoose.connect(MongoDbUrl, {});
} catch (error) { } catch (error) {
console.error(`[Error - Database] Failed to connect to MongoDB: ${error}`); console.error(`[Error - Database] Failed to connect to MongoDB: ${error}`);
process.exit(1); process.exit(1);
@ -42,7 +49,9 @@ export async function main() {
for (const Command of Object.values(DiscordInteractionCommandsIndex)) { for (const Command of Object.values(DiscordInteractionCommandsIndex)) {
const instance = new Command(); const instance = new Command();
DiscordInteractionCommands.add(instance.name, instance); DiscordInteractionCommands.add(instance.name, instance);
console.info(`[Info - Discord] Loaded interaction command: ${instance.name}`); console.info(
`[Info - Discord] Loaded interaction command: ${instance.name}`
);
} }
// Load Discord events // Load Discord events
for (const Event of Object.values(DiscordEventsIndex)) { for (const Event of Object.values(DiscordEventsIndex)) {
@ -54,7 +63,9 @@ export async function main() {
await discordClient.login(discordBotToken); await discordClient.login(discordBotToken);
try { try {
console.log(`Started refreshing ${DiscordInteractionCommands.size} application (/) commands.`); console.log(
`Started refreshing ${DiscordInteractionCommands.size} application (/) commands.`
);
const interactionCommandsData = []; const interactionCommandsData = [];
for (const command of DiscordInteractionCommands.values()) { for (const command of DiscordInteractionCommands.values()) {
interactionCommandsData.push(command.builder.toJSON()); interactionCommandsData.push(command.builder.toJSON());
@ -63,11 +74,11 @@ export async function main() {
// The put method is used to fully refresh all commands in the guild with the current set // The put method is used to fully refresh all commands in the guild with the current set
const data = await discordREST.put( const data = await discordREST.put(
Routes.applicationCommands(discordClientID), Routes.applicationCommands(discordClientID),
{ body: interactionCommandsData }, { body: interactionCommandsData }
);
console.log(
`Successfully reloaded ${interactionCommandsData?.length} application (/) commands.`
); );
// @ts-ignore
console.log(`Successfully reloaded ${data?.length} application (/) commands.`);
} catch (error) { } catch (error) {
// And of course, make sure you catch and log any errors! // And of course, make sure you catch and log any errors!
console.error(error); console.error(error);

View File

@ -1,4 +1,7 @@
{ {
"scripts": {
"start": "npx tsc && node dist/index.js"
},
"devDependencies": { "devDependencies": {
"@types/uuid": "^9.0.8", "@types/uuid": "^9.0.8",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",

View File

@ -11,11 +11,11 @@
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */ /* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */ // "jsx": "preserve", /* Specify what JSX code is generated. */
"experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ "experimentalDecorators": true /* Enable experimental support for legacy experimental decorators. */,
"emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ "emitDecoratorMetadata": true /* Emit design-type metadata for decorated declarations in source files. */,
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
@ -25,7 +25,7 @@
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */ /* Modules */
"module": "commonjs", /* Specify what module code is generated. */ "module": "commonjs" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */ // "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
@ -39,7 +39,7 @@
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
"resolveJsonModule": true, /* Enable importing .json files. */ "resolveJsonModule": true /* Enable importing .json files. */,
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
@ -55,7 +55,7 @@
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */ "outDir": "./dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */ // "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */ // "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
@ -77,12 +77,12 @@
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */ /* Type Checking */
"strict": true, /* Enable all strict type-checking options. */ "strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */