Apply v3.3 changes on various modules

This commit is contained in:
Némunaire 2012-11-04 15:32:39 +01:00
parent 5afe5cb15a
commit c6d5d88723
11 changed files with 150 additions and 156 deletions

2
bot.py
View File

@ -353,7 +353,7 @@ class Bot:
"""Treat a message before send""" """Treat a message before send"""
for h, lvl, store in self.create_cache("all_post"): for h, lvl, store in self.create_cache("all_post"):
if h.is_matching(None, channel=res.channel, server=res.server): 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) self.check_rest_times(store, h)
if not c: if not c:
return False return False

View File

@ -142,9 +142,9 @@ class Hook:
return (channel is None or len(self.channels) <= 0 or return (channel is None or len(self.channels) <= 0 or
channel in self.channels) and (server is None or channel in self.channels) and (server is None or
self.server is None or self.server == server) and ( self.server is None or self.server == server) and (
(self.name is not None and strcmp == self.name) or ( (self.name is None or strcmp == self.name) or (
self.end is not None and strcmp == self.end) or ( self.end is None or strcmp == self.end) or (
self.regexp is not None and re.match(self.regexp, strcmp))) self.regexp is None or re.match(self.regexp, strcmp)))
def run(self, msg, data2=None, strcmp=None): def run(self, msg, data2=None, strcmp=None):
"""Run the hook""" """Run the hook"""

View File

@ -9,7 +9,7 @@ import time
import threading import threading
import traceback import traceback
nemubotversion = 3.2 nemubotversion = 3.3
from event import ModuleEvent from event import ModuleEvent
from hooks import Hook from hooks import Hook
@ -81,23 +81,23 @@ def cmd_vacances(msg):
channel=msg.channel) channel=msg.channel)
def start_countdown(msg): def start_countdown(msg):
if msg.cmd[1] not in DATAS.index: if msg.cmds[1] not in DATAS.index:
strnd = ModuleState("strend") strnd = ModuleState("strend")
strnd["server"] = msg.srv.id strnd["server"] = msg.server
strnd["channel"] = msg.channel strnd["channel"] = msg.channel
strnd["proprio"] = msg.nick strnd["proprio"] = msg.nick
strnd["sender"] = msg.sender strnd["sender"] = msg.sender
strnd["start"] = datetime.now() strnd["start"] = datetime.now()
strnd["name"] = msg.cmd[1] strnd["name"] = msg.cmds[1]
DATAS.addChild(strnd) DATAS.addChild(strnd)
evt = ModuleEvent(call=fini, call_data=dict(strend=strnd)) evt = ModuleEvent(call=fini, call_data=dict(strend=strnd))
if len(msg.cmd) > 2: if len(msg.cmds) > 2:
result1 = re.findall("([0-9]+)([smhdjwSMHDJW])?", msg.cmd[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.cmd[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.cmd[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: if result2 is not None or result3 is not None:
try: try:
now = datetime.now() now = datetime.now()
@ -125,12 +125,12 @@ def start_countdown(msg):
strnd["id"] = CONTEXT.add_event(evt) strnd["id"] = CONTEXT.add_event(evt)
save() save()
return Response(msg.sender, "%s commencé le %s et se terminera le %s." % 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"))) strnd.getDate("end").strftime("%A %d %B %Y a %H:%M:%S")))
except: except:
DATAS.delChild(strnd) DATAS.delChild(strnd)
return Response(msg.sender, 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: elif result1 is not None and len(result1) > 0:
strnd["end"] = datetime.now() strnd["end"] = datetime.now()
for (t, g) in result1: for (t, g) in result1:
@ -148,43 +148,43 @@ def start_countdown(msg):
strnd["id"] = CONTEXT.add_event(evt) strnd["id"] = CONTEXT.add_event(evt)
save() save()
return Response(msg.sender, "%s commencé le %s et se terminera le %s." % 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"))) strnd.getDate("end").strftime("%A %d %B %Y a %H:%M:%S")))
save() 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"))) datetime.now().strftime("%A %d %B %Y a %H:%M:%S")))
else: 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): def end_countdown(msg):
if msg.cmd[1] in DATAS.index: if msg.cmds[1] in DATAS.index:
res = Response(msg.sender, res = Response(msg.sender,
"%s a duré %s." % (msg.cmd[1], "%s a duré %s." % (msg.cmds[1],
msg.just_countdown(datetime.now () - DATAS.index[msg.cmd[1]].getDate("start"))), msg.just_countdown(datetime.now () - DATAS.index[msg.cmds[1]].getDate("start"))),
channel=msg.channel) channel=msg.channel)
if DATAS.index[msg.cmd[1]]["proprio"] == msg.nick or (msg.cmd[0] == "forceend" and msg.nick == msg.srv.owner): if DATAS.index[msg.cmds[1]]["proprio"] == msg.nick or (msg.cmds[0] == "forceend" and msg.is_owner):
CONTEXT.del_event(DATAS.index[msg.cmd[1]]["id"]) CONTEXT.del_event(DATAS.index[msg.cmds[1]]["id"])
DATAS.delChild(DATAS.index[msg.cmd[1]]) DATAS.delChild(DATAS.index[msg.cmds[1]])
save() save()
else: 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 return res
else: 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): def liste(msg):
msg.send_snd ("Compteurs connus : %s." % ", ".join(DATAS.index.keys())) msg.send_snd ("Compteurs connus : %s." % ", ".join(DATAS.index.keys()))
def parseanswer(msg): def parseanswer(msg):
if msg.cmd[0] in DATAS.index: if msg.cmds[0] in DATAS.index:
if DATAS.index[msg.cmd[0]].name == "strend": if DATAS.index[msg.cmds[0]].name == "strend":
if DATAS.index[msg.cmd[0]].hasAttribute("end"): if DATAS.index[msg.cmds[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) 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: 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: else:
save() 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): def parseask(msg):
msgl = msg.content.lower() msgl = msg.content.lower()
@ -206,7 +206,7 @@ def parseask(msg):
if msg_before.find ("%s") != -1 and msg_after.find ("%s") != -1: if msg_before.find ("%s") != -1 and msg_after.find ("%s") != -1:
evt = ModuleState("event") evt = ModuleState("event")
evt["server"] = msg.srv.id evt["server"] = msg.server
evt["channel"] = msg.channel evt["channel"] = msg.channel
evt["proprio"] = msg.nick evt["proprio"] = msg.nick
evt["sender"] = msg.sender evt["sender"] = msg.sender
@ -226,7 +226,7 @@ def parseask(msg):
" compte à rebours.") " compte à rebours.")
elif texts is not None and texts.group (2) is not None: elif texts is not None and texts.group (2) is not None:
evt = ModuleState("event") evt = ModuleState("event")
evt["server"] = msg.srv.id evt["server"] = msg.server
evt["channel"] = msg.channel evt["channel"] = msg.channel
evt["proprio"] = msg.nick evt["proprio"] = msg.nick
evt["sender"] = msg.sender evt["sender"] = msg.sender

View File

@ -5,14 +5,14 @@ import imp
from datetime import datetime from datetime import datetime
from datetime import timedelta from datetime import timedelta
nemubotversion = 3.2 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 "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): def load(context):
from hooks import Hook from hooks import Hook
@ -21,10 +21,10 @@ def load(context):
def cmd_sleep(msg): def cmd_sleep(msg):
if len (msg.cmd) > 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.cmd[1]) is not None: msg.cmds[1]) is not None:
# First, parse the hour # 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, f = [datetime(datetime.today().year,
datetime.today().month, datetime.today().month,
datetime.today().day, datetime.today().day,

View File

@ -5,13 +5,13 @@ import re
import socket import socket
from urllib.parse import quote from urllib.parse import quote
nemubotversion = 3.2 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> [<word> ...]: give a list of synonyms for each <word> (maximum 5 each time)." return "!syno <word>: give a list of synonyms for <word>."
def load(context): def load(context):
from hooks import Hook from hooks import Hook
@ -20,18 +20,16 @@ def load(context):
def cmd_syno(msg): def cmd_syno(msg):
if 1 < len(msg.cmd) < 6: if 1 < len(msg.cmds) < 6:
for word in msg.cmd[1:]: for word in msg.cmds[1:]:
synos = get_synos(word) synos = get_synos(word)
if synos is None: if synos is None:
return Response(msg.sender, return Response(msg.sender,
"Une erreur s'est produite durant la recherche" "Une erreur s'est produite durant la recherche"
" d'un synonyme de %s" % word, msg.channel) " d'un synonyme de %s" % word, msg.channel)
elif len(synos) > 0: elif len(synos) > 0:
return Response(msg.sender, return Response(msg.sender, synos, msg.channel,
"Synonymes de %s : %s" % title="Synonymes de %s" % word)
(word, ', '.join(synos)),
msg.channel)
else: else:
return Response(msg.sender, return Response(msg.sender,
"Aucun synonymes de %s n'a été trouvé" % word, "Aucun synonymes de %s n'a été trouvé" % word,

View File

@ -12,7 +12,7 @@ from urllib.parse import unquote
from .atom import Atom from .atom import Atom
nemubotversion = 3.2 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"""
@ -21,12 +21,8 @@ def help_tiny ():
def help_full (): def help_full ():
return "This module is autonomous you can't interract with it." return "This module is autonomous you can't interract with it."
CONTEXT = None
def load(context): def load(context):
"""Register watched website""" """Register watched website"""
global CONTEXT
CONTEXT = context
for site in DATAS.getNodes("watch"): for site in DATAS.getNodes("watch"):
start_watching(site) start_watching(site)
@ -41,7 +37,7 @@ def start_watching(site):
func_data=dict(s=site["server"], p=site["page"]), func_data=dict(s=site["server"], p=site["page"]),
intervalle=site.getInt("time"), intervalle=site.getInt("time"),
call=alert_change, call_data=site) call=alert_change, call_data=site)
site["evt_id"] = CONTEXT.add_event(evt) site["evt_id"] = add_event(evt)
def explore_url(url): def explore_url(url):
@ -54,15 +50,15 @@ def found_site(s, p):
return None return None
def del_site(msg): 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 ?", return Response(msg.sender, "quel site dois-je arrêter de surveiller ?",
msg.channel, msg.nick) msg.channel, msg.nick)
rx = explore_url(msg.cmd[1]) rx = explore_url(msg.cmds[1])
if rx is not None: if rx is not None:
site = found_site(rx.group(2), rx.group(3)) site = found_site(rx.group(2), rx.group(3))
if site is not None and (msg.sender == site["sender"] or msg.is_owner): 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) DATAS.delChild(site)
save() save()
return Response(msg.sender, "je ne surveille désormais plus cette URL.", 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) channel=msg.channel, nick=msg.nick)
def add_site(msg): def add_site(msg):
if len(msg.cmd) <= 1: if len(msg.cmds) <= 1:
return Response(msg.sender, "quel site dois-je surveiller ?", return Response(msg.sender, "quel site dois-je surveiller ?",
msg.channel, msg.nick) msg.channel, msg.nick)
rx = explore_url(msg.cmd[1]) rx = explore_url(msg.cmds[1])
if rx is None: if rx is None:
return Response(msg.sender, "je ne peux pas surveiller cette URL", return Response(msg.sender, "je ne peux pas surveiller cette URL",
channel=msg.channel, nick=msg.nick) channel=msg.channel, nick=msg.nick)

89
modules/ycc.py Normal file
View File

@ -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 [<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()
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)

View File

@ -1,4 +0,0 @@
<?xml version="1.0" ?>
<nemubotmodule name="ycc">
<message type="cmd" name="ycc" call="cmd_ycc" />
</nemubotmodule>

View File

@ -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)

View File

@ -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 [<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):
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

View File

@ -39,6 +39,13 @@ class Response:
self.set_sender(sender) self.set_sender(sender)
self.count = count 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): def set_sender(self, sender):
if sender is None or sender.find("!") < 0: if sender is None or sender.find("!") < 0:
if sender is not None: if sender is not None: