Using newly added Python decorator for hook registration

This commit is contained in:
nemunaire 2014-08-12 20:10:19 +02:00
parent 23bc61cce0
commit fe0f120038
19 changed files with 119 additions and 147 deletions

View File

@ -4,19 +4,12 @@ import re
import sys import sys
from datetime import datetime from datetime import datetime
from hooks import hook
nemubotversion = 3.3 nemubotversion = 3.3
def load(context): def load(context):
"""Load this module""" """Load this module"""
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_listalias, "listalias"))
add_hook("cmd_hook", Hook(cmd_listvars, "listvars"))
add_hook("cmd_hook", Hook(cmd_unalias, "unalias"))
add_hook("cmd_hook", Hook(cmd_alias, "alias"))
add_hook("cmd_hook", Hook(cmd_set, "set"))
add_hook("all_pre", Hook(treat_alias))
add_hook("all_post", Hook(treat_variables))
global DATAS global DATAS
if not DATAS.hasNode("aliases"): if not DATAS.hasNode("aliases"):
DATAS.addChild(ModuleState("aliases")) DATAS.addChild(ModuleState("aliases"))
@ -56,6 +49,7 @@ def get_variable(name, msg=None):
else: else:
return "" return ""
@hook("cmd_hook", "set")
def cmd_set(msg): def cmd_set(msg):
if len (msg.cmds) > 2: if len (msg.cmds) > 2:
set_variable(msg.cmds[1], " ".join(msg.cmds[2:]), msg.nick) set_variable(msg.cmds[1], " ".join(msg.cmds[2:]), msg.nick)
@ -64,6 +58,7 @@ def cmd_set(msg):
return res return res
return Response(msg.sender, "!set prend au minimum deux arguments : le nom de la variable et sa valeur.") return Response(msg.sender, "!set prend au minimum deux arguments : le nom de la variable et sa valeur.")
@hook("cmd_hook", "listalias")
def cmd_listalias(msg): def cmd_listalias(msg):
if len(msg.cmds) > 1: if len(msg.cmds) > 1:
res = list() res = list()
@ -77,6 +72,7 @@ def cmd_listalias(msg):
else: else:
return Response(msg.sender, "Alias connus : %s." % ", ".join(DATAS.getNode("aliases").index.keys()), channel=msg.channel) return Response(msg.sender, "Alias connus : %s." % ", ".join(DATAS.getNode("aliases").index.keys()), channel=msg.channel)
@hook("cmd_hook", "listvars")
def cmd_listvars(msg): def cmd_listvars(msg):
if len(msg.cmds) > 1: if len(msg.cmds) > 1:
res = list() res = list()
@ -90,6 +86,7 @@ def cmd_listvars(msg):
else: else:
return Response(msg.sender, "Variables connues : %s." % ", ".join(DATAS.getNode("variables").index.keys()), channel=msg.channel) return Response(msg.sender, "Variables connues : %s." % ", ".join(DATAS.getNode("variables").index.keys()), channel=msg.channel)
@hook("cmd_hook", "alias")
def cmd_alias(msg): def cmd_alias(msg):
if len (msg.cmds) > 1: if len (msg.cmds) > 1:
res = list() res = list()
@ -108,6 +105,7 @@ def cmd_alias(msg):
return Response(msg.sender, "!alias prend en argument l'alias à étendre.", return Response(msg.sender, "!alias prend en argument l'alias à étendre.",
channel=msg.channel) channel=msg.channel)
@hook("cmd_hook", "unalias")
def cmd_unalias(msg): def cmd_unalias(msg):
if len (msg.cmds) > 1: if len (msg.cmds) > 1:
res = list() res = list()
@ -145,6 +143,7 @@ def replace_variables(cnt, msg=None):
return " ".join(cnt) return " ".join(cnt)
@hook("all_post")
def treat_variables(res): def treat_variables(res):
for i in range(0, len(res.messages)): for i in range(0, len(res.messages)):
if isinstance(res.messages[i], list): if isinstance(res.messages[i], list):
@ -153,6 +152,7 @@ def treat_variables(res):
res.messages[i] = replace_variables(res.messages[i], res) res.messages[i] = replace_variables(res.messages[i], res)
return True return True
@hook("all_pre")
def treat_alias(msg, hooks_cache): def treat_alias(msg, hooks_cache):
if msg.cmd == "PRIVMSG": if msg.cmd == "PRIVMSG":
if len(msg.cmds) > 0 and (len(msg.cmds[0]) > 0 if len(msg.cmds) > 0 and (len(msg.cmds[0]) > 0

View File

@ -5,15 +5,12 @@ import sys
from datetime import datetime from datetime import datetime
from datetime import date from datetime import date
from hooks import hook
from xmlparser.node import ModuleState from xmlparser.node import ModuleState
nemubotversion = 3.3 nemubotversion = 3.3
def load(context): def load(context):
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_anniv, "anniv"))
add_hook("cmd_hook", Hook(cmd_age, "age"))
global DATAS global DATAS
DATAS.setIndex("name", "birthday") DATAS.setIndex("name", "birthday")
@ -44,6 +41,7 @@ def findName(msg):
return (matches, name) return (matches, name)
@hook("cmd_hook", "anniv")
def cmd_anniv(msg): def cmd_anniv(msg):
(matches, name) = findName(msg) (matches, name) = findName(msg)
if len(matches) == 1: if len(matches) == 1:
@ -71,6 +69,7 @@ def cmd_anniv(msg):
" de %s. Quand est-il né ?" % name, " de %s. Quand est-il né ?" % name,
msg.channel, msg.nick) msg.channel, msg.nick)
@hook("cmd_hook", "age")
def cmd_age(msg): def cmd_age(msg):
(matches, name) = findName(msg) (matches, name) = findName(msg)
if len(matches) == 1: if len(matches) == 1:

View File

@ -2,24 +2,17 @@
from datetime import datetime from datetime import datetime
from hooks import hook
nemubotversion = 3.3 nemubotversion = 3.3
yr = datetime.today().year
yrn = datetime.today().year + 1
def load(context): def load(context):
yr = datetime.today().year
yrn = datetime.today().year + 1
d = datetime(yrn, 1, 1, 0, 0, 0) - datetime.now() d = datetime(yrn, 1, 1, 0, 0, 0) - datetime.now()
# d = datetime(yr, 12, 31, 19, 34, 0) - datetime.now()
add_event(ModuleEvent(intervalle=0, offset=d.total_seconds(), call=bonneannee)) add_event(ModuleEvent(intervalle=0, offset=d.total_seconds(), call=bonneannee))
from hooks import Hook
add_hook("cmd_rgxp", Hook(cmd_timetoyear, data=yrn, regexp="^[0-9]{4}$"))
add_hook("cmd_hook", Hook(cmd_newyear, str(yrn), yrn))
add_hook("cmd_hook", Hook(cmd_newyear, "ny", yrn))
add_hook("cmd_hook", Hook(cmd_newyear, "newyear", yrn))
add_hook("cmd_hook", Hook(cmd_newyear, "new-year", yrn))
add_hook("cmd_hook", Hook(cmd_newyear, "new year", yrn))
def bonneannee(): def bonneannee():
txt = "Bonne année %d !" % datetime.today().year txt = "Bonne année %d !" % datetime.today().year
print (txt) print (txt)
@ -27,10 +20,11 @@ def bonneannee():
send_response("localhost:2771", Response(None, txt, "#yaka")) send_response("localhost:2771", Response(None, txt, "#yaka"))
send_response("localhost:2771", Response(None, txt, "#epita2014")) send_response("localhost:2771", Response(None, txt, "#epita2014"))
send_response("localhost:2771", Response(None, txt, "#ykar")) send_response("localhost:2771", Response(None, txt, "#ykar"))
send_response("localhost:2771", Response(None, txt, "#ordissimo"))
send_response("localhost:2771", Response(None, txt, "#42sh")) send_response("localhost:2771", Response(None, txt, "#42sh"))
send_response("localhost:2771", Response(None, txt, "#nemubot")) send_response("localhost:2771", Response(None, txt, "#nemubot"))
@hook("cmd_hook", "newyear")
@hook("cmd_hook", str(yrn), yrn)
def cmd_newyear(msg, yr): def cmd_newyear(msg, yr):
return Response(msg.sender, return Response(msg.sender,
msg.countdown_format(datetime(yr, 1, 1, 0, 0, 1), msg.countdown_format(datetime(yr, 1, 1, 0, 0, 1),
@ -38,6 +32,7 @@ def cmd_newyear(msg, yr):
"Nous faisons déjà la fête depuis %s !"), "Nous faisons déjà la fête depuis %s !"),
channel=msg.channel) channel=msg.channel)
@hook("cmd_rgxp", data=yrn, regexp="^[0-9]{4}$")
def cmd_timetoyear(msg, cur): def cmd_timetoyear(msg, cur):
yr = int(msg.cmds[0]) yr = int(msg.cmds[0])

View File

@ -5,6 +5,7 @@ import traceback
import sys import sys
from urllib.parse import quote from urllib.parse import quote
from hooks import hook
from tools import web from tools import web
from tools.web import striphtml from tools.web import striphtml
from collections import defaultdict from collections import defaultdict
@ -27,17 +28,14 @@ d = defaultdict(list)
for k, v in s: for k, v in s:
d[k].append(v) d[k].append(v)
def help_tiny (): def help_tiny():
return "Find french conjugaison" return "Find french conjugaison"
def help_full (): def help_full():
return "!conjugaison <tens> <verb>: give the conjugaison for <verb> in <tens>." return "!conjugaison <tens> <verb>: give the conjugaison for <verb> in <tens>."
def load(context):
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_conjug, "conjugaison"))
@hook("cmd_hook", "conjugaison", help="!conjugaison <tens> <verb>: give the conjugaison for <verb> in <tens>.")
def cmd_conjug(msg): def cmd_conjug(msg):
if len(msg.cmds) < 3: if len(msg.cmds) < 3:
raise IRCException("donne moi un temps et un verbe, et je te donnerai sa conjugaison!") raise IRCException("donne moi un temps et un verbe, et je te donnerai sa conjugaison!")
@ -50,8 +48,8 @@ def cmd_conjug(msg):
conjug = get_conjug(verb, tens) conjug = get_conjug(verb, tens)
if len(conjug) > 0: if len(conjug) > 0:
return Response(msg.sender, conjug, channel=msg.channel, return Response(msg.sender, conjug, channel=msg.channel,
title="Conjugaison de %s" % verb) title="Conjugaison de %s" % verb)
else: else:
raise IRCException("aucune conjugaison de '%s' n'a été trouvé" % verb) raise IRCException("aucune conjugaison de '%s' n'a été trouvé" % verb)

View File

@ -10,7 +10,7 @@ class Wikipedia:
def __init__(self, terms, lang="fr", site="wikipedia.org", section=0): def __init__(self, terms, lang="fr", site="wikipedia.org", section=0):
self.terms = terms self.terms = terms
self.lang = lang self.lang = lang
self.curRT = 0 self.curRT = section
raw = urllib.request.urlopen(urllib.request.Request("http://" + self.lang + "." + site + "/w/api.php?format=xml&redirects&action=query&prop=revisions&rvprop=content&titles=%s" % (quote(terms)), headers={"User-agent": "Nemubot v3"})) raw = urllib.request.urlopen(urllib.request.Request("http://" + self.lang + "." + site + "/w/api.php?format=xml&redirects&action=query&prop=revisions&rvprop=content&titles=%s" % (quote(terms)), headers={"User-agent": "Nemubot v3"}))
self.wres = xmlparser.parse_string(raw.read()) self.wres = xmlparser.parse_string(raw.read())
@ -18,7 +18,7 @@ class Wikipedia:
self.wres = None self.wres = None
else: else:
self.wres = self.wres.getFirstNode("query").getFirstNode("pages").getFirstNode("page").getFirstNode("revisions").getFirstNode("rev").getContent() self.wres = self.wres.getFirstNode("query").getFirstNode("pages").getFirstNode("page").getFirstNode("revisions").getFirstNode("rev").getContent()
self.wres = striplink(self.wres) self.wres = striplink(self.wres)
@property @property
def nextRes(self): def nextRes(self):

View File

@ -2,6 +2,8 @@
import imp import imp
from hooks import hook
nemubotversion = 3.3 nemubotversion = 3.3
from . import DDGSearch from . import DDGSearch
@ -13,17 +15,6 @@ def load(context):
global CONF global CONF
WFASearch.CONF = CONF WFASearch.CONF = CONF
from hooks import Hook
add_hook("cmd_hook", Hook(define, "define"))
add_hook("cmd_hook", Hook(search, "search"))
add_hook("cmd_hook", Hook(search, "ddg"))
add_hook("cmd_hook", Hook(search, "g"))
add_hook("cmd_hook", Hook(calculate, "wa"))
add_hook("cmd_hook", Hook(calculate, "calc"))
add_hook("cmd_hook", Hook(wiki, "dico"))
add_hook("cmd_hook", Hook(wiki, "wiki"))
add_hook("cmd_hook", Hook(udsearch, "urbandictionnary"))
def reload(): def reload():
imp.reload(DDGSearch) imp.reload(DDGSearch)
imp.reload(UrbanDictionnary) imp.reload(UrbanDictionnary)
@ -31,6 +22,7 @@ def reload():
imp.reload(Wikipedia) imp.reload(Wikipedia)
@hook("cmd_hook", "define")
def define(msg): def define(msg):
if len(msg.cmds) <= 1: if len(msg.cmds) <= 1:
return Response(msg.sender, return Response(msg.sender,
@ -45,7 +37,7 @@ def define(msg):
return res return res
@hook("cmd_hook", "search")
def search(msg): def search(msg):
if len(msg.cmds) <= 1: if len(msg.cmds) <= 1:
return Response(msg.sender, return Response(msg.sender,
@ -68,6 +60,7 @@ def search(msg):
return res return res
@hook("cmd_hook", "urbandictionnary")
def udsearch(msg): def udsearch(msg):
if len(msg.cmds) <= 1: if len(msg.cmds) <= 1:
return Response(msg.sender, return Response(msg.sender,
@ -85,6 +78,7 @@ def udsearch(msg):
return res return res
@hook("cmd_hook", "calculate")
def calculate(msg): def calculate(msg):
if len(msg.cmds) <= 1: if len(msg.cmds) <= 1:
return Response(msg.sender, return Response(msg.sender,
@ -104,7 +98,19 @@ def calculate(msg):
return Response(msg.sender, s.error, msg.channel) return Response(msg.sender, s.error, msg.channel)
def wiki(msg): @hook("cmd_hook", "wikipedia")
def wikipedia(msg):
return wiki("wikipedia.org", 0, msg)
@hook("cmd_hook", "wiktionary")
def wiktionary(msg):
return wiki("wiktionary.org", 1, msg)
@hook("cmd_hook", "etymology")
def wiktionary(msg):
return wiki("wiktionary.org", 0, msg)
def wiki(site, section, msg):
if len(msg.cmds) <= 1: if len(msg.cmds) <= 1:
return Response(msg.sender, return Response(msg.sender,
"Indicate a term to search", "Indicate a term to search",
@ -115,12 +121,6 @@ def wiki(msg):
else: else:
lang = "fr" lang = "fr"
extract = 1 extract = 1
if msg.cmds[0] == "dico":
site = "wiktionary.org"
section = 1
else:
site = "wikipedia.org"
section = 0
s = Wikipedia.Wikipedia(' '.join(msg.cmds[extract:]), lang, site, section) s = Wikipedia.Wikipedia(' '.join(msg.cmds[extract:]), lang, site, section)

View File

@ -12,7 +12,7 @@ import traceback
nemubotversion = 3.3 nemubotversion = 3.3
from event import ModuleEvent from event import ModuleEvent
from hooks import Hook from hooks import Hook, hook
def help_tiny (): def help_tiny ():
"""Line inserted in the response to the command !help""" """Line inserted in the response to the command !help"""
@ -26,14 +26,6 @@ def load(context):
#Define the index #Define the index
DATAS.setIndex("name") DATAS.setIndex("name")
add_hook("cmd_hook", Hook(start_countdown, "start"))
add_hook("cmd_hook", Hook(end_countdown, "end"))
add_hook("cmd_hook", Hook(end_countdown, "forceend"))
add_hook("cmd_hook", Hook(liste, "eventslist"))
add_hook("cmd_hook", Hook(cmd_gouter, "goûter"))
add_hook("cmd_hook", Hook(cmd_we, "week-end"))
for evt in DATAS.index.keys(): for evt in DATAS.index.keys():
if DATAS.index[evt].hasAttribute("end"): if DATAS.index[evt].hasAttribute("end"):
event = ModuleEvent(call=fini, call_data=dict(strend=DATAS.index[evt])) event = ModuleEvent(call=fini, call_data=dict(strend=DATAS.index[evt]))
@ -48,6 +40,7 @@ def fini(d, strend):
DATAS.delChild(DATAS.index[strend["name"]]) DATAS.delChild(DATAS.index[strend["name"]])
save() save()
@hook("cmd_hook", "goûter")
def cmd_gouter(msg): def cmd_gouter(msg):
ndate = datetime.today() ndate = datetime.today()
ndate = datetime(ndate.year, ndate.month, ndate.day, 16, 42) ndate = datetime(ndate.year, ndate.month, ndate.day, 16, 42)
@ -57,6 +50,7 @@ def cmd_gouter(msg):
"Nous avons %s de retard pour le goûter :("), "Nous avons %s de retard pour le goûter :("),
channel=msg.channel) channel=msg.channel)
@hook("cmd_hook", "week-end")
def cmd_we(msg): def cmd_we(msg):
ndate = datetime.today() + timedelta(5 - datetime.today().weekday()) ndate = datetime.today() + timedelta(5 - datetime.today().weekday())
ndate = datetime(ndate.year, ndate.month, ndate.day, 0, 0, 1) ndate = datetime(ndate.year, ndate.month, ndate.day, 0, 0, 1)
@ -66,6 +60,7 @@ def cmd_we(msg):
"Youhou, on est en week-end depuis %s."), "Youhou, on est en week-end depuis %s."),
channel=msg.channel) channel=msg.channel)
@hook("cmd_hook", "start", help="!start /something/: launch a timer")
def start_countdown(msg): def start_countdown(msg):
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")
@ -140,6 +135,8 @@ def start_countdown(msg):
return Response(msg.sender, "%s commencé le %s"% (msg.cmds[1], return Response(msg.sender, "%s commencé le %s"% (msg.cmds[1],
datetime.now().strftime("%A %d %B %Y à %H:%M:%S"))) datetime.now().strftime("%A %d %B %Y à %H:%M:%S")))
@hook("cmd_hook", "end")
@hook("cmd_hook", "forceend")
def end_countdown(msg): 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 ?")
@ -157,6 +154,7 @@ def end_countdown(msg):
else: else:
return Response(msg.sender, "%s n'est pas un compteur connu."% (msg.cmds[1]), channel=msg.channel, nick=msg.nick) return Response(msg.sender, "%s n'est pas un compteur connu."% (msg.cmds[1]), channel=msg.channel, nick=msg.nick)
@hook("cmd_hook", "eventslist", help="!eventslist: gets list of timer")
def liste(msg): def liste(msg):
if len(msg.cmds) > 1: if len(msg.cmds) > 1:
res = list() res = list()

View File

@ -3,6 +3,8 @@
import urllib.request import urllib.request
import json import json
from hooks import hook
nemubotversion = 3.3 nemubotversion = 3.3
def help_tiny (): def help_tiny ():
@ -11,12 +13,7 @@ def help_tiny ():
def help_full (): def help_full ():
return "Search a movie title with: !imdbs <approximative title> ; View movie details with !imdb <title>" return "Search a movie title with: !imdbs <approximative title> ; View movie details with !imdb <title>"
def load(context): @hook("cmd_hook", "imdb", help="View movie details with !imdb <title>")
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_imdb, "imdb"))
add_hook("cmd_hook", Hook(cmd_search, "imdbs"))
def cmd_imdb(msg): def cmd_imdb(msg):
if len(msg.cmds) < 2: if len(msg.cmds) < 2:
raise IRCException("precise a movie/serie title!") raise IRCException("precise a movie/serie title!")
@ -46,6 +43,7 @@ def cmd_imdb(msg):
raise IRCException("An error occurs during movie search") raise IRCException("An error occurs during movie search")
@hook("cmd_hook", "imdbs", help="!imdbs <approximative title> to search a movie title")
def cmd_search(msg): def cmd_search(msg):
url = "http://www.omdbapi.com/?s=%s" % urllib.parse.quote(' '.join(msg.cmds[1:])) url = "http://www.omdbapi.com/?s=%s" % urllib.parse.quote(' '.join(msg.cmds[1:]))
print_debug(url) print_debug(url)

View File

@ -4,22 +4,20 @@ import subprocess
import re import re
import os import os
from hooks import hook
nemubotversion = 3.3 nemubotversion = 3.3
def load(context): def help_tiny():
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_man, "MAN"))
add_hook("cmd_hook", Hook(cmd_whatis, "man"))
def help_tiny ():
"""Line inserted in the response to the command !help""" """Line inserted in the response to the command !help"""
return "Read manual pages on IRC" return "Read manual pages on IRC"
def help_full (): def help_full():
return "!man [0-9] /what/: gives informations about /what/." return "!man [0-9] /what/: gives informations about /what/."
RGXP_s = re.compile(b'\x1b\\[[0-9]+m') RGXP_s = re.compile(b'\x1b\\[[0-9]+m')
@hook("cmd_hook", "MAN")
def cmd_man(msg): def cmd_man(msg):
args = ["man"] args = ["man"]
num = None num = None
@ -48,6 +46,7 @@ def cmd_man(msg):
return res return res
@hook("cmd_hook", "man")
def cmd_whatis(msg): def cmd_whatis(msg):
args = ["whatis", " ".join(msg.cmds[1:])] args = ["whatis", " ".join(msg.cmds[1:])]

View File

@ -7,13 +7,12 @@ import socket
import subprocess import subprocess
import urllib import urllib
from hooks import Hook, hook
from tools import web from tools import web
nemubotversion = 3.3 nemubotversion = 3.3
def load(context): def load(context):
from hooks import Hook
if not CONF or not CONF.hasNode("whoisxmlapi") or not CONF.getNode("whoisxmlapi").hasAttribute("username") or not CONF.getNode("whoisxmlapi").hasAttribute("password"): if not CONF or not CONF.hasNode("whoisxmlapi") or not CONF.getNode("whoisxmlapi").hasAttribute("username") or not CONF.getNode("whoisxmlapi").hasAttribute("password"):
print ("You need a WhoisXML API account in order to use the " print ("You need a WhoisXML API account in order to use the "
"!netwhois feature. Add it to the module configuration file:\n" "!netwhois feature. Add it to the module configuration file:\n"
@ -22,21 +21,14 @@ def load(context):
else: else:
add_hook("cmd_hook", Hook(cmd_whois, "netwhois")) add_hook("cmd_hook", Hook(cmd_whois, "netwhois"))
add_hook("cmd_hook", Hook(cmd_w3c, "w3c")) def help_tiny():
add_hook("cmd_hook", Hook(cmd_w3m, "w3m"))
add_hook("cmd_hook", Hook(cmd_traceurl, "traceurl"))
add_hook("cmd_hook", Hook(cmd_isup, "isup"))
add_hook("cmd_hook", Hook(cmd_curl, "curl"))
add_hook("cmd_hook", Hook(cmd_curly, "curly"))
def help_tiny ():
"""Line inserted in the response to the command !help""" """Line inserted in the response to the command !help"""
return "The networking module" return "The networking module"
def help_full (): def help_full():
return "!traceurl /url/: Follow redirections from /url/." return "!traceurl /url/: Follow redirections from /url/."
@hook("cmd_hook", "w3m")
def cmd_w3m(msg): def cmd_w3m(msg):
if len(msg.cmds) > 1: if len(msg.cmds) > 1:
args = ["w3m", "-T", "text/html", "-dump"] args = ["w3m", "-T", "text/html", "-dump"]
@ -49,6 +41,7 @@ def cmd_w3m(msg):
else: else:
raise IRCException("Veuillez indiquer une URL à visiter.") raise IRCException("Veuillez indiquer une URL à visiter.")
@hook("cmd_hook", "curl")
def cmd_curl(msg): def cmd_curl(msg):
if len(msg.cmds) > 1: if len(msg.cmds) > 1:
try: try:
@ -68,6 +61,7 @@ def cmd_curl(msg):
return Response(msg.sender, "Veuillez indiquer une URL à visiter.", return Response(msg.sender, "Veuillez indiquer une URL à visiter.",
channel=msg.channel) channel=msg.channel)
@hook("cmd_hook", "curly")
def cmd_curly(msg): def cmd_curly(msg):
if len(msg.cmds) > 1: if len(msg.cmds) > 1:
url = msg.cmds[1] url = msg.cmds[1]
@ -98,6 +92,7 @@ def cmd_curly(msg):
else: else:
raise IRCException("Veuillez indiquer une URL à visiter.") raise IRCException("Veuillez indiquer une URL à visiter.")
@hook("cmd_hook", "traceurl")
def cmd_traceurl(msg): def cmd_traceurl(msg):
if 1 < len(msg.cmds) < 6: if 1 < len(msg.cmds) < 6:
res = list() res = list()
@ -190,6 +185,7 @@ def cmd_whois(msg):
)) ))
return res return res
@hook("cmd_hook", "isup")
def cmd_isup(msg): def cmd_isup(msg):
if 1 < len(msg.cmds) < 6: if 1 < len(msg.cmds) < 6:
res = list() res = list()
@ -257,6 +253,7 @@ def traceURL(url, timeout=5, stack=None):
else: else:
return stack return stack
@hook("cmd_hook", "w3c")
def cmd_w3c(msg): def cmd_w3c(msg):
if len(msg.cmds) < 2: if len(msg.cmds) < 2:
raise IRCException("Indiquer une URL à valider !") raise IRCException("Indiquer une URL à valider !")

View File

@ -6,21 +6,18 @@ import urllib
nemubotversion = 3.3 nemubotversion = 3.3
def load(context): from hooks import hook
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_subreddit, "subreddit"))
add_hook("all_post", Hook(parseresponse))
def help_tiny():
def help_tiny ():
"""Line inserted in the response to the command !help""" """Line inserted in the response to the command !help"""
return "The subreddit module" return "The subreddit module"
def help_full (): def help_full():
return "!subreddit /subreddit/: Display information on the subreddit." return "!subreddit /subreddit/: Display information on the subreddit."
LAST_SUBS = dict() LAST_SUBS = dict()
@hook("cmd_hook", "subreddit", help="!subreddit /subreddit/: Display information on the subreddit.")
def cmd_subreddit(msg): def cmd_subreddit(msg):
global LAST_SUBS global LAST_SUBS
if len(msg.cmds) <= 1: if len(msg.cmds) <= 1:
@ -74,6 +71,7 @@ def parselisten(msg):
return False return False
@hook("all_post")
def parseresponse(res): def parseresponse(res):
parselisten(res) parselisten(res)
return True return True

View File

@ -2,12 +2,11 @@
import random import random
from hooks import hook
nemubotversion = 3.3 nemubotversion = 3.3
def load(context): @hook("cmd_hook", "choice")
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_choice, "choice"))
def cmd_choice(msg): def cmd_choice(msg):
if len(msg.cmds) > 1: if len(msg.cmds) > 1:
return Response(msg.sender, random.choice(msg.cmds[1:]), channel=msg.channel, nick=msg.nick) return Response(msg.sender, random.choice(msg.cmds[1:]), channel=msg.channel, nick=msg.nick)

View File

@ -3,6 +3,8 @@
import urllib.request import urllib.request
import json import json
import re import re
from hooks import hook
from tools import web from tools import web
from tools.web import striphtml from tools.web import striphtml
@ -14,11 +16,7 @@ def help_tiny ():
def help_full (): def help_full ():
return "!tcode <transaction code|keywords>" return "!tcode <transaction code|keywords>"
def load(context): @hook("cmd_hook", "tcode")
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_tcode, "tcode"))
def cmd_tcode(msg): def cmd_tcode(msg):
if len(msg.cmds) != 2: if len(msg.cmds) != 2:
raise IRCException("indicate a transaction code or a keyword to search!") raise IRCException("indicate a transaction code or a keyword to search!")

View File

@ -5,21 +5,18 @@ import imp
from datetime import datetime from datetime import datetime
from datetime import timedelta from datetime import timedelta
from hooks import hook
nemubotversion = 3.3 nemubotversion = 3.3
def help_tiny (): def help_tiny():
"""Line inserted in the response to the command !help""" """Line inserted in the response to the command !help"""
return "as http://sleepyti.me/, give you the best time to go to bed" return "as http://sleepyti.me/, give you the best time to go to bed"
def help_full (): def help_full():
return "If you would like to sleep soon, use !sleepytime to know the best time to wake up; use !sleepytime hh:mm if you want to wake up at hh:mm" return "If you would like to sleep soon, use !sleepytime to know the best time to wake up; use !sleepytime hh:mm if you want to wake up at hh:mm"
def load(context): @hook("cmd_hook", "sleepytime", help="If you would like to sleep soon, use !sleepytime to know the best time to wake up; use !sleepytime hh:mm if you want to wake up at hh:mm")
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_sleep, "sleeptime"))
add_hook("cmd_hook", Hook(cmd_sleep, "sleepytime"))
def cmd_sleep(msg): def cmd_sleep(msg):
if len (msg.cmds) > 1 and re.match("[0-9]{1,2}[h':.,-]([0-9]{1,2})?[m'\":.,-]?", if len (msg.cmds) > 1 and re.match("[0-9]{1,2}[h':.,-]([0-9]{1,2})?[m'\":.,-]?",
msg.cmds[1]) is not None: msg.cmds[1]) is not None:

View File

@ -7,20 +7,19 @@ import urllib.error
import urllib.request import urllib.request
import urllib.parse import urllib.parse
from hooks import hook
nemubotversion = 3.3 nemubotversion = 3.3
def load(context): def load(context):
global DATAS global DATAS
DATAS.setIndex("name", "phone") DATAS.setIndex("name", "phone")
from hooks import Hook def help_tiny():
add_hook("cmd_hook", Hook(cmd_sms, "sms"))
def help_tiny ():
"""Line inserted in the response to the command !help""" """Line inserted in the response to the command !help"""
return "Send SMS using SMS API (currently only Free Mobile)" return "Send SMS using SMS API (currently only Free Mobile)"
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/."
def send_sms(frm, api_usr, api_key, content): def send_sms(frm, api_usr, api_key, content):
@ -46,6 +45,7 @@ def send_sms(frm, api_usr, api_key, content):
return None return None
@hook("cmd_hook", "sms")
def cmd_sms(msg): def cmd_sms(msg):
if len(msg.cmds) <= 2: if len(msg.cmds) <= 2:
raise IRCException("À qui veux-tu envoyer ce SMS ?") raise IRCException("À qui veux-tu envoyer ce SMS ?")

View File

@ -3,27 +3,24 @@
import re import re
from urllib.parse import quote from urllib.parse import quote
from hooks import hook
from .pyaspell import Aspell from .pyaspell import Aspell
from .pyaspell import AspellError from .pyaspell import AspellError
nemubotversion = 3.3 nemubotversion = 3.3
def help_tiny (): def help_tiny():
return "Check words spelling" return "Check words spelling"
def help_full (): 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 global DATAS
DATAS.setIndex("name", "score") DATAS.setIndex("name", "score")
from hooks import Hook @hook("cmd_hook", "spell")
add_hook("cmd_hook", Hook(cmd_spell, "spell"))
add_hook("cmd_hook", Hook(cmd_spell, "orthographe"))
add_hook("cmd_hook", Hook(cmd_score, "spellscore"))
def cmd_spell(msg): def cmd_spell(msg):
if len(msg.cmds) < 2: if len(msg.cmds) < 2:
raise IRCException("indique une orthographe approximative du mot dont tu veux vérifier l'orthographe.") raise IRCException("indique une orthographe approximative du mot dont tu veux vérifier l'orthographe.")
@ -62,6 +59,7 @@ def add_score(nick, t):
DATAS.index[nick][t] = 1 DATAS.index[nick][t] = 1
save() save()
@hook("cmd_hook", "spellscore")
def cmd_score(msg): def cmd_score(msg):
global DATAS global DATAS
res = list() res = list()

View File

@ -5,24 +5,22 @@ import traceback
import sys import sys
from urllib.parse import quote from urllib.parse import quote
from hooks import hook
from tools import web from tools import web
nemubotversion = 3.3 nemubotversion = 3.3
def help_tiny (): def help_tiny():
return "Find french synonyms" return "Find french synonyms"
def help_full (): def help_full():
return "!syno <word>: give a list of synonyms for <word>." return "!syno <word>: give a list of synonyms for <word>."
def load(context):
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_syno, "synonymes"))
add_hook("cmd_hook", Hook(cmd_anto, "antonymes"))
@hook("cmd_hook", "synonymes", help="!syno <word>: give a list of synonyms for <word>.")
def cmd_syno(msg): def cmd_syno(msg):
return go("synonymes", msg) return go("synonymes", msg)
@hook("cmd_hook", "antonymes")
def cmd_anto(msg): def cmd_anto(msg):
return go("antonymes", msg) return go("antonymes", msg)

View File

@ -11,6 +11,8 @@ import urllib.parse
from urllib.parse import urlparse from urllib.parse import urlparse
from urllib.request import urlopen from urllib.request import urlopen
from hooks import hook
from .atom import Atom from .atom import Atom
nemubotversion = 3.3 nemubotversion = 3.3
@ -24,11 +26,6 @@ def help_full ():
def load(context): def load(context):
"""Register watched website""" """Register watched website"""
from hooks import Hook
add_hook("cmd_hook", Hook(add_site, "watch", data="diff"))
add_hook("cmd_hook", Hook(add_site, "updown", data="updown"))
add_hook("cmd_hook", Hook(del_site, "unwatch"))
DATAS.setIndex("url", "watch") DATAS.setIndex("url", "watch")
for site in DATAS.getNodes("watch"): for site in DATAS.getNodes("watch"):
if site.hasNode("alert"): if site.hasNode("alert"):
@ -56,6 +53,7 @@ def start_watching(site):
site["_evt_id"] = add_event(evt) site["_evt_id"] = add_event(evt)
@hook("cmd_hook", "unwatch")
def del_site(msg): def del_site(msg):
if len(msg.cmds) <= 1: if len(msg.cmds) <= 1:
raise IRCException("quel site dois-je arrêter de surveiller ?") raise IRCException("quel site dois-je arrêter de surveiller ?")
@ -79,6 +77,9 @@ def del_site(msg):
channel=msg.channel, nick=msg.nick) channel=msg.channel, nick=msg.nick)
raise IRCException("je ne surveillais pas cette URL !") raise IRCException("je ne surveillais pas cette URL !")
@hook("cmd_hook", "watch", data="diff")
@hook("cmd_hook", "updown", data="updown")
def add_site(msg, diffType="diff"): def add_site(msg, diffType="diff"):
print (diffType) print (diffType)
if len(msg.cmds) <= 1: if len(msg.cmds) <= 1:

View File

@ -5,20 +5,17 @@ from urllib.parse import urlparse
from urllib.parse import quote from urllib.parse import quote
from urllib.request import urlopen from urllib.request import urlopen
from hooks import hook
nemubotversion = 3.3 nemubotversion = 3.3
def help_tiny (): def help_tiny():
"""Line inserted in the response to the command !help""" """Line inserted in the response to the command !help"""
return "Gets YCC urls" return "Gets YCC urls"
def help_full (): def help_full():
return "!ycc [<url>]: with an argument, reduce the given <url> thanks to ycc.fr; without argument, reduce the last URL said on the current channel." return "!ycc [<url>]: with an argument, reduce the given <url> thanks to ycc.fr; without argument, reduce the last URL said on the current channel."
def load(context):
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_ycc, "ycc"))
add_hook("all_post", Hook(parseresponse))
LAST_URLS = dict() LAST_URLS = dict()
def gen_response(res, msg, srv): def gen_response(res, msg, srv):
@ -29,6 +26,7 @@ def gen_response(res, msg, srv):
else: else:
raise IRCException("mauvaise URL : %s" % srv) raise IRCException("mauvaise URL : %s" % srv)
@hook("cmd_hook", "ycc", help="!ycc [<url>]: with an argument, reduce the given <url> thanks to ycc.fr; without argument, reduce the last URL said on the current channel.")
def cmd_ycc(msg): def cmd_ycc(msg):
if len(msg.cmds) == 1: if len(msg.cmds) == 1:
global LAST_URLS global LAST_URLS
@ -71,6 +69,7 @@ def parselisten(msg):
pass pass
return False return False
@hook("all_post")
def parseresponse(res): def parseresponse(res):
parselisten(res) parselisten(res)
return True return True