2018-07-02 11:51:36 +00:00
|
|
|
import json, re
|
2018-10-03 12:22:37 +00:00
|
|
|
from src import ModuleManager, utils
|
2016-03-29 11:56:58 +00:00
|
|
|
|
2018-07-02 11:51:36 +00:00
|
|
|
URL_TRANSLATE = "http://translate.googleapis.com/translate_a/single"
|
|
|
|
URL_LANGUAGES = "https://cloud.google.com/translate/docs/languages"
|
2018-07-14 08:06:52 +00:00
|
|
|
REGEX_LANGUAGES = re.compile("(\w+)?:(\w+)? ")
|
2016-03-29 11:56:58 +00:00
|
|
|
|
2018-09-26 17:27:17 +00:00
|
|
|
class Module(ModuleManager.BaseModule):
|
2018-10-10 09:42:41 +00:00
|
|
|
@utils.hook("received.command.tr", alias_of="translate")
|
|
|
|
@utils.hook("received.command.translate")
|
2016-03-29 11:56:58 +00:00
|
|
|
def translate(self, event):
|
2018-09-26 17:27:17 +00:00
|
|
|
"""
|
2018-09-30 16:29:09 +00:00
|
|
|
:help: Translate the provided phrase or the last line in thie current
|
|
|
|
channel
|
|
|
|
:usage: [phrase]
|
2018-09-26 17:27:17 +00:00
|
|
|
"""
|
2016-03-29 11:56:58 +00:00
|
|
|
phrase = event["args"]
|
|
|
|
if not phrase:
|
2018-09-30 10:43:34 +00:00
|
|
|
phrase = event["target"].buffer.get()
|
2016-03-29 11:56:58 +00:00
|
|
|
if phrase:
|
2018-11-14 14:44:01 +00:00
|
|
|
phrase = utils.irc.strip_font(phrase.message)
|
2016-03-29 11:56:58 +00:00
|
|
|
if not phrase:
|
2018-10-16 14:09:58 +00:00
|
|
|
raise utils.EventError("No phrase provided.")
|
2016-03-29 11:56:58 +00:00
|
|
|
source_language = "auto"
|
|
|
|
target_language = "en"
|
|
|
|
|
|
|
|
language_match = re.match(REGEX_LANGUAGES, phrase)
|
|
|
|
if language_match:
|
|
|
|
if language_match.group(1):
|
|
|
|
source_language = language_match.group(1)
|
|
|
|
if language_match.group(2):
|
|
|
|
target_language = language_match.group(2)
|
|
|
|
phrase = phrase.split(" ", 1)[1]
|
|
|
|
|
2018-12-11 22:26:38 +00:00
|
|
|
page = utils.http.request(URL_TRANSLATE, get_params={
|
2018-07-02 11:51:36 +00:00
|
|
|
"client": "gtx", "sl": source_language,
|
|
|
|
"tl": target_language, "dt": "t", "q": phrase})
|
|
|
|
|
2018-12-11 22:26:38 +00:00
|
|
|
if page and not page.data == "[null,null,\"\"]":
|
|
|
|
data = page.data
|
2018-07-02 11:51:36 +00:00
|
|
|
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:
|
|
|
|
event["stderr"].write("Failed to translate, try checking "
|
|
|
|
"source/target languages (" + URL_LANGUAGES + ")")
|
2016-03-29 11:56:58 +00:00
|
|
|
|