diff --git a/bot.py b/bot.py index bca52ae..2f61b6b 100644 --- a/bot.py +++ b/bot.py @@ -353,7 +353,7 @@ class Bot: """Treat a message before send""" for h, lvl, store in self.create_cache("all_post"): if h.is_matching(None, channel=res.channel, server=res.server): - c = h.run(msg) + c = h.run(res) self.check_rest_times(store, h) if not c: return False diff --git a/hooks.py b/hooks.py index 965a50f..809352c 100644 --- a/hooks.py +++ b/hooks.py @@ -142,9 +142,9 @@ class Hook: return (channel is None or len(self.channels) <= 0 or channel in self.channels) and (server is None or self.server is None or self.server == server) and ( - (self.name is not None and strcmp == self.name) or ( - self.end is not None and strcmp == self.end) or ( - self.regexp is not None and re.match(self.regexp, strcmp))) + (self.name is None or strcmp == self.name) or ( + self.end is None or strcmp == self.end) or ( + self.regexp is None or re.match(self.regexp, strcmp))) def run(self, msg, data2=None, strcmp=None): """Run the hook""" diff --git a/modules/events/__init__.py b/modules/events/__init__.py index 3423678..e40c1bb 100644 --- a/modules/events/__init__.py +++ b/modules/events/__init__.py @@ -9,17 +9,17 @@ import time import threading import traceback -nemubotversion = 3.2 +nemubotversion = 3.3 from event import ModuleEvent from hooks import Hook def help_tiny (): - """Line inserted in the response to the command !help""" - return "events manager" + """Line inserted in the response to the command !help""" + return "events manager" def help_full (): - return "This module store a lot of events: ny, we, vacs, " + (", ".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, vacs, " + (", ".join(DATAS.index.keys())) + "\n!eventslist: gets list of timer\n!start /something/: launch a timer" CONTEXT = None @@ -81,23 +81,23 @@ def cmd_vacances(msg): channel=msg.channel) def start_countdown(msg): - if msg.cmd[1] not in DATAS.index: + if msg.cmds[1] not in DATAS.index: strnd = ModuleState("strend") - strnd["server"] = msg.srv.id + strnd["server"] = msg.server strnd["channel"] = msg.channel strnd["proprio"] = msg.nick strnd["sender"] = msg.sender strnd["start"] = datetime.now() - strnd["name"] = msg.cmd[1] + strnd["name"] = msg.cmds[1] DATAS.addChild(strnd) evt = ModuleEvent(call=fini, call_data=dict(strend=strnd)) - if len(msg.cmd) > 2: - result1 = re.findall("([0-9]+)([smhdjwSMHDJW])?", msg.cmd[2]) - result2 = re.match("([0-3]?[0-9])/([0-1]?[0-9])/((19|20)?[01239][0-9])", msg.cmd[2]) - result3 = re.match("([0-2]?[0-9]):([0-5]?[0-9])(:([0-5]?[0-9]))?", msg.cmd[2]) + if len(msg.cmds) > 2: + result1 = re.findall("([0-9]+)([smhdjwSMHDJW])?", msg.cmds[2]) + result2 = re.match("([0-3]?[0-9])/([0-1]?[0-9])/((19|20)?[01239][0-9])", msg.cmds[2]) + result3 = re.match("([0-2]?[0-9]):([0-5]?[0-9])(:([0-5]?[0-9]))?", msg.cmds[2]) if result2 is not None or result3 is not None: try: now = datetime.now() @@ -125,12 +125,12 @@ def start_countdown(msg): strnd["id"] = CONTEXT.add_event(evt) save() return Response(msg.sender, "%s commencé le %s et se terminera le %s." % - (msg.cmd[1], datetime.now().strftime("%A %d %B %Y a %H:%M:%S"), + (msg.cmds[1], datetime.now().strftime("%A %d %B %Y a %H:%M:%S"), strnd.getDate("end").strftime("%A %d %B %Y a %H:%M:%S"))) except: DATAS.delChild(strnd) return Response(msg.sender, - "Mauvais format de date pour l'evenement %s. Il n'a pas ete cree." % msg.cmd[1]) + "Mauvais format de date pour l'evenement %s. Il n'a pas ete cree." % msg.cmds[1]) elif result1 is not None and len(result1) > 0: strnd["end"] = datetime.now() for (t, g) in result1: @@ -148,43 +148,43 @@ def start_countdown(msg): strnd["id"] = CONTEXT.add_event(evt) save() return Response(msg.sender, "%s commencé le %s et se terminera le %s." % - (msg.cmd[1], datetime.now().strftime("%A %d %B %Y a %H:%M:%S"), + (msg.cmds[1], datetime.now().strftime("%A %d %B %Y a %H:%M:%S"), strnd.getDate("end").strftime("%A %d %B %Y a %H:%M:%S"))) save() - return Response(msg.sender, "%s commencé le %s"% (msg.cmd[1], + return Response(msg.sender, "%s commencé le %s"% (msg.cmds[1], datetime.now().strftime("%A %d %B %Y a %H:%M:%S"))) else: - return Response(msg.sender, "%s existe déjà."% (msg.cmd[1])) + return Response(msg.sender, "%s existe déjà."% (msg.cmds[1])) def end_countdown(msg): - if msg.cmd[1] in DATAS.index: + if msg.cmds[1] in DATAS.index: res = Response(msg.sender, - "%s a duré %s." % (msg.cmd[1], - msg.just_countdown(datetime.now () - DATAS.index[msg.cmd[1]].getDate("start"))), + "%s a duré %s." % (msg.cmds[1], + msg.just_countdown(datetime.now () - DATAS.index[msg.cmds[1]].getDate("start"))), channel=msg.channel) - if DATAS.index[msg.cmd[1]]["proprio"] == msg.nick or (msg.cmd[0] == "forceend" and msg.nick == msg.srv.owner): - CONTEXT.del_event(DATAS.index[msg.cmd[1]]["id"]) - DATAS.delChild(DATAS.index[msg.cmd[1]]) + if DATAS.index[msg.cmds[1]]["proprio"] == msg.nick or (msg.cmds[0] == "forceend" and msg.is_owner): + CONTEXT.del_event(DATAS.index[msg.cmds[1]]["id"]) + DATAS.delChild(DATAS.index[msg.cmds[1]]) save() else: - res.append_message("Vous ne pouvez pas terminer le compteur %s, créé par %s."% (msg.cmd[1], DATAS.index[msg.cmd[1]]["proprio"])) + res.append_message("Vous ne pouvez pas terminer le compteur %s, créé par %s."% (msg.cmds[1], DATAS.index[msg.cmds[1]]["proprio"])) return res else: - return Response(msg.sender, "%s n'est pas un compteur connu."% (msg.cmd[1])) + return Response(msg.sender, "%s n'est pas un compteur connu."% (msg.cmds[1])) def liste(msg): msg.send_snd ("Compteurs connus : %s." % ", ".join(DATAS.index.keys())) def parseanswer(msg): - if msg.cmd[0] in DATAS.index: - if DATAS.index[msg.cmd[0]].name == "strend": - if DATAS.index[msg.cmd[0]].hasAttribute("end"): - return Response(msg.sender, "%s commencé il y a %s et se terminera dans %s." % (msg.cmd[0], msg.just_countdown(datetime.now() - DATAS.index[msg.cmd[0]].getDate("start")), msg.just_countdown(DATAS.index[msg.cmd[0]].getDate("end") - datetime.now())), channel=msg.channel) + if msg.cmds[0] in DATAS.index: + if DATAS.index[msg.cmds[0]].name == "strend": + if DATAS.index[msg.cmds[0]].hasAttribute("end"): + return Response(msg.sender, "%s commencé il y a %s et se terminera dans %s." % (msg.cmds[0], msg.just_countdown(datetime.now() - DATAS.index[msg.cmds[0]].getDate("start")), msg.just_countdown(DATAS.index[msg.cmds[0]].getDate("end") - datetime.now())), channel=msg.channel) else: - return Response(msg.sender, "%s commencé il y a %s." % (msg.cmd[0], msg.just_countdown(datetime.now () - DATAS.index[msg.cmd[0]].getDate("start"))), channel=msg.channel) + return Response(msg.sender, "%s commencé il y a %s." % (msg.cmds[0], msg.just_countdown(datetime.now () - DATAS.index[msg.cmds[0]].getDate("start"))), channel=msg.channel) else: save() - return Response(msg.sender, msg.countdown_format (DATAS.index[msg.cmd[0]].getDate("start"), DATAS.index[msg.cmd[0]]["msg_before"], DATAS.index[msg.cmd[0]]["msg_after"]), channel=msg.channel) + return Response(msg.sender, msg.countdown_format (DATAS.index[msg.cmds[0]].getDate("start"), DATAS.index[msg.cmds[0]]["msg_before"], DATAS.index[msg.cmds[0]]["msg_after"]), channel=msg.channel) def parseask(msg): msgl = msg.content.lower() @@ -206,7 +206,7 @@ def parseask(msg): if msg_before.find ("%s") != -1 and msg_after.find ("%s") != -1: evt = ModuleState("event") - evt["server"] = msg.srv.id + evt["server"] = msg.server evt["channel"] = msg.channel evt["proprio"] = msg.nick evt["sender"] = msg.sender @@ -226,7 +226,7 @@ def parseask(msg): " compte à rebours.") elif texts is not None and texts.group (2) is not None: evt = ModuleState("event") - evt["server"] = msg.srv.id + evt["server"] = msg.server evt["channel"] = msg.channel evt["proprio"] = msg.nick evt["sender"] = msg.sender diff --git a/modules/sleepytime.py b/modules/sleepytime.py index 8482b99..b53a2e5 100644 --- a/modules/sleepytime.py +++ b/modules/sleepytime.py @@ -5,14 +5,14 @@ import imp from datetime import datetime from datetime import timedelta -nemubotversion = 3.2 +nemubotversion = 3.3 def help_tiny (): """Line inserted in the response to the command !help""" return "as http://sleepyti.me/, give you the best time to go to bed" def help_full (): - return "TODO" + 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): from hooks import Hook @@ -21,10 +21,10 @@ def load(context): def cmd_sleep(msg): - if len (msg.cmd) > 1 and re.match("[0-9]{1,2}[h':.,-]([0-9]{1,2})?[m'\":.,-]?", - msg.cmd[1]) is not None: + if len (msg.cmds) > 1 and re.match("[0-9]{1,2}[h':.,-]([0-9]{1,2})?[m'\":.,-]?", + msg.cmds[1]) is not None: # First, parse the hour - p = re.match("([0-9]{1,2})[h':.,-]([0-9]{1,2})?[m':.,-]?", msg.cmd[1]) + p = re.match("([0-9]{1,2})[h':.,-]([0-9]{1,2})?[m':.,-]?", msg.cmds[1]) f = [datetime(datetime.today().year, datetime.today().month, datetime.today().day, diff --git a/modules/syno.py b/modules/syno.py index 7a40f4e..8820dc0 100644 --- a/modules/syno.py +++ b/modules/syno.py @@ -5,13 +5,13 @@ import re import socket from urllib.parse import quote -nemubotversion = 3.2 +nemubotversion = 3.3 def help_tiny (): return "Find french synonyms" def help_full (): - return "!syno [ ...]: give a list of synonyms for each (maximum 5 each time)." + return "!syno : give a list of synonyms for ." def load(context): from hooks import Hook @@ -20,18 +20,16 @@ def load(context): def cmd_syno(msg): - if 1 < len(msg.cmd) < 6: - for word in msg.cmd[1:]: + if 1 < len(msg.cmds) < 6: + for word in msg.cmds[1:]: synos = get_synos(word) if synos is None: return Response(msg.sender, "Une erreur s'est produite durant la recherche" " d'un synonyme de %s" % word, msg.channel) elif len(synos) > 0: - return Response(msg.sender, - "Synonymes de %s : %s" % - (word, ', '.join(synos)), - msg.channel) + return Response(msg.sender, synos, msg.channel, + title="Synonymes de %s" % word) else: return Response(msg.sender, "Aucun synonymes de %s n'a été trouvé" % word, diff --git a/modules/watchWebsite/__init__.py b/modules/watchWebsite/__init__.py index b2ecea6..52b8abf 100644 --- a/modules/watchWebsite/__init__.py +++ b/modules/watchWebsite/__init__.py @@ -12,7 +12,7 @@ from urllib.parse import unquote from .atom import Atom -nemubotversion = 3.2 +nemubotversion = 3.3 def help_tiny (): """Line inserted in the response to the command !help""" @@ -21,12 +21,8 @@ def help_tiny (): def help_full (): return "This module is autonomous you can't interract with it." -CONTEXT = None - def load(context): """Register watched website""" - global CONTEXT - CONTEXT = context for site in DATAS.getNodes("watch"): start_watching(site) @@ -41,7 +37,7 @@ def start_watching(site): func_data=dict(s=site["server"], p=site["page"]), intervalle=site.getInt("time"), call=alert_change, call_data=site) - site["evt_id"] = CONTEXT.add_event(evt) + site["evt_id"] = add_event(evt) def explore_url(url): @@ -54,15 +50,15 @@ def found_site(s, p): return None def del_site(msg): - if len(msg.cmd) <= 1: + if len(msg.cmds) <= 1: return Response(msg.sender, "quel site dois-je arrêter de surveiller ?", msg.channel, msg.nick) - rx = explore_url(msg.cmd[1]) + rx = explore_url(msg.cmds[1]) if rx is not None: site = found_site(rx.group(2), rx.group(3)) if site is not None and (msg.sender == site["sender"] or msg.is_owner): - CONTEXT.del_event(site["evt_id"]) + del_event(site["evt_id"]) DATAS.delChild(site) save() return Response(msg.sender, "je ne surveille désormais plus cette URL.", @@ -77,11 +73,11 @@ def del_site(msg): channel=msg.channel, nick=msg.nick) def add_site(msg): - if len(msg.cmd) <= 1: + if len(msg.cmds) <= 1: return Response(msg.sender, "quel site dois-je surveiller ?", msg.channel, msg.nick) - rx = explore_url(msg.cmd[1]) + rx = explore_url(msg.cmds[1]) if rx is None: return Response(msg.sender, "je ne peux pas surveiller cette URL", channel=msg.channel, nick=msg.nick) diff --git a/modules/ycc.py b/modules/ycc.py new file mode 100644 index 0000000..4c41d71 --- /dev/null +++ b/modules/ycc.py @@ -0,0 +1,89 @@ +# coding=utf-8 + +import http.client +import imp +import re +import sys + +nemubotversion = 3.3 + +def help_tiny (): + """Line inserted in the response to the command !help""" + return "Gets YCC urls" + +def help_full (): + return "!ycc []: with an argument, reduce the given 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() + +def gen_response(res, msg, srv): + if res is None: + return Response(msg.sender, "La situation est embarassante, il semblerait que YCC soit down :(", msg.channel) + elif isinstance(res, str): + return Response(msg.sender, "URL pour %s : %s" % (srv, res), msg.channel) + else: + return Response(msg.sender, "Mauvaise URL : %s" % srv, msg.channel) + +def cmd_ycc(msg): + if len(msg.cmds) == 1: + global LAST_URLS + if msg.channel in LAST_URLS and len(LAST_URLS[msg.channel]) > 0: + msg.cmds.append(LAST_URLS[msg.channel].pop()) + else: + return Response(msg.sender, "Je n'ai pas d'autre URL à réduire.", msg.channel) + + if len(msg.cmds) < 6: + res = list() + for url in msg.cmds[1:]: + srv = re.match(".*((ht|f)tps?://|www.)([^/ ]+).*", url) + if srv is not None: + res.append(gen_response(tinyfy(url), msg, srv.group(3))) + else: + res.append(gen_response(False, msg, url)) + return res + else: + return Response(msg.sender, "je ne peux pas réduire autant d'URL " + "d'un seul coup.", msg.channel, nick=msg.nick) + +def parselisten(msg): + global LAST_URLS + res = re.match(".*(((ht|f)tps?://|www\.)[^ ]+).*", msg.content) + if res is not None: + if res.group(1).find("ycc.fr") >= 0: + return False + if msg.channel not in LAST_URLS: + LAST_URLS[msg.channel] = list() + LAST_URLS[msg.channel].append(res.group(1)) + return True + return False +def parseresponse(res): + parselisten(res) + return True + +def tinyfy(url): + (status, page) = getPage("ycc.fr", "/redirection/create/" + url) + if status == http.client.OK and len(page) < 100: + return page.decode() + else: + print ("ERROR: ycc.fr seem down?") + return None + + +def getPage(s, p): + conn = http.client.HTTPConnection(s, timeout=10) + try: + conn.request("GET", p) + except socket.gaierror: + print ("[%s] impossible de récupérer la page %s."%(s, p)) + return None + + res = conn.getresponse() + data = res.read() + + conn.close() + return (res.status, data) diff --git a/modules/ycc.xml b/modules/ycc.xml deleted file mode 100644 index ff6ca6c..0000000 --- a/modules/ycc.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/modules/ycc/Tinyfier.py b/modules/ycc/Tinyfier.py deleted file mode 100644 index a1be5d7..0000000 --- a/modules/ycc/Tinyfier.py +++ /dev/null @@ -1,37 +0,0 @@ -# coding=utf-8 - -import http.client -import threading -import re - -class Tinyfier(threading.Thread): - def __init__(self, url, msg): - self.url = url - self.msg = msg - threading.Thread.__init__(self) - - def run(self): - (status, page) = getPage("ycc.fr", "/redirection/create/" + self.url) - if status == http.client.OK and len(page) < 100: - srv = re.match(".*((ht|f)tps?://|www.)([^/ ]+).*", self.url) - if srv is None: - self.msg.srv.send_response(Response(self.msg.sender, "Mauvaise URL : %s" % (self.url), self.msg.channel), None) - else: - self.msg.srv.send_response(Response(self.msg.sender, "URL pour %s : %s" % (srv.group(3), page.decode()), self.msg.channel), None) - else: - print ("ERROR: ycc.fr seem down?") - self.msg.srv.send_response(Response(self.msg.sender, "La situation est embarassante, il semblerait que YCC soit down :(", self.msg.channel), None) - -def getPage(s, p): - conn = http.client.HTTPConnection(s, timeout=10) - try: - conn.request("GET", p) - except socket.gaierror: - print ("[%s] impossible de récupérer la page %s."%(s, p)) - return None - - res = conn.getresponse() - data = res.read() - - conn.close() - return (res.status, data) diff --git a/modules/ycc/__init__.py b/modules/ycc/__init__.py deleted file mode 100644 index 6b412ff..0000000 --- a/modules/ycc/__init__.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding=utf-8 - -import http.client -import imp -import re -import sys - -from . import Tinyfier - -nemubotversion = 3.2 - -def help_tiny (): - """Line inserted in the response to the command !help""" - return "Gets YCC urls" - -def help_full (): - return "!ycc []: with an argument, reduce the given thanks to ycc.fr; without argument, reduce the last URL said on the current channel." - -def load(context): - Tinyfier.Response = Response - -def reload(): - imp.reload(Tinyfier) - Tinyfier.Response = Response - -def cmd_ycc(msg): - global LAST_URLS - if len(msg.cmd) == 1: - if msg.channel in LAST_URLS and len(LAST_URLS[msg.channel]) > 0: - url = LAST_URLS[msg.channel].pop() - t = Tinyfier.Tinyfier(url, msg) - t.start() - else: - return Response(msg.sender, "je n'ai pas d'autre URL à réduire", msg.channel, nick=msg.nick) - else: - if len(msg.cmd) < 6: - for url in msg.cmd[1:]: - t = Tinyfier.Tinyfier(url, msg) - t.start() - else: - return Response(msg.sender, "je ne peux pas réduire autant d'URL " - "d'un seul coup.", msg.channel, nick=msg.nick) - return False - -LAST_URLS = dict() - -def parselisten(msg): - global LAST_URLS - if re.match(".*(https?://|www\.)[^ ]+.*", msg.content) is not None: - res = re.match(".*(((ht|f)tps?://|www\.)[^ ]+).*", msg.content) - if msg.channel not in LAST_URLS: - LAST_URLS[msg.channel] = list() - LAST_URLS[msg.channel].append(res.group(1)) - return True - return False diff --git a/response.py b/response.py index 17c6c41..a4489c6 100644 --- a/response.py +++ b/response.py @@ -39,6 +39,13 @@ class Response: self.set_sender(sender) self.count = count + @property + def content(self): + if self.title is not None: + return self.title + ", ".join(self.messages) + else: + return ", ".join(self.messages) + def set_sender(self, sender): if sender is None or sender.find("!") < 0: if sender is not None: