Convert modules to new importer

This commit is contained in:
nemunaire 2015-02-11 18:12:39 +01:00
parent 1f5364c387
commit 28005e5654
23 changed files with 165 additions and 186 deletions

View file

@ -7,6 +7,7 @@ import sys
from datetime import datetime, timezone from datetime import datetime, timezone
import shlex import shlex
from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IRCException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.message import TextMessage, Command from nemubot.message import TextMessage, Command
@ -19,13 +20,12 @@ from more import Response
def load(context): def load(context):
"""Load this module""" """Load this module"""
global DATAS if not context.data.hasNode("aliases"):
if not DATAS.hasNode("aliases"): context.data.addChild(ModuleState("aliases"))
DATAS.addChild(ModuleState("aliases")) context.data.getNode("aliases").setIndex("alias")
DATAS.getNode("aliases").setIndex("alias") if not context.data.hasNode("variables"):
if not DATAS.hasNode("variables"): context.data.addChild(ModuleState("variables"))
DATAS.addChild(ModuleState("variables")) context.data.getNode("variables").setIndex("name")
DATAS.getNode("variables").setIndex("name")
def help_full(): def help_full():
@ -37,7 +37,7 @@ def set_variable(name, value, creator):
var["name"] = name var["name"] = name
var["value"] = value var["value"] = value
var["creator"] = creator var["creator"] = creator
DATAS.getNode("variables").addChild(var) context.data.getNode("variables").addChild(var)
def get_variable(name, msg=None): def get_variable(name, msg=None):
@ -47,8 +47,8 @@ def get_variable(name, msg=None):
return msg.channel return msg.channel
elif name == "date": elif name == "date":
return datetime.now(timezone.utc).strftime("%c") return datetime.now(timezone.utc).strftime("%c")
elif name in DATAS.getNode("variables").index: elif name in context.data.getNode("variables").index:
return DATAS.getNode("variables").index[name]["value"] return context.data.getNode("variables").index[name]["value"]
else: else:
return "" return ""
@ -59,7 +59,7 @@ def cmd_set(msg):
set_variable(msg.cmds[1], " ".join(msg.cmds[2:]), msg.nick) set_variable(msg.cmds[1], " ".join(msg.cmds[2:]), msg.nick)
res = Response("Variable \$%s définie." % msg.cmds[1], res = Response("Variable \$%s définie." % msg.cmds[1],
channel=msg.channel) channel=msg.channel)
save() context.save()
return res return res
return Response("!set prend au minimum deux arguments : " return Response("!set prend au minimum deux arguments : "
"le nom de la variable et sa valeur.", "le nom de la variable et sa valeur.",
@ -71,7 +71,7 @@ def cmd_listalias(msg):
if len(msg.cmds) > 1: if len(msg.cmds) > 1:
res = list() res = list()
for user in msg.cmds[1:]: 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: if len(als) > 0:
res.append("Alias créés par %s : %s" % (user, ", ".join(als))) res.append("Alias créés par %s : %s" % (user, ", ".join(als)))
else: else:
@ -79,7 +79,7 @@ def cmd_listalias(msg):
return Response(" ; ".join(res), channel=msg.channel) return Response(" ; ".join(res), channel=msg.channel)
else: else:
return Response("Alias connus : %s." % return Response("Alias connus : %s." %
", ".join(DATAS.getNode("aliases").index.keys()), ", ".join(context.data.getNode("aliases").index.keys()),
channel=msg.channel) channel=msg.channel)
@ -88,7 +88,7 @@ def cmd_listvars(msg):
if len(msg.cmds) > 1: if len(msg.cmds) > 1:
res = list() res = list()
for user in msg.cmds[1:]: 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: if len(als) > 0:
res.append("Variables créées par %s : %s" % (user, ", ".join(als))) res.append("Variables créées par %s : %s" % (user, ", ".join(als)))
else: else:
@ -96,7 +96,7 @@ def cmd_listvars(msg):
return Response(" ; ".join(res), channel=msg.channel) return Response(" ; ".join(res), channel=msg.channel)
else: else:
return Response("Variables connues : %s." % return Response("Variables connues : %s." %
", ".join(DATAS.getNode("variables").index.keys()), ", ".join(context.data.getNode("variables").index.keys()),
channel=msg.channel) channel=msg.channel)
@ -107,9 +107,9 @@ def cmd_alias(msg):
for alias in msg.cmds[1:]: for alias in msg.cmds[1:]:
if alias[0] == "!": if alias[0] == "!":
alias = alias[1:] alias = alias[1:]
if alias in DATAS.getNode("aliases").index: if alias in context.data.getNode("aliases").index:
res.append(Response("!%s correspond à %s" % res.append(Response("!%s correspond à %s" %
(alias, DATAS.getNode("aliases").index[alias]["origin"]), (alias, context.data.getNode("aliases").index[alias]["origin"]),
channel=msg.channel)) channel=msg.channel))
else: else:
res.append(Response("!%s n'est pas un alias" % alias, res.append(Response("!%s n'est pas un alias" % alias,
@ -127,9 +127,9 @@ def cmd_unalias(msg):
for alias in msg.cmds[1:]: for alias in msg.cmds[1:]:
if alias[0] == "!" and len(alias) > 1: if alias[0] == "!" and len(alias) > 1:
alias = alias[1:] alias = alias[1:]
if alias in DATAS.getNode("aliases").index: if alias in context.data.getNode("aliases").index:
if DATAS.getNode("aliases").index[alias]["creator"] == msg.nick or msg.frm_owner: if context.data.getNode("aliases").index[alias]["creator"] == msg.nick or msg.frm_owner:
DATAS.getNode("aliases").delChild(DATAS.getNode("aliases").index[alias]) context.data.getNode("aliases").delChild(context.data.getNode("aliases").index[alias])
res.append(Response("%s a bien été supprimé" % alias, res.append(Response("%s a bien été supprimé" % alias,
channel=msg.channel)) channel=msg.channel))
else: else:
@ -167,8 +167,8 @@ def replace_variables(cnt, msg=None):
@hook("pre_Command") @hook("pre_Command")
def treat_alias(msg): def treat_alias(msg):
if msg.cmd in DATAS.getNode("aliases").index: if msg.cmd in context.data.getNode("aliases").index:
txt = DATAS.getNode("aliases").index[msg.cmd]["origin"] txt = context.data.getNode("aliases").index[msg.cmd]["origin"]
# TODO: for legacy compatibility # TODO: for legacy compatibility
if txt[0] == "!": if txt[0] == "!":
txt = txt[1:] txt = txt[1:]
@ -190,16 +190,16 @@ def parseask(msg):
global ALIAS global ALIAS
if re.match(".*(set|cr[ée]{2}|nouvel(le)?) alias.*", msg.text) is not None: if re.match(".*(set|cr[ée]{2}|nouvel(le)?) alias.*", msg.text) is not None:
result = re.match(".*alias !?([^ ]+) (pour|=|:) (.+)$", msg.text) 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.") raise IRCException("cet alias est déjà défini.")
else: else:
alias = ModuleState("alias") alias = ModuleState("alias")
alias["alias"] = result.group(1) alias["alias"] = result.group(1)
alias["origin"] = result.group(3) alias["origin"] = result.group(3)
alias["creator"] = msg.nick 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." % res = Response("Nouvel alias %s défini avec succès." %
result.group(1), channel=msg.channel) result.group(1), channel=msg.channel)
save() context.save()
return res return res
return None return None

View file

@ -6,6 +6,7 @@ import re
import sys import sys
from datetime import date, datetime from datetime import date, datetime
from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IRCException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.countdown import countdown_format from nemubot.tools.countdown import countdown_format
@ -18,8 +19,7 @@ from more import Response
def load(context): def load(context):
global DATAS context.data.setIndex("name", "birthday")
DATAS.setIndex("name", "birthday")
def help_full(): def help_full():
@ -38,10 +38,10 @@ def findName(msg):
matches = [] matches = []
if name in DATAS.index: if name in context.data.index:
matches.append(name) matches.append(name)
else: else:
for k in DATAS.index.keys(): for k in context.data.index.keys():
if k.find(name) == 0: if k.find(name) == 0:
matches.append(k) matches.append(k)
return (matches, name) return (matches, name)
@ -52,13 +52,13 @@ def cmd_anniv(msg):
(matches, name) = findName(msg) (matches, name) = findName(msg)
if len(matches) == 1: if len(matches) == 1:
name = matches[0] 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) tyd = datetime(date.today().year, tyd.month, tyd.day)
if (tyd.day == datetime.today().day and if (tyd.day == datetime.today().day and
tyd.month == datetime.today().month): tyd.month == datetime.today().month):
return Response(countdown_format( return Response(countdown_format(
DATAS.index[name].getDate("born"), "", context.data.index[name].getDate("born"), "",
"C'est aujourd'hui l'anniversaire de %s !" "C'est aujourd'hui l'anniversaire de %s !"
" Il a %s. Joyeux anniversaire :)" % (name, "%s")), " Il a %s. Joyeux anniversaire :)" % (name, "%s")),
msg.channel) msg.channel)
@ -81,7 +81,7 @@ def cmd_age(msg):
(matches, name) = findName(msg) (matches, name) = findName(msg)
if len(matches) == 1: if len(matches) == 1:
name = matches[0] name = matches[0]
d = DATAS.index[name].getDate("born") d = context.data.index[name].getDate("born")
return Response(countdown_format(d, return Response(countdown_format(d,
"%s va naître dans %s." % (name, "%s"), "%s va naître dans %s." % (name, "%s"),
@ -107,14 +107,14 @@ def parseask(msg):
nick = res.group(1) nick = res.group(1)
if nick == "my" or nick == "I" or nick == "i" or nick == "je" or nick == "mon" or nick == "ma": if nick == "my" or nick == "I" or nick == "i" or nick == "je" or nick == "mon" or nick == "ma":
nick = msg.nick nick = msg.nick
if nick.lower() in DATAS.index: if nick.lower() in context.data.index:
DATAS.index[nick.lower()]["born"] = extDate context.data.index[nick.lower()]["born"] = extDate
else: else:
ms = ModuleState("birthday") ms = ModuleState("birthday")
ms.setAttribute("name", nick.lower()) ms.setAttribute("name", nick.lower())
ms.setAttribute("born", extDate) ms.setAttribute("born", extDate)
DATAS.addChild(ms) context.data.addChild(ms)
save() context.save()
return Response("ok, c'est noté, %s est né le %s" return Response("ok, c'est noté, %s est né le %s"
% (nick, extDate.strftime("%A %d %B %Y à %H:%M")), % (nick, extDate.strftime("%A %d %B %Y à %H:%M")),
msg.channel, msg.channel,

View file

@ -4,6 +4,7 @@
from datetime import datetime, timezone from datetime import datetime, timezone
from nemubot import context
from nemubot.event import ModuleEvent from nemubot.event import ModuleEvent
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.countdown import countdown_format from nemubot.tools.countdown import countdown_format
@ -17,7 +18,7 @@ yrn = datetime.now(timezone.utc).year + 1
def load(context): 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 " print("You can append in your configuration some balise to "
"automaticaly wish an happy new year on some channels like:\n" "automaticaly wish an happy new year on some channels like:\n"
"<sayon hostid=\"nemubot@irc.freenode.net:6667\" " "<sayon hostid=\"nemubot@irc.freenode.net:6667\" "
@ -26,19 +27,19 @@ def load(context):
def bonneannee(): def bonneannee():
txt = "Bonne année %d !" % yrn txt = "Bonne année %d !" % yrn
print(txt) print(txt)
if CONF and CONF.hasNode("sayon"): if context.config and context.config.hasNode("sayon"):
for sayon in CONF.getNodes("sayon"): for sayon in context.config.getNodes("sayon"):
if "hostid" not in sayon or "channel" not in sayon: if "hostid" not in sayon or "channel" not in sayon:
print("Error: missing hostif or channel") print("Error: missing hostif or channel")
continue continue
srv = sayon["hostid"] srv = sayon["hostid"]
chan = sayon["channel"] chan = sayon["channel"]
send_response(srv, Response(txt, chan)) context.send_response(srv, Response(txt, chan))
d = datetime(yrn, 1, 1, 0, 0, 0, 0, d = datetime(yrn, 1, 1, 0, 0, 0, 0,
timezone.utc) - datetime.now(timezone.utc) timezone.utc) - datetime.now(timezone.utc)
add_event(ModuleEvent(interval=0, offset=d.total_seconds(), context.add_event(ModuleEvent(interval=0, offset=d.total_seconds(),
call=bonneannee)) call=bonneannee))
@hook("cmd_hook", "newyear") @hook("cmd_hook", "newyear")

View file

@ -4,6 +4,7 @@
import urllib import urllib
from nemubot import context
from nemubot.exception import IRCException 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
@ -14,7 +15,7 @@ from more import Response
def load(context): def load(context):
if not CONF or not CONF.hasNode("goodreadsapi") or not CONF.getNode("goodreadsapi").hasAttribute("key"): 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 " print ("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<goodreadsapi"
" key=\"XXXXXXXXXXXXXXXX\" />\nGet one at " " key=\"XXXXXXXXXXXXXXXX\" />\nGet one at "
@ -25,7 +26,7 @@ def load(context):
def get_book(title): def get_book(title):
"""Retrieve a book from its title""" """Retrieve a book from its title"""
response = web.getXML("https://www.goodreads.com/book/title.xml?key=%s&title=%s" % 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"): if response is not None and response.hasNode("book"):
return response.getNode("book") return response.getNode("book")
else: else:
@ -35,7 +36,7 @@ def get_book(title):
def search_books(title): def search_books(title):
"""Get a list of book matching given title""" """Get a list of book matching given title"""
response = web.getXML("https://www.goodreads.com/search.xml?key=%s&q=%s" % 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"): if response is not None and response.hasNode("search"):
return response.getNode("search").getNode("results").getNodes("work") return response.getNode("search").getNode("results").getNodes("work")
else: else:
@ -45,10 +46,10 @@ def search_books(title):
def search_author(name): def search_author(name):
"""Looking for an author""" """Looking for an author"""
response = web.getXML("https://www.goodreads.com/api/author_url/%s?key=%s" % 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"): 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" % 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"): if response is not None and response.hasNode("author"):
return response.getNode("author") return response.getNode("author")
return None return None

View file

@ -44,7 +44,6 @@ def cmd_conjug(msg):
"sa conjugaison!") "sa conjugaison!")
tens = ' '.join(msg.cmds[1:-1]) tens = ' '.join(msg.cmds[1:-1])
print_debug(tens)
verb = msg.cmds[-1] verb = msg.cmds[-1]
@ -60,7 +59,6 @@ def cmd_conjug(msg):
def get_conjug(verb, stringTens): def get_conjug(verb, stringTens):
url = ("http://leconjugueur.lefigaro.fr/conjugaison/verbe/%s.html" % url = ("http://leconjugueur.lefigaro.fr/conjugaison/verbe/%s.html" %
quote(verb.encode("ISO-8859-1"))) quote(verb.encode("ISO-8859-1")))
print_debug(url)
page = web.getURLContent(url) page = web.getURLContent(url)
if page is not None: if page is not None:

View file

@ -1,6 +1,5 @@
import urllib.request import urllib.request
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import pprint
from nemubot.hooks import hook from nemubot.hooks import hook
from more import Response from more import Response

View file

@ -4,6 +4,7 @@
import imp import imp
from nemubot import context
from nemubot.hooks import hook from nemubot.hooks import hook
nemubotversion = 3.4 nemubotversion = 3.4
@ -15,8 +16,7 @@ from . import UrbanDictionnary
from . import WFASearch from . import WFASearch
def load(context): def load(context):
global CONF WFASearch.CONF = context.config
WFASearch.CONF = CONF
def reload(): def reload():
imp.reload(DDGSearch) imp.reload(DDGSearch)

View file

@ -10,6 +10,7 @@ import time
import threading import threading
import traceback import traceback
from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IRCException
from nemubot.event import ModuleEvent from nemubot.event import ModuleEvent
from nemubot.hooks import hook from nemubot.hooks import hook
@ -22,28 +23,25 @@ nemubotversion = 3.4
from more import Response from more import Response
def help_full (): 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): def load(context):
global DATAS
#Define the index #Define the index
DATAS.setIndex("name") context.data.setIndex("name")
for evt in DATAS.index.keys(): for evt in context.data.index.keys():
if DATAS.index[evt].hasAttribute("end"): if context.data.index[evt].hasAttribute("end"):
event = ModuleEvent(call=fini, call_data=dict(strend=DATAS.index[evt])) event = ModuleEvent(call=fini, call_data=dict(strend=context.data.index[evt]))
if DATAS.index[evt]["server"] not in context.servers: event._end = context.data.index[evt].getDate("end")
print("WARNING: registering event for a unexistant server: %s, please connect to it." % DATAS.index[evt]["server"]) idt = context.add_event(event)
event._end = DATAS.index[evt].getDate("end")
idt = add_event(event)
if idt is not None: if idt is not None:
DATAS.index[evt]["_id"] = idt context.data.index[evt]["_id"] = idt
def fini(d, strend): def fini(d, strend):
send_response(strend["server"], Response("%s arrivé à échéance." % strend["name"], channel=strend["channel"], nick=strend["proprio"])) context.send_response(strend["server"], Response("%s arrivé à échéance." % strend["name"], channel=strend["channel"], nick=strend["proprio"]))
DATAS.delChild(DATAS.index[strend["name"]]) context.data.delChild(context.data.index[strend["name"]])
save() context.save()
@hook("cmd_hook", "goûter") @hook("cmd_hook", "goûter")
def cmd_gouter(msg): def cmd_gouter(msg):
@ -68,7 +66,7 @@ def start_countdown(msg):
"""!start /something/: launch a timer""" """!start /something/: launch a timer"""
if len(msg.cmds) < 2: if len(msg.cmds) < 2:
raise IRCException("indique le nom d'un événement à chronométrer") 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]) raise IRCException("%s existe déjà." % msg.cmds[1])
strnd = ModuleState("strend") strnd = ModuleState("strend")
@ -77,7 +75,7 @@ def start_countdown(msg):
strnd["proprio"] = msg.nick strnd["proprio"] = msg.nick
strnd["start"] = msg.date strnd["start"] = msg.date
strnd["name"] = msg.cmds[1] strnd["name"] = msg.cmds[1]
DATAS.addChild(strnd) context.data.addChild(strnd)
evt = ModuleEvent(call=fini, call_data=dict(strend=strnd)) evt = ModuleEvent(call=fini, call_data=dict(strend=strnd))
@ -106,9 +104,9 @@ def start_countdown(msg):
else: else:
strnd["end"] = datetime(now.year, now.month, now.day + 1, hou, minu, sec, timezone.utc) strnd["end"] = datetime(now.year, now.month, now.day + 1, hou, minu, sec, timezone.utc)
evt._end = strnd.getDate("end") evt._end = strnd.getDate("end")
strnd["_id"] = add_event(evt) strnd["_id"] = context.add_event(evt)
except: 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]) 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: elif result1 is not None and len(result1) > 0:
@ -127,11 +125,11 @@ def start_countdown(msg):
else: else:
strnd["end"] += timedelta(seconds=int(t)) strnd["end"] += timedelta(seconds=int(t))
evt._end = strnd.getDate("end") evt._end = strnd.getDate("end")
eid = add_event(evt) eid = context.add_event(evt)
if eid is not None: if eid is not None:
strnd["_id"] = eid strnd["_id"] = eid
save() context.save()
if "end" in strnd: if "end" in strnd:
return Response("%s commencé le %s et se terminera le %s." % return Response("%s commencé le %s et se terminera le %s." %
(msg.cmds[1], msg.date.strftime("%A %d %B %Y à %H:%M:%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: if len(msg.cmds) < 2:
raise IRCException("quel événement terminer ?") raise IRCException("quel événement terminer ?")
if msg.cmds[1] in DATAS.index: if msg.cmds[1] in context.data.index:
if DATAS.index[msg.cmds[1]]["proprio"] == msg.nick or (msg.cmds[0] == "forceend" and msg.frm_owner): if context.data.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")) duration = countdown(msg.date - context.data.index[msg.cmds[1]].getDate("start"))
del_event(DATAS.index[msg.cmds[1]]["_id"]) context.del_event(context.data.index[msg.cmds[1]]["_id"])
DATAS.delChild(DATAS.index[msg.cmds[1]]) context.data.delChild(context.data.index[msg.cmds[1]])
save() context.save()
return Response("%s a duré %s." % (msg.cmds[1], duration), return Response("%s a duré %s." % (msg.cmds[1], duration),
channel=msg.channel, nick=msg.nick) channel=msg.channel, nick=msg.nick)
else: 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: else:
return Response("%s n'est pas un compteur connu."% (msg.cmds[1]), channel=msg.channel, nick=msg.nick) 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: if len(msg.cmds) > 1:
res = list() res = list()
for user in msg.cmds[1:]: 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: if len(cmptr) > 0:
res.append("Compteurs créés par %s : %s" % (user, ", ".join(cmptr))) res.append("Compteurs créés par %s : %s" % (user, ", ".join(cmptr)))
else: else:
res.append("%s n'a pas créé de compteur" % user) res.append("%s n'a pas créé de compteur" % user)
return Response(" ; ".join(res), channel=msg.channel) return Response(" ; ".join(res), channel=msg.channel)
else: 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") @hook("cmd_default")
def parseanswer(msg): def parseanswer(msg):
if msg.cmds[0] in DATAS.index: if msg.cmds[0] in context.data.index:
res = Response(channel=msg.channel) res = Response(channel=msg.channel)
# Avoid message starting by ! which can be interpreted as command by other bots # Avoid message starting by ! which can be interpreted as command by other bots
if msg.cmds[0][0] == "!": if msg.cmds[0][0] == "!":
res.nick = msg.nick res.nick = msg.nick
if DATAS.index[msg.cmds[0]].name == "strend": if context.data.index[msg.cmds[0]].name == "strend":
if DATAS.index[msg.cmds[0]].hasAttribute("end"): 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 - DATAS.index[msg.cmds[0]].getDate("start")), countdown(DATAS.index[msg.cmds[0]].getDate("end") - msg.date))) 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: 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: 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 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) 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) name = re.match("^.*!([^ \"'@!]+).*$", msg.text)
if name is None: if name is None:
raise IRCException("il faut que tu attribues une commande à l'événement.") 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à.") 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) 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["start"] = extDate
evt["msg_after"] = msg_after evt["msg_after"] = msg_after
evt["msg_before"] = msg_before evt["msg_before"] = msg_before
DATAS.addChild(evt) context.data.addChild(evt)
save() context.save()
return Response("Nouvel événement !%s ajouté avec succès." % name.group(1), return Response("Nouvel événement !%s ajouté avec succès." % name.group(1),
channel=msg.channel) channel=msg.channel)
@ -243,8 +241,8 @@ def parseask(msg):
evt["proprio"] = msg.nick evt["proprio"] = msg.nick
evt["name"] = name.group(1) evt["name"] = name.group(1)
evt["msg_before"] = texts.group (2) evt["msg_before"] = texts.group (2)
DATAS.addChild(evt) context.data.addChild(evt)
save() context.save()
return Response("Nouvelle commande !%s ajoutée avec succès." % name.group(1), return Response("Nouvelle commande !%s ajoutée avec succès." % name.group(1),
channel=msg.channel) channel=msg.channel)

View file

@ -34,8 +34,6 @@ def get_movie(title=None, year=None, imdbid=None, fullplot=True, tomatoes=False)
if tomatoes: if tomatoes:
url += "tomatoes=true&" url += "tomatoes=true&"
print_debug(url)
# Make the request # Make the request
data = web.getJSON(url) data = web.getJSON(url)
@ -55,7 +53,6 @@ def find_movies(title):
# Built URL # Built URL
url = "http://www.omdbapi.com/?s=%s" % urllib.parse.quote(title) url = "http://www.omdbapi.com/?s=%s" % urllib.parse.quote(title)
print_debug(url)
# Make the request # Make the request
data = web.getJSON(url) data = web.getJSON(url)

View file

@ -14,7 +14,7 @@ from more import Response
def load(context): 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 " print ("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<mapquestapi"
" key=\"XXXXXXXXXXXXXXXX\" />\nRegister at " " key=\"XXXXXXXXXXXXXXXX\" />\nRegister at "
@ -22,7 +22,7 @@ def load(context):
return None return None
from nemubot.hooks.messagehook import MessageHook 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(): def help_full():
@ -31,7 +31,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("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]: if "results" in obj and "locations" in obj["results"][0]:
for loc in obj["results"][0]["locations"]: for loc in obj["results"][0]["locations"]:

View file

@ -19,7 +19,6 @@ def get_namespaces(site, ssl=False):
# Built URL # Built URL
url = "http%s://%s/w/api.php?format=json&action=query&meta=siteinfo&siprop=namespaces" % ( url = "http%s://%s/w/api.php?format=json&action=query&meta=siteinfo&siprop=namespaces" % (
"s" if ssl else "", site) "s" if ssl else "", site)
print_debug(url)
# Make the request # Make the request
data = web.getJSON(url) data = web.getJSON(url)
@ -34,7 +33,6 @@ def get_raw_page(site, term, ssl=False):
# Built URL # Built URL
url = "http%s://%s/w/api.php?format=json&redirects&action=query&prop=revisions&rvprop=content&titles=%s" % ( 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)) "s" if ssl else "", site, urllib.parse.quote(term))
print_debug(url)
# Make the request # Make the request
data = web.getJSON(url) data = web.getJSON(url)
@ -50,7 +48,6 @@ def get_unwikitextified(site, wikitext, ssl=False):
# Built URL # Built URL
url = "http%s://%s/w/api.php?format=json&action=expandtemplates&text=%s" % ( url = "http%s://%s/w/api.php?format=json&action=expandtemplates&text=%s" % (
"s" if ssl else "", site, urllib.parse.quote(wikitext)) "s" if ssl else "", site, urllib.parse.quote(wikitext))
print_debug(url)
# Make the request # Make the request
data = web.getJSON(url) data = web.getJSON(url)
@ -107,7 +104,6 @@ def opensearch(site, term, ssl=False):
# Built URL # Built URL
url = "http%s://%s/w/api.php?format=xml&action=opensearch&search=%s" % ( url = "http%s://%s/w/api.php?format=xml&action=opensearch&search=%s" % (
"s" if ssl else "", site, urllib.parse.quote(term)) "s" if ssl else "", site, urllib.parse.quote(term))
print_debug(url)
# Make the request # Make the request
response = web.getXML(url) response = web.getXML(url)
@ -123,7 +119,6 @@ def search(site, term, ssl=False):
# Built URL # Built URL
url = "http%s://%s/w/api.php?format=json&action=query&list=search&srsearch=%s&srprop=titlesnippet|snippet" % ( 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)) "s" if ssl else "", site, urllib.parse.quote(term))
print_debug(url)
# Make the request # Make the request
data = web.getJSON(url) data = web.getJSON(url)

View file

@ -17,15 +17,14 @@ from . import whois
def load(context): def load(context):
for mod in [isup, page, w3c, watchWebsite, whois]: for mod in [isup, page, w3c, watchWebsite, whois]:
mod.add_event = add_event mod.add_event = context.add_event
mod.del_event = del_event mod.del_event = context.del_event
mod.save = save mod.save = context.save
mod.print = print mod.print = print
mod.print_debug = print_debug mod.send_response = context.send_response
mod.send_response = send_response page.load(context.config, context.add_hook)
page.load(CONF, add_hook) watchWebsite.load(context.data)
watchWebsite.load(DATAS) whois.load(context.config, context.add_hook)
whois.load(CONF, add_hook)
def help_full(): def help_full():

View file

@ -185,7 +185,7 @@ def start_watching(site, offset=0):
""" """
o = urlparse(site["url"], "http") 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), evt = ModuleEvent(func=lambda url: page.render(url, None),
cmp_data=site["lastcontent"], cmp_data=site["lastcontent"],

View file

@ -9,6 +9,7 @@ import urllib.error
import urllib.request import urllib.request
import urllib.parse import urllib.parse
from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IRCException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.xmlparser.node import ModuleState from nemubot.tools.xmlparser.node import ModuleState
@ -18,8 +19,7 @@ nemubotversion = 3.4
from more import Response from more import Response
def load(context): def load(context):
global DATAS context.data.setIndex("name", "phone")
DATAS.setIndex("name", "phone")
def help_full(): def help_full():
return "!sms /who/[,/who/[,...]] message: send a SMS to /who/." return "!sms /who/[,/who/[,...]] message: send a SMS to /who/."
@ -55,20 +55,20 @@ def cmd_sms(msg):
# Check dests # Check dests
cur_epoch = time.mktime(time.localtime()); cur_epoch = time.mktime(time.localtime());
for u in msg.cmds[1].split(","): 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) 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) raise IRCException("Un peu de calme, %s a déjà reçu un SMS il n'y a pas si longtemps." % u)
# Go! # Go!
fails = list() fails = list()
for u in msg.cmds[1].split(","): 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: if msg.to_response[0] == msg.frm:
frm = msg.frm frm = msg.frm
else: else:
frm = msg.frm + "@" + msg.to[0] 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: if test is not None:
fails.append( "%s: %s" % (u, test) ) fails.append( "%s: %s" % (u, test) )
@ -96,16 +96,16 @@ def parseask(msg):
if test is not None: if test is not None:
return Response("je n'ai pas pu enregistrer tes identifiants : %s" % test, msg.channel, msg.nick) return Response("je n'ai pas pu enregistrer tes identifiants : %s" % test, msg.channel, msg.nick)
if msg.nick in DATAS.index: if msg.nick in context.data.index:
DATAS.index[msg.nick]["user"] = apiuser context.data.index[msg.nick]["user"] = apiuser
DATAS.index[msg.nick]["key"] = apikey context.data.index[msg.nick]["key"] = apikey
else: else:
ms = ModuleState("phone") ms = ModuleState("phone")
ms.setAttribute("name", msg.nick) ms.setAttribute("name", msg.nick)
ms.setAttribute("user", apiuser) ms.setAttribute("user", apiuser)
ms.setAttribute("key", apikey) ms.setAttribute("key", apikey)
ms.setAttribute("lastuse", 0) ms.setAttribute("lastuse", 0)
DATAS.addChild(ms) context.data.addChild(ms)
save() context.save()
return Response("ok, c'est noté. Je t'ai envoyé un SMS pour tester ;)", return Response("ok, c'est noté. Je t'ai envoyé un SMS pour tester ;)",
msg.channel, msg.nick) msg.channel, msg.nick)

View file

@ -20,12 +20,12 @@ SMILEY = list()
CORRECTIONS = list() CORRECTIONS = list()
def load(context): def load(context):
for smiley in CONF.getNodes("smiley"): for smiley in context.config.getNodes("smiley"):
if smiley.hasAttribute("txt") and smiley.hasAttribute("mood"): if smiley.hasAttribute("txt") and smiley.hasAttribute("mood"):
SMILEY.append((smiley.getAttribute("txt"), smiley.getAttribute("mood"))) SMILEY.append((smiley.getAttribute("txt"), smiley.getAttribute("mood")))
print ("%d smileys loaded" % len(SMILEY)) 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"): if correct.hasAttribute("bad") and correct.hasAttribute("good"):
CORRECTIONS.append((" " + (correct.getAttribute("bad") + " "), (" " + correct.getAttribute("good") + " "))) CORRECTIONS.append((" " + (correct.getAttribute("bad") + " "), (" " + correct.getAttribute("good") + " ")))
print ("%d corrections loaded" % len(CORRECTIONS)) print ("%d corrections loaded" % len(CORRECTIONS))
@ -38,7 +38,6 @@ class Speaker(Thread):
while not queue.empty(): while not queue.empty():
sentence = queue.get_nowait() sentence = queue.get_nowait()
lang = "fr" lang = "fr"
print_debug(sentence)
subprocess.call(["espeak", "-v", lang, "--", sentence]) subprocess.call(["espeak", "-v", lang, "--", sentence])
queue.task_done() queue.task_done()

View file

@ -5,6 +5,7 @@
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.hooks import hook
from nemubot.tools.xmlparser.node import ModuleState from nemubot.tools.xmlparser.node import ModuleState
@ -20,8 +21,7 @@ def help_full():
return "!spell [<lang>] <word>: give the correct spelling of <word> in <lang=fr>." return "!spell [<lang>] <word>: give the correct spelling of <word> in <lang=fr>."
def load(context): def load(context):
global DATAS context.data.setIndex("name", "score")
DATAS.setIndex("name", "score")
@hook("cmd_hook", "spell") @hook("cmd_hook", "spell")
def cmd_spell(msg): def cmd_spell(msg):
@ -50,27 +50,25 @@ def cmd_spell(msg):
return Response(strRes, channel=msg.channel, nick=msg.nick) return Response(strRes, channel=msg.channel, nick=msg.nick)
def add_score(nick, t): def add_score(nick, t):
global DATAS if nick not in context.data.index:
if nick not in DATAS.index:
st = ModuleState("score") st = ModuleState("score")
st["name"] = nick st["name"] = nick
DATAS.addChild(st) context.data.addChild(st)
if DATAS.index[nick].hasAttribute(t): if context.data.index[nick].hasAttribute(t):
DATAS.index[nick][t] = DATAS.index[nick].getInt(t) + 1 context.data.index[nick][t] = context.data.index[nick].getInt(t) + 1
else: else:
DATAS.index[nick][t] = 1 context.data.index[nick][t] = 1
save() context.save()
@hook("cmd_hook", "spellscore") @hook("cmd_hook", "spellscore")
def cmd_score(msg): def cmd_score(msg):
global DATAS
res = list() res = list()
unknown = list() unknown = list()
if len(msg.cmds) > 1: if len(msg.cmds) > 1:
for cmd in msg.cmds[1:]: for cmd in msg.cmds[1:]:
if cmd in DATAS.index: if cmd in context.data.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)) 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: else:
unknown.append(cmd) unknown.append(cmd)
else: else:

View file

@ -21,18 +21,17 @@ def help_full():
def load(context): def load(context):
global lang_binding 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 " print ("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<bighugelabs"
" key=\"XXXXXXXXXXXXXXXX\" />\nRegister at " " key=\"XXXXXXXXXXXXXXXX\" />\nRegister at "
"https://words.bighugelabs.com/getkey.php") "https://words.bighugelabs.com/getkey.php")
else: 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): def get_french_synos(word):
url = "http://www.crisco.unicaen.fr/des/synonymes/" + quote(word.encode("ISO-8859-1")) url = "http://www.crisco.unicaen.fr/des/synonymes/" + quote(word.encode("ISO-8859-1"))
print_debug(url)
page = web.getURLContent(url) page = web.getURLContent(url)
best = list(); synos = list(); anton = list() best = list(); synos = list(); anton = list()

View file

@ -15,16 +15,16 @@ URL_TPBAPI = None
def load(context): def load(context):
global URL_TPBAPI 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 " print ("You need a TPB API in order to use the !tpb feature. Add it to "
"the module configuration file:\n" "the module configuration file:\n"
"<tpbapi url=\"http://tpbapi.org/\" />\nSample API: " "<tpbapi url=\"http://tpbapi.org/\" />\nSample API: "
"https://gist.github.com/colona/07a925f183cfb47d5f20") "https://gist.github.com/colona/07a925f183cfb47d5f20")
else: else:
URL_TPBAPI = CONF.getNode("tpbapi")["url"] URL_TPBAPI = context.config.getNode("tpbapi")["url"]
from nemubot.hooks.messagehook import MessageHook 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): def cmd_tpb(msg):

View file

@ -19,17 +19,17 @@ URL = "http://api.wordreference.com/0.8/%s/json/%%s%%s/%%s"
def load(context): def load(context):
global URL 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." print ("You need a WordReference API key in order to use this module."
" Add it to the module configuration file:\n<wrapi key=\"XXXXX\"" " Add it to the module configuration file:\n<wrapi key=\"XXXXX\""
" />\nRegister at " " />\nRegister at "
"http://www.wordreference.com/docs/APIregistration.aspx") "http://www.wordreference.com/docs/APIregistration.aspx")
return None return None
else: else:
URL = URL % CONF.getNode("wrapi")["key"] URL = URL % context.config.getNode("wrapi")["key"]
from nemubot.hooks.messagehook import MessageHook 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(): def help_full():

View file

@ -4,6 +4,7 @@
import re import re
from nemubot import context
from nemubot.exception import IRCException 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
@ -14,8 +15,7 @@ from more import Response
def load(context): def load(context):
global DATAS context.data.setIndex("name", "station")
DATAS.setIndex("name", "station")
# evt = ModuleEvent(station_available, "42706", # evt = ModuleEvent(station_available, "42706",
# (lambda a, b: a != b), None, 60, # (lambda a, b: a != b), None, 60,
@ -30,7 +30,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(CONF.getNode("server")["url"] + station) response = web.getXML(context.config.getNode("server")["url"] + 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:
@ -72,7 +72,6 @@ def print_station_status(msg, station):
@hook("cmd_hook", "velib") @hook("cmd_hook", "velib")
def ask_stations(msg): def ask_stations(msg):
"""Hook entry from !velib""" """Hook entry from !velib"""
global DATAS
if len(msg.cmds) > 5: if len(msg.cmds) > 5:
raise IRCException("demande-moi moins de stations à la fois.") raise IRCException("demande-moi moins de stations à la fois.")
@ -80,9 +79,9 @@ def ask_stations(msg):
for station in msg.cmds[1:]: for station in msg.cmds[1:]:
if re.match("^[0-9]{4,5}$", station): if re.match("^[0-9]{4,5}$", station):
return print_station_status(msg, station) return print_station_status(msg, station)
elif station in DATAS.index: elif station in context.data.index:
return print_station_status(msg, return print_station_status(msg,
DATAS.index[station]["number"]) context.data.index[station]["number"])
else: else:
raise IRCException("numéro de station invalide.") raise IRCException("numéro de station invalide.")

View file

@ -6,6 +6,7 @@ import datetime
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.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -19,10 +20,9 @@ from more import Response
def load(context): def load(context):
global DATAS context.data.setIndex("name", "city")
DATAS.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 " print ("You need a Dark-Sky API key in order to use this "
"module. Add it to the module configuration file:\n<darkskyapi" "module. Add it to the module configuration file:\n<darkskyapi"
" key=\"XXXXXXXXXXXXXXXX\" />\nRegister at " " key=\"XXXXXXXXXXXXXXXX\" />\nRegister at "
@ -30,9 +30,9 @@ def load(context):
return None return None
from nemubot.hooks.messagehook import MessageHook from nemubot.hooks.messagehook import MessageHook
add_hook("cmd_hook", MessageHook(cmd_weather, "météo")) context.add_hook("cmd_hook", MessageHook(cmd_weather, "météo"))
add_hook("cmd_hook", MessageHook(cmd_alert, "alert")) context.add_hook("cmd_hook", MessageHook(cmd_alert, "alert"))
add_hook("cmd_hook", MessageHook(cmd_coordinates, "coordinates")) context.add_hook("cmd_hook", MessageHook(cmd_coordinates, "coordinates"))
def help_full (): def help_full ():
@ -111,10 +111,10 @@ def treat_coord(msg):
except ValueError: except ValueError:
pass pass
if city in DATAS.index: if city in context.data.index:
coords = list() coords = list()
coords.append(DATAS.index[city]["lat"]) coords.append(context.data.index[city]["lat"])
coords.append(DATAS.index[city]["long"]) coords.append(context.data.index[city]["long"])
return city, coords, specific return city, coords, specific
else: else:
@ -132,7 +132,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" % (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 # First read flags
if "darksky-unavailable" in wth["flags"]: if "darksky-unavailable" in wth["flags"]:
@ -146,10 +146,10 @@ def cmd_coordinates(msg):
raise IRCException("indique-moi un nom de ville.") raise IRCException("indique-moi un nom de ville.")
j = msg.args[0].lower() 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]) 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) 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_lat = res.group("lat").replace(",", ".")
gps_long = res.group("long").replace(",", ".") gps_long = res.group("long").replace(",", ".")
if city_name in DATAS.index: if city_name in context.data.index:
DATAS.index[city_name]["lat"] = gps_lat context.data.index[city_name]["lat"] = gps_lat
DATAS.index[city_name]["long"] = gps_long context.data.index[city_name]["long"] = gps_long
else: else:
ms = ModuleState("city") ms = ModuleState("city")
ms.setAttribute("name", city_name) ms.setAttribute("name", city_name)
ms.setAttribute("lat", gps_lat) ms.setAttribute("lat", gps_lat)
ms.setAttribute("long", gps_long) ms.setAttribute("long", gps_long)
DATAS.addChild(ms) context.data.addChild(ms)
save() context.save()
return Response("ok, j'ai bien noté les coordonnées de %s" % res.group("city"), return Response("ok, j'ai bien noté les coordonnées de %s" % res.group("city"),
msg.channel, msg.nick) msg.channel, msg.nick)

View file

@ -8,6 +8,7 @@ import re
from urllib.parse import quote from urllib.parse import quote
from urllib.request import urlopen from urllib.request import urlopen
from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IRCException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.xmlparser.node import ModuleState from nemubot.tools.xmlparser.node import ModuleState
@ -20,7 +21,7 @@ API_URL="http://worldcup.sfg.io/%s"
def load(context): def load(context):
from nemubot.event import ModuleEvent 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 (): def help_full ():
@ -28,31 +29,29 @@ def help_full ():
def start_watch(msg): def start_watch(msg):
global DATAS
w = ModuleState("watch") w = ModuleState("watch")
w["server"] = msg.server w["server"] = msg.server
w["channel"] = msg.channel w["channel"] = msg.channel
w["proprio"] = msg.nick w["proprio"] = msg.nick
w["start"] = datetime.now(timezone.utc) w["start"] = datetime.now(timezone.utc)
DATAS.addChild(w) context.data.addChild(w)
save() context.save()
raise IRCException("This channel is now watching world cup events!") raise IRCException("This channel is now watching world cup events!")
@hook("cmd_hook", "watch_worldcup") @hook("cmd_hook", "watch_worldcup")
def cmd_watch(msg): def cmd_watch(msg):
global DATAS
# Get current state # Get current state
node = None node = None
for n in DATAS.getChilds(): for n in context.data.getChilds():
if n["server"] == msg.server and n["channel"] == msg.channel: if n["server"] == msg.server and n["channel"] == msg.channel:
node = n node = n
break break
if len(msg.cmds) >= 2: if len(msg.cmds) >= 2:
if msg.cmds[1] == "stop" and node is not None: if msg.cmds[1] == "stop" and node is not None:
DATAS.delChild(node) context.data.delChild(node)
save() context.save()
raise IRCException("This channel will not anymore receives world cup events.") raise IRCException("This channel will not anymore receives world cup events.")
elif msg.cmds[1] == "start" and node is None: elif msg.cmds[1] == "start" and node is None:
start_watch(msg) start_watch(msg)
@ -62,14 +61,12 @@ def cmd_watch(msg):
if node is None: if node is None:
start_watch(msg) start_watch(msg)
else: else:
DATAS.delChild(node) context.data.delChild(node)
save() context.save()
raise IRCException("This channel will not anymore receives world cup events.") raise IRCException("This channel will not anymore receives world cup events.")
def current_match_new_action(match_str, osef): def current_match_new_action(match_str, osef):
global DATAS 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))
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) matches = json.loads(match_str)
@ -81,8 +78,8 @@ def current_match_new_action(match_str, osef):
if len(events) > 0: if len(events) > 0:
msg += " ; à la " + txt_event(events[0]) msg += " ; à la " + txt_event(events[0])
for n in DATAS.getChilds(): for n in context.data.getChilds():
send_response(n["server"], Response(msg, channel=n["channel"])) context.send_response(n["server"], Response(msg, channel=n["channel"]))
def is_int(s): def is_int(s):
try: try:

View file

@ -30,7 +30,6 @@ def reduce(url):
""" """
snd_url = "http://ycc.fr/redirection/create/" + quote(url, "/:%@&=?") snd_url = "http://ycc.fr/redirection/create/" + quote(url, "/:%@&=?")
print_debug(snd_url)
return web.getURLContent(snd_url) return web.getURLContent(snd_url)