fulvia/modules/translate.py

82 lines
2.2 KiB
Python
Raw Normal View History

2018-03-16 03:13:43 -04:00
#!/usr/bin/env python3
"""
Google translate that shit.
"""
import random
import requests
2020-01-29 14:15:43 -05:00
import tools
2018-03-16 03:13:43 -04:00
from module import commands, example
def translate(text, in_lang='auto', out_lang='en'):
"""
Queries Google Translate.
"""
headers = {"User-Agent": "do you no de wae?"}
query = {
"client": "gtx",
"sl": in_lang,
"tl": out_lang,
"dt": "t",
"q": text,
}
url = "http://translate.googleapis.com/translate_a/single"
res = requests.get(url, params=query, timeout=40, headers=headers,
verify=True)
res.raise_for_status()
data = res.json()
return data[0][0][0], data[2]
@commands('translate', 'tr')
@example('.tr -i en -o fr my dog', '"mon chien" (en to fr, translate.google.com)')
2018-03-16 03:13:43 -04:00
@example('.tr היי', '"Hey" (iw to en, translate.google.com)')
@example('.tr mon chien', '"my dog" (fr to en, translate.google.com)')
def tr2(bot, trigger):
"""
Translates a phrase, with an optional language hint.
-i LANG, --inlang LANG - specifies the assumed input language.
-o LANG, --outlang LANG - specifies the desired output language.
"""
2020-01-07 18:58:19 -05:00
if len(trigger.args) < 2:
2018-03-16 03:13:43 -04:00
return bot.reply("Translate what?")
2020-01-29 14:15:43 -05:00
parser = tools.FulviaArgparse()
2018-03-16 03:13:43 -04:00
parser.add_argument("text", nargs=argparse.REMAINDER)
parser.add_argument("-i", "--inlang", default="auto")
parser.add_argument("-o", "--outlang", default="en")
2020-01-29 14:15:43 -05:00
try:
args = parser.parse_args(trigger.args[1:])
except Exception as e:
return bot.reply(type(e).__name__ + ": " + str(e))
2018-03-16 03:13:43 -04:00
args.text = " ".join(args.text)
tr_text, in_lang = translate(args.text, in_lang=args.inlang,
out_lang=args.outlang)
2018-05-25 15:21:18 -04:00
bot.msg(f'"{tr_text}" ({in_lang} to {args.outlang})')
2018-03-16 03:13:43 -04:00
@commands('mangle')
def mangle(bot, trigger):
"""Repeatedly translate the input until it makes absolutely no sense."""
2020-01-07 18:58:19 -05:00
if len(trigger.args) < 2:
2018-03-16 03:13:43 -04:00
return bot.reply("Mangle what?")
2020-01-07 18:58:19 -05:00
tr_text = ' '.join(trigger.args[1:])
2018-03-16 03:13:43 -04:00
long_lang_list = ['fr', 'de', 'es', 'it', 'no', 'he', 'la', 'ja', 'cy',
'ar', 'yi', 'zh', 'nl', 'ru', 'fi', 'hi', 'af', 'jw', 'mr', 'ceb',
'cs', 'ga', 'sv', 'eo', 'el', 'ms', 'lv']
lang_list = []
for __ in range(0, 8):
lang_list.append(random.choice(long_lang_list))
for lang in lang_list:
tr_text, _ = translate(tr_text, "auto", lang)
tr_text, _ = translate(tr_text, "auto", "en")
bot.msg(tr_text)