diff --git a/modules/alias.py b/modules/alias.py index 3365141..050e2d6 100644 --- a/modules/alias.py +++ b/modules/alias.py @@ -7,6 +7,7 @@ import sys from datetime import datetime, timezone import shlex +from nemubot import context from nemubot.exception import IRCException from nemubot.hooks import hook from nemubot.message import TextMessage, Command @@ -19,13 +20,12 @@ from more import Response def load(context): """Load this module""" - global DATAS - if not DATAS.hasNode("aliases"): - DATAS.addChild(ModuleState("aliases")) - DATAS.getNode("aliases").setIndex("alias") - if not DATAS.hasNode("variables"): - DATAS.addChild(ModuleState("variables")) - DATAS.getNode("variables").setIndex("name") + if not context.data.hasNode("aliases"): + context.data.addChild(ModuleState("aliases")) + context.data.getNode("aliases").setIndex("alias") + if not context.data.hasNode("variables"): + context.data.addChild(ModuleState("variables")) + context.data.getNode("variables").setIndex("name") def help_full(): @@ -37,7 +37,7 @@ def set_variable(name, value, creator): var["name"] = name var["value"] = value var["creator"] = creator - DATAS.getNode("variables").addChild(var) + context.data.getNode("variables").addChild(var) def get_variable(name, msg=None): @@ -47,8 +47,8 @@ def get_variable(name, msg=None): return msg.channel elif name == "date": return datetime.now(timezone.utc).strftime("%c") - elif name in DATAS.getNode("variables").index: - return DATAS.getNode("variables").index[name]["value"] + elif name in context.data.getNode("variables").index: + return context.data.getNode("variables").index[name]["value"] else: return "" @@ -59,7 +59,7 @@ def cmd_set(msg): set_variable(msg.cmds[1], " ".join(msg.cmds[2:]), msg.nick) res = Response("Variable \$%s définie." % msg.cmds[1], channel=msg.channel) - save() + context.save() return res return Response("!set prend au minimum deux arguments : " "le nom de la variable et sa valeur.", @@ -71,7 +71,7 @@ def cmd_listalias(msg): if len(msg.cmds) > 1: res = list() for user in msg.cmds[1:]: - als = [x["alias"] for x in DATAS.getNode("aliases").index.values() if x["creator"] == user] + als = [x["alias"] for x in context.data.getNode("aliases").index.values() if x["creator"] == user] if len(als) > 0: res.append("Alias créés par %s : %s" % (user, ", ".join(als))) else: @@ -79,7 +79,7 @@ def cmd_listalias(msg): return Response(" ; ".join(res), channel=msg.channel) else: return Response("Alias connus : %s." % - ", ".join(DATAS.getNode("aliases").index.keys()), + ", ".join(context.data.getNode("aliases").index.keys()), channel=msg.channel) @@ -88,7 +88,7 @@ def cmd_listvars(msg): if len(msg.cmds) > 1: res = list() for user in msg.cmds[1:]: - als = [x["alias"] for x in DATAS.getNode("variables").index.values() if x["creator"] == user] + als = [x["alias"] for x in context.data.getNode("variables").index.values() if x["creator"] == user] if len(als) > 0: res.append("Variables créées par %s : %s" % (user, ", ".join(als))) else: @@ -96,7 +96,7 @@ def cmd_listvars(msg): return Response(" ; ".join(res), channel=msg.channel) else: return Response("Variables connues : %s." % - ", ".join(DATAS.getNode("variables").index.keys()), + ", ".join(context.data.getNode("variables").index.keys()), channel=msg.channel) @@ -107,9 +107,9 @@ def cmd_alias(msg): for alias in msg.cmds[1:]: if alias[0] == "!": alias = alias[1:] - if alias in DATAS.getNode("aliases").index: + if alias in context.data.getNode("aliases").index: res.append(Response("!%s correspond à %s" % - (alias, DATAS.getNode("aliases").index[alias]["origin"]), + (alias, context.data.getNode("aliases").index[alias]["origin"]), channel=msg.channel)) else: res.append(Response("!%s n'est pas un alias" % alias, @@ -127,9 +127,9 @@ def cmd_unalias(msg): for alias in msg.cmds[1:]: if alias[0] == "!" and len(alias) > 1: alias = alias[1:] - if alias in DATAS.getNode("aliases").index: - if DATAS.getNode("aliases").index[alias]["creator"] == msg.nick or msg.frm_owner: - DATAS.getNode("aliases").delChild(DATAS.getNode("aliases").index[alias]) + if alias in context.data.getNode("aliases").index: + if context.data.getNode("aliases").index[alias]["creator"] == msg.nick or msg.frm_owner: + context.data.getNode("aliases").delChild(context.data.getNode("aliases").index[alias]) res.append(Response("%s a bien été supprimé" % alias, channel=msg.channel)) else: @@ -167,8 +167,8 @@ def replace_variables(cnt, msg=None): @hook("pre_Command") def treat_alias(msg): - if msg.cmd in DATAS.getNode("aliases").index: - txt = DATAS.getNode("aliases").index[msg.cmd]["origin"] + if msg.cmd in context.data.getNode("aliases").index: + txt = context.data.getNode("aliases").index[msg.cmd]["origin"] # TODO: for legacy compatibility if txt[0] == "!": txt = txt[1:] @@ -190,16 +190,16 @@ def parseask(msg): global ALIAS if re.match(".*(set|cr[ée]{2}|nouvel(le)?) alias.*", msg.text) is not None: result = re.match(".*alias !?([^ ]+) (pour|=|:) (.+)$", msg.text) - if result.group(1) in DATAS.getNode("aliases").index or result.group(3).find("alias") >= 0: + if result.group(1) in context.data.getNode("aliases").index or result.group(3).find("alias") >= 0: raise IRCException("cet alias est déjà défini.") else: alias = ModuleState("alias") alias["alias"] = result.group(1) alias["origin"] = result.group(3) alias["creator"] = msg.nick - DATAS.getNode("aliases").addChild(alias) + context.data.getNode("aliases").addChild(alias) res = Response("Nouvel alias %s défini avec succès." % result.group(1), channel=msg.channel) - save() + context.save() return res return None diff --git a/modules/birthday.py b/modules/birthday.py index 8137a08..337b20f 100644 --- a/modules/birthday.py +++ b/modules/birthday.py @@ -6,6 +6,7 @@ import re import sys from datetime import date, datetime +from nemubot import context from nemubot.exception import IRCException from nemubot.hooks import hook from nemubot.tools.countdown import countdown_format @@ -18,8 +19,7 @@ from more import Response def load(context): - global DATAS - DATAS.setIndex("name", "birthday") + context.data.setIndex("name", "birthday") def help_full(): @@ -38,10 +38,10 @@ def findName(msg): matches = [] - if name in DATAS.index: + if name in context.data.index: matches.append(name) else: - for k in DATAS.index.keys(): + for k in context.data.index.keys(): if k.find(name) == 0: matches.append(k) return (matches, name) @@ -52,13 +52,13 @@ def cmd_anniv(msg): (matches, name) = findName(msg) if len(matches) == 1: name = matches[0] - tyd = DATAS.index[name].getDate("born") + tyd = context.data.index[name].getDate("born") tyd = datetime(date.today().year, tyd.month, tyd.day) if (tyd.day == datetime.today().day and tyd.month == datetime.today().month): return Response(countdown_format( - DATAS.index[name].getDate("born"), "", + context.data.index[name].getDate("born"), "", "C'est aujourd'hui l'anniversaire de %s !" " Il a %s. Joyeux anniversaire :)" % (name, "%s")), msg.channel) @@ -81,7 +81,7 @@ def cmd_age(msg): (matches, name) = findName(msg) if len(matches) == 1: name = matches[0] - d = DATAS.index[name].getDate("born") + d = context.data.index[name].getDate("born") return Response(countdown_format(d, "%s va naître dans %s." % (name, "%s"), @@ -107,14 +107,14 @@ def parseask(msg): nick = res.group(1) if nick == "my" or nick == "I" or nick == "i" or nick == "je" or nick == "mon" or nick == "ma": nick = msg.nick - if nick.lower() in DATAS.index: - DATAS.index[nick.lower()]["born"] = extDate + if nick.lower() in context.data.index: + context.data.index[nick.lower()]["born"] = extDate else: ms = ModuleState("birthday") ms.setAttribute("name", nick.lower()) ms.setAttribute("born", extDate) - DATAS.addChild(ms) - save() + context.data.addChild(ms) + context.save() return Response("ok, c'est noté, %s est né le %s" % (nick, extDate.strftime("%A %d %B %Y à %H:%M")), msg.channel, diff --git a/modules/bonneannee.py b/modules/bonneannee.py index 2eb9b7e..d1eef72 100644 --- a/modules/bonneannee.py +++ b/modules/bonneannee.py @@ -4,6 +4,7 @@ from datetime import datetime, timezone +from nemubot import context from nemubot.event import ModuleEvent from nemubot.hooks import hook from nemubot.tools.countdown import countdown_format @@ -17,7 +18,7 @@ yrn = datetime.now(timezone.utc).year + 1 def load(context): - if not CONF or not CONF.hasNode("sayon"): + if not context.config or not context.config.hasNode("sayon"): print("You can append in your configuration some balise to " "automaticaly wish an happy new year on some channels like:\n" "\nGet one at " @@ -25,7 +26,7 @@ def load(context): def get_book(title): """Retrieve a book from its title""" response = web.getXML("https://www.goodreads.com/book/title.xml?key=%s&title=%s" % - (CONF.getNode("goodreadsapi")["key"], urllib.parse.quote(title))) + (context.config.getNode("goodreadsapi")["key"], urllib.parse.quote(title))) if response is not None and response.hasNode("book"): return response.getNode("book") else: @@ -35,7 +36,7 @@ def get_book(title): def search_books(title): """Get a list of book matching given title""" response = web.getXML("https://www.goodreads.com/search.xml?key=%s&q=%s" % - (CONF.getNode("goodreadsapi")["key"], urllib.parse.quote(title))) + (context.config.getNode("goodreadsapi")["key"], urllib.parse.quote(title))) if response is not None and response.hasNode("search"): return response.getNode("search").getNode("results").getNodes("work") else: @@ -45,10 +46,10 @@ def search_books(title): def search_author(name): """Looking for an author""" response = web.getXML("https://www.goodreads.com/api/author_url/%s?key=%s" % - (urllib.parse.quote(name), CONF.getNode("goodreadsapi")["key"])) + (urllib.parse.quote(name), context.config.getNode("goodreadsapi")["key"])) if response is not None and response.hasNode("author") and response.getNode("author").hasAttribute("id"): response = web.getXML("https://www.goodreads.com/author/show/%s.xml?key=%s" % - (urllib.parse.quote(response.getNode("author")["id"]), CONF.getNode("goodreadsapi")["key"])) + (urllib.parse.quote(response.getNode("author")["id"]), context.config.getNode("goodreadsapi")["key"])) if response is not None and response.hasNode("author"): return response.getNode("author") return None diff --git a/modules/conjugaison.py b/modules/conjugaison.py index 35faa40..656118c 100644 --- a/modules/conjugaison.py +++ b/modules/conjugaison.py @@ -44,7 +44,6 @@ def cmd_conjug(msg): "sa conjugaison!") tens = ' '.join(msg.cmds[1:-1]) - print_debug(tens) verb = msg.cmds[-1] @@ -60,7 +59,6 @@ def cmd_conjug(msg): def get_conjug(verb, stringTens): url = ("http://leconjugueur.lefigaro.fr/conjugaison/verbe/%s.html" % quote(verb.encode("ISO-8859-1"))) - print_debug(url) page = web.getURLContent(url) if page is not None: diff --git a/modules/cve.py b/modules/cve.py index e02bc55..5f6435d 100644 --- a/modules/cve.py +++ b/modules/cve.py @@ -1,6 +1,5 @@ import urllib.request from bs4 import BeautifulSoup -import pprint from nemubot.hooks import hook from more import Response diff --git a/modules/ddg/__init__.py b/modules/ddg/__init__.py index 94e3587..63ef340 100644 --- a/modules/ddg/__init__.py +++ b/modules/ddg/__init__.py @@ -4,6 +4,7 @@ import imp +from nemubot import context from nemubot.hooks import hook nemubotversion = 3.4 @@ -15,8 +16,7 @@ from . import UrbanDictionnary from . import WFASearch def load(context): - global CONF - WFASearch.CONF = CONF + WFASearch.CONF = context.config def reload(): imp.reload(DDGSearch) diff --git a/modules/events.py b/modules/events.py index 0731cc5..29a5918 100644 --- a/modules/events.py +++ b/modules/events.py @@ -10,6 +10,7 @@ import time import threading import traceback +from nemubot import context from nemubot.exception import IRCException from nemubot.event import ModuleEvent from nemubot.hooks import hook @@ -22,28 +23,25 @@ nemubotversion = 3.4 from more import Response def help_full (): - return "This module store a lot of events: ny, we, " + (", ".join(DATAS.index.keys())) + "\n!eventslist: gets list of timer\n!start /something/: launch a timer" + return "This module store a lot of events: ny, we, " + (", ".join(context.datas.index.keys())) + "\n!eventslist: gets list of timer\n!start /something/: launch a timer" def load(context): - global DATAS #Define the index - DATAS.setIndex("name") + context.data.setIndex("name") - for evt in DATAS.index.keys(): - if DATAS.index[evt].hasAttribute("end"): - event = ModuleEvent(call=fini, call_data=dict(strend=DATAS.index[evt])) - if DATAS.index[evt]["server"] not in context.servers: - print("WARNING: registering event for a unexistant server: %s, please connect to it." % DATAS.index[evt]["server"]) - event._end = DATAS.index[evt].getDate("end") - idt = add_event(event) + for evt in context.data.index.keys(): + if context.data.index[evt].hasAttribute("end"): + event = ModuleEvent(call=fini, call_data=dict(strend=context.data.index[evt])) + event._end = context.data.index[evt].getDate("end") + idt = context.add_event(event) if idt is not None: - DATAS.index[evt]["_id"] = idt + context.data.index[evt]["_id"] = idt def fini(d, strend): - send_response(strend["server"], Response("%s arrivé à échéance." % strend["name"], channel=strend["channel"], nick=strend["proprio"])) - DATAS.delChild(DATAS.index[strend["name"]]) - save() + context.send_response(strend["server"], Response("%s arrivé à échéance." % strend["name"], channel=strend["channel"], nick=strend["proprio"])) + context.data.delChild(context.data.index[strend["name"]]) + context.save() @hook("cmd_hook", "goûter") def cmd_gouter(msg): @@ -68,7 +66,7 @@ def start_countdown(msg): """!start /something/: launch a timer""" if len(msg.cmds) < 2: raise IRCException("indique le nom d'un événement à chronométrer") - if msg.cmds[1] in DATAS.index: + if msg.cmds[1] in context.data.index: raise IRCException("%s existe déjà." % msg.cmds[1]) strnd = ModuleState("strend") @@ -77,7 +75,7 @@ def start_countdown(msg): strnd["proprio"] = msg.nick strnd["start"] = msg.date strnd["name"] = msg.cmds[1] - DATAS.addChild(strnd) + context.data.addChild(strnd) evt = ModuleEvent(call=fini, call_data=dict(strend=strnd)) @@ -106,9 +104,9 @@ def start_countdown(msg): else: strnd["end"] = datetime(now.year, now.month, now.day + 1, hou, minu, sec, timezone.utc) evt._end = strnd.getDate("end") - strnd["_id"] = add_event(evt) + strnd["_id"] = context.add_event(evt) except: - DATAS.delChild(strnd) + context.data.delChild(strnd) raise IRCException("Mauvais format de date pour l'événement %s. Il n'a pas été créé." % msg.cmds[1]) elif result1 is not None and len(result1) > 0: @@ -127,11 +125,11 @@ def start_countdown(msg): else: strnd["end"] += timedelta(seconds=int(t)) evt._end = strnd.getDate("end") - eid = add_event(evt) + eid = context.add_event(evt) if eid is not None: strnd["_id"] = eid - save() + context.save() if "end" in strnd: return Response("%s commencé le %s et se terminera le %s." % (msg.cmds[1], msg.date.strftime("%A %d %B %Y à %H:%M:%S"), @@ -148,16 +146,16 @@ def end_countdown(msg): if len(msg.cmds) < 2: raise IRCException("quel événement terminer ?") - if msg.cmds[1] in DATAS.index: - if DATAS.index[msg.cmds[1]]["proprio"] == msg.nick or (msg.cmds[0] == "forceend" and msg.frm_owner): - duration = countdown(msg.date - DATAS.index[msg.cmds[1]].getDate("start")) - del_event(DATAS.index[msg.cmds[1]]["_id"]) - DATAS.delChild(DATAS.index[msg.cmds[1]]) - save() + if msg.cmds[1] in context.data.index: + if context.data.index[msg.cmds[1]]["proprio"] == msg.nick or (msg.cmds[0] == "forceend" and msg.frm_owner): + duration = countdown(msg.date - context.data.index[msg.cmds[1]].getDate("start")) + context.del_event(context.data.index[msg.cmds[1]]["_id"]) + context.data.delChild(context.data.index[msg.cmds[1]]) + context.save() return Response("%s a duré %s." % (msg.cmds[1], duration), channel=msg.channel, nick=msg.nick) else: - raise IRCException("Vous ne pouvez pas terminer le compteur %s, créé par %s." % (msg.cmds[1], DATAS.index[msg.cmds[1]]["proprio"])) + raise IRCException("Vous ne pouvez pas terminer le compteur %s, créé par %s." % (msg.cmds[1], context.data.index[msg.cmds[1]]["proprio"])) else: return Response("%s n'est pas un compteur connu."% (msg.cmds[1]), channel=msg.channel, nick=msg.nick) @@ -167,31 +165,31 @@ def liste(msg): if len(msg.cmds) > 1: res = list() for user in msg.cmds[1:]: - cmptr = [x["name"] for x in DATAS.index.values() if x["proprio"] == user] + cmptr = [x["name"] for x in context.data.index.values() if x["proprio"] == user] if len(cmptr) > 0: res.append("Compteurs créés par %s : %s" % (user, ", ".join(cmptr))) else: res.append("%s n'a pas créé de compteur" % user) return Response(" ; ".join(res), channel=msg.channel) else: - return Response("Compteurs connus : %s." % ", ".join(DATAS.index.keys()), channel=msg.channel) + return Response("Compteurs connus : %s." % ", ".join(context.data.index.keys()), channel=msg.channel) @hook("cmd_default") def parseanswer(msg): - if msg.cmds[0] in DATAS.index: + if msg.cmds[0] in context.data.index: res = Response(channel=msg.channel) # Avoid message starting by ! which can be interpreted as command by other bots if msg.cmds[0][0] == "!": res.nick = msg.nick - if DATAS.index[msg.cmds[0]].name == "strend": - if DATAS.index[msg.cmds[0]].hasAttribute("end"): - res.append_message("%s commencé il y a %s et se terminera dans %s." % (msg.cmds[0], countdown(msg.date - DATAS.index[msg.cmds[0]].getDate("start")), countdown(DATAS.index[msg.cmds[0]].getDate("end") - msg.date))) + if context.data.index[msg.cmds[0]].name == "strend": + if context.data.index[msg.cmds[0]].hasAttribute("end"): + res.append_message("%s commencé il y a %s et se terminera dans %s." % (msg.cmds[0], countdown(msg.date - context.data.index[msg.cmds[0]].getDate("start")), countdown(context.data.index[msg.cmds[0]].getDate("end") - msg.date))) else: - res.append_message("%s commencé il y a %s." % (msg.cmds[0], countdown(msg.date - DATAS.index[msg.cmds[0]].getDate("start")))) + res.append_message("%s commencé il y a %s." % (msg.cmds[0], countdown(msg.date - context.data.index[msg.cmds[0]].getDate("start")))) else: - res.append_message(countdown_format(DATAS.index[msg.cmds[0]].getDate("start"), DATAS.index[msg.cmds[0]]["msg_before"], DATAS.index[msg.cmds[0]]["msg_after"])) + res.append_message(countdown_format(context.data.index[msg.cmds[0]].getDate("start"), context.data.index[msg.cmds[0]]["msg_before"], context.data.index[msg.cmds[0]]["msg_after"])) return res RGXP_ask = re.compile(r"^.*((create|new)\s+(a|an|a\s*new|an\s*other)?\s*(events?|commande?)|(nouvel(le)?|ajoute|cr[ée]{1,3})\s+(un)?\s*([eé]v[ée]nements?|commande?)).*$", re.I) @@ -202,7 +200,7 @@ def parseask(msg): name = re.match("^.*!([^ \"'@!]+).*$", msg.text) if name is None: raise IRCException("il faut que tu attribues une commande à l'événement.") - if name.group(1) in DATAS.index: + if name.group(1) in context.data.index: raise IRCException("un événement portant ce nom existe déjà.") texts = re.match("^[^\"]*(avant|après|apres|before|after)?[^\"]*\"([^\"]+)\"[^\"]*((avant|après|apres|before|after)?.*\"([^\"]+)\".*)?$", msg.text, re.I) @@ -231,8 +229,8 @@ def parseask(msg): evt["start"] = extDate evt["msg_after"] = msg_after evt["msg_before"] = msg_before - DATAS.addChild(evt) - save() + context.data.addChild(evt) + context.save() return Response("Nouvel événement !%s ajouté avec succès." % name.group(1), channel=msg.channel) @@ -243,8 +241,8 @@ def parseask(msg): evt["proprio"] = msg.nick evt["name"] = name.group(1) evt["msg_before"] = texts.group (2) - DATAS.addChild(evt) - save() + context.data.addChild(evt) + context.save() return Response("Nouvelle commande !%s ajoutée avec succès." % name.group(1), channel=msg.channel) diff --git a/modules/imdb.py b/modules/imdb.py index 4b381ae..fb1f0b3 100644 --- a/modules/imdb.py +++ b/modules/imdb.py @@ -34,8 +34,6 @@ def get_movie(title=None, year=None, imdbid=None, fullplot=True, tomatoes=False) if tomatoes: url += "tomatoes=true&" - print_debug(url) - # Make the request data = web.getJSON(url) @@ -55,7 +53,6 @@ def find_movies(title): # Built URL url = "http://www.omdbapi.com/?s=%s" % urllib.parse.quote(title) - print_debug(url) # Make the request data = web.getJSON(url) diff --git a/modules/mapquest.py b/modules/mapquest.py index 7d41f2b..17e842b 100644 --- a/modules/mapquest.py +++ b/modules/mapquest.py @@ -14,7 +14,7 @@ from more import Response def load(context): - if not CONF or not CONF.hasNode("mapquestapi") or not CONF.getNode("mapquestapi").hasAttribute("key"): + 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\nRegister at " @@ -22,7 +22,7 @@ def load(context): return None from nemubot.hooks.messagehook import MessageHook - add_hook("cmd_hook", MessageHook(cmd_geocode, "geocode")) + context.add_hook("cmd_hook", MessageHook(cmd_geocode, "geocode")) def help_full(): @@ -31,7 +31,7 @@ def help_full(): def geocode(location): obj = web.getJSON("http://open.mapquestapi.com/geocoding/v1/address?key=%s&location=%s" % - (CONF.getNode("mapquestapi")["key"], quote(location))) + (context.config.getNode("mapquestapi")["key"], quote(location))) if "results" in obj and "locations" in obj["results"][0]: for loc in obj["results"][0]["locations"]: diff --git a/modules/mediawiki.py b/modules/mediawiki.py index 730911c..dc461bb 100644 --- a/modules/mediawiki.py +++ b/modules/mediawiki.py @@ -19,7 +19,6 @@ def get_namespaces(site, ssl=False): # Built URL url = "http%s://%s/w/api.php?format=json&action=query&meta=siteinfo&siprop=namespaces" % ( "s" if ssl else "", site) - print_debug(url) # Make the request data = web.getJSON(url) @@ -34,7 +33,6 @@ def get_raw_page(site, term, ssl=False): # Built URL url = "http%s://%s/w/api.php?format=json&redirects&action=query&prop=revisions&rvprop=content&titles=%s" % ( "s" if ssl else "", site, urllib.parse.quote(term)) - print_debug(url) # Make the request data = web.getJSON(url) @@ -50,7 +48,6 @@ def get_unwikitextified(site, wikitext, ssl=False): # Built URL url = "http%s://%s/w/api.php?format=json&action=expandtemplates&text=%s" % ( "s" if ssl else "", site, urllib.parse.quote(wikitext)) - print_debug(url) # Make the request data = web.getJSON(url) @@ -107,7 +104,6 @@ def opensearch(site, term, ssl=False): # Built URL url = "http%s://%s/w/api.php?format=xml&action=opensearch&search=%s" % ( "s" if ssl else "", site, urllib.parse.quote(term)) - print_debug(url) # Make the request response = web.getXML(url) @@ -123,7 +119,6 @@ def search(site, term, ssl=False): # Built URL url = "http%s://%s/w/api.php?format=json&action=query&list=search&srsearch=%s&srprop=titlesnippet|snippet" % ( "s" if ssl else "", site, urllib.parse.quote(term)) - print_debug(url) # Make the request data = web.getJSON(url) diff --git a/modules/networking/__init__.py b/modules/networking/__init__.py index c6d960c..0caab06 100644 --- a/modules/networking/__init__.py +++ b/modules/networking/__init__.py @@ -17,15 +17,14 @@ from . import whois def load(context): for mod in [isup, page, w3c, watchWebsite, whois]: - mod.add_event = add_event - mod.del_event = del_event - mod.save = save + mod.add_event = context.add_event + mod.del_event = context.del_event + mod.save = context.save mod.print = print - mod.print_debug = print_debug - mod.send_response = send_response - page.load(CONF, add_hook) - watchWebsite.load(DATAS) - whois.load(CONF, add_hook) + mod.send_response = context.send_response + page.load(context.config, context.add_hook) + watchWebsite.load(context.data) + whois.load(context.config, context.add_hook) def help_full(): diff --git a/modules/networking/watchWebsite.py b/modules/networking/watchWebsite.py index 7035b4b..47b1b17 100644 --- a/modules/networking/watchWebsite.py +++ b/modules/networking/watchWebsite.py @@ -185,7 +185,7 @@ def start_watching(site, offset=0): """ o = urlparse(site["url"], "http") - print_debug("Add %s event for site: %s" % (site["type"], o.netloc)) + #print_debug("Add %s event for site: %s" % (site["type"], o.netloc)) evt = ModuleEvent(func=lambda url: page.render(url, None), cmp_data=site["lastcontent"], diff --git a/modules/sms.py b/modules/sms.py index dd467f7..add430b 100644 --- a/modules/sms.py +++ b/modules/sms.py @@ -9,6 +9,7 @@ import urllib.error import urllib.request import urllib.parse +from nemubot import context from nemubot.exception import IRCException from nemubot.hooks import hook from nemubot.tools.xmlparser.node import ModuleState @@ -18,8 +19,7 @@ nemubotversion = 3.4 from more import Response def load(context): - global DATAS - DATAS.setIndex("name", "phone") + context.data.setIndex("name", "phone") def help_full(): return "!sms /who/[,/who/[,...]] message: send a SMS to /who/." @@ -55,20 +55,20 @@ def cmd_sms(msg): # Check dests cur_epoch = time.mktime(time.localtime()); for u in msg.cmds[1].split(","): - if u not in DATAS.index: + if u not in context.data.index: raise IRCException("Désolé, je sais pas comment envoyer de SMS à %s." % u) - elif cur_epoch - float(DATAS.index[u]["lastuse"]) < 42: + elif cur_epoch - float(context.data.index[u]["lastuse"]) < 42: raise IRCException("Un peu de calme, %s a déjà reçu un SMS il n'y a pas si longtemps." % u) # Go! fails = list() for u in msg.cmds[1].split(","): - DATAS.index[u]["lastuse"] = cur_epoch + context.data.index[u]["lastuse"] = cur_epoch if msg.to_response[0] == msg.frm: frm = msg.frm else: frm = msg.frm + "@" + msg.to[0] - test = send_sms(frm, DATAS.index[u]["user"], DATAS.index[u]["key"], " ".join(msg.cmds[2:])) + test = send_sms(frm, context.data.index[u]["user"], context.data.index[u]["key"], " ".join(msg.cmds[2:])) if test is not None: fails.append( "%s: %s" % (u, test) ) @@ -96,16 +96,16 @@ def parseask(msg): if test is not None: return Response("je n'ai pas pu enregistrer tes identifiants : %s" % test, msg.channel, msg.nick) - if msg.nick in DATAS.index: - DATAS.index[msg.nick]["user"] = apiuser - DATAS.index[msg.nick]["key"] = apikey + if msg.nick in context.data.index: + context.data.index[msg.nick]["user"] = apiuser + context.data.index[msg.nick]["key"] = apikey else: ms = ModuleState("phone") ms.setAttribute("name", msg.nick) ms.setAttribute("user", apiuser) ms.setAttribute("key", apikey) ms.setAttribute("lastuse", 0) - DATAS.addChild(ms) - save() + context.data.addChild(ms) + context.save() return Response("ok, c'est noté. Je t'ai envoyé un SMS pour tester ;)", msg.channel, msg.nick) diff --git a/modules/speak.py b/modules/speak.py index d8808b8..f5c88c2 100644 --- a/modules/speak.py +++ b/modules/speak.py @@ -20,12 +20,12 @@ SMILEY = list() CORRECTIONS = list() def load(context): - for smiley in CONF.getNodes("smiley"): + for smiley in context.config.getNodes("smiley"): if smiley.hasAttribute("txt") and smiley.hasAttribute("mood"): SMILEY.append((smiley.getAttribute("txt"), smiley.getAttribute("mood"))) print ("%d smileys loaded" % len(SMILEY)) - for correct in CONF.getNodes("correction"): + for correct in context.config.getNodes("correction"): if correct.hasAttribute("bad") and correct.hasAttribute("good"): CORRECTIONS.append((" " + (correct.getAttribute("bad") + " "), (" " + correct.getAttribute("good") + " "))) print ("%d corrections loaded" % len(CORRECTIONS)) @@ -38,7 +38,6 @@ class Speaker(Thread): while not queue.empty(): sentence = queue.get_nowait() lang = "fr" - print_debug(sentence) subprocess.call(["espeak", "-v", lang, "--", sentence]) queue.task_done() diff --git a/modules/spell/__init__.py b/modules/spell/__init__.py index 9e2faba..0953fae 100644 --- a/modules/spell/__init__.py +++ b/modules/spell/__init__.py @@ -5,6 +5,7 @@ import re from urllib.parse import quote +from nemubot import context from nemubot.exception import IRCException from nemubot.hooks import hook from nemubot.tools.xmlparser.node import ModuleState @@ -20,8 +21,7 @@ def help_full(): return "!spell [] : give the correct spelling of in ." def load(context): - global DATAS - DATAS.setIndex("name", "score") + context.data.setIndex("name", "score") @hook("cmd_hook", "spell") def cmd_spell(msg): @@ -50,27 +50,25 @@ def cmd_spell(msg): return Response(strRes, channel=msg.channel, nick=msg.nick) def add_score(nick, t): - global DATAS - if nick not in DATAS.index: + if nick not in context.data.index: st = ModuleState("score") st["name"] = nick - DATAS.addChild(st) + context.data.addChild(st) - if DATAS.index[nick].hasAttribute(t): - DATAS.index[nick][t] = DATAS.index[nick].getInt(t) + 1 + if context.data.index[nick].hasAttribute(t): + context.data.index[nick][t] = context.data.index[nick].getInt(t) + 1 else: - DATAS.index[nick][t] = 1 - save() + context.data.index[nick][t] = 1 + context.save() @hook("cmd_hook", "spellscore") def cmd_score(msg): - global DATAS res = list() unknown = list() if len(msg.cmds) > 1: for cmd in msg.cmds[1:]: - if cmd in DATAS.index: - res.append(Response("%s: %s" % (cmd, " ; ".join(["%s: %d" % (a, DATAS.index[cmd].getInt(a)) for a in DATAS.index[cmd].attributes.keys() if a != "name"])), channel=msg.channel)) + if cmd in context.data.index: + res.append(Response("%s: %s" % (cmd, " ; ".join(["%s: %d" % (a, context.data.index[cmd].getInt(a)) for a in context.data.index[cmd].attributes.keys() if a != "name"])), channel=msg.channel)) else: unknown.append(cmd) else: diff --git a/modules/syno.py b/modules/syno.py index 603277b..281b947 100644 --- a/modules/syno.py +++ b/modules/syno.py @@ -21,18 +21,17 @@ def help_full(): def load(context): global lang_binding - if not CONF or not CONF.hasNode("bighugelabs") or not CONF.getNode("bighugelabs").hasAttribute("key"): + 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\nRegister at " "https://words.bighugelabs.com/getkey.php") else: - lang_binding["en"] = lambda word: get_english_synos(CONF.getNode("bighugelabs")["key"], word) + lang_binding["en"] = lambda word: get_english_synos(context.config.getNode("bighugelabs")["key"], word) def get_french_synos(word): url = "http://www.crisco.unicaen.fr/des/synonymes/" + quote(word.encode("ISO-8859-1")) - print_debug(url) page = web.getURLContent(url) best = list(); synos = list(); anton = list() diff --git a/modules/tpb.py b/modules/tpb.py index b525210..6ea4a2d 100644 --- a/modules/tpb.py +++ b/modules/tpb.py @@ -15,16 +15,16 @@ URL_TPBAPI = None def load(context): global URL_TPBAPI - if not CONF or not CONF.hasNode("tpbapi") or not CONF.getNode("tpbapi").hasAttribute("url"): + 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" "\nSample API: " "https://gist.github.com/colona/07a925f183cfb47d5f20") else: - URL_TPBAPI = CONF.getNode("tpbapi")["url"] + URL_TPBAPI = context.config.getNode("tpbapi")["url"] from nemubot.hooks.messagehook import MessageHook - add_hook("cmd_hook", MessageHook(cmd_tpb, "tpb")) + context.add_hook("cmd_hook", MessageHook(cmd_tpb, "tpb")) def cmd_tpb(msg): diff --git a/modules/translate.py b/modules/translate.py index 0b73b90..8cc5bac 100644 --- a/modules/translate.py +++ b/modules/translate.py @@ -19,17 +19,17 @@ URL = "http://api.wordreference.com/0.8/%s/json/%%s%%s/%%s" def load(context): global URL - if not CONF or not CONF.hasNode("wrapi") or not CONF.getNode("wrapi").hasAttribute("key"): + 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\nRegister at " "http://www.wordreference.com/docs/APIregistration.aspx") return None else: - URL = URL % CONF.getNode("wrapi")["key"] + URL = URL % context.config.getNode("wrapi")["key"] from nemubot.hooks.messagehook import MessageHook - add_hook("cmd_hook", MessageHook(cmd_translate, "translate")) + context.add_hook("cmd_hook", MessageHook(cmd_translate, "translate")) def help_full(): diff --git a/modules/velib.py b/modules/velib.py index be196ad..00105c9 100644 --- a/modules/velib.py +++ b/modules/velib.py @@ -4,6 +4,7 @@ import re +from nemubot import context from nemubot.exception import IRCException from nemubot.hooks import hook from nemubot.tools import web @@ -14,8 +15,7 @@ from more import Response def load(context): - global DATAS - DATAS.setIndex("name", "station") + context.data.setIndex("name", "station") # evt = ModuleEvent(station_available, "42706", # (lambda a, b: a != b), None, 60, @@ -30,7 +30,7 @@ def help_full(): def station_status(station): """Gets available and free status of a given station""" - response = web.getXML(CONF.getNode("server")["url"] + station) + response = web.getXML(context.config.getNode("server")["url"] + station) if response is not None: available = response.getNode("available").getContent() if available is not None and len(available) > 0: @@ -72,7 +72,6 @@ def print_station_status(msg, station): @hook("cmd_hook", "velib") def ask_stations(msg): """Hook entry from !velib""" - global DATAS if len(msg.cmds) > 5: raise IRCException("demande-moi moins de stations à la fois.") @@ -80,9 +79,9 @@ def ask_stations(msg): for station in msg.cmds[1:]: if re.match("^[0-9]{4,5}$", station): return print_station_status(msg, station) - elif station in DATAS.index: + elif station in context.data.index: return print_station_status(msg, - DATAS.index[station]["number"]) + context.data.index[station]["number"]) else: raise IRCException("numéro de station invalide.") diff --git a/modules/weather.py b/modules/weather.py index e41bdb2..a3d5daf 100644 --- a/modules/weather.py +++ b/modules/weather.py @@ -6,6 +6,7 @@ import datetime 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 @@ -19,10 +20,9 @@ from more import Response def load(context): - global DATAS - DATAS.setIndex("name", "city") + context.data.setIndex("name", "city") - if not CONF or not CONF.hasNode("darkskyapi") or not CONF.getNode("darkskyapi").hasAttribute("key"): + 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\nRegister at " @@ -30,9 +30,9 @@ def load(context): return None from nemubot.hooks.messagehook import MessageHook - add_hook("cmd_hook", MessageHook(cmd_weather, "météo")) - add_hook("cmd_hook", MessageHook(cmd_alert, "alert")) - add_hook("cmd_hook", MessageHook(cmd_coordinates, "coordinates")) + context.add_hook("cmd_hook", MessageHook(cmd_weather, "météo")) + context.add_hook("cmd_hook", MessageHook(cmd_alert, "alert")) + context.add_hook("cmd_hook", MessageHook(cmd_coordinates, "coordinates")) def help_full (): @@ -111,10 +111,10 @@ def treat_coord(msg): except ValueError: pass - if city in DATAS.index: + if city in context.data.index: coords = list() - coords.append(DATAS.index[city]["lat"]) - coords.append(DATAS.index[city]["long"]) + coords.append(context.data.index[city]["lat"]) + coords.append(context.data.index[city]["long"]) return city, coords, specific else: @@ -132,7 +132,7 @@ def treat_coord(msg): def get_json_weather(coords): - wth = web.getJSON("https://api.forecast.io/forecast/%s/%s,%s" % (CONF.getNode("darkskyapi")["key"], float(coords[0]), float(coords[1]))) + wth = web.getJSON("https://api.forecast.io/forecast/%s/%s,%s" % (context.config.getNode("darkskyapi")["key"], float(coords[0]), float(coords[1]))) # First read flags if "darksky-unavailable" in wth["flags"]: @@ -146,10 +146,10 @@ def cmd_coordinates(msg): raise IRCException("indique-moi un nom de ville.") j = msg.args[0].lower() - if j not in DATAS.index: + if j not in context.data.index: raise IRCException("%s n'est pas une ville connue" % msg.args[0]) - coords = DATAS.index[j] + coords = context.data.index[j] return Response("Les coordonnées de %s sont %s,%s" % (msg.args[0], coords["lat"], coords["long"]), channel=msg.channel) @@ -227,15 +227,15 @@ def parseask(msg): gps_lat = res.group("lat").replace(",", ".") gps_long = res.group("long").replace(",", ".") - if city_name in DATAS.index: - DATAS.index[city_name]["lat"] = gps_lat - DATAS.index[city_name]["long"] = gps_long + if city_name in context.data.index: + context.data.index[city_name]["lat"] = gps_lat + context.data.index[city_name]["long"] = gps_long else: ms = ModuleState("city") ms.setAttribute("name", city_name) ms.setAttribute("lat", gps_lat) ms.setAttribute("long", gps_long) - DATAS.addChild(ms) - save() + context.data.addChild(ms) + context.save() return Response("ok, j'ai bien noté les coordonnées de %s" % res.group("city"), msg.channel, msg.nick) diff --git a/modules/worldcup.py b/modules/worldcup.py index 0a9c1cb..712dba4 100644 --- a/modules/worldcup.py +++ b/modules/worldcup.py @@ -8,6 +8,7 @@ import re from urllib.parse import quote from urllib.request import urlopen +from nemubot import context from nemubot.exception import IRCException from nemubot.hooks import hook from nemubot.tools.xmlparser.node import ModuleState @@ -20,7 +21,7 @@ API_URL="http://worldcup.sfg.io/%s" def load(context): from nemubot.event import ModuleEvent - add_event(ModuleEvent(func=lambda url: urlopen(url, timeout=10).read().decode(), func_data=API_URL % "matches/current?by_date=DESC", call=current_match_new_action, interval=30)) + context.add_event(ModuleEvent(func=lambda url: urlopen(url, timeout=10).read().decode(), func_data=API_URL % "matches/current?by_date=DESC", call=current_match_new_action, interval=30)) def help_full (): @@ -28,31 +29,29 @@ def help_full (): def start_watch(msg): - global DATAS w = ModuleState("watch") w["server"] = msg.server w["channel"] = msg.channel w["proprio"] = msg.nick w["start"] = datetime.now(timezone.utc) - DATAS.addChild(w) - save() + context.data.addChild(w) + context.save() raise IRCException("This channel is now watching world cup events!") @hook("cmd_hook", "watch_worldcup") def cmd_watch(msg): - global DATAS # Get current state node = None - for n in DATAS.getChilds(): + for n in context.data.getChilds(): if n["server"] == msg.server and n["channel"] == msg.channel: node = n break if len(msg.cmds) >= 2: if msg.cmds[1] == "stop" and node is not None: - DATAS.delChild(node) - save() + context.data.delChild(node) + context.save() raise IRCException("This channel will not anymore receives world cup events.") elif msg.cmds[1] == "start" and node is None: start_watch(msg) @@ -62,14 +61,12 @@ def cmd_watch(msg): if node is None: start_watch(msg) else: - DATAS.delChild(node) - save() + context.data.delChild(node) + context.save() raise IRCException("This channel will not anymore receives world cup events.") def current_match_new_action(match_str, osef): - global DATAS - - add_event(ModuleEvent(func=lambda url: urlopen(url).read().decode(), func_data=API_URL % "matches/current?by_date=DESC", call=current_match_new_action, interval=30)) + context.add_event(ModuleEvent(func=lambda url: urlopen(url).read().decode(), func_data=API_URL % "matches/current?by_date=DESC", call=current_match_new_action, interval=30)) matches = json.loads(match_str) @@ -81,8 +78,8 @@ def current_match_new_action(match_str, osef): if len(events) > 0: msg += " ; à la " + txt_event(events[0]) - for n in DATAS.getChilds(): - send_response(n["server"], Response(msg, channel=n["channel"])) + for n in context.data.getChilds(): + context.send_response(n["server"], Response(msg, channel=n["channel"])) def is_int(s): try: diff --git a/modules/ycc.py b/modules/ycc.py index 97cde3f..fba6650 100644 --- a/modules/ycc.py +++ b/modules/ycc.py @@ -30,7 +30,6 @@ def reduce(url): """ snd_url = "http://ycc.fr/redirection/create/" + quote(url, "/:%@&=?") - print_debug(snd_url) return web.getURLContent(snd_url)