From f4aae4e9e55f77d7732c3cce6d430a111f1d35dd Mon Sep 17 00:00:00 2001 From: Christoph <29735603+Chr1s70ph@users.noreply.github.com> Date: Wed, 6 Apr 2022 10:09:09 +0200 Subject: [PATCH 01/10] fix footer needing object. Closes #136 --- commands/fun/fact.ts | 5 ++++- commands/fun/komedi.ts | 5 ++++- commands/fun/tenor.ts | 7 ++++--- commands/utility/countdown.ts | 5 ++++- scripts/iCalReader.ts | 11 ++++------- 5 files changed, 20 insertions(+), 13 deletions(-) diff --git a/commands/fun/fact.ts b/commands/fun/fact.ts index 942f06c..6872fd8 100644 --- a/commands/fun/fact.ts +++ b/commands/fun/fact.ts @@ -31,7 +31,10 @@ exports.run = (client: DiscordClient, message: DiscordMessage) => { new MessageEmbed() .setTitle(client.translate({ key: 'commands.fun.fact', lng: message.author.language })) .setDescription(fact) - .setFooter(message.author.tag, message.author.avatarURL({ dynamic: true })), + .setFooter({ + text: message.author.tag, + iconURL: message.author.avatarURL({ dynamic: true }), + }), ], }) } diff --git a/commands/fun/komedi.ts b/commands/fun/komedi.ts index 952b5b4..0c2b1c3 100644 --- a/commands/fun/komedi.ts +++ b/commands/fun/komedi.ts @@ -15,6 +15,9 @@ exports.run = (client: DiscordClient, message: Message) => embeds: [ new MessageEmbed() .setImage('https://cdn.discordapp.com/attachments/768117219812835378/818145599894847488/eqmmb89gml941.png') - .setFooter(message.author.tag, message.author.avatarURL({ dynamic: true })), + .setFooter({ + text: message.author.tag, + iconURL: message.author.avatarURL({ dynamic: true }), + }), ], }) diff --git a/commands/fun/tenor.ts b/commands/fun/tenor.ts index 0d9023e..3514ac9 100644 --- a/commands/fun/tenor.ts +++ b/commands/fun/tenor.ts @@ -75,9 +75,10 @@ function queryTenorAndReply( * * {@link MessageEmbedFooter} is set to the user's tag and avatar who issued the command. */ - let embed = new MessageEmbed() - .setColor('RANDOM') - .setFooter(message.author.tag, message.author.avatarURL({ dynamic: true })) + let embed = new MessageEmbed().setColor('RANDOM').setFooter({ + text: message.author.tag, + iconURL: message.author.avatarURL({ dynamic: true }), + }) /** * Set image of embed if Tenor query returned any. diff --git a/commands/utility/countdown.ts b/commands/utility/countdown.ts index 0c05782..cb0cef4 100644 --- a/commands/utility/countdown.ts +++ b/commands/utility/countdown.ts @@ -13,7 +13,10 @@ exports.run = async (client: DiscordClient, message: DiscordMessage) => { */ const msgEmbed = new MessageEmbed() .setTitle(client.translate({ key: 'commands.utility.countdown.Countdown', lng: message.author.language })) - .setFooter(message.author.tag, message.author.avatarURL({ dynamic: true })) + .setFooter({ + text: message.author.tag, + iconURL: message.author.avatarURL({ dynamic: true }), + }) .setThumbnail('https://upload.wikimedia.org/wikipedia/commons/3/33/Cartoon_space_rocket.png') /** diff --git a/scripts/iCalReader.ts b/scripts/iCalReader.ts index 97b6db7..699d083 100644 --- a/scripts/iCalReader.ts +++ b/scripts/iCalReader.ts @@ -659,13 +659,10 @@ function dynamicEmbed( .setDescription(`Die ${courseType} fängt in ${lessonsOffset} Minuten an`) .setThumbnail('https://pics.freeicons.io/uploads/icons/png/6029094171580282643-512.png') .addField('Dozent', professor, false) - .setFooter( - 'Viel Spaß und Erfolg wünscht euch euer ETIT-Master', - client.guilds - .resolve(client.config.ids.serverID) - .members.resolve(client.config.ids.userID.botUserID) - .user.avatarURL(), - ) + .setFooter({ + text: 'Viel Spaß und Erfolg wünscht euch euer ETIT-Master', + iconURL: client.user.avatarURL({ dynamic: true }), + }) } catch (e) { /** * Error Message. From 6f56a420a8ab1e145a319225d95f26768acb3d4e Mon Sep 17 00:00:00 2001 From: Christoph <29735603+Chr1s70ph@users.noreply.github.com> Date: Wed, 6 Apr 2022 10:15:15 +0200 Subject: [PATCH 02/10] remove not needed import --- types/customTypes.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/customTypes.ts b/types/customTypes.ts index ef468f5..51f692c 100644 --- a/types/customTypes.ts +++ b/types/customTypes.ts @@ -8,7 +8,6 @@ import { MessageOptions, Collection, User, - GuildMemberRoleManager, CommandInteraction, AutocompleteInteraction, ButtonInteraction, From 1e83fd191f47fb1f2317dd0ef2205d9fd011d3d4 Mon Sep 17 00:00:00 2001 From: Christoph <29735603+Chr1s70ph@users.noreply.github.com> Date: Wed, 6 Apr 2022 10:59:27 +0200 Subject: [PATCH 03/10] fix interaction locale fetching --- types/customTypes.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/customTypes.ts b/types/customTypes.ts index 51f692c..27668a4 100644 --- a/types/customTypes.ts +++ b/types/customTypes.ts @@ -150,7 +150,7 @@ export class DiscordClient extends Client { return (user.language = language) } } else if (interaction) { - if (interaction.locale === language) return language + if (interaction.locale === language) return (user.language = language) } } From b217975449f7d350a358dc931157d7fd1a47c762 Mon Sep 17 00:00:00 2001 From: Christoph <29735603+Chr1s70ph@users.noreply.github.com> Date: Wed, 6 Apr 2022 11:00:27 +0200 Subject: [PATCH 04/10] rename en locale to en-US --- index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/index.ts b/index.ts index ea3d29b..dd17037 100644 --- a/index.ts +++ b/index.ts @@ -11,9 +11,9 @@ const backend = new Backend({ }) i18next.use(backend).init({ - lng: 'en', - fallbackLng: 'en', - preload: ['en', 'de'], + lng: 'en-US', + fallbackLng: 'en-US', + preload: ['en-US', 'de'], ns: ['translation'], defaultNS: 'translation', debug: true, From d71fdab624377f3f05bde807abb83c7a0db49969 Mon Sep 17 00:00:00 2001 From: Christoph <29735603+Chr1s70ph@users.noreply.github.com> Date: Wed, 6 Apr 2022 11:01:53 +0200 Subject: [PATCH 05/10] rename slashCommands translation key to interaction --- interactions/help.ts | 2 +- interactions/klausuren.ts | 2 +- interactions/language.ts | 6 +++--- interactions/vorschlag.ts | 8 ++++---- interactions/wochenplan.ts | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/interactions/help.ts b/interactions/help.ts index 1038d45..8862dcf 100644 --- a/interactions/help.ts +++ b/interactions/help.ts @@ -14,7 +14,7 @@ async function getCommands(client: DiscordClient, interaction: DiscordCommandInt const commandsEmbed = new MessageEmbed() .setColor('#ffa500') .setAuthor({ - name: client.translate({ key: 'slashCommands.help', lng: interaction.user.language }), + name: client.translate({ key: 'interactions.help', lng: interaction.user.language }), iconURL: 'https://bit.ly/3CJU0lf', }) .setTimestamp() diff --git a/interactions/klausuren.ts b/interactions/klausuren.ts index e5e4315..21bb684 100644 --- a/interactions/klausuren.ts +++ b/interactions/klausuren.ts @@ -33,7 +33,7 @@ async function klausuren(client: DiscordClient, interaction: DiscordCommandInter const embed = new MessageEmbed().setAuthor({ name: client.translate({ - key: 'slashCommands.klausuren.Exams', + key: 'interactions.klausuren.Exams', options: { user: interaction.user.username, lng: interaction.user.language, diff --git a/interactions/language.ts b/interactions/language.ts index 85005ea..6abf804 100644 --- a/interactions/language.ts +++ b/interactions/language.ts @@ -54,7 +54,7 @@ exports.Command = async (client: DiscordClient, interaction: DiscordCommandInter */ new MessageSelectMenu() .setCustomId('language') - .setPlaceholder(client.translate({ key: 'slashCommands.language.DefaultSelect', lng: interaction.user.language })) + .setPlaceholder(client.translate({ key: 'interactions.language.DefaultSelect', lng: interaction.user.language })) .addOptions(options), ) @@ -62,7 +62,7 @@ exports.Command = async (client: DiscordClient, interaction: DiscordCommandInter * Reply with {@link row} to interaction */ await interaction.reply({ - content: client.translate({ key: 'slashCommands.language.Select', lng: interaction.user.language }), + content: client.translate({ key: 'interactions.language.Select', lng: interaction.user.language }), components: [row], ephemeral: true, }) @@ -106,7 +106,7 @@ exports.SelectMenu = async (client: DiscordClient, interaction: SelectMenuIntera new MessageEmbed() .setTitle( client.translate({ - key: 'slashCommands.language.LanguageUpdated', + key: 'interactions.language.LanguageUpdated', options: { language: `${flag} ${language}`, lng: interaction.values[0], diff --git a/interactions/vorschlag.ts b/interactions/vorschlag.ts index 2e1e5e7..ad69289 100644 --- a/interactions/vorschlag.ts +++ b/interactions/vorschlag.ts @@ -31,8 +31,8 @@ exports.Command = async (client: DiscordClient, interaction: DiscordCommandInter await interaction.reply({ embeds: [ new MessageEmbed() - .setTitle(client.translate({ key: 'slashCommands.issue.Recieved', lng: interaction.user.language })) - .setDescription(client.translate({ key: 'slashCommands.issue.Thanks', lng: interaction.user.language })), + .setTitle(client.translate({ key: 'interactions.issue.Recieved', lng: interaction.user.language })) + .setDescription(client.translate({ key: 'interactions.issue.Thanks', lng: interaction.user.language })), ], ephemeral: true, }) @@ -40,8 +40,8 @@ exports.Command = async (client: DiscordClient, interaction: DiscordCommandInter await interaction.reply({ embeds: [ new MessageEmbed() - .setTitle(client.translate({ key: 'slashCommands.issue.Error', lng: interaction.user.language })) - .setDescription(client.translate({ key: 'slashCommands.issue.TryAgain', lng: interaction.user.language })), + .setTitle(client.translate({ key: 'interactions.issue.Error', lng: interaction.user.language })) + .setDescription(client.translate({ key: 'interactions.issue.TryAgain', lng: interaction.user.language })), ], }) throw new Error(error) diff --git a/interactions/wochenplan.ts b/interactions/wochenplan.ts index c93bd5c..5f2ab75 100644 --- a/interactions/wochenplan.ts +++ b/interactions/wochenplan.ts @@ -81,7 +81,7 @@ async function wochenplan(client: DiscordClient, interaction: DiscordCommandInte const embed = new MessageEmbed() .setAuthor({ name: client.translate({ - key: 'slashCommands.wochenplan.Schedule', + key: 'interactions.wochenplan.Schedule', options: { user: interaction.user.username, lng: interaction.user.language, @@ -90,7 +90,7 @@ async function wochenplan(client: DiscordClient, interaction: DiscordCommandInte }) .setDescription( client.translate({ - key: 'slashCommands.wochenplan.Week', + key: 'interactions.wochenplan.Week', options: { date: moment(startOfWeek).format('DD.MM.yyyy'), lng: interaction.user.language }, }), ) From a3e350df880c8a4fe0d90a27575e0646c7a1c0c3 Mon Sep 17 00:00:00 2001 From: Christoph <29735603+Chr1s70ph@users.noreply.github.com> Date: Wed, 6 Apr 2022 11:02:05 +0200 Subject: [PATCH 06/10] add translation to mensa --- interactions/mensa.ts | 45 +++++++++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/interactions/mensa.ts b/interactions/mensa.ts index d23ec00..342d522 100644 --- a/interactions/mensa.ts +++ b/interactions/mensa.ts @@ -219,7 +219,7 @@ function _updateJson(client: DiscordClient, interaction: DiscordCommandInteracti }) } -async function mensa(client, interaction, req_weekday, req_mensa) { +async function mensa(client: DiscordClient, interaction: DiscordCommandInteraction, req_weekday, req_mensa) { /** * Mensa embed */ @@ -259,7 +259,7 @@ async function mensa(client, interaction, req_weekday, req_mensa) { if (currentDate + 7 * 86400000 > lastDate) { // 7 * 86400 : number of seconds in one week - embed.setDescription(':fork_knife_plate: Aktualisiere JSON...') + embed.setDescription(client.translate({ key: 'interactions.mensa.refreshJSON', lng: interaction.user.language })) interaction.channel.send({ embeds: [embed], @@ -273,8 +273,12 @@ async function mensa(client, interaction, req_weekday, req_mensa) { if (Object.keys(mensa_json).indexOf(req_mensa) === -1) { embed - .setTitle(`Mensa ${mensaOptions[req_mensa].name}`) - .setDescription('Diese Mensa hat am angeforderten Tag leider geschlossen.') + .setTitle( + `${client.translate({ key: 'interactions.mensa.cafeteria', lng: interaction.user.language })} ${ + mensaOptions[req_mensa].name + }`, + ) + .setDescription(client.translate({ key: 'interactions.mensa.lineClosed', lng: interaction.user.language })) interaction.reply({ embeds: [embed], @@ -297,7 +301,11 @@ async function mensa(client, interaction, req_weekday, req_mensa) { const date = new Date(dayString) embed - .setTitle(`Mensa ${mensaOptions[req_mensa].name}`) + .setTitle( + `${client.translate({ key: 'interactions.mensa.cafeteria', lng: interaction.user.language })} ${ + mensaOptions[req_mensa].name + }`, + ) .setDescription( `${date.toLocaleDateString('de-DE', { weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric' })}`, ) @@ -311,13 +319,16 @@ async function mensa(client, interaction, req_weekday, req_mensa) { // eslint-disable-next-line max-depth if (foodLineData.nodata) { - mealValues = '__Leider gibt es für diesen Tag hier keine Informationen!__' + mealValues = client.translate({ key: 'interactions.mensa.noInformation', lng: interaction.user.language }) break } // eslint-disable-next-line max-depth if (foodLineData.closing_start) { - mealValues = `__Leider ist hier heute geschlossen. Grund: ${foodLineData.closing_text}__` + mealValues = client.translate({ + key: 'interactions.mensa.closed', + options: { reason: foodLineData.closing_text, lng: interaction.user.language }, + }) break } @@ -327,9 +338,15 @@ async function mensa(client, interaction, req_weekday, req_mensa) { mealValues += ['', '.'].indexOf(dish) === -1 ? `${meal}${dish}\n` : meal - const allAdditions = foodLineData.add.join(', ') + const allAdditives = foodLineData.add.join(', ') - mealValues += allAdditions !== '' ? `_Zusatz: [${allAdditions}]_` : '_Keine Zusätze_' + mealValues += + allAdditives !== '' + ? client.translate({ + key: 'interactions.mensa.foodAdditives', + options: { additives: allAdditives, lng: interaction.user.language }, + }) + : client.translate({ key: 'interactions.mensa.noFoodAdditives', lng: interaction.user.language }) const foodContainsStringToEmoji = { bio: ':earth_africa:', @@ -368,9 +385,13 @@ async function mensa(client, interaction, req_weekday, req_mensa) { embed.addFields({ name: '⠀', - value: `Eine Liste aller Zusätze findest du [hier](${ - client.config.mensa.base_url + client.config.mensa.additional_info - }).`, + value: client.translate({ + key: 'interactions.mensa.allAdditivesList', + options: { + link: client.config.mensa.base_url + client.config.mensa.additional_info, + lng: interaction.user.language, + }, + }), inline: false, }) From 6ef5d2628075d602bf2eb305bceed61f7f1d7f86 Mon Sep 17 00:00:00 2001 From: Christoph <29735603+Chr1s70ph@users.noreply.github.com> Date: Wed, 6 Apr 2022 11:02:35 +0200 Subject: [PATCH 07/10] reformat json, rename slashCommands key to interactions, add mensa --- locales/de.json | 190 ++++++++++++++++++++++--------------------- locales/en-US.json | 196 ++++++++++++++++++++++++--------------------- 2 files changed, 203 insertions(+), 183 deletions(-) diff --git a/locales/de.json b/locales/de.json index 4102b22..902e1ee 100644 --- a/locales/de.json +++ b/locales/de.json @@ -1,93 +1,103 @@ { - "language": "Deutsch", - "flag": "🇩🇪", - "commands": { - "admin": { - "missingPermission": "Du bist nicht berechtigt, diesen Befehl auszuführen.", - "devtest": {}, - "restart": "🤖Starte neu...", - "say": {}, - "status": "👥Präsenz wurde geändert!" - }, - "fun": { - "fact": "🧠Fakt", - "komedi": {}, - "tenor": { - "ErrorMissingSearchQuery": "Bitte gebe ein suchwort an!", - "ErrorNoGifsFound": "<@{{userID}}> Es konnten keine Gifs gefunden werden für : '{{searchQuery}}'" - } - }, - "tests": { - "hello": { - "welcome": "hallo welt" - } - }, - "utility": { - "antwortaufalles": "Die Antwort auf die Frage nach dem Leben, dem Universum und dem ganzen Rest ist :four::two:", - "channelinfo": { - "Answer": "Anzahl an Kanalmitgliedern in: {{memberNumber}}\nin {{channelName}}.", - "ErrorNotAvailable": "Kanalinformationen sind in diesem Kanal nicht verfügbar. Versuche es mit einem anderen Kanal." - }, - "command": { - "ErrorNoCommandName": "Bitte gebe einen Befehlsnamen an.", - "CommandHelp": "Befehlshilfe", - "Description": "Beschreibung", - "Usage": "Benutzung", - "Aliases": "Aliase" - }, - "countdown": { - "Countdown": "Fahrstuhl aus in:", - "Departure": "Abfluuuug", - "Liftoff": "🚀Abgehoben🚀" - }, - "git": { - "Title": "[🌐] GIT Wiki", - "Gitlab": "[Link]({{- gitlab}}) zur Gitlab Startseite", - "Github": "Github [Repository]({{- github}}) von <@{{userID}}>" - }, - "onlinecount": { - "OnlineCounter": "[🌐] Online Zähler", - "Online": "🟢Online", - "Idle": "🟡Abwesend", - "DND": "🔴Nicht stören" - }, - "ping": "🏓Die Latenz beträgt {{latency}}ms. API - Latenz ist {{api_latency}}", - "start": { - "ErrorNoVoice": "⚠️ Du bist nicht in einem Sprach-Kanal.\nBitte trete einenm Sprach-Kanal bei, um diesen Befehl nutzen zu können.", - "ErrorInvalidOption": "⚠️ Nicht zulässige Option!", - "Info": "❔ Wenn du der Aktivität nicht beitreten kannst, **erstelle ** sie, indem du oben auf den **[Link]({{- invite}})** klickst." - }, - "test": "🌐Dieser Bot funktioniert einwandfrei!", - "uptime": { - "Title": "⏰Betriebszeit", - "Time": "Zeit seit dem letzten neustart:", - "Info": "{{days}} Tage, {{hours}} Stunden, {{minutes}} Minuten, {{seconds}} Sekunden" - }, - "userprofile": { - "UserProfile": "👤Benutzerprofil", - "Joined": "Beigetreten", - "NoNitroStatus": "Zurzeit nicht abboniert" - }, - "zoom": {} - } + "language": "Deutsch", + "flag": "🇩🇪", + "commands": { + "admin": { + "missingPermission": "Du bist nicht berechtigt, diesen Befehl auszuführen.", + "devtest": {}, + "restart": "🤖Starte neu...", + "say": {}, + "status": "👥Präsenz wurde geändert!" }, - "slashCommands": { - "help": "Hilfe", - "issue": { - "Recieved": "Vorschlag angekommen!", - "Thanks": "Vielen Dank für deinen Vorschlag!", - "Error": "⚠Fehler", - "TryAgain": "Es ist ein Fehler aufgetreten. Bitte versuche es später erneut." - }, - "ping": {}, - "wochenplan": { - "Schedule": "🗓️ Wochenplan für {{user}}", - "Week": "Woche vom {{date}}" - }, - "language": { - "Select": "Wähle deine bevorzugte Sprache", - "DefaultSelect": "Nichts ausgewählt", - "LanguageUpdated": "Sprache wurde erfolgreich zu {{language}} geändert." - } + "fun": { + "fact": "🧠Fakt", + "komedi": {}, + "tenor": { + "ErrorMissingSearchQuery": "Bitte gebe ein suchwort an!", + "ErrorNoGifsFound": "<@{{userID}}> Es konnten keine Gifs gefunden werden für : '{{searchQuery}}'" + } + }, + "tests": { + "hello": { + "welcome": "hallo welt" + } + }, + "utility": { + "antwortaufalles": "Die Antwort auf die Frage nach dem Leben, dem Universum und dem ganzen Rest ist :four::two:", + "channelinfo": { + "Answer": "Anzahl an Kanalmitgliedern in: {{memberNumber}}\nin {{channelName}}.", + "ErrorNotAvailable": "Kanalinformationen sind in diesem Kanal nicht verfügbar. Versuche es mit einem anderen Kanal." + }, + "command": { + "ErrorNoCommandName": "Bitte gebe einen Befehlsnamen an.", + "CommandHelp": "Befehlshilfe", + "Description": "Beschreibung", + "Usage": "Benutzung", + "Aliases": "Aliase" + }, + "countdown": { + "Countdown": "Fahrstuhl aus in:", + "Departure": "Abfluuuug", + "Liftoff": "🚀Abgehoben🚀" + }, + "git": { + "Title": "[🌐] GIT Wiki", + "Gitlab": "[Link]({{- gitlab}}) zur Gitlab Startseite", + "Github": "Github [Repository]({{- github}}) von <@{{userID}}>" + }, + "onlinecount": { + "OnlineCounter": "[🌐] Online Zähler", + "Online": "🟢Online", + "Idle": "🟡Abwesend", + "DND": "🔴Nicht stören" + }, + "ping": "🏓Die Latenz beträgt {{latency}}ms. API - Latenz ist {{api_latency}}", + "start": { + "ErrorNoVoice": "⚠️ Du bist nicht in einem Sprach-Kanal.\nBitte trete einenm Sprach-Kanal bei, um diesen Befehl nutzen zu können.", + "ErrorInvalidOption": "⚠️ Nicht zulässige Option!", + "Info": "❔ Wenn du der Aktivität nicht beitreten kannst, **erstelle ** sie, indem du oben auf den **[Link]({{- invite}})** klickst." + }, + "test": "🌐Dieser Bot funktioniert einwandfrei!", + "uptime": { + "Title": "⏰Betriebszeit", + "Time": "Zeit seit dem letzten neustart:", + "Info": "{{days}} Tage, {{hours}} Stunden, {{minutes}} Minuten, {{seconds}} Sekunden" + }, + "userprofile": { + "UserProfile": "👤Benutzerprofil", + "Joined": "Beigetreten", + "NoNitroStatus": "Zurzeit nicht abboniert" + }, + "zoom": {} + } + }, + "interactions": { + "help": "Hilfe", + "issue": { + "Recieved": "Vorschlag angekommen!", + "Thanks": "Vielen Dank für deinen Vorschlag!", + "Error": "⚠Fehler", + "TryAgain": "Es ist ein Fehler aufgetreten. Bitte versuche es später erneut." + }, + "ping": {}, + "wochenplan": { + "Schedule": "🗓️ Wochenplan für {{user}}", + "Week": "Woche vom {{date}}" + }, + "language": { + "Select": "Wähle deine bevorzugte Sprache", + "DefaultSelect": "Nichts ausgewählt", + "LanguageUpdated": "Sprache wurde erfolgreich zu {{language}} geändert." + }, + "mensa": { + "cafeteria": "Mensa", + "refreshJSON": "🍽 Aktualisiere JSON...", + "lineClosed": "Diese Mensa hat am angeforderten Tag leider geschlossen.", + "noInformation": "__Leider gibt es für diesen Tag hier keine Informationen!__", + "closed": "__Leider ist hier heute geschlossen. Grund: {{reason}}__", + "foodAdditives": "_Zusatz: [{{additives}}]_", + "noFoodAdditives": "_Keine Zusätze_", + "allAdditivesList": "Eine Liste aller Zusätze findest du [hier](https://{{link}})." } -} \ No newline at end of file + } +} diff --git a/locales/en-US.json b/locales/en-US.json index 2bba1a9..2493a2b 100644 --- a/locales/en-US.json +++ b/locales/en-US.json @@ -1,96 +1,106 @@ { - "language": "English", - "flag": "🇺🇸", - "commands": { - "admin": { - "missingPermission": "You do not have permission to perform that command.", - "devtest": {}, - "restart": "🤖Restarting...", - "say": {}, - "status": "👥Presence has been updated!" - }, - "fun": { - "fact": "🧠Fact", - "komedi": {}, - "tenor": { - "ErrorMissingSearchQuery": "Please enter a search query!", - "ErrorNoGifsFound": "<@{{userID}}> No Gifs have been found for : '{{searchQuery}}'" - } - }, - "tests": { - "hello": { - "welcome": "hello world" - } - }, - "utility": { - "antwortaufalles": "The answer to the question about life, the universe, and all the rest is :four: :two:", - "channelinfo": { - "Answer": "Number of channel members: {{memberNumber}}\nin {{channelName}}.", - "ErrorNotAvailable": "Channel info is not available in this channel. Try a different channel." - }, - "command": { - "ErrorNoCommandName": "Please provide a command name.", - "CommandHelp": "Command assistance", - "Description": "Description", - "Usage": "Usage", - "Aliases": "Aliases" - }, - "countdown": { - "Countdown": "Liftoff in:", - "Departure": "Departuuuure", - "Liftoff": "🚀Departed🚀" - }, - "git": { - "Title": "[🌐] GIT Wiki", - "Gitlab": "[Link]({{- gitlab}}) to Gitlab Homepage", - "Github": "Github [Repository]({{- github}}) of <@{{userID}}>" - }, - "onlinecount": { - "OnlineCounter": "[🌐] Online Counter", - "Online": "🟢Online", - "Idle": "🟡Idle", - "DND": "🔴DND" - }, - "ping": "🏓Latency is {{latency}}ms. API Latency is {{api_latency}}ms", - "start": { - "ErrorNoVoice": "⚠️ You are not in a Voice-Channel.\nPlease join a Voice-Channel to use this command.", - "ErrorInvalidOption": "⚠️ Invalid option!", - "Info": "❔ If you can't join the activity **create it** by clicking the **[Link]({{- invite}})** above." - }, - "test": "🌐 This Bot is working as intended!", - "uptime": { - "Title": "⏰Uptime", - "Time": "Time since last restart:", - "Info": "{{days}} Days, {{hours}} Hours, {{minutes}} Minutes, {{seconds}} Seconds" - }, - "userprofile": { - "UserProfile": "👤Userprofile", - "Joined": "Joined:", - "NoNitroStatus": "Not currently subscribed" - }, - "zoom": {} - } + "language": "English", + "flag": "🇺🇸", + "commands": { + "admin": { + "missingPermission": "You do not have permission to perform that command.", + "devtest": {}, + "restart": "🤖Restarting...", + "say": {}, + "status": "👥Presence has been updated!" }, - "slashCommands": { - "help": "Help", - "issue": { - "Recieved": "Issue recieved!", - "Thanks": "Thank you for submitting your issue!", - "Error": "⚠Error", - "TryAgain": "An error occured. Please try again later." - }, - "ping": {}, - "wochenplan": { - "Schedule": "🗓️ Weekly schedule for {{user}}", - "Week": "Week of {{date}}" - }, - "klausuren": { - "Exams": "🗓️ Exams for {{user}}" - }, - "language": { - "Select": "Select your desired language", - "DefaultSelect": "Nothing Selected", - "LanguageUpdated": "Language has been successfully updated to {{language}}." - } + "fun": { + "fact": "🧠Fact", + "komedi": {}, + "tenor": { + "ErrorMissingSearchQuery": "Please enter a search query!", + "ErrorNoGifsFound": "<@{{userID}}> No Gifs have been found for : '{{searchQuery}}'" + } + }, + "tests": { + "hello": { + "welcome": "hello world" + } + }, + "utility": { + "antwortaufalles": "The answer to the question about life, the universe, and all the rest is :four: :two:", + "channelinfo": { + "Answer": "Number of channel members: {{memberNumber}}\nin {{channelName}}.", + "ErrorNotAvailable": "Channel info is not available in this channel. Try a different channel." + }, + "command": { + "ErrorNoCommandName": "Please provide a command name.", + "CommandHelp": "Command assistance", + "Description": "Description", + "Usage": "Usage", + "Aliases": "Aliases" + }, + "countdown": { + "Countdown": "Liftoff in:", + "Departure": "Departuuuure", + "Liftoff": "🚀Departed🚀" + }, + "git": { + "Title": "[🌐] GIT Wiki", + "Gitlab": "[Link]({{- gitlab}}) to Gitlab Homepage", + "Github": "Github [Repository]({{- github}}) of <@{{userID}}>" + }, + "onlinecount": { + "OnlineCounter": "[🌐] Online Counter", + "Online": "🟢Online", + "Idle": "🟡Idle", + "DND": "🔴DND" + }, + "ping": "🏓Latency is {{latency}}ms. API Latency is {{api_latency}}ms", + "start": { + "ErrorNoVoice": "⚠️ You are not in a Voice-Channel.\nPlease join a Voice-Channel to use this command.", + "ErrorInvalidOption": "⚠️ Invalid option!", + "Info": "❔ If you can't join the activity **create it** by clicking the **[Link]({{- invite}})** above." + }, + "test": "🌐 This Bot is working as intended!", + "uptime": { + "Title": "⏰Uptime", + "Time": "Time since last restart:", + "Info": "{{days}} Days, {{hours}} Hours, {{minutes}} Minutes, {{seconds}} Seconds" + }, + "userprofile": { + "UserProfile": "👤Userprofile", + "Joined": "Joined:", + "NoNitroStatus": "Not currently subscribed" + }, + "zoom": {} + } + }, + "interactions": { + "help": "Help", + "issue": { + "Recieved": "Issue recieved!", + "Thanks": "Thank you for submitting your issue!", + "Error": "⚠Error", + "TryAgain": "An error occured. Please try again later." + }, + "ping": {}, + "wochenplan": { + "Schedule": "🗓️ Weekly schedule for {{user}}", + "Week": "Week of {{date}}" + }, + "klausuren": { + "Exams": "🗓️ Exams for {{user}}" + }, + "language": { + "Select": "Select your desired language", + "DefaultSelect": "Nothing Selected", + "LanguageUpdated": "Language has been successfully updated to {{language}}." + }, + "mensa": { + "cafeteria": "Cafeteria", + "refreshJSON": "🍽 refresh JSON...", + "lineClosed": "This cafeteria has closed on the requested day.", + "noInformation": "__Sadly there is no information for this day!__", + "closed": "__Sadly this cafeteria is closed today. Reason: {{reason}}__", + "foodAdditives": "_Additives: [{{additives}}]_", + "noFoodAdditives": "_No additives_", + "allAdditivesList": "You can find a list of all additives [here](https://{{link}})." } -} \ No newline at end of file + } +} From 16118d886e0d318523846504df0feb01cd7e444b Mon Sep 17 00:00:00 2001 From: Christoph <29735603+Chr1s70ph@users.noreply.github.com> Date: Thu, 7 Apr 2022 16:56:43 +0200 Subject: [PATCH 08/10] dont force options and add exports --- interactions/mensa.ts | 100 +++++++++++++++++++++++++++--------------- 1 file changed, 65 insertions(+), 35 deletions(-) diff --git a/interactions/mensa.ts b/interactions/mensa.ts index 342d522..883ab65 100644 --- a/interactions/mensa.ts +++ b/interactions/mensa.ts @@ -77,22 +77,48 @@ export const data = new SlashCommandBuilder() .setName('mensa') .setDescription('Was es wohl heute zu Essen gibt?') .addStringOption(option => - option - .setName('wochentag') - .setDescription('Der Wochentag, der angezeigt werden soll.') - .addChoices(weekday_choices) - .setRequired(true), + option.setName('wochentag').setDescription('Der Wochentag, der angezeigt werden soll.').addChoices(weekday_choices), ) .addStringOption(option => - option - .setName('ort') - .setDescription('Die Mensa, die angezeigt werden soll.') - .addChoices(line_choices) - .setRequired(true), + option.setName('ort').setDescription('Die Mensa, die angezeigt werden soll.').addChoices(line_choices), ) exports.Command = async (client: DiscordClient, interaction: DiscordCommandInteraction): Promise => { - await mensa(client, interaction, interaction.options.getString('wochentag'), interaction.options.getString('ort')) + const today = new Date() + const weekday = interaction.options.getString('wochentag') + ? interaction.options.getString('wochentag') + : today.getHours() >= 16 + ? getWeekday(today.getDay()) + : getWeekday(today.getDay() - 1) + + const line = interaction.options.getString('ort') ? interaction.options.getString('ort') : 'adenauerring' + interaction.reply({ embeds: [await mensa(client, weekday, line, interaction)] }) +} + +/** + * Returns the correct shortend weekday based on {@link index} + * @param {number} index index of Weekday + * @returns {string} weekday + */ +export function getWeekday(index: number): string { + switch (index) { + case 0: + return 'mo' + case 1: + return 'di' + case 2: + return 'mi' + case 3: + return 'do' + case 4: + return 'fr' + case 5: + return 'sa' + case 6: + return 'so' + default: + return 'mo' + } } class FoodLine { @@ -169,7 +195,7 @@ const weekdayOptions = { so: new Weekday('Sonntag', 6), } -function _updateJson(client: DiscordClient, interaction: DiscordCommandInteraction): Promise { +function _updateJson(client: DiscordClient): Promise { return new Promise((resolve, reject) => { /** * Fancy API stuff and user credential hashing @@ -197,7 +223,6 @@ function _updateJson(client: DiscordClient, interaction: DiscordCommandInteracti /** * TODO: valid error handling */ - interaction.reply(`Error, sadface\n${error}`) reject(error) }) res.on('end', () => { @@ -209,7 +234,6 @@ function _updateJson(client: DiscordClient, interaction: DiscordCommandInteracti /** * TODO: valid error handling */ - interaction.followUp('Sadface') reject(err) } resolve(body) @@ -219,18 +243,25 @@ function _updateJson(client: DiscordClient, interaction: DiscordCommandInteracti }) } -async function mensa(client: DiscordClient, interaction: DiscordCommandInteraction, req_weekday, req_mensa) { +export async function mensa( + client: DiscordClient, + req_weekday, + req_mensa, + interaction: DiscordCommandInteraction | null, +): Promise { /** * Mensa embed */ const embed = new MessageEmbed().setColor('#FAD51B').setAuthor({ name: '🍽️ Mensaplan' }) + const embed_language = interaction?.user?.language ?? 'de' + let raw_mensa, mensa_json if ((await fs.promises.readFile(`data/mensa.json`)).toString().length === 0) { /** * Fetch new mensa plan if none found */ - const buffer = await _updateJson(client, interaction) + const buffer = await _updateJson(client) if (buffer) mensa_json = JSON.parse(buffer) } else { /** @@ -259,13 +290,14 @@ async function mensa(client: DiscordClient, interaction: DiscordCommandInteracti if (currentDate + 7 * 86400000 > lastDate) { // 7 * 86400 : number of seconds in one week - embed.setDescription(client.translate({ key: 'interactions.mensa.refreshJSON', lng: interaction.user.language })) - - interaction.channel.send({ - embeds: [embed], - }) - - const buffer = await _updateJson(client, interaction) + embed.setDescription( + client.translate({ + key: 'interactions.mensa.refreshJSON', + lng: embed_language, + }), + ) + + const buffer = await _updateJson(client) if (buffer) mensa_json = JSON.parse(buffer) mensa_json = await fs.promises.readFile(`data/mensa.json`) @@ -274,15 +306,13 @@ async function mensa(client: DiscordClient, interaction: DiscordCommandInteracti if (Object.keys(mensa_json).indexOf(req_mensa) === -1) { embed .setTitle( - `${client.translate({ key: 'interactions.mensa.cafeteria', lng: interaction.user.language })} ${ + `${client.translate({ key: 'interactions.mensa.cafeteria', lng: embed_language })} ${ mensaOptions[req_mensa].name }`, ) - .setDescription(client.translate({ key: 'interactions.mensa.lineClosed', lng: interaction.user.language })) + .setDescription(client.translate({ key: 'interactions.mensa.lineClosed', lng: embed_language })) - interaction.reply({ - embeds: [embed], - }) + return embed } for (const timestampKey in Object.keys(mensa_json[req_mensa])) { @@ -302,7 +332,7 @@ async function mensa(client: DiscordClient, interaction: DiscordCommandInteracti embed .setTitle( - `${client.translate({ key: 'interactions.mensa.cafeteria', lng: interaction.user.language })} ${ + `${client.translate({ key: 'interactions.mensa.cafeteria', lng: embed_language })} ${ mensaOptions[req_mensa].name }`, ) @@ -319,7 +349,7 @@ async function mensa(client: DiscordClient, interaction: DiscordCommandInteracti // eslint-disable-next-line max-depth if (foodLineData.nodata) { - mealValues = client.translate({ key: 'interactions.mensa.noInformation', lng: interaction.user.language }) + mealValues = client.translate({ key: 'interactions.mensa.noInformation', lng: embed_language }) break } @@ -327,7 +357,7 @@ async function mensa(client: DiscordClient, interaction: DiscordCommandInteracti if (foodLineData.closing_start) { mealValues = client.translate({ key: 'interactions.mensa.closed', - options: { reason: foodLineData.closing_text, lng: interaction.user.language }, + options: { reason: foodLineData.closing_text, lng: embed_language }, }) break } @@ -344,9 +374,9 @@ async function mensa(client: DiscordClient, interaction: DiscordCommandInteracti allAdditives !== '' ? client.translate({ key: 'interactions.mensa.foodAdditives', - options: { additives: allAdditives, lng: interaction.user.language }, + options: { additives: allAdditives, lng: embed_language }, }) - : client.translate({ key: 'interactions.mensa.noFoodAdditives', lng: interaction.user.language }) + : client.translate({ key: 'interactions.mensa.noFoodAdditives', lng: embed_language }) const foodContainsStringToEmoji = { bio: ':earth_africa:', @@ -389,11 +419,11 @@ async function mensa(client: DiscordClient, interaction: DiscordCommandInteracti key: 'interactions.mensa.allAdditivesList', options: { link: client.config.mensa.base_url + client.config.mensa.additional_info, - lng: interaction.user.language, + lng: embed_language, }, }), inline: false, }) - interaction.reply({ embeds: [embed] }) + return embed } From 30bd067b28142b00d8566c00d48e2b76d1280547 Mon Sep 17 00:00:00 2001 From: Christoph <29735603+Chr1s70ph@users.noreply.github.com> Date: Thu, 7 Apr 2022 16:57:03 +0200 Subject: [PATCH 09/10] add periodic mensa updates --- scripts/addCommands.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/scripts/addCommands.ts b/scripts/addCommands.ts index 901c8a6..654879b 100644 --- a/scripts/addCommands.ts +++ b/scripts/addCommands.ts @@ -1,7 +1,11 @@ import { readdir, statSync } from 'fs' import { readdir as promiseReaddir } from 'fs/promises' import { REST } from '@discordjs/rest' +import { TextChannel } from 'discord.js' +import { scheduleJob } from 'node-schedule' +import { mensa, getWeekday } from '../interactions/mensa' import { DiscordClient } from '../types/customTypes' + const { Routes } = require('discord-api-types/v9') /** @@ -17,6 +21,7 @@ const slashCommandsFolder = './interactions/' exports.run = (client: DiscordClient) => { Commands(client) loadSlashCommands(client) + mensa_automation(client) } function Commands(client) { @@ -133,3 +138,20 @@ async function postSlashCommands(client, slashCommandData) { console.error(error) } } + +/** + * Send Periodic Updates on whats new in the cafetaria. + * @param {DiscordClient} client Bot-Client + */ +async function mensa_automation(client: DiscordClient) { + await scheduleJob('0 5 * * 1-5', async () => { + const today = new Date() + const weekday = today.getHours() >= 16 ? getWeekday(today.getDay()) : getWeekday(today.getDay() - 1) + + const channel = client.channels.cache.find( + _channel => _channel.id === client.config.ids.channelIDs.mensa, + ) as TextChannel + + channel.send({ embeds: [await mensa(client, weekday, 'adenauerring', null)] }) + }) +} From 00d6660ca03f4491384a9ade169deafc1771b937 Mon Sep 17 00:00:00 2001 From: Christoph <29735603+Chr1s70ph@users.noreply.github.com> Date: Thu, 7 Apr 2022 17:00:25 +0200 Subject: [PATCH 10/10] crosspost mensa message (aka auto publish) --- scripts/addCommands.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/addCommands.ts b/scripts/addCommands.ts index 654879b..a0cb9bc 100644 --- a/scripts/addCommands.ts +++ b/scripts/addCommands.ts @@ -152,6 +152,7 @@ async function mensa_automation(client: DiscordClient) { _channel => _channel.id === client.config.ids.channelIDs.mensa, ) as TextChannel - channel.send({ embeds: [await mensa(client, weekday, 'adenauerring', null)] }) + const message = channel.send({ embeds: [await mensa(client, weekday, 'adenauerring', null)] }) + ;(await message).crosspost() }) }