# coding=utf-8 """Translation module""" import re from urllib.parse import quote from nemubot.exception import IRCException from nemubot.hooks import hook from nemubot.tools import web nemubotversion = 4.0 from more import Response LANG = ["ar", "zh", "cz", "en", "fr", "gr", "it", "ja", "ko", "pl", "pt", "ro", "es", "tr"] URL = "http://api.wordreference.com/0.8/%s/json/%%s%%s/%%s" def load(context): if not context.config or "wrapikey" not in context.config: raise ImportError("You need a WordReference API key in order to use " "this module. Add it to the module configuration " "file:\n\nRegister at http://" "www.wordreference.com/docs/APIregistration.aspx") global URL URL = URL % context.config["wrapikey"] def help_full(): return "!translate [lang] [ [...]]: Found translation of from/to english to/from . Data © WordReference.com" @hook("cmd_hook", "translate") def cmd_translate(msg): if not len(msg.args): raise IRCException("which word would you translate?") if len(msg.args) > 2 and msg.args[0] in LANG and msg.args[1] in LANG: if msg.args[0] != "en" and msg.args[1] != "en": raise IRCException("sorry, I can only translate to or from english") langFrom = msg.args[0] langTo = msg.args[1] term = ' '.join(msg.args[2:]) elif len(msg.args) > 1 and msg.args[0] in LANG: langFrom = msg.args[0] if langFrom == "en": langTo = "fr" else: langTo = "en" term = ' '.join(msg.args[1:]) else: langFrom = "en" langTo = "fr" term = ' '.join(msg.args) wres = web.getJSON(URL % (langFrom, langTo, quote(term))) if "Error" in wres: raise IRCException(wres["Note"]) else: res = Response(channel=msg.channel, count=" (%d more meanings)", nomore="No more translation") for k in sorted(wres.keys()): t = wres[k] if len(k) > 4 and k[:4] == "term": if "Entries" in t: ent = t["Entries"] else: ent = t["PrincipalTranslations"] for i in sorted(ent.keys()): res.append_message("Translation of %s%s: %s" % ( ent[i]["OriginalTerm"]["term"], meaning(ent[i]["OriginalTerm"]), extract_traslation(ent[i]))) return res def meaning(entry): ret = list() if "sense" in entry and len(entry["sense"]) > 0: ret.append('« %s »' % entry["sense"]) if "usage" in entry and len(entry["usage"]) > 0: ret.append(entry["usage"]) if len(ret) > 0: return " as " + "/".join(ret) else: return "" def extract_traslation(entry): ret = list() for i in [ "FirstTranslation", "SecondTranslation", "ThirdTranslation", "FourthTranslation" ]: if i in entry: ret.append("\x03\x02%s\x03\x02%s" % (entry[i]["term"], meaning(entry[i]))) if "Note" in entry and entry["Note"]: ret.append("note: %s" % entry["Note"]) return ", ".join(ret)