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 { MemberModel } from '../../database/Member';
import Partner, {
PartnerCommissionType,
PartnerDepartment,
PartnerModel,
PartnerRoleType,
} from '../../database/Partner';
import {
ChatInputCommandInteraction,
EmbedBuilder,
GuildMember,
} from 'discord.js';
import MemberUtil from '../../util/MemberUtil';
import EmojiConfig from '../../util/EmojiConfig';
import DiscordInteractionCommand from "../../util/DiscordInteractionCommand";
import { MemberModel } from "../../database/Member";
import Partner, { PartnerCommissionType, PartnerDepartment, 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 {
constructor() {
super('whois', 'Retrieves information about a user.');
this.builder.addUserOption((option) =>
option
.setName('member')
.setDescription('The member to get information about.')
.setRequired(true)
);
}
constructor() {
super("whois", "Retrieves information about a user.");
this.builder.addUserOption(option => option.setName("member").setDescription("The member to get information about.").setRequired(true));
}
public async execute(interaction: ChatInputCommandInteraction) {
// defer our reply and perform database/external API operations/lookups
await interaction.deferReply({ ephemeral: false });
const target = interaction.options.getUser('member', true);
const guild =
interaction.guild || interaction.client.guilds.cache.get(this.GUILD_ID);
const guildMember = await guild?.members.fetch(target.id);
const databaseMember = await MemberModel.findOne({ discordID: target.id });
const partner = await PartnerModel.findOne({ discordID: target.id });
// return an error if target was not located
if (!guildMember)
return interaction.editReply({
content: `Member target ${target.id} was not located.`,
});
// build our embed
const embed = new EmbedBuilder();
// 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
const formattedName = MemberUtil.formatName(guildMember, partner);
embed.setAuthor({
name: formattedName.text,
iconURL: formattedName.iconURL,
});
// set the thumbnail to the user's avatar
embed.setThumbnail(guildMember.user.displayAvatarURL());
// initialize the description string
let embedDescription = '';
if (partner) {
// set the title to the partner's title if applicable
if (partner.title)
embedDescription += `## __${EmojiConfig.LOC} ${partner.title}__\n`;
embedDescription += '### Partner Information\n';
if (partner.emailAddress)
embedDescription += `**Email Address**: ${partner.emailAddress}\n`;
switch (partner.department) {
case PartnerDepartment.ENGINEERING:
embedDescription += '**Department**: Dept. of Engineering\n';
break;
case PartnerDepartment.OPERATIONS:
embedDescription += '**Department**: Dept. of Operations\n';
break;
case PartnerDepartment.INDEPENDENT_AGENCY:
embedDescription += '**Department**: Independent Agency/Contractor\n';
break;
}
switch (partner.commissionType) {
case PartnerCommissionType.TENURE:
embedDescription += '**Commission Type**: Tenure\n';
break;
case PartnerCommissionType.PROVISIONAL:
embedDescription += '**Commission Type**: Provisional\n';
break;
case PartnerCommissionType.CONTRACTUAL:
embedDescription +=
'**Commission Type**: Contractual/Independent/Collaborator\n';
break;
case PartnerCommissionType.ACTING:
embedDescription += '**Commission Type**: Acting\n';
break;
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`;
public async execute(interaction: ChatInputCommandInteraction) {
// defer our reply and perform database/external API operations/lookups
await interaction.deferReply({ ephemeral: false });
const target = interaction.options.getUser("member", true);
const guild = interaction.guild || interaction.client.guilds.cache.get(this.GUILD_ID);
const guildMember = await guild?.members.fetch(target.id);
const databaseMember = await MemberModel.findOne({ discordID: target.id });
const partner = await PartnerModel.findOne({ discordID: target.id });
// return an error if target was not located
if (!guildMember) return interaction.editReply({ content: `Member target ${target.id} was not located.`});
// build our embed
const embed = new EmbedBuilder();
// 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
const formattedName = MemberUtil.formatName(guildMember, partner);
embed.setAuthor({ name: formattedName.text, iconURL: formattedName.iconURL });
// set the thumbnail to the user's avatar
embed.setThumbnail(guildMember.user.displayAvatarURL());
// initialize the description string
let embedDescription = '';
if (partner) {
// set the title to the partner's title if applicable
if (partner.title) embedDescription += `## __${EmojiConfig.LOC} ${partner.title}__\n`;
embedDescription += "### Partner Information\n";
if (partner.emailAddress) embedDescription += `**Email Address**: ${partner.emailAddress}\n`;
switch (partner.department) {
case PartnerDepartment.ENGINEERING:
embedDescription += "**Department**: Dept. of Engineering\n";
break;
case PartnerDepartment.OPERATIONS:
embedDescription += "**Department**: Dept. of Operations\n";
break;
case PartnerDepartment.INDEPENDENT_AGENCY:
embedDescription += "**Department**: Independent Agency/Contractor\n";
break;
}
switch (partner.commissionType) {
case PartnerCommissionType.TENURE:
embedDescription += "**Commission Type**: Tenure\n";
break;
case PartnerCommissionType.PROVISIONAL:
embedDescription += "**Commission Type**: Provisional\n";
break;
case PartnerCommissionType.CONTRACTUAL:
embedDescription += "**Commission Type**: Contractual/Independent/Collaborator\n";
break;
case PartnerCommissionType.ACTING:
embedDescription += "**Commission Type**: Acting\n";
break;
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);
// add status to embed
if (guildMember.presence?.status) {
// TODO: this currently doesn't work for some reason
switch (guildMember.presence.status) {
case 'online':
embed.addFields({ name: 'Status', value: 'Online', inline: true });
break;
case 'idle':
embed.addFields({ name: 'Status', value: 'Idle', inline: true });
break;
case 'dnd':
embed.addFields({
name: 'Status',
value: 'Do Not Disturb',
inline: true,
});
break;
case 'offline':
embed.addFields({ name: 'Status', value: 'Offline', inline: true });
break;
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}` : ''
}`,
});
embed.setColor(guildMember.displayColor);
if (embedDescription?.length > 0) embed.setDescription(embedDescription);
// add status to embed
if (guildMember.presence?.status) { // TODO: this currently doesn't work for some reason
switch (guildMember.presence.status) {
case "online":
embed.addFields({ name: "Status", value: "Online", inline: true });
break;
case "idle":
embed.addFields({ name: "Status", value: "Idle", inline: true });
break;
case "dnd":
embed.addFields({ name: "Status", value: "Do Not Disturb", inline: true });
break;
case "offline" || "invisible":
embed.addFields({ name: "Status", value: "Online", 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 { discordBotToken, discordClientID, MongoDbUrl } from './config.json';
import Collection from './util/Collection';
import DiscordInteractionCommand from './util/DiscordInteractionCommand';
import DiscordEvent from './util/DiscordEvent';
import * as DiscordInteractionCommandsIndex from './discord/commands';
import * as DiscordEventsIndex from './discord/events';
import mongoose from 'mongoose';
import { Client, GatewayIntentBits, Partials, REST, Routes } from "discord.js";
import { discordBotToken, discordClientID } from "./config.json"
import Collection from "./util/Collection";
import DiscordInteractionCommand from "./util/DiscordInteractionCommand";
import DiscordEvent from "./util/DiscordEvent";
import * as DiscordInteractionCommandsIndex from "./discord/commands";
import * as DiscordEventsIndex from "./discord/events";
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();
// Instantiates a new Discord client
const discordClient = new Client({
intents: [
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildModeration,
],
partials: [
Partials.GuildMember,
Partials.Message,
Partials.User,
Partials.Channel,
],
intents: [
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildModeration,
],
partials: [ Partials.GuildMember, Partials.Message, Partials.User, Partials.Channel, ],
});
const discordREST = new REST().setToken(discordBotToken);
// const stripeClient = new Stripe(stripeToken, { typescript: true });
export async function main() {
// Connect to the databases
try {
//@ts-ignore
mongoose.connection.once('open', () => {
console.info('[Info - Database] Connected to MongoDB');
});
// TODO: Fetch the MongoDB URI from the config file
await mongoose.connect(MongoDbUrl, {});
} catch (error) {
console.error(`[Error - Database] Failed to connect to MongoDB: ${error}`);
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());
// Connect to the databases
try {
mongoose.connection.once("open", () => {
console.info("[Info - Database] Connected to MongoDB");
})
// TODO: Fetch the MongoDB URI from the config file
await mongoose.connect("mongodb://localhost:27017/crra-main", {});
} catch (error) {
console.error(`[Error - Database] Failed to connect to MongoDB: ${error}`);
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);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await discordREST.put(
Routes.applicationCommands(discordClientID),
{ body: interactionCommandsData }
);
console.log(
`Successfully reloaded ${interactionCommandsData?.length} application (/) commands.`
);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
try {
console.log(`Started refreshing ${DiscordInteractionCommands.size} application (/) commands.`);
const interactionCommandsData = [];
for (const command of DiscordInteractionCommands.values()) {
interactionCommandsData.push(command.builder.toJSON());
}
// The put method is used to fully refresh all commands in the guild with the current set
const data = await discordREST.put(
Routes.applicationCommands(discordClientID),
{ 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();

View File

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

View File

@ -11,11 +11,11 @@
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* 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. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
"experimentalDecorators": true /* Enable experimental support for legacy experimental decorators. */,
"emitDecoratorMetadata": true /* Emit design-type metadata for decorated declarations in source files. */,
"experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
"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'. */
// "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*'. */
@ -25,7 +25,7 @@
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* 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. */
// "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. */
@ -39,7 +39,7 @@
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package 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. */
"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. */
// "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. */
// "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. */
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "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. */
@ -77,12 +77,12 @@
// "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. */
// "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. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* 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. */
// "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. */
@ -104,6 +104,6 @@
/* Completeness */
// "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. */
}
}