2022-11-28 23:29:22 +01:00
|
|
|
from translate import Translator
|
2020-11-04 17:21:52 +01:00
|
|
|
|
|
|
|
from edmond.plugin import Plugin
|
|
|
|
|
|
|
|
|
|
|
|
class TranslatePlugin(Plugin):
|
2022-08-15 14:12:57 +02:00
|
|
|
"""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.
|
|
|
|
"""
|
2020-11-04 17:21:52 +01:00
|
|
|
|
|
|
|
REQUIRED_CONFIGS = [
|
2022-08-09 23:47:28 +02:00
|
|
|
"commands",
|
|
|
|
"default_dest",
|
|
|
|
"param_source",
|
|
|
|
"param_dest",
|
2020-11-04 17:21:52 +01:00
|
|
|
]
|
|
|
|
|
|
|
|
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)."""
|
2022-08-15 14:12:57 +02:00
|
|
|
# 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:])
|