2021-09-03 18:53:05 +02:00
|
|
|
import discord
|
|
|
|
from googletrans import Translator, LANGUAGES
|
|
|
|
from functions.stringFormatters import title_case
|
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
|
|
|
|
class Translation:
|
2021-09-03 20:40:03 +02:00
|
|
|
def __init__(self, text: str, fr: str, to: str):
|
2021-09-03 18:53:05 +02:00
|
|
|
self.text = text
|
2021-09-03 20:40:03 +02:00
|
|
|
self.fr = fr
|
2021-09-03 18:53:05 +02:00
|
|
|
self.to = to
|
|
|
|
self.embed: Optional[discord.Embed] = None
|
|
|
|
self.translation = None
|
|
|
|
|
2021-09-03 20:40:03 +02:00
|
|
|
self.translate(text, fr, to)
|
2021-09-03 18:53:05 +02:00
|
|
|
|
2021-09-03 20:40:03 +02:00
|
|
|
def translate(self, query: str, fr: str, to: str):
|
2021-09-03 18:53:05 +02:00
|
|
|
"""
|
|
|
|
Translate [query] into [to]
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
translator = Translator()
|
2021-09-03 20:40:03 +02:00
|
|
|
self.translation = translator.translate(query, to, fr)
|
2021-09-03 18:53:05 +02:00
|
|
|
except ValueError as e:
|
|
|
|
message = str(e)
|
|
|
|
|
|
|
|
if "destination" in message:
|
|
|
|
self._create_error_embed(f"{title_case(to)} is geen geldige taal.")
|
2021-09-03 20:40:03 +02:00
|
|
|
return
|
|
|
|
|
|
|
|
if "source" in message:
|
|
|
|
self._create_error_embed(f"{title_case(fr)} is geen geldige taal.")
|
|
|
|
return
|
2021-09-03 18:53:05 +02:00
|
|
|
|
|
|
|
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")
|
|
|
|
|
2021-09-03 20:40:03 +02:00
|
|
|
if self.fr == "auto":
|
|
|
|
language = self.translation.src
|
|
|
|
embed.add_field(name="Gedetecteerde taal", value=title_case(LANGUAGES[language]))
|
2021-09-03 18:53:05 +02:00
|
|
|
|
|
|
|
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
|