2018-07-02 11:51:36 +00:00
|
|
|
import json, re
|
2016-03-29 11:56:58 +00:00
|
|
|
import Utils
|
|
|
|
|
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
|
|
|
|
|
|
|
class Module(object):
|
2018-08-31 11:55:52 +00:00
|
|
|
def __init__(self, bot, events):
|
|
|
|
events.on("received").on("command").on("translate", "tr").hook(
|
2016-03-29 11:56:58 +00:00
|
|
|
self.translate, help="Translate the provided phrase or the "
|
2016-04-06 11:02:44 +00:00
|
|
|
"last line seen.", usage="[phrase]")
|
2016-03-29 11:56:58 +00:00
|
|
|
|
|
|
|
def translate(self, event):
|
|
|
|
phrase = event["args"]
|
|
|
|
if not phrase:
|
2018-08-28 11:23:57 +00:00
|
|
|
phrase = event["buffer"].get()
|
2016-03-29 11:56:58 +00:00
|
|
|
if phrase:
|
|
|
|
phrase = phrase.message
|
|
|
|
if not phrase:
|
|
|
|
event["stderr"].write("No phrase provided.")
|
|
|
|
return
|
|
|
|
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-07-02 11:51:36 +00:00
|
|
|
data = Utils.get_url(URL_TRANSLATE, get_params={
|
|
|
|
"client": "gtx", "sl": source_language,
|
|
|
|
"tl": target_language, "dt": "t", "q": phrase})
|
|
|
|
|
|
|
|
if data and not data == "[null,null,\"\"]":
|
|
|
|
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
|
|
|
|