Skip to content

Commit

Permalink
chore: remove code smells
Browse files Browse the repository at this point in the history
  • Loading branch information
Vyvy-vi committed Oct 6, 2022
1 parent 9ec1a66 commit a2e3a05
Show file tree
Hide file tree
Showing 16 changed files with 97 additions and 80 deletions.
3 changes: 1 addition & 2 deletions packages/discord-bot/src/commands/activate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export const activate: Command = {

help: {
name: 'activate',
text: 'Command to activate praise for discord account. You need to open the link returned by the command and sign a message with your eth wallet to link and activate your discord account with your eth wallet address.\n\
**Usage**: `/activate`\n',
text: 'Command to activate praise for discord account. You need to open the link returned by the command and sign a message with your eth wallet to link and activate your discord account with your eth wallet address.\n**Usage**: `/activate`\n',
},
};
3 changes: 1 addition & 2 deletions packages/discord-bot/src/commands/forward.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ export const forward: Command = {
},
help: {
name: 'forward',
text: 'Command to forward praise from a giver to receivers in the discord server. You need to have an activated account on the Praise System along with FORWARDER role permissions to use this command.\n\
**Usage**: `/forward giver: <@userA> receivers: <@user1 @user2 ...> reason: for something`\n',
text: 'Command to forward praise from a giver to receivers in the discord server. You need to have an activated account on the Praise System along with FORWARDER role permissions to use this command.\n**Usage**: `/forward giver: <@userA> receivers: <@user1 @user2 ...> reason: for something`\n',
},
};
3 changes: 1 addition & 2 deletions packages/discord-bot/src/commands/praise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ export const praise: Command = {

help: {
name: 'praise',
text: 'Command to praise users in the discord server. You need to have an activated account on the Praise System to use this command.\n\
**Usage**: `/praise receivers: <@user1 @user2 ...> reason: for something`\n',
text: 'Command to praise users in the discord server. You need to have an activated account on the Praise System to use this command.\n**Usage**: `/praise receivers: <@user1 @user2 ...> reason: for something`\n',
},
};
6 changes: 2 additions & 4 deletions packages/discord-bot/src/commands/praiseAdmin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,11 @@ export const praiseAdmin: Command = {

help: {
name: 'admin',
text: 'Command to perform admin actions in the Praise system and the PraiseBot\n\
**Usage**: `/admin <announce|...>`\n',
text: 'Command to perform admin actions in the Praise system and the PraiseBot\n**Usage**: `/admin <announce|...>`\n',
subCommands: [
{
name: 'announce',
text: 'Command to publish announcements that are distributed as direct messages to Praise users.\n\
Usage: `/admin announce message: <you have been selected for quantification...>`',
text: 'Command to publish announcements that are distributed as direct messages to Praise users.\nUsage: `/admin announce message: <you have been selected for quantification...>`',
},
],
},
Expand Down
6 changes: 3 additions & 3 deletions packages/discord-bot/src/handlers/activate.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { UserAccountModel } from 'api/dist/useraccount/entities';
import { UserAccount } from 'api/src/useraccount/types';
import { EventLogTypeKey } from 'api/src/eventlog/types';
import { logEvent } from 'api/src/eventlog/utils';
import { UserAccount } from 'api/dist/useraccount/types';
import { EventLogTypeKey } from 'api/dist/eventlog/types';
import { logEvent } from 'api/dist/eventlog/utils';
import randomstring from 'randomstring';
import { CommandHandler } from 'src/interfaces/CommandHandler';
import { alreadyActivatedError } from '../utils/embeds/praiseEmbeds';
Expand Down
3 changes: 1 addition & 2 deletions packages/discord-bot/src/handlers/announce.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { UserAccountModel } from 'api/dist/useraccount/entities';
import { UserAccount } from 'api/src/useraccount/types';
import { UserAccount } from 'api/dist/useraccount/types';
import { UserModel } from 'api/dist/user/entities';
import {
SelectMenuInteraction,
Expand Down Expand Up @@ -160,6 +160,5 @@ export const announcementHandler: CommandHandler = async (interaction) => {
content:
'You do not have the needed permissions to use this command. If you would like to perform admin actions, you would need to be granted an `ADMIN` role on the Praise Dashboard.',
});
return;
}
};
41 changes: 21 additions & 20 deletions packages/discord-bot/src/handlers/forward.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { GuildMember } from 'discord.js';
import { UserModel } from 'api/dist/user/entities';
import { EventLogTypeKey } from 'api/src/eventlog/types';
import { logEvent } from 'api/src/eventlog/utils';
import { EventLogTypeKey } from 'api/dist/eventlog/types';
import { logEvent } from 'api/dist/eventlog/utils';
import logger from 'jet-logger';
import { UserRole } from 'api/dist/user/types';
import { settingValue } from 'api/dist/shared/settings';
import { getReceiverData } from '../utils/getReceiverData';
import { getUserAccount } from '../utils/getUserAccount';
import {
dmError,
Expand Down Expand Up @@ -69,15 +70,14 @@ export const forwardHandler: CommandHandler = async (
if (!(await assertPraiseGiver(praiseGiver, interaction, true))) return;

const receivers = interaction.options.getString('receivers');
const receiverData = {
validReceiverIds: receivers?.match(/<@!?([0-9]+)>/g),
undefinedReceivers: receivers?.match(/[^<]@([a-z0-9]+)/gi),
roleMentions: receivers?.match(/<@&([0-9]+)>/g),
};

if (!receivers || receivers.length === 0) {
await interaction.editReply(await invalidReceiverError());
return;
}

const receiverData = getReceiverData(receivers);
if (
!receivers ||
receivers.length === 0 ||
!receiverData.validReceiverIds ||
receiverData.validReceiverIds?.length === 0
) {
Expand Down Expand Up @@ -162,17 +162,19 @@ export const forwardHandler: CommandHandler = async (
}
}

Receivers.length !== 0
? await interaction.editReply(
await forwardSuccess(
praiseGiver.user,
praised.map((id) => `<@!${id}>`),
reason
)
if (Receivers.length !== 0) {
await interaction.editReply(
await forwardSuccess(
praiseGiver.user,
praised.map((id) => `<@!${id}>`),
reason
)
: warnSelfPraise
? await interaction.editReply(await selfPraiseWarning())
: await interaction.editReply(await invalidReceiverError());
);
} else if (warnSelfPraise) {
await interaction.editReply(await selfPraiseWarning());
} else {
await interaction.editReply(await invalidReceiverError());
}

const warningMsg =
(receiverData.undefinedReceivers
Expand All @@ -194,5 +196,4 @@ export const forwardHandler: CommandHandler = async (
if (warningMsg && warningMsg.length !== 0) {
await interaction.followUp({ content: warningMsg, ephemeral: true });
}
return;
};
41 changes: 21 additions & 20 deletions packages/discord-bot/src/handlers/praise.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { PraiseModel } from 'api/dist/praise/entities';
import { EventLogTypeKey } from 'api/src/eventlog/types';
import { logEvent } from 'api/src/eventlog/utils';
import { EventLogTypeKey } from 'api/dist/eventlog/types';
import { logEvent } from 'api/dist/eventlog/utils';
import logger from 'jet-logger';
import { GuildMember, User } from 'discord.js';
import { settingValue } from 'api/dist/shared/settings';
import { getReceiverData } from '../utils/getReceiverData';
import {
dmError,
invalidReceiverError,
Expand Down Expand Up @@ -49,15 +50,15 @@ export const praiseHandler: CommandHandler = async (
if (!(await assertPraiseAllowedInChannel(interaction))) return;

const receivers = interaction.options.getString('receivers');
const receiverData = {
validReceiverIds: receivers?.match(/<@!?([0-9]+)>/g),
undefinedReceivers: receivers?.match(/[^<]@([a-z0-9]+)/gi),
roleMentions: receivers?.match(/<@&([0-9]+)>/g),
};

if (!receivers || receivers.length === 0) {
await interaction.editReply(await invalidReceiverError());
return;
}

const receiverData = getReceiverData(receivers);

if (
!receivers ||
receivers.length === 0 ||
!receiverData.validReceiverIds ||
receiverData.validReceiverIds?.length === 0
) {
Expand Down Expand Up @@ -145,16 +146,18 @@ export const praiseHandler: CommandHandler = async (
}
}

Receivers.length !== 0
? await interaction.editReply(
await praiseSuccess(
praised.map((id) => `<@!${id}>`),
reason
)
if (Receivers.length !== 0) {
await interaction.editReply(
await praiseSuccess(
praised.map((id) => `<@!${id}>`),
reason
)
: warnSelfPraise
? await interaction.editReply(await selfPraiseWarning())
: await interaction.editReply(await invalidReceiverError());
);
} else if (warnSelfPraise) {
await interaction.editReply(await selfPraiseWarning());
} else {
await interaction.editReply(await invalidReceiverError());
}

const warningMsg =
(receiverData.undefinedReceivers
Expand Down Expand Up @@ -185,6 +188,4 @@ export const praiseHandler: CommandHandler = async (
ephemeral: true,
});
}

return;
};
1 change: 0 additions & 1 deletion packages/discord-bot/src/handlers/whoami.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,4 @@ export const whoamiHandler = async (
await interaction.editReply({
embeds: [getStateEmbed(state)],
});
return;
};
2 changes: 1 addition & 1 deletion packages/discord-bot/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Client, GatewayIntentBits } from 'discord.js';
import logger from 'jet-logger';
import mongoose, { ConnectOptions } from 'mongoose';
import { envCheck } from 'api/src/pre-start/envCheck';
import { envCheck } from 'api/dist/pre-start/envCheck';
import { DiscordClient } from './interfaces/DiscordClient';
import { registerCommands } from './utils/registerCommands';
import { requiredEnvVariables } from './pre-start/env-required';
Expand Down
2 changes: 1 addition & 1 deletion packages/discord-bot/src/utils/createPraise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,5 @@ export const createPraise = async (
)}`,
receiver: receiverAccount._id,
};
return await PraiseModel.create(praiseData);
return PraiseModel.create(praiseData);
};
26 changes: 14 additions & 12 deletions packages/discord-bot/src/utils/dmTargets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,18 +84,21 @@ const sendDMs = async (
failed.unknownErrorUsers.length;
const failedMsg = `Announcement could not be delivered to ${failedCount} users.`;
const successMsg = `Announcement successfully delivered to ${successful.length} recipients.`;
const content =
successful.length === 0
? failedMsg
: failedCount === 0
? successMsg
: successMsg + '\n' + failedMsg;
let content;

if (successful.length !== 0 && failedCount !== 0) {
content = successMsg + '\n' + failedMsg;
} else if (failedCount !== 0) {
content = failedMsg;
} else {
content = successMsg;
}

let summary = 'User\t\t\tStatus\t\tReason\n';
successful.forEach((username: string) => {
summary += `${
username.length <= 24
? username + new String(' ').repeat(24 - username.length)
? username + String(' ').repeat(24 - username.length)
: username.slice(0, 21) + ' '
}Delivered\t-\n${
username.length > 24 ? username.slice(21, username.length) + '\n' : ''
Expand All @@ -104,7 +107,7 @@ const sendDMs = async (
failed.invalidUsers.forEach((username: string) => {
summary += `${
username.length <= 24
? username + new String(' ').repeat(24 - username.length)
? username + String(' ').repeat(24 - username.length)
: username.slice(0, 21) + ' '
}Not Delivered\tInvalid User\n${
username.length > 24 ? username.slice(21, username.length) + '\n' : ''
Expand All @@ -113,7 +116,7 @@ const sendDMs = async (
failed.notFoundUsers.forEach((username: string) => {
summary += `${
username.length <= 24
? username + new String(' ').repeat(24 - username.length)
? username + String(' ').repeat(24 - username.length)
: username.slice(0, 21) + ' '
}Not Delivered\tUser Not Found In Discord\n${
username.length > 24 ? username.slice(21, username.length) + '\n' : ''
Expand All @@ -122,7 +125,7 @@ const sendDMs = async (
failed.closedDmUsers.forEach((username: string) => {
summary += `${
username.length <= 24
? username + new String(' ').repeat(24 - username.length)
? username + String(' ').repeat(24 - username.length)
: username.slice(0, 21) + ' '
}Not Delivered\tDMs closed\n${
username.length > 24 ? username.slice(21, username.length) + '\n' : ''
Expand All @@ -131,7 +134,7 @@ const sendDMs = async (
failed.unknownErrorUsers.forEach((username: string) => {
summary += `${
username.length <= 24
? username + new String(' ').repeat(24 - username.length)
? username + String(' ').repeat(24 - username.length)
: username.slice(0, 21) + ' '
}Not Delivered\tUnknown Error\n${
username.length > 24 ? username.slice(21, username.length) + '\n' : ''
Expand Down Expand Up @@ -230,5 +233,4 @@ export const selectTargets = async (
return;
}
}
return;
};
4 changes: 2 additions & 2 deletions packages/discord-bot/src/utils/embeds/praiseEmbeds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const praiseSuccess = async (
const msg = (await settingValue('PRAISE_SUCCESS_MESSAGE')) as string;
if (msg) {
return msg
?.replace('{@receivers}', `${praised.join(', ')}`)
.replace('{@receivers}', `${praised.join(', ')}`)
.replace('{reason}', reason);
} else {
return 'PRAISE SUCCESSFUL (message not set)';
Expand Down Expand Up @@ -201,7 +201,7 @@ export const roleMentionWarning = async (
receivers: string,
user: User
): Promise<string> => {
const msg = (await settingValue('PRAISE_TO_ROLE_WARNING')) as String;
const msg = (await settingValue('PRAISE_TO_ROLE_WARNING')) as string;
if (msg) {
return msg
.replace('{@receivers}', receivers)
Expand Down
21 changes: 14 additions & 7 deletions packages/discord-bot/src/utils/embeds/stateEmbed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,22 @@ const formatDate = (date: Date): string => format(date, 'yyyy-MM-dd');
* @returns {EmbedBuilder}
*/
export const getStateEmbed = (state: UserState): EmbedBuilder => {
let userStateDescription: string;
if (state.activated && state.hasPraiseGiverRole) {
userStateDescription = 'Your account is activated and has praise powers.';
} else if (state.hasPraiseGiverRole) {
userStateDescription =
"You have praise powers, however your account isn't activated(use `/activate` command).";
} else if (state.activated) {
userStateDescription =
"Your account is activated, however you don't have praise powers.";
} else {
userStateDescription =
"You don't have praise powers, and your account isn't activated(use `/activate` command).";
}
const embed = new EmbedBuilder()
.setTitle(state.username)
.setDescription(
state.hasPraiseGiverRole && state.activated
? 'Your account is activated and has praise powers.'
: state.hasPraiseGiverRole
? "You have praise powers, however your account isn't activated(use `/activate` command)."
: "Your account is activated, however you don't have praise powers."
);
.setDescription(userStateDescription);
if (state.avatar) {
embed.setThumbnail(
`https://cdn.discordapp.com/avatars/${state.id}/${state.avatar}`
Expand Down
13 changes: 13 additions & 0 deletions packages/discord-bot/src/utils/getReceiverData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
interface receiverData {
validReceiverIds: RegExpMatchArray | null;
undefinedReceivers: RegExpMatchArray | null;
roleMentions: RegExpMatchArray | null;
}

export const getReceiverData = (receivers: string): receiverData => {
return {
validReceiverIds: receivers?.match(/<@!?([\d]+)>/g),
undefinedReceivers: receivers?.match(/[^<]@([\w]+)/gi),
roleMentions: receivers?.match(/<@&([\d]+)>/g),
};
};
2 changes: 1 addition & 1 deletion packages/discord-bot/src/utils/getUserAccount.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { UserAccountModel } from 'api/dist/useraccount/entities';
import { UserAccount, UserAccountDocument } from 'api/src/useraccount/types';
import { UserAccount, UserAccountDocument } from 'api/dist/useraccount/types';
import { GuildMember } from 'discord.js';

/**
Expand Down

0 comments on commit a2e3a05

Please sign in to comment.