From 937dd76fe7ce5bad05fad8e7b03b85ecb4145969 Mon Sep 17 00:00:00 2001 From: Robert Date: Wed, 8 Jan 2020 17:09:10 +0100 Subject: [PATCH] Added translations --- api/translation.py | 32 ++++++++++++++++++++++++++++++++ cogs/api/translation.py | 25 +++++++++++++++++++++++++ util/checking.py | 4 +--- 3 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 api/translation.py create mode 100644 cogs/api/translation.py diff --git a/api/translation.py b/api/translation.py new file mode 100644 index 0000000..d07c07b --- /dev/null +++ b/api/translation.py @@ -0,0 +1,32 @@ +''' +This file provides the functionality for +the translation function, by first converting the +country/language name to an ISO369-1 language identifier +and then translating it using the Yandex Translation API +''' +import requests, urllib.parse +from util import logging, config +import pycountry + +api_key = config.settings["api_keys"]["yandex"] +langs = pycountry.languages + +def name_to_ISO(name: str) -> str: + alpha = "" + for language in langs: + if language.name.lower() == name.lower(): + alpha = language.alpha_2 + break + + return alpha + +def translate(text: str, lang: str) -> str: + url_encoded_text = urllib.parse.quote(text) + url = f"https://translate.yandex.net/api/v1.5/tr.json/translate?key={api_key}&text={url_encoded_text}&lang={lang}" + + response = requests.get(url) + if not response.ok: + logging.error(f"Failed to contact Yandex API: {response.status_code}") + return "" + + return response.json()["text"][0] \ No newline at end of file diff --git a/cogs/api/translation.py b/cogs/api/translation.py new file mode 100644 index 0000000..0016ef1 --- /dev/null +++ b/cogs/api/translation.py @@ -0,0 +1,25 @@ +import discord +from discord.ext import commands +from util import checking +from api import translation + +class Translation(commands.Cog): + + def __init__(self, client: discord.Client): + self.client = client + + @commands.command(name="translate", description="Translates the given text", usage="translate ", aliases=["tl"]) + @commands.check(checking.is_author_bot) + async def translate(self, ctx: commands.Context, language: str, *message: str): + # Get language code + code = translation.name_to_ISO(language) + text = ' '.join(message) + if code == "": + await ctx.send(f"There is no language named {language}.") + return + + translated = translation.translate(text, code) + await ctx.send(translated) + +def setup(client: discord.Client): + client.add_cog(Translation(client)) \ No newline at end of file diff --git a/util/checking.py b/util/checking.py index 043c7ec..0d03dc6 100644 --- a/util/checking.py +++ b/util/checking.py @@ -8,6 +8,4 @@ from discord.ext import commands from util import logging def is_author_bot(ctx : commands.Context) -> bool: - if ctx.message.author.bot: - return False - return True \ No newline at end of file + return (not ctx.author.bot) \ No newline at end of file