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

View file

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

View file

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

View file

@ -12,15 +12,16 @@ def load(CONF, add_hook):
global URL_WHOIS 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"): 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 " raise ImportError("You need a WhoisXML API account in order to use "
"!netwhois feature. Add it to the module configuration file:\n" "the !netwhois feature. Add it to the module "
"<whoisxmlapi username=\"XX\" password=\"XXX\" />\nRegister at " "configuration file:\n<whoisxmlapi username=\"XX\" "
"http://www.whoisxmlapi.com/newaccount.php") "password=\"XXX\" />\nRegister at "
else: "http://www.whoisxmlapi.com/newaccount.php")
URL_WHOIS = URL_WHOIS % (urllib.parse.quote(CONF.getNode("whoisxmlapi")["username"]), urllib.parse.quote(CONF.getNode("whoisxmlapi")["password"]))
import nemubot.hooks URL_WHOIS = URL_WHOIS % (urllib.parse.quote(CONF.getNode("whoisxmlapi")["username"]), urllib.parse.quote(CONF.getNode("whoisxmlapi")["password"]))
add_hook("cmd_hook", nemubot.hooks.Message(cmd_whois, "netwhois"))
import nemubot.hooks
add_hook("cmd_hook", nemubot.hooks.Message(cmd_whois, "netwhois"))
def extractdate(str): def extractdate(str):

View file

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

View file

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

View file

@ -6,32 +6,28 @@ from nemubot.hooks import hook
from nemubot.tools import human from nemubot.tools import human
from nemubot.tools.web import getJSON from nemubot.tools.web import getJSON
nemubotversion = 3.4 nemubotversion = 4.0
from more import Response from more import Response
URL_TPBAPI = None URL_TPBAPI = None
def load(context): def load(context):
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")
global URL_TPBAPI global URL_TPBAPI
URL_TPBAPI = context.config["url"]
if not context.config or not context.config.hasNode("tpbapi") or not context.config.getNode("tpbapi").hasAttribute("url"): @hook("cmd_hook", "tpb")
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: "
"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"))
def cmd_tpb(msg): def cmd_tpb(msg):
if len(msg.cmds) < 1: if not len(msg.args):
raise IRCException("indicate an item to search!") 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)") 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 urllib.parse import quote
from nemubot.exception import IRCException from nemubot.exception import IRCException
from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
nemubotversion = 3.4 nemubotversion = 4.0
from more import Response 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" URL = "http://api.wordreference.com/0.8/%s/json/%%s%%s/%%s"
def load(context): 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 global URL
if not context.config or not context.config.hasNode("wrapi") or not context.config.getNode("wrapi").hasAttribute("key"): URL = URL % context.config["wrapikey"]
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"))
def help_full(): def help_full():
return "!translate [lang] <term>[ <term>[...]]: Found translation of <term> from/to english to/from <lang>. Data © WordReference.com" 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): def cmd_translate(msg):
if len(msg.cmds) < 2: if not len(msg.args):
raise IRCException("which word would you translate?") 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 len(msg.args) > 2 and msg.args[0] in LANG and msg.args[1] in LANG:
if msg.cmds[1] != "en" and msg.cmds[2] != "en": if msg.args[0] != "en" and msg.args[1] != "en":
raise IRCException("sorry, I can only translate to or from english") raise IRCException("sorry, I can only translate to or from english")
langFrom = msg.cmds[1] langFrom = msg.args[0]
langTo = msg.cmds[2] langTo = msg.args[1]
term = ' '.join(msg.cmds[3:]) term = ' '.join(msg.args[2:])
elif len(msg.cmds) > 2 and msg.cmds[1] in LANG: elif len(msg.args) > 1 and msg.args[0] in LANG:
langFrom = msg.cmds[1] langFrom = msg.args[0]
if langFrom == "en": if langFrom == "en":
langTo = "fr" langTo = "fr"
else: else:
langTo = "en" langTo = "en"
term = ' '.join(msg.cmds[2:]) term = ' '.join(msg.args[1:])
else: else:
langFrom = "en" langFrom = "en"
langTo = "fr" langTo = "fr"
term = ' '.join(msg.cmds[1:]) term = ' '.join(msg.args)
wres = web.getJSON(URL % (langFrom, langTo, quote(term))) 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.hooks import hook
from nemubot.tools import web from nemubot.tools import web
nemubotversion = 3.4 nemubotversion = 4.0
from more import Response from more import Response
URL_API = None # http://www.velib.paris.fr/service/stationdetails/paris/%s
def load(context): 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") context.data.setIndex("name", "station")
# evt = ModuleEvent(station_available, "42706", # evt = ModuleEvent(station_available, "42706",
@ -30,7 +36,7 @@ def help_full():
def station_status(station): def station_status(station):
"""Gets available and free status of a given 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: if response is not None:
available = response.getNode("available").getContent() available = response.getNode("available").getContent()
if available is not None and len(available) > 0: if available is not None and len(available) > 0:

View file

@ -14,28 +14,21 @@ from nemubot.tools.xmlparser.node import ModuleState
import mapquest import mapquest
nemubotversion = 3.4 nemubotversion = 4.0
from more import Response from more import Response
URL_DSAPI = "https://api.forecast.io/forecast/%s/%%s,%%s"
def load(context): 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") context.data.setIndex("name", "city")
global URL_DSAPI
if not context.config or not context.config.hasNode("darkskyapi") or not context.config.getNode("darkskyapi").hasAttribute("key"): URL_DSAPI = URL_DSAPI % context.config["darkskyapikey"]
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"))
def help_full (): def help_full ():
@ -135,7 +128,7 @@ def treat_coord(msg):
def get_json_weather(coords): 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 # First read flags
if "darksky-unavailable" in wth["flags"]: if "darksky-unavailable" in wth["flags"]:
@ -144,6 +137,7 @@ def get_json_weather(coords):
return wth return wth
@hook("cmd_hook", "coordinates")
def cmd_coordinates(msg): def cmd_coordinates(msg):
if len(msg.args) < 1: if len(msg.args) < 1:
raise IRCException("indique-moi un nom de ville.") 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) 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): def cmd_alert(msg):
loc, coords, specific = treat_coord(msg) loc, coords, specific = treat_coord(msg)
wth = get_json_weather(coords) wth = get_json_weather(coords)
@ -169,6 +164,7 @@ def cmd_alert(msg):
return res return res
@hook("cmd_hook", "météo")
def cmd_weather(msg): def cmd_weather(msg):
loc, coords, specific = treat_coord(msg) loc, coords, specific = treat_coord(msg)
wth = get_json_weather(coords) wth = get_json_weather(coords)