Compare commits

..

No commits in common. "7ea009714bea8e45d9e52499b02677e7ec029c9a" and "c40f26c640998f2066067bd8f7f349f8e8db6176" have entirely different histories.

4 changed files with 170 additions and 220 deletions

View File

@ -1,94 +1,70 @@
import DiscordInteractionCommand from '../../util/DiscordInteractionCommand'; import DiscordInteractionCommand from "../../util/DiscordInteractionCommand";
import { MemberModel } from '../../database/Member'; import { MemberModel } from "../../database/Member";
import Partner, { import Partner, { PartnerCommissionType, PartnerDepartment, PartnerModel, PartnerRoleType } from "../../database/Partner";
PartnerCommissionType, import { ChatInputCommandInteraction, EmbedBuilder, GuildMember } from "discord.js";
PartnerDepartment, import MemberUtil from "../../util/MemberUtil";
PartnerModel, import EmojiConfig from "../../util/EmojiConfig"
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) => this.builder.addUserOption(option => option.setName("member").setDescription("The member to get information about.").setRequired(true));
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 = const guild = interaction.guild || interaction.client.guilds.cache.get(this.GUILD_ID);
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) if (!guildMember) return interaction.editReply({ content: `Member target ${target.id} was not located.`});
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({ embed.setAuthor({ name: formattedName.text, iconURL: formattedName.iconURL });
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) if (partner.title) embedDescription += `## __${EmojiConfig.LOC} ${partner.title}__\n`;
embedDescription += `## __${EmojiConfig.LOC} ${partner.title}__\n`; embedDescription += "### Partner Information\n";
embedDescription += '### Partner Information\n'; if (partner.emailAddress) embedDescription += `**Email Address**: ${partner.emailAddress}\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 += embedDescription += "**Commission Type**: Contractual/Independent/Collaborator\n";
'**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) {
@ -100,39 +76,27 @@ 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) { if (guildMember.presence?.status) { // TODO: this currently doesn't work for some reason
// 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({ embed.addFields({ name: "Status", value: "Do Not Disturb", inline: true });
name: 'Status',
value: 'Do Not Disturb',
inline: true,
});
break; break;
case 'offline': case "offline" || "invisible":
embed.addFields({ name: 'Status', value: 'Offline', inline: true }); embed.addFields({ name: "Status", value: "Online", 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({ embed.setFooter({ text: `Discord ID: ${guildMember.id}${databaseMember ? `Internal ID: ${databaseMember?._id}` : ''}` });
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,14 +1,13 @@
import { Client, GatewayIntentBits, Partials, REST, Routes } from 'discord.js'; import { Client, GatewayIntentBits, Partials, REST, Routes } from "discord.js";
import { discordBotToken, discordClientID, MongoDbUrl } from './config.json'; import { discordBotToken, discordClientID } 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> = export const DiscordInteractionCommands: Collection<DiscordInteractionCommand> = new Collection();
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
@ -22,12 +21,7 @@ const discordClient = new Client({
GatewayIntentBits.GuildInvites, GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildModeration, GatewayIntentBits.GuildModeration,
], ],
partials: [ partials: [ Partials.GuildMember, Partials.Message, Partials.User, Partials.Channel, ],
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 });
@ -35,12 +29,11 @@ const discordREST = new REST().setToken(discordBotToken);
export async function main() { export async function main() {
// Connect to the databases // Connect to the databases
try { try {
//@ts-ignore mongoose.connection.once("open", () => {
mongoose.connection.once('open', () => { console.info("[Info - Database] Connected to MongoDB");
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(MongoDbUrl, {}); await mongoose.connect("mongodb://localhost:27017/crra-main", {});
} 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);
@ -49,9 +42,7 @@ 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( console.info(`[Info - Discord] Loaded interaction command: ${instance.name}`);
`[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)) {
@ -63,9 +54,7 @@ export async function main() {
await discordClient.login(discordBotToken); await discordClient.login(discordBotToken);
try { try {
console.log( console.log(`Started refreshing ${DiscordInteractionCommands.size} application (/) commands.`);
`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());
@ -74,11 +63,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,7 +1,4 @@
{ {
"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": "./dist" /* Specify an output folder for all emitted files. */, // "outDir": "./", /* 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. */