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,139 +1,103 @@
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) return interaction.editReply({ content: `Member target ${target.id} was not located.`});
if (!guildMember) // build our embed
return interaction.editReply({ const embed = new EmbedBuilder();
content: `Member target ${target.id} was not located.`, // 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
// build our embed const formattedName = MemberUtil.formatName(guildMember, partner);
const embed = new EmbedBuilder(); embed.setAuthor({ name: formattedName.text, iconURL: formattedName.iconURL });
// if the role type is managerial, add a [k] to the end of the name // set the thumbnail to the user's avatar
// if the partner exists, set the iconURL to the organizational logo embed.setThumbnail(guildMember.user.displayAvatarURL());
const formattedName = MemberUtil.formatName(guildMember, partner); // initialize the description string
embed.setAuthor({ let embedDescription = '';
name: formattedName.text, if (partner) {
iconURL: formattedName.iconURL, // set the title to the partner's title if applicable
}); if (partner.title) embedDescription += `## __${EmojiConfig.LOC} ${partner.title}__\n`;
// set the thumbnail to the user's avatar embedDescription += "### Partner Information\n";
embed.setThumbnail(guildMember.user.displayAvatarURL()); if (partner.emailAddress) embedDescription += `**Email Address**: ${partner.emailAddress}\n`;
// initialize the description string switch (partner.department) {
let embedDescription = ''; case PartnerDepartment.ENGINEERING:
if (partner) { embedDescription += "**Department**: Dept. of Engineering\n";
// set the title to the partner's title if applicable break;
if (partner.title) case PartnerDepartment.OPERATIONS:
embedDescription += `## __${EmojiConfig.LOC} ${partner.title}__\n`; embedDescription += "**Department**: Dept. of Operations\n";
embedDescription += '### Partner Information\n'; break;
if (partner.emailAddress) case PartnerDepartment.INDEPENDENT_AGENCY:
embedDescription += `**Email Address**: ${partner.emailAddress}\n`; embedDescription += "**Department**: Independent Agency/Contractor\n";
switch (partner.department) { break;
case PartnerDepartment.ENGINEERING: }
embedDescription += '**Department**: Dept. of Engineering\n'; switch (partner.commissionType) {
break; case PartnerCommissionType.TENURE:
case PartnerDepartment.OPERATIONS: embedDescription += "**Commission Type**: Tenure\n";
embedDescription += '**Department**: Dept. of Operations\n'; break;
break; case PartnerCommissionType.PROVISIONAL:
case PartnerDepartment.INDEPENDENT_AGENCY: embedDescription += "**Commission Type**: Provisional\n";
embedDescription += '**Department**: Independent Agency/Contractor\n'; break;
break; case PartnerCommissionType.CONTRACTUAL:
} embedDescription += "**Commission Type**: Contractual/Independent/Collaborator\n";
switch (partner.commissionType) { break;
case PartnerCommissionType.TENURE: case PartnerCommissionType.ACTING:
embedDescription += '**Commission Type**: Tenure\n'; embedDescription += "**Commission Type**: Acting\n";
break; break;
case PartnerCommissionType.PROVISIONAL: case PartnerCommissionType.INTERIM:
embedDescription += '**Commission Type**: Provisional\n'; embedDescription += "**Commission Type**: Interim\n";
break; break;
case PartnerCommissionType.CONTRACTUAL: case PartnerCommissionType.TRIAL:
embedDescription += embedDescription += "**Commission Type**: Trial/Intern\n";
'**Commission Type**: Contractual/Independent/Collaborator\n'; break;
break; }
case PartnerCommissionType.ACTING: if (partner.directReport) {
embedDescription += '**Commission Type**: Acting\n'; if (partner.directReport instanceof Partner) {
break; embedDescription += `**Direct Report**: ${partner.directReport.title}\n`;
case PartnerCommissionType.INTERIM: }
embedDescription += '**Commission Type**: Interim\n'; }
break;
case PartnerCommissionType.TRIAL:
embedDescription += '**Commission Type**: Trial/Intern\n';
break;
}
if (partner.directReport) {
if (partner.directReport instanceof Partner) {
embedDescription += `**Direct Report**: ${partner.directReport.title}\n`;
} }
} embed.setColor(guildMember.displayColor);
} if (embedDescription?.length > 0) embed.setDescription(embedDescription);
embed.setColor(guildMember.displayColor); // add status to embed
if (embedDescription?.length > 0) embed.setDescription(embedDescription); if (guildMember.presence?.status) { // TODO: this currently doesn't work for some reason
// add status to embed switch (guildMember.presence.status) {
if (guildMember.presence?.status) { case "online":
// TODO: this currently doesn't work for some reason embed.addFields({ name: "Status", value: "Online", inline: true });
switch (guildMember.presence.status) { break;
case 'online': case "idle":
embed.addFields({ name: 'Status', value: 'Online', inline: true }); embed.addFields({ name: "Status", value: "Idle", inline: true });
break; break;
case 'idle': case "dnd":
embed.addFields({ name: 'Status', value: 'Idle', inline: true }); embed.addFields({ name: "Status", value: "Do Not Disturb", inline: true });
break; break;
case 'dnd': case "offline" || "invisible":
embed.addFields({ embed.addFields({ name: "Status", value: "Online", inline: true });
name: 'Status', break;
value: 'Do Not Disturb', default:
inline: true, // TODO: decide what placeholder we should use for values that fall "out of range"
}); embed.addFields({ name: "Status", value: "", inline: true });
break; break;
case 'offline': }
embed.addFields({ name: 'Status', value: 'Offline', inline: true }); }
break; embed.setFooter({ text: `Discord ID: ${guildMember.id}${databaseMember ? `Internal ID: ${databaseMember?._id}` : ''}` });
case 'invisible':
embed.addFields({ name: 'Status', value: 'invisible', inline: true });
break;
default:
// TODO: decide what placeholder we should use for values that fall "out of range"
embed.addFields({ name: 'Status', value: '', inline: true });
break;
}
}
embed.setFooter({
text: `Discord ID: ${guildMember.id}${
databaseMember ? `Internal ID: ${databaseMember?._id}` : ''
}`,
});
return await interaction.editReply({ embeds: [embed] }); return await interaction.editReply({ embeds: [embed] });
} }
} }

135
index.ts
View File

@ -1,88 +1,77 @@
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
const discordClient = new Client({ const discordClient = new Client({
intents: [ intents: [
GatewayIntentBits.DirectMessages, GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildIntegrations, GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessages,
GatewayIntentBits.Guilds, GatewayIntentBits.Guilds,
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 });
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("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);
}
// Load Discord interaction commands
for (const Command of Object.values(DiscordInteractionCommandsIndex)) {
const instance = new Command();
DiscordInteractionCommands.add(instance.name, instance);
console.info(
`[Info - Discord] Loaded interaction command: ${instance.name}`
);
}
// Load Discord events
for (const Event of Object.values(DiscordEventsIndex)) {
const instance = new Event(discordClient);
DiscordEvents.add(instance.name, instance);
discordClient.on(instance.name, instance.execute);
console.info(`[Info - Discord] Loaded event: ${instance.name}`);
}
await discordClient.login(discordBotToken);
try {
console.log(
`Started refreshing ${DiscordInteractionCommands.size} application (/) commands.`
);
const interactionCommandsData = [];
for (const command of DiscordInteractionCommands.values()) {
interactionCommandsData.push(command.builder.toJSON());
} }
// Load Discord interaction commands
for (const Command of Object.values(DiscordInteractionCommandsIndex)) {
const instance = new Command();
DiscordInteractionCommands.add(instance.name, instance);
console.info(`[Info - Discord] Loaded interaction command: ${instance.name}`);
}
// Load Discord events
for (const Event of Object.values(DiscordEventsIndex)) {
const instance = new Event(discordClient);
DiscordEvents.add(instance.name, instance);
discordClient.on(instance.name, instance.execute);
console.info(`[Info - Discord] Loaded event: ${instance.name}`);
}
await discordClient.login(discordBotToken);
// The put method is used to fully refresh all commands in the guild with the current set try {
const data = await discordREST.put( console.log(`Started refreshing ${DiscordInteractionCommands.size} application (/) commands.`);
Routes.applicationCommands(discordClientID), const interactionCommandsData = [];
{ body: interactionCommandsData } for (const command of DiscordInteractionCommands.values()) {
); interactionCommandsData.push(command.builder.toJSON());
console.log( }
`Successfully reloaded ${interactionCommandsData?.length} application (/) commands.`
); // The put method is used to fully refresh all commands in the guild with the current set
} catch (error) { const data = await discordREST.put(
// And of course, make sure you catch and log any errors! Routes.applicationCommands(discordClientID),
console.error(error); { body: interactionCommandsData },
} );
// @ts-ignore
console.log(`Successfully reloaded ${data?.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
} }
main(); main();

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",
@ -15,4 +12,4 @@
"typeorm": "^0.3.20", "typeorm": "^0.3.20",
"uuid": "^9.0.1" "uuid": "^9.0.1"
} }
} }

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. */
@ -104,6 +104,6 @@
/* Completeness */ /* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */
} }
} }