In some modules, raise ImportError to avoid module loading on errors

This commit is contained in:
nemunaire 2015-06-03 22:07:06 +02:00
commit d95de8c195
10 changed files with 109 additions and 114 deletions

View file

@ -9,18 +9,17 @@ from nemubot.exception import IRCException
from nemubot.hooks import hook
from nemubot.tools import web
nemubotversion = 3.4
nemubotversion = 4.0
from more import Response
def load(context):
if not context.config or not context.config.hasNode("goodreadsapi") or not context.config.getNode("goodreadsapi").hasAttribute("key"):
print ("You need a Goodreads API key in order to use this "
"module. Add it to the module configuration file:\n<goodreadsapi"
" key=\"XXXXXXXXXXXXXXXX\" />\nGet one at "
"https://www.goodreads.com/api/keys")
return None
if not context.config or not context.config.getAttribute("goodreadskey"):
raise ImportError("You need a Goodreads API key in order to use this "
"module. Add it to the module configuration file:\n"
"<module name=\"books\" goodreadskey=\"XXXXXX\" />\n"
"Get one at https://www.goodreads.com/api/keys")
def get_book(title):
@ -57,10 +56,10 @@ def search_author(name):
@hook("cmd_hook", "book")
def cmd_book(msg):
if len(msg.cmds) < 2:
if not len(msg.args):
raise IRCException("please give me a title to search")
book = get_book(" ".join(msg.cmds[1:]))
book = get_book(" ".join(msg.args))
if book is None:
raise IRCException("unable to find book named like this")
res = Response(channel=msg.channel)
@ -72,10 +71,10 @@ def cmd_book(msg):
@hook("cmd_hook", "search_books")
def cmd_books(msg):
if len(msg.cmds) < 2:
if not len(msg.args):
raise IRCException("please give me a title to search")
title = " ".join(msg.cmds[1:])
title = " ".join(msg.args)
res = Response(channel=msg.channel,
title="%s" % (title),
count=" (%d more books)")
@ -88,10 +87,10 @@ def cmd_books(msg):
@hook("cmd_hook", "author_books")
def cmd_author(msg):
if len(msg.cmds) < 2:
if not len(msg.args):
raise IRCException("please give me an author to search")
ath = search_author(" ".join(msg.cmds[1:]))
ath = search_author(" ".join(msg.args))
return Response([b.getNode("title").getContent() for b in ath.getNode("books").getNodes("book")],
channel=msg.channel,
title=ath.getNode("name").getContent())

View file

@ -1,30 +1,28 @@
# coding=utf-8
"""The mapquest module"""
"""Transform name location to GPS coordinates"""
import re
from urllib.parse import quote
from nemubot import context
from nemubot.exception import IRCException
from nemubot.hooks import hook
from nemubot.tools import web
nemubotversion = 3.4
nemubotversion = 4.0
from more import Response
URL_API = "http://open.mapquestapi.com/geocoding/v1/address?key=%s&location=%%s"
def load(context):
if not context.config or not context.config.hasNode("mapquestapi") or not context.config.getNode("mapquestapi").hasAttribute("key"):
print ("You need a MapQuest API key in order to use this "
"module. Add it to the module configuration file:\n<mapquestapi"
" key=\"XXXXXXXXXXXXXXXX\" />\nRegister at "
"http://developer.mapquest.com/")
return None
import nemubot.hooks
context.add_hook("cmd_hook",
nemubot.hooks.Message(cmd_geocode, "geocode"))
if not context.config or not context.config.hasAttribute("apikey"):
raise ImportError("You need a MapQuest API key in order to use this "
"module. Add it to the module configuration file:\n"
"<module name=\"mapquest\" key=\"XXXXXXXXXXXXXXXX\" "
"/>\nRegister at http://developer.mapquest.com/")
global URL_API
URL_API = URL_API % context.config["apikey"].replace("%", "%%")
def help_full():
@ -32,8 +30,7 @@ def help_full():
def geocode(location):
obj = web.getJSON("http://open.mapquestapi.com/geocoding/v1/address?key=%s&location=%s" %
(context.config.getNode("mapquestapi")["key"], quote(location)))
obj = web.getJSON(URL_API % quote(location))
if "results" in obj and "locations" in obj["results"][0]:
for loc in obj["results"][0]["locations"]:
@ -46,15 +43,15 @@ def where(loc):
"{adminArea1}".format(**loc)).strip()
@hook("cmd_hook", "geocode")
def cmd_geocode(msg):
if len(msg.cmds) < 2:
if not len(msg.args):
raise IRCException("indicate a name")
locname = ' '.join(msg.cmds[1:])
res = Response(channel=msg.channel, nick=msg.nick,
nomore="No more geocode", count=" (%s more geocode)")
for loc in geocode(locname):
for loc in geocode(' '.join(msg.args)):
res.append_message("%s is at %s,%s (%s precision)" %
(where(loc),
loc["latLng"]["lat"],

View file

@ -24,7 +24,10 @@ def load(context):
mod.send_response = context.send_response
page.load(context.config, context.add_hook)
watchWebsite.load(context.data)
try:
whois.load(context.config, context.add_hook)
except ImportError:
logger.exception("Unable to load netwhois module")
def help_full():

View file

@ -12,11 +12,12 @@ def load(CONF, add_hook):
global URL_WHOIS
if not CONF or not CONF.hasNode("whoisxmlapi") or not CONF.getNode("whoisxmlapi").hasAttribute("username") or not CONF.getNode("whoisxmlapi").hasAttribute("password"):
print ("You need a WhoisXML API account in order to use the "
"!netwhois feature. Add it to the module configuration file:\n"
"<whoisxmlapi username=\"XX\" password=\"XXX\" />\nRegister at "
raise ImportError("You need a WhoisXML API account in order to use "
"the !netwhois feature. Add it to the module "
"configuration file:\n<whoisxmlapi username=\"XX\" "
"password=\"XXX\" />\nRegister at "
"http://www.whoisxmlapi.com/newaccount.php")
else:
URL_WHOIS = URL_WHOIS % (urllib.parse.quote(CONF.getNode("whoisxmlapi")["username"]), urllib.parse.quote(CONF.getNode("whoisxmlapi")["password"]))
import nemubot.hooks

View file

@ -12,7 +12,7 @@ from nemubot.hooks import hook
from nemubot.tools import web
from nemubot.tools.web import striphtml
nemubotversion = 3.4
nemubotversion = 4.0
from more import Response
@ -23,12 +23,12 @@ def help_full():
@hook("cmd_hook", "tcode")
def cmd_tcode(msg):
if len(msg.cmds) != 2:
if not len(msg.args):
raise IRCException("indicate a transaction code or "
"a keyword to search!")
url = ("http://www.tcodesearch.com/tcodes/search?q=%s" %
urllib.parse.quote(msg.cmds[1]))
urllib.parse.quote(msg.args[0]))
page = web.getURLContent(url)
soup = BeautifulSoup(page)

View file

@ -9,7 +9,7 @@ from nemubot.exception import IRCException
from nemubot.hooks import hook
from nemubot.tools import web
nemubotversion = 3.4
nemubotversion = 4.0
from more import Response
@ -21,13 +21,13 @@ def help_full():
def load(context):
global lang_binding
if not context.config or not context.config.hasNode("bighugelabs") or not context.config.getNode("bighugelabs").hasAttribute("key"):
print ("You need a NigHugeLabs API key in order to have english "
"theasorus. Add it to the module configuration file:\n<bighugelabs"
" key=\"XXXXXXXXXXXXXXXX\" />\nRegister at "
"https://words.bighugelabs.com/getkey.php")
if not context.config or not context.config.hasAttribute("bighugelabskey"):
logger.error("You need a NigHugeLabs API key in order to have english "
"theasorus. Add it to the module configuration file:\n"
"<module name=\"syno\" bighugelabskey=\"XXXXXXXXXXXXXXXX\""
" />\nRegister at https://words.bighugelabs.com/getkey.php")
else:
lang_binding["en"] = lambda word: get_english_synos(context.config.getNode("bighugelabs")["key"], word)
lang_binding["en"] = lambda word: get_english_synos(context.config["bighugelabskey"], word)
def get_french_synos(word):
@ -75,18 +75,18 @@ lang_binding = { 'fr': get_french_synos }
@hook("cmd_hook", "synonymes", data="synonymes")
@hook("cmd_hook", "antonymes", data="antonymes")
def go(msg, what):
if len(msg.cmds) < 2:
if not len(msg.args):
raise IRCException("de quel mot veux-tu connaître la liste des synonymes ?")
# Detect lang
if msg.cmds[1] in lang_binding:
func = lang_binding[msg.cmds[1]]
word = ' '.join(msg.cmds[2:])
if msg.args[0] in lang_binding:
func = lang_binding[msg.args[0]]
word = ' '.join(msg.args[1:])
else:
func = lang_binding["fr"]
word = ' '.join(msg.cmds[1:])
word = ' '.join(msg.args)
# TODO: depreciate usage without lang
#raise IRCException("language %s is not handled yet." % msg.cmds[1])
#raise IRCException("language %s is not handled yet." % msg.args[0])
try:
best, synos, anton = func(word)

View file

@ -6,32 +6,28 @@ from nemubot.hooks import hook
from nemubot.tools import human
from nemubot.tools.web import getJSON
nemubotversion = 3.4
nemubotversion = 4.0
from more import Response
URL_TPBAPI = None
def load(context):
global URL_TPBAPI
if not context.config or not context.config.hasNode("tpbapi") or not context.config.getNode("tpbapi").hasAttribute("url"):
print ("You need a TPB API in order to use the !tpb feature. Add it to "
"the module configuration file:\n"
"<tpbapi url=\"http://tpbapi.org/\" />\nSample API: "
if not context.config or not context.config.hasAttribute("url"):
raise ImportError("You need a TPB API in order to use the !tpb feature"
". Add it to the module configuration file:\n<module"
"name=\"tpb\" url=\"http://tpbapi.org/\" />\nSample "
"API: "
"https://gist.github.com/colona/07a925f183cfb47d5f20")
else:
URL_TPBAPI = context.config.getNode("tpbapi")["url"]
from nemubot.hooks.message import Message
context.add_hook("cmd_hook", Message(cmd_tpb, "tpb"))
global URL_TPBAPI
URL_TPBAPI = context.config["url"]
@hook("cmd_hook", "tpb")
def cmd_tpb(msg):
if len(msg.cmds) < 1:
if not len(msg.args):
raise IRCException("indicate an item to search!")
torrents = getJSON(URL_TPBAPI + urllib.parse.quote(" ".join(msg.cmds[1:])))
torrents = getJSON(URL_TPBAPI + urllib.parse.quote(" ".join(msg.args)))
res = Response(channel=msg.channel, nomore="No more torrents", count=" (%d more torrents)")

View file

@ -6,9 +6,10 @@ import re
from urllib.parse import quote
from nemubot.exception import IRCException
from nemubot.hooks import hook
from nemubot.tools import web
nemubotversion = 3.4
nemubotversion = 4.0
from more import Response
@ -18,46 +19,42 @@ LANG = ["ar", "zh", "cz", "en", "fr", "gr", "it",
URL = "http://api.wordreference.com/0.8/%s/json/%%s%%s/%%s"
def load(context):
if not context.config or not context.config.hasAttribute("wrapikey"):
raise ImportError("You need a WordReference API key in order to use "
"this module. Add it to the module configuration "
"file:\n<module name=\"translate\" wrapikey=\"XXXXX\""
" />\nRegister at http://"
"www.wordreference.com/docs/APIregistration.aspx")
global URL
if not context.config or not context.config.hasNode("wrapi") or not context.config.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 % context.config.getNode("wrapi")["key"]
import nemubot.hooks
context.add_hook("cmd_hook",
nemubot.hooks.Message(cmd_translate, "translate"))
URL = URL % context.config["wrapikey"]
def help_full():
return "!translate [lang] <term>[ <term>[...]]: Found translation of <term> from/to english to/from <lang>. Data © WordReference.com"
@hook("cmd_hook", "translate")
def cmd_translate(msg):
if len(msg.cmds) < 2:
if not len(msg.args):
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":
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.cmds[1]
langTo = msg.cmds[2]
term = ' '.join(msg.cmds[3:])
elif len(msg.cmds) > 2 and msg.cmds[1] in LANG:
langFrom = msg.cmds[1]
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.cmds[2:])
term = ' '.join(msg.args[1:])
else:
langFrom = "en"
langTo = "fr"
term = ' '.join(msg.cmds[1:])
term = ' '.join(msg.args)
wres = web.getJSON(URL % (langFrom, langTo, quote(term)))

View file

@ -9,12 +9,18 @@ from nemubot.exception import IRCException
from nemubot.hooks import hook
from nemubot.tools import web
nemubotversion = 3.4
nemubotversion = 4.0
from more import Response
URL_API = None # http://www.velib.paris.fr/service/stationdetails/paris/%s
def load(context):
global URL_API
if not context.config or not context.config.hasAttribute("url"):
raise ImportError("Please provide url attribute in the module configuration")
URL_API = context.config["url"]
context.data.setIndex("name", "station")
# evt = ModuleEvent(station_available, "42706",
@ -30,7 +36,7 @@ def help_full():
def station_status(station):
"""Gets available and free status of a given station"""
response = web.getXML(context.config.getNode("server")["url"] + station)
response = web.getXML(URL_API % station)
if response is not None:
available = response.getNode("available").getContent()
if available is not None and len(available) > 0:

View file

@ -14,28 +14,21 @@ from nemubot.tools.xmlparser.node import ModuleState
import mapquest
nemubotversion = 3.4
nemubotversion = 4.0
from more import Response
URL_DSAPI = "https://api.forecast.io/forecast/%s/%%s,%%s"
def load(context):
if not context.config or not context.config.hasAttribute("darkskyapikey"):
raise ImportError("You need a Dark-Sky API key in order to use this "
"module. Add it to the module configuration file:\n"
"<module name=\"weather\" darkskyapikey=\"XXX\" />\n"
"Register at http://developer.forecast.io/")
context.data.setIndex("name", "city")
if not context.config or not context.config.hasNode("darkskyapi") or not context.config.getNode("darkskyapi").hasAttribute("key"):
print ("You need a Dark-Sky API key in order to use this "
"module. Add it to the module configuration file:\n<darkskyapi"
" key=\"XXXXXXXXXXXXXXXX\" />\nRegister at "
"http://developer.forecast.io/")
return None
import nemubot.hooks
context.add_hook("cmd_hook",
nemubot.hooks.Message(cmd_weather, "météo"))
context.add_hook("cmd_hook",
nemubot.hooks.Message(cmd_alert, "alert"))
context.add_hook("cmd_hook",
nemubot.hooks.Message(cmd_coordinates, "coordinates"))
global URL_DSAPI
URL_DSAPI = URL_DSAPI % context.config["darkskyapikey"]
def help_full ():
@ -135,7 +128,7 @@ def treat_coord(msg):
def get_json_weather(coords):
wth = web.getJSON("https://api.forecast.io/forecast/%s/%s,%s" % (context.config.getNode("darkskyapi")["key"], float(coords[0]), float(coords[1])))
wth = web.getJSON(URL_DSAPI % (float(coords[0]), float(coords[1])))
# First read flags
if "darksky-unavailable" in wth["flags"]:
@ -144,6 +137,7 @@ def get_json_weather(coords):
return wth
@hook("cmd_hook", "coordinates")
def cmd_coordinates(msg):
if len(msg.args) < 1:
raise IRCException("indique-moi un nom de ville.")
@ -156,6 +150,7 @@ def cmd_coordinates(msg):
return Response("Les coordonnées de %s sont %s,%s" % (msg.args[0], coords["lat"], coords["long"]), channel=msg.channel)
@hook("cmd_hook", "alert")
def cmd_alert(msg):
loc, coords, specific = treat_coord(msg)
wth = get_json_weather(coords)
@ -169,6 +164,7 @@ def cmd_alert(msg):
return res
@hook("cmd_hook", "météo")
def cmd_weather(msg):
loc, coords, specific = treat_coord(msg)
wth = get_json_weather(coords)