#!/usr/bin/env python3 """ Google translate that shit. """ import random import argparse import requests import tools 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)') @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. """ if len(trigger.args) < 2: return bot.reply("Translate what?") parser = tools.FulviaArgparse() parser.add_argument("text", nargs=argparse.REMAINDER) parser.add_argument("-i", "--inlang", default="auto") parser.add_argument("-o", "--outlang", default="en") try: args = parser.parse_args(trigger.args[1:]) except Exception as e: return bot.reply(type(e).__name__ + ": " + str(e)) args.text = " ".join(args.text) tr_text, in_lang = translate(args.text, in_lang=args.inlang, out_lang=args.outlang) bot.msg(f'"{tr_text}" ({in_lang} to {args.outlang})') @commands('mangle') def mangle(bot, trigger): """Repeatedly translate the input until it makes absolutely no sense.""" if len(trigger.args) < 2: return bot.reply("Mangle what?") tr_text = ' '.join(trigger.args[1:]) 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)