From ef547a709073e8919397b0b25a33150226a3f27c Mon Sep 17 00:00:00 2001 From: Stijn De Clercq Date: Fri, 3 Sep 2021 18:53:05 +0200 Subject: [PATCH] Translate slash command --- cogs/birthdays.py | 4 +-- cogs/faq.py | 4 +-- cogs/fun.py | 2 +- cogs/slash/translate_slash.py | 26 +++++++++++++++++ cogs/translate.py | 2 +- data/embeds/translate.py | 54 +++++++++++++++++++++++++++++++++++ data/embeds/ufora.py | 2 +- functions/football.py | 4 +-- functions/stringFormatters.py | 4 +-- functions/timeFormatters.py | 10 +++---- 10 files changed, 96 insertions(+), 16 deletions(-) create mode 100644 cogs/slash/translate_slash.py create mode 100644 data/embeds/translate.py diff --git a/cogs/birthdays.py b/cogs/birthdays.py index 2c3c284..8c0f351 100644 --- a/cogs/birthdays.py +++ b/cogs/birthdays.py @@ -163,8 +163,8 @@ class Birthdays(commands.Cog): # Create a datetime object for this birthday timeString = "{}/{}/{}".format( - stringFormatters.leadingZero(str(day)), - stringFormatters.leadingZero(str(month)), + stringFormatters.leading_zero(str(day)), + stringFormatters.leading_zero(str(month)), year ) diff --git a/cogs/faq.py b/cogs/faq.py index 8817b29..1b198fe 100644 --- a/cogs/faq.py +++ b/cogs/faq.py @@ -37,7 +37,7 @@ class Faq(commands.Cog): return await self.faqCategory(ctx, (constants.faq_channels[ctx.channel.id],)) # List of all categories with the first letter capitalized - resp = [stringFormatters.titleCase(cat[0]) for cat in faq.getCategories()] + resp = [stringFormatters.title_case(cat[0]) for cat in faq.getCategories()] # Sort alphabetically resp.sort() @@ -146,7 +146,7 @@ class Faq(commands.Cog): resp.sort(key=lambda x: int(x[0])) embed = discord.Embed(colour=discord.Colour.blue()) - embed.set_author(name="FAQ {}".format(stringFormatters.titleCase(category))) + embed.set_author(name="FAQ {}".format(stringFormatters.title_case(category))) # Add everything into the embed for i, pair in enumerate(resp): diff --git a/cogs/fun.py b/cogs/fun.py index 8d7a381..11b0a21 100644 --- a/cogs/fun.py +++ b/cogs/fun.py @@ -120,7 +120,7 @@ class Fun(commands.Cog): memeList = memes.getAllMemes() # Turn the list into a list of [Name: fields] - memeList = [": ".join([stringFormatters.titleCase(meme[1]), + memeList = [": ".join([stringFormatters.title_case(meme[1]), str(meme[2])]) for meme in sorted(memeList, key=lambda x: x[1])] pages = paginatedLeaderboard.Pages(source=paginatedLeaderboard.Source(memeList, "Memes", discord.Colour.blue()), diff --git a/cogs/slash/translate_slash.py b/cogs/slash/translate_slash.py new file mode 100644 index 0000000..226aa0d --- /dev/null +++ b/cogs/slash/translate_slash.py @@ -0,0 +1,26 @@ +from discord.ext import commands +from dislash import SlashInteraction, slash_command, Option, OptionType + +from data.embeds.translate import Translation +from startup.didier import Didier + + +class TranslateSlash(commands.Cog): + def __init__(self, client: Didier): + self.client: Didier = client + + @slash_command( + name="translate", + description="Google Translate", + options=[ + Option("text", "Tekst om te vertalen", OptionType.STRING, required=True), + Option("to", "Taal om naar te vertalen (default NL)", OptionType.STRING) + ] + ) + async def _translate_slash(self, interaction: SlashInteraction, text: str, to: str = "nl"): + translation = Translation(text=text, to=to.lower()) + await interaction.reply(embed=translation.to_embed()) + + +def setup(client: Didier): + client.add_cog(TranslateSlash(client)) diff --git a/cogs/translate.py b/cogs/translate.py index e607ca8..74186b7 100644 --- a/cogs/translate.py +++ b/cogs/translate.py @@ -2,7 +2,7 @@ from decorators import help import discord from discord.ext import commands from enums.help_categories import Category -from functions.stringFormatters import titleCase as tc +from functions.stringFormatters import title_case as tc from googletrans import Translator, LANGUAGES import re diff --git a/data/embeds/translate.py b/data/embeds/translate.py new file mode 100644 index 0000000..86ade0e --- /dev/null +++ b/data/embeds/translate.py @@ -0,0 +1,54 @@ +import discord +from googletrans import Translator, LANGUAGES +from functions.stringFormatters import title_case +from typing import Optional + + +class Translation: + def __init__(self, text: str, to: str): + self.text = text + self.to = to + self.embed: Optional[discord.Embed] = None + self.translation = None + + self.translate(text, to) + + def translate(self, query: str, to: str): + """ + Translate [query] into [to] + """ + try: + translator = Translator() + self.translation = translator.translate(query, to, "auto") + except ValueError as e: + message = str(e) + + if "destination" in message: + self._create_error_embed(f"{title_case(to)} is geen geldige taal.") + + raise e + + def _create_error_embed(self, message): + embed = discord.Embed(colour=discord.Colour.red()) + embed.set_author(name="Didier Translate") + embed.description = message + self.embed = embed + + def to_embed(self) -> discord.Embed: + # There's an error embed to show + if self.embed is not None: + return self.embed + + embed = discord.Embed(colour=discord.Colour.blue()) + embed.set_author(name="Didier Translate") + + language = self.translation.src + embed.add_field(name="Gedetecteerde taal", value=title_case(LANGUAGES[language])) + + if self.translation.extra_data["confidence"] is not None: + embed.add_field(name="Zekerheid", value="{}%".format(self.translation.extra_data["confidence"] * 100)) + + embed.add_field(name="Origineel ({})".format(self.translation.src.upper()), value=self.text, inline=False) + embed.add_field(name="Vertaling ({})".format(self.to.upper()), value=self.translation.text) + + return embed diff --git a/data/embeds/ufora.py b/data/embeds/ufora.py index c445e1b..613c932 100644 --- a/data/embeds/ufora.py +++ b/data/embeds/ufora.py @@ -1,6 +1,6 @@ from datetime import datetime from discord import Embed, Colour -from functions.stringFormatters import leadingZero as lz +from functions.stringFormatters import leading_zero as lz from functions.timeFormatters import intToWeekday from markdownify import markdownify as md import pytz diff --git a/functions/football.py b/functions/football.py index 0648096..59edf45 100644 --- a/functions/football.py +++ b/functions/football.py @@ -5,7 +5,7 @@ from datetime import datetime from enum import Enum from functions.timeFormatters import fromString from functions.scrapers.sporza import getJPLMatches, getJPLTable -from functions.stringFormatters import leadingZero +from functions.stringFormatters import leading_zero import re from requests import get import tabulate @@ -103,7 +103,7 @@ class Match: # No score to show yet, show time when the match starts if not self._hasStarted(): - return "{}:{}".format(leadingZero(str(self.start.hour)), leadingZero(str(self.start.minute))) + return "{}:{}".format(leading_zero(str(self.start.hour)), leading_zero(str(self.start.minute))) return "{} - {}".format(self.homeScore, self.awayScore) diff --git a/functions/stringFormatters.py b/functions/stringFormatters.py index c38c3c3..b1646cf 100644 --- a/functions/stringFormatters.py +++ b/functions/stringFormatters.py @@ -1,4 +1,4 @@ -def titleCase(string): +def title_case(string): return " ".join(capitalize(word) for word in string.split(" ")) @@ -8,7 +8,7 @@ def capitalize(string): return string[0].upper() -def leadingZero(string, size=2): +def leading_zero(string, size=2): string = str(string) while len(string) < size: string = "0" + string diff --git a/functions/timeFormatters.py b/functions/timeFormatters.py index 4460156..1d7788a 100644 --- a/functions/timeFormatters.py +++ b/functions/timeFormatters.py @@ -161,14 +161,14 @@ def fromString(timeString: str, formatString="%d/%m/%Y", tzinfo=pytz.timezone("E def fromArray(data: List[int]) -> datetime: - day = stringFormatters.leadingZero(str(data[0])) - month = stringFormatters.leadingZero(str(data[1])) + day = stringFormatters.leading_zero(str(data[0])) + month = stringFormatters.leading_zero(str(data[1])) year = str(data[2]) if len(data) == 6: - hour = stringFormatters.leadingZero(str(data[3])) - minute = stringFormatters.leadingZero(str(data[4])) - second = stringFormatters.leadingZero(str(data[5])) + hour = stringFormatters.leading_zero(str(data[3])) + minute = stringFormatters.leading_zero(str(data[4])) + second = stringFormatters.leading_zero(str(data[5])) return fromString(f"{day}/{month}/{year} {hour}:{minute}:{second}", formatString="%d/%m/%Y %H:%M:%S")