Skip to content

Commit

Permalink
Merge pull request #65 from Linguition/refactor-and-reduce-code-dupli…
Browse files Browse the repository at this point in the history
…cation

Version 1.0.1 - Refactor code and reduce code duplication.
  • Loading branch information
vxern authored Oct 28, 2022
2 parents 9a920fb + 432f3e1 commit 6cfa1b3
Show file tree
Hide file tree
Showing 15 changed files with 261 additions and 221 deletions.
74 changes: 69 additions & 5 deletions assets/localisations/commands.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { User } from '../../deps.ts';
import { ApplicationCommandOptionTypes, User } from '../../deps.ts';
import { links } from '../../src/constants.ts';
import configuration from '../../src/configuration.ts';
import { capitalise, list } from '../../src/formatting.ts';
Expand Down Expand Up @@ -315,7 +315,7 @@ class Commands {
'English':
'Translates a text from the source language to the target language.',
'Polish': 'Tłumaczy dany tekst z języka źródłowego na język docelowy.',
'Romanian': 'Traduce un text dat din limbă-sursă în limbă-țintă.',
'Romanian': 'Traduce textul dat din limbă-sursă în limbă-țintă.',
},
options: {
from: {
Expand Down Expand Up @@ -427,7 +427,7 @@ class Commands {
description: {
'English': 'Displays information about a given word.',
'Polish': 'Wyświetla informacje o danym słowie.',
'Romanian': 'Afișează informații despre un cuvânt dat.',
'Romanian': 'Afișează informații despre un anumit cuvânt.',
},
options: {
word: {
Expand Down Expand Up @@ -703,7 +703,7 @@ class Commands {
description: {
'English': 'Removes the last given warning to a user.',
'Polish': 'Usuwa ostatnie ostrzeżenie dane użytkownikowi.',
'Romanian': 'Șterge ultima avertizare dat unui utilizator.',
'Romanian': 'Șterge ultima avertizare dată unui utilizator.',
},
options: {
warning: {
Expand Down Expand Up @@ -1523,6 +1523,70 @@ class Commands {
},
});

static readonly praise = typedLocalisations({
name: {
'English': 'praise',
'Polish': 'pochwal',
'Romanian': 'lăudare',
},
description: {
'English': 'Praises a user for their contribution.',
'Polish': 'Chwali użytkownika za jego wkład.',
'Romanian': 'Laudă un utilizator pentru contribuțiile sale.',
},
options: {
comment: {
name: {
'English': 'comment',
'Polish': 'komentarz',
'Romanian': 'comentariu',
},
description: {
'English': 'A comment to attach to the praise.',
'Polish': 'Komentarz, który ma zostać załączony do pochwały.',
'Romanian': 'Comentariul care să fie atașat la laudă.',
},
type: ApplicationCommandOptionTypes.String,
},
},
strings: {
cannotPraiseSelf: {
'English': 'You cannot praise yourself.',
'Polish': 'Nie możesz pochwalić samego siebie.',
'Romanian': 'Nu te poți lăuda pe tine însuți/însăți.',
},
failed: {
'English': 'Failed to praise user.',
'Polish': 'Nie udało się pochwalić użytkownika.',
'Romanian': 'Nu s-a putut lăuda utilizatorul.',
},
waitBeforePraising: {
'English':
'You have already praised a user recently. You must wait before praising somebody again.',
'Polish':
'Zanim ponownie spróbujesz pochwalić użytkownika, powinieneś troszeczkę poczekać.',
'Romanian':
'Înainte să încerci să lauzi un utilizator din nou, ar trebui să aștepți puțin.',
},
praised: {
'English': (userMention: string) =>
`Unless ${userMention} has their DMs closed, they have just been notified that you have praised them.`,
'Polish': (userMention: string) =>
`Jeśli ${userMention} nie zablokował swoich DM-ów, właśnie został/a powiadomiony/a o pochwale.`,
'Romanian': (userMention: string) =>
`Cu excepția că ${userMention} și-a blocat DM-urile sale, tocmai ce a fost notificat despre laudă.`,
},
praisedDirect: {
'English': (userMention: string) =>
`You have just been praised by ${userMention}!`,
'Polish': (userMention: string) =>
`Użytkownik ${userMention} właśnie Cię pochwalił!`,
'Romanian': (userMention: string) =>
`Abia ce ai primit o laudă de la ${userMention}!`,
},
},
});

static readonly profile = typedLocalisations({
name: {
'English': 'profile',
Expand Down Expand Up @@ -1613,7 +1677,7 @@ class Commands {
failed: {
'English': 'Failed to show information about the chosen member.',
'Polish': 'Nie udało się wyświetlić informacji o danym członku.',
'Romanian': 'Nu s-au putut afișa informații despre un membru dat.',
'Romanian': 'Nu s-au putut afișa informații despre membrul dat.',
},
informationForUser: {
'English': (username: string) => `Information about ${username}`,
Expand Down
6 changes: 3 additions & 3 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ import configuration from './configuration.ts';
import { Command, InteractionHandler } from './commands/command.ts';
import { defaultLanguage, Language, supportedLanguages } from './types.ts';
import { commandBuilders } from './commands/modules.ts';
import { mentionUser } from './utils.ts';
import { setupLogging } from './controllers/logging.ts';
import { diagnosticMentionUser } from './utils.ts';
import { setupLogging } from './controllers/logging/logging.ts';
import { localise } from '../assets/localisations/types.ts';
import { Misc } from '../assets/localisations/misc.ts';

Expand Down Expand Up @@ -458,7 +458,7 @@ function resolveInteractionToMember(
type: InteractionResponseTypes.ApplicationCommandAutocompleteResult,
data: {
choices: matchedMembers.slice(0, 20).map((member) => ({
name: mentionUser(member.user!, true),
name: diagnosticMentionUser(member.user!, true),
value: member.id.toString(),
})),
},
Expand Down
75 changes: 29 additions & 46 deletions src/commands/information/commands/information/guild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
ApplicationCommandFlags,
Bot,
ChannelTypes,
getGuildIconURL,
Guild,
Interaction,
InteractionResponseTypes,
Expand All @@ -14,7 +13,7 @@ import { Client } from '../../../../client.ts';
import configuration from '../../../../configuration.ts';
import { displayTime, mention, MentionTypes } from '../../../../formatting.ts';
import { defaultLanguage } from '../../../../types.ts';
import { snowflakeToTimestamp } from '../../../../utils.ts';
import { guildAsThumbnail, snowflakeToTimestamp } from '../../../../utils.ts';
import { getProficiencyCategory } from '../../../social/module.ts';

/** Displays information about the guild that this command was executed in. */
Expand Down Expand Up @@ -44,24 +43,11 @@ function displayGuildInformation(
data: {
flags: ApplicationCommandFlags.Ephemeral,
embeds: [{
thumbnail: guildAsThumbnail(bot, guild),
title: localise(
Commands.information.options.guild.strings.informationAbout,
interaction.locale,
)(guild.name),
...(() => {
const iconURL = getGuildIconURL(bot, guild.id, guild.icon, {
size: 4096,
format: 'png',
});
if (!iconURL) return {};

const icon = { url: iconURL };

return {
author: { ...icon, name: '' },
thumbnail: icon,
};
})(),
color: configuration.interactions.responses.colors.invisible,
fields: [
{
Expand Down Expand Up @@ -105,35 +91,7 @@ function displayGuildInformation(
interaction.locale,
)
}`,
value: (() => {
const channels = guild.channels.array();

const getCountByType = (type: ChannelTypes): number => {
return channels.filter((channel) => channel.type === type)
.length;
};

const textChannelsCount = getCountByType(
ChannelTypes.GuildText,
);
const voiceChannelsCount = getCountByType(
ChannelTypes.GuildVoice,
);

return `📜 ${textChannelsCount} ${
localise(
Commands.information.options.guild.strings.channelTypes
.text,
interaction.locale,
)
} | 🔊 ${voiceChannelsCount} ${
localise(
Commands.information.options.guild.strings.channelTypes
.voice,
interaction.locale,
)
}`;
})(),
value: displayInformationAboutChannels(guild, interaction.locale),
inline: true,
},
hasDistinctOwner
Expand Down Expand Up @@ -184,8 +142,33 @@ function displayGuildInformation(
);
}

function displayInformationAboutChannels(guild: Guild, locale: string | undefined): string {
const channels = guild.channels.array();

const getCountByType = (type: ChannelTypes): number => {
return channels.filter((channel) => channel.type === type).length;
};

const textChannelsCount = getCountByType(ChannelTypes.GuildText);
const voiceChannelsCount = getCountByType(ChannelTypes.GuildVoice);

return `📜 ${textChannelsCount} ${
localise(
Commands.information.options.guild.strings.channelTypes
.text,
locale,
)
} | 🔊 ${voiceChannelsCount} ${
localise(
Commands.information.options.guild.strings.channelTypes
.voice,
locale,
)
}`;
}

/**
* Taking a guild object, gets a distribution of proficiency roles of its members.
* Taking a guild object, gets the distribution of proficiency roles of its members.
*
* @param client - The client instance to use.
* @param guild - The guild of which the role frequencies to get.
Expand Down
11 changes: 3 additions & 8 deletions src/commands/language/commands/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
import {
ApplicationCommandFlags,
Bot,
ButtonComponent,
ButtonStyles,
editOriginalInteractionResponse,
Interaction,
Expand Down Expand Up @@ -87,19 +86,15 @@ async function startGame(
}],
components: [{
type: MessageComponentTypes.ActionRow,
components: <[
ButtonComponent,
ButtonComponent,
ButtonComponent,
ButtonComponent,
]> (<unknown> sentenceSelection.choices.map(
// @ts-ignore: There are always 4 buttons for the 4 sentences selected.
components: sentenceSelection.choices.map(
(choice, index) => ({
type: MessageComponentTypes.Button,
style: ButtonStyles.Success,
label: choice,
customId: `${customId}|${index}`,
}),
)),
),
}],
};
};
Expand Down
14 changes: 3 additions & 11 deletions src/commands/moderation/commands/pardon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
ApplicationCommandOptionTypes,
Bot,
getDmChannel,
getGuildIconURL,
Interaction,
InteractionResponseTypes,
InteractionTypes,
Expand All @@ -20,14 +19,15 @@ import {
} from '../../../database/functions/warnings.ts';
import { user } from '../../parameters.ts';
import { getRelevantWarnings } from '../module.ts';
import { log } from '../../../controllers/logging.ts';
import { log } from '../../../controllers/logging/logging.ts';
import { displayTime, mention, MentionTypes } from '../../../formatting.ts';
import {
createLocalisations,
localise,
} from '../../../../assets/localisations/types.ts';
import { Commands } from '../../../../assets/localisations/commands.ts';
import { defaultLanguage } from '../../../types.ts';
import { guildAsAuthor } from '../../../utils.ts';

const command: CommandBuilder = {
...createLocalisations(Commands.pardon),
Expand Down Expand Up @@ -204,15 +204,7 @@ async function unwarnUser(
return void sendMessage(bot, dmChannel.id, {
embeds: [
{
thumbnail: (() => {
const iconURL = getGuildIconURL(bot, guild.id, guild.icon, {
size: 64,
format: 'webp',
});
if (!iconURL) return;

return { url: iconURL };
})(),
author: guildAsAuthor(bot, guild),
description: localise(
Commands.pardon.strings.pardonedDirect,
defaultLanguage,
Expand Down
17 changes: 4 additions & 13 deletions src/commands/moderation/commands/timeout/clear.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@ import {
Bot,
editMember,
getDmChannel,
getGuildIconURL,
Interaction,
InteractionResponseTypes,
sendInteractionResponse,
sendMessage,
} from '../../../../../deps.ts';
import { Client, resolveInteractionToMember } from '../../../../client.ts';
import configuration from '../../../../configuration.ts';
import { mentionUser } from '../../../../utils.ts';
import { log } from '../../../../controllers/logging.ts';
import { diagnosticMentionUser, guildAsAuthor } from '../../../../utils.ts';
import { log } from '../../../../controllers/logging/logging.ts';
import { localise } from '../../../../../assets/localisations/types.ts';
import { Commands } from '../../../../../assets/localisations/commands.ts';
import { defaultLanguage } from '../../../../types.ts';
Expand Down Expand Up @@ -84,7 +83,7 @@ async function clearTimeout(
description: localise(
Commands.timeout.strings.timeoutCleared,
interaction.locale,
)(mentionUser(member.user!)),
)(diagnosticMentionUser(member.user!)),
color: configuration.interactions.responses.colors.green,
}],
},
Expand All @@ -97,15 +96,7 @@ async function clearTimeout(
return void sendMessage(bot, dmChannel.id, {
embeds: [
{
thumbnail: (() => {
const iconURL = getGuildIconURL(bot, guild.id, guild.icon, {
size: 64,
format: 'webp',
});
if (!iconURL) return;

return { url: iconURL };
})(),
author: guildAsAuthor(bot, guild),
description: localise(
Commands.timeout.strings.timeoutClearedDirect,
defaultLanguage,
Expand Down
Loading

0 comments on commit 6cfa1b3

Please sign in to comment.