from translate import Translator from edmond.plugin import Plugin class TranslatePlugin(Plugin): """Translate text using the `translate` package. The translate package can use a bunch of translation interfaces but the default is MyMemory which is fine for our purposes. There are two ways to ask for a translation: - Without any additional params, the source language is autodetected and the target language is specified in the config file; - With BOTH source and target languages. """ 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: self.signal_failure(event.target) return True words = text.split() if len(words) == 0: self.signal_failure(event.target) return True 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).""" # If no language specification is found, use default params. if ( len(words) < 5 or words[0] != self.config["param_source"] or words[2] != self.config["param_dest"] ): return "autodetect", self.config["default_dest"], " ".join(words) # Else use the parameters provided. return words[1], words[3], " ".join(words[4:])