nemubot/modules/translate.py

106 lines
3.3 KiB
Python
Raw Normal View History

# coding=utf-8
import http.client
import re
import socket
import json
from urllib.parse import quote
2014-07-25 15:45:01 +00:00
from urllib.request import urlopen
2012-11-04 14:58:42 +00:00
nemubotversion = 3.3
import xmlparser
2012-08-16 03:50:49 +00:00
LANG = ["ar", "zh", "cz", "en", "fr", "gr", "it",
"ja", "ko", "pl", "pt", "ro", "es", "tr"]
2014-07-25 15:45:01 +00:00
URL = "http://api.wordreference.com/0.8/%s/json/%%s%%s/%%s"
2012-08-16 03:50:49 +00:00
def load(context):
2014-07-25 15:45:01 +00:00
global URL
if not CONF or not CONF.hasNode("wrapi") or not CONF.getNode("wrapi").hasAttribute("key"):
print ("You need a WordReference API key in order to use this module."
" Add it to the module configuration file:\n<wrapi key=\"XXXXX\""
" />\nRegister at "
"http://www.wordreference.com/docs/APIregistration.aspx")
return None
else:
URL = URL % CONF.getNode("wrapi")["key"]
2012-08-16 03:50:49 +00:00
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_translate, "translate"))
2014-07-25 15:45:01 +00:00
def help_tiny():
"""Line inserted in the response to the command !help"""
return "Translation module"
def help_full():
return "!translate [lang] <term>[ <term>[...]]: Found translation of <term> from/to english to/from <lang>. Data © WordReference.com"
2012-08-16 03:50:49 +00:00
def cmd_translate(msg):
2014-07-25 15:45:01 +00:00
if len(msg.cmds) < 2:
raise IRCException("which word would you translate?")
if len(msg.cmds) > 3 and msg.cmds[1] in LANG and msg.cmds[2] in LANG:
if msg.cmds[1] != "en" and msg.cmds[2] != "en":
raise IRCException("sorry, I can only translate to or from english")
langFrom = msg.cmds[1]
2014-07-25 15:45:01 +00:00
langTo = msg.cmds[2]
term = ' '.join(msg.cmds[3:])
elif len(msg.cmds) > 2 and msg.cmds[1] in LANG:
langFrom = msg.cmds[1]
if langFrom == "en":
langTo = "fr"
else:
langTo = "en"
term = ' '.join(msg.cmds[2:])
else:
2014-07-25 15:45:01 +00:00
langFrom = "en"
2012-08-16 03:50:49 +00:00
langTo = "fr"
2014-07-25 15:45:01 +00:00
term = ' '.join(msg.cmds[1:])
2012-08-16 03:50:49 +00:00
try:
2014-07-25 15:45:01 +00:00
raw = urlopen(URL % (langFrom, langTo, quote(term)))
except:
raise IRCException("invalid request")
wres = json.loads(raw.read().decode())
2014-07-25 15:45:01 +00:00
if "Error" in wres:
raise IRCException(wres["Note"])
else:
res = Response(msg.sender, channel=msg.channel,
nomore="No more translation")
for k, t in wres.items():
if len(k) > 4 and k[:4] == "term":
if "Entries" in t:
ent = t["Entries"]
else:
ent = t["PrincipalTranslations"]
for i in ent:
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 ""
2014-07-25 15:45:01 +00:00
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])))
return ", ".join(ret)