Skip to content

Commit

Permalink
Merge pull request #163 from Chr1s70ph/cleanup
Browse files Browse the repository at this point in the history
Code Cleanup and bugfixing
  • Loading branch information
Chr1s70ph authored Apr 7, 2022
2 parents aff2961 + 00d6660 commit 32440be
Show file tree
Hide file tree
Showing 16 changed files with 350 additions and 250 deletions.
5 changes: 4 additions & 1 deletion commands/fun/fact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
}),
],
})
}
5 changes: 4 additions & 1 deletion commands/fun/komedi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
}),
],
})
7 changes: 4 additions & 3 deletions commands/fun/tenor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion commands/utility/countdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')

/**
Expand Down
6 changes: 3 additions & 3 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion interactions/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion interactions/klausuren.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions interactions/language.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,15 @@ 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),
)

/**
* 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,
})
Expand Down Expand Up @@ -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],
Expand Down
127 changes: 89 additions & 38 deletions interactions/mensa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> => {
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 {
Expand Down Expand Up @@ -169,7 +195,7 @@ const weekdayOptions = {
so: new Weekday('Sonntag', 6),
}

function _updateJson(client: DiscordClient, interaction: DiscordCommandInteraction): Promise<string> {
function _updateJson(client: DiscordClient): Promise<string> {
return new Promise((resolve, reject) => {
/**
* Fancy API stuff and user credential hashing
Expand Down Expand Up @@ -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', () => {
Expand All @@ -209,7 +234,6 @@ function _updateJson(client: DiscordClient, interaction: DiscordCommandInteracti
/**
* TODO: valid error handling
*/
interaction.followUp('Sadface')
reject(err)
}
resolve(body)
Expand All @@ -219,18 +243,25 @@ function _updateJson(client: DiscordClient, interaction: DiscordCommandInteracti
})
}

async function mensa(client, interaction, req_weekday, req_mensa) {
export async function mensa(
client: DiscordClient,
req_weekday,
req_mensa,
interaction: DiscordCommandInteraction | null,
): Promise<MessageEmbed> {
/**
* 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 {
/**
Expand Down Expand Up @@ -259,26 +290,29 @@ 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...')

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`)
}

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.')

interaction.reply({
embeds: [embed],
})
.setTitle(
`${client.translate({ key: 'interactions.mensa.cafeteria', lng: embed_language })} ${
mensaOptions[req_mensa].name
}`,
)
.setDescription(client.translate({ key: 'interactions.mensa.lineClosed', lng: embed_language }))

return embed
}

for (const timestampKey in Object.keys(mensa_json[req_mensa])) {
Expand All @@ -297,7 +331,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: embed_language })} ${
mensaOptions[req_mensa].name
}`,
)
.setDescription(
`${date.toLocaleDateString('de-DE', { weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric' })}`,
)
Expand All @@ -311,13 +349,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: embed_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: embed_language },
})
break
}

Expand All @@ -327,9 +368,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: embed_language },
})
: client.translate({ key: 'interactions.mensa.noFoodAdditives', lng: embed_language })

const foodContainsStringToEmoji = {
bio: ':earth_africa:',
Expand Down Expand Up @@ -368,11 +415,15 @@ 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: embed_language,
},
}),
inline: false,
})

interaction.reply({ embeds: [embed] })
return embed
}
8 changes: 4 additions & 4 deletions interactions/vorschlag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,17 @@ 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,
})
} catch (error) {
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)
Expand Down
4 changes: 2 additions & 2 deletions interactions/wochenplan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 },
}),
)
Expand Down
Loading

0 comments on commit 32440be

Please sign in to comment.