Edm0nd/edmond/plugins/translate.py

57 lines
1.8 KiB
Python
Raw Normal View History

2020-11-04 17:21:52 +01:00
try:
from translate import Translator
DEPENDENCIES_FOUND = True
except ImportError:
DEPENDENCIES_FOUND = False
from edmond.plugin import Plugin
class TranslatePlugin(Plugin):
REQUIRED_CONFIGS = [
"commands", "default_dest", "param_source", "param_dest",
]
def __init__(self, bot):
super().__init__(bot)
def on_pubmsg(self, event):
if not self.should_handle_command(event.arguments[0]):
return False
text = self.command.content
if not text:
2020-11-06 15:17:29 +01:00
self.signal_failure(event.target)
return True
2020-11-04 17:21:52 +01:00
words = text.split()
if len(words) == 0:
2020-11-06 15:17:29 +01:00
self.signal_failure(event.target)
return True
2020-11-04 17:21:52 +01:00
from_lang, to_lang, text = self.parse_words(words)
self.bot.log_d(f"Translating '{text}' from {from_lang} to {to_lang}.")
translator = Translator(to_lang=to_lang, from_lang=from_lang)
translation = translator.translate(text)
self.bot.say(event.target, translation)
return True
def parse_words(self, words):
"""Parse given words for parameters and return (from, to, text)."""
from_lang = "autodetect"
to_lang = self.config["default_dest"]
num_param_found = 0
for word in words:
if not word.startswith("!"):
break
num_param_found += 1
param_word = word.lstrip("!")
if not ":" in param_word:
continue
param_name, param_value = param_word.split(":")
if param_name == self.config["param_source"]:
from_lang = param_value
elif param_name == self.config["param_dest"]:
to_lang = param_value
return from_lang, to_lang, " ".join(words[num_param_found:])