Revert "Update translate.py"

This reverts commit eff99aff05.
This commit is contained in:
jesopo 2020-11-18 14:34:56 +00:00
parent 131e089697
commit b15cba2ca2

View file

@ -1,19 +1,16 @@
#--depends-on commands #--depends-on commands
#--require-config google-api-key
import json, re import json, re
from src import ModuleManager, utils from src import ModuleManager, utils
URL_TRANSLATE = "https://translation.googleapis.com/language/translate/v2" URL_TRANSLATE = "http://translate.googleapis.com/translate_a/single"
URL_LANGUAGES = "https://cloud.google.com/translate/docs/languages" URL_LANGUAGES = "https://cloud.google.com/translate/docs/languages"
REGEX_LANGUAGES = re.compile("(\w+)?:(\w+)? ") REGEX_LANGUAGES = re.compile("(\w+)?:(\w+)? ")
class Module(ModuleManager.BaseModule): class Module(ModuleManager.BaseModule):
@utils.hook("received.command.tr", alias_of="translate") @utils.hook("received.command.tr", alias_of="translate")
@utils.hook("received.command.translate") @utils.hook("received.command.translate")
@utils.spec("?<from:to>lstring !<phrase>lstring") @utils.spec("!<phrase>lstring")
def translate(self, event): def translate(self, event):
""" """
:help: Translate the provided phrase or the last line in thie current :help: Translate the provided phrase or the last line in thie current
@ -32,19 +29,21 @@ class Module(ModuleManager.BaseModule):
target_language = language_match.group(2) target_language = language_match.group(2)
phrase = phrase.split(" ", 1)[1] phrase = phrase.split(" ", 1)[1]
page = utils.http.request(URL_TRANSLATE, page = utils.http.request(URL_TRANSLATE, get_params={
method="POST", "client": "gtx", "dt": "t", "q": phrase,
post_data={ "sl": source_language, "tl": target_language})
"q": phrase,
"format": "text",
"source": source_language,
"target": target_language,
"key": self.bot.config["google-api-key"]
}).json()
if "data" in page: if page and not page.data.startswith(b"[null,null,"):
translation = page["data"]["translations"][0]["translatedText"] data = page.decode("utf8")
event["stdout"].write("(%s -> %s) %s" % (source_language, target_language, translation)) while ",," in data:
data = data.replace(",,", ",null,")
data = data.replace("[,", "[null,")
data_json = json.loads(data)
detected_source = data_json[2]
event["stdout"].write("(%s -> %s) %s" % (
detected_source, target_language.lower(),
data_json[0][0][0]))
else: else:
event["stderr"].write("Failed to translate, try checking " event["stderr"].write("Failed to translate, try checking "
"source/target languages (" + URL_LANGUAGES + ")") "source/target languages (" + URL_LANGUAGES + ")")