Added translations

This commit is contained in:
Robert 2020-01-08 17:09:10 +01:00
parent fa34f8510d
commit 937dd76fe7
3 changed files with 58 additions and 3 deletions

32
api/translation.py Normal file
View file

@ -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]

25
cogs/api/translation.py Normal file
View file

@ -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 <ISO CountryCode>", 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))

View file

@ -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
return (not ctx.author.bot)