Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
bitbot/modules/translate.py /
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
49 lines (42 sloc)
1.81 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #--depends-on commands | |
| import json, re | |
| from src import ModuleManager, utils | |
| URL_TRANSLATE = "http://translate.googleapis.com/translate_a/single" | |
| URL_LANGUAGES = "https://cloud.google.com/translate/docs/languages" | |
| REGEX_LANGUAGES = re.compile("(\w+)?:(\w+)? ") | |
| class Module(ModuleManager.BaseModule): | |
| @utils.hook("received.command.tr", alias_of="translate") | |
| @utils.hook("received.command.translate") | |
| @utils.spec("!<phrase>lstring") | |
| def translate(self, event): | |
| """ | |
| :help: Translate the provided phrase or the last line in thie current | |
| channel | |
| :usage: [phrase] | |
| """ | |
| phrase = event["spec"][0] | |
| 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] | |
| page = utils.http.request(URL_TRANSLATE, get_params={ | |
| "client": "gtx", "dt": "t", "q": phrase, | |
| "sl": source_language, "tl": target_language}) | |
| if page and not page.data.startswith(b"[null,null,"): | |
| data = page.decode("utf8") | |
| 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 + ")") |