Response sender is not needed anymore, private channels are now better handled

This commit is contained in:
nemunaire 2014-09-18 07:57:06 +02:00
parent 5e202063d4
commit 772d68a34d
32 changed files with 161 additions and 182 deletions

5
bot.py
View File

@ -77,14 +77,13 @@ class Bot(threading.Thread):
self.hooks = HooksManager()
def in_ping(msg):
if re.match("^ *(m[' ]?entends?[ -]+tu|h?ear me|do you copy|ping)", msg.text, re.I) is not None:
return response.Response(msg.sender, message="pong", channel=msg.receivers, nick=msg.nick)
return response.Response(message="pong", channel=msg.receivers, nick=msg.nick)
self.hooks.add_hook(MessageHook(in_ping), "in", "PRIVMSG")
def _help_msg(msg):
"""Parse and response to help messages"""
cmd = msg.cmds
sndr = msg.sender
res = response.Response(sndr)
res = response.Response()
if len(cmd) > 1:
if cmd[1] in self.modules:
if len(cmd) > 2:

View File

@ -26,7 +26,7 @@ import sys
import bot
from server.DCC import DCC
from message import Message
import response
from response import Response
import server
logger = logging.getLogger("nemubot.consumer")
@ -118,8 +118,13 @@ class MessageConsumer:
if h.match(message=msg, server=self.srv):
res = h.run(msg)
if isinstance(res, list):
for r in res:
if isinstance(r, Response):
r.set_sender(msg.sender)
self.responses += res
elif res is not None:
if isinstance(res, Response):
res.set_sender(msg.sender)
self.responses.append(res)
@ -174,9 +179,7 @@ class MessageConsumer:
self.post_treat(context.hooks)
except:
logger.exception("Error occurred during the processing of the message: %s", self.msgs[0].raw)
return
#return self.responses
for res in self.responses:
to_server = None
if res.server is None:
@ -188,7 +191,7 @@ class MessageConsumer:
if to_server is None:
logger.error("The server defined in this response doesn't "
"exist: %s", res.server)
return False
continue
# Sent the message only if treat_post authorize it
to_server.send_response(res)

View File

@ -26,4 +26,4 @@ class IRCException(Exception):
self.personnal = personnal
def fill_response(self, msg):
return Response(msg.sender, self.message, channel=msg.receivers, nick=(msg.nick if self.personnal else None))
return Response(self.message, channel=msg.receivers, nick=(msg.nick if self.personnal else None))

View File

@ -51,10 +51,10 @@ def get_variable(name, msg=None):
def cmd_set(msg):
if len (msg.cmds) > 2:
set_variable(msg.cmds[1], " ".join(msg.cmds[2:]), msg.nick)
res = Response(msg.sender, "Variable \$%s définie." % msg.cmds[1])
res = Response("Variable \$%s définie." % msg.cmds[1])
save()
return res
return Response(msg.sender, "!set prend au minimum deux arguments : le nom de la variable et sa valeur.")
return Response("!set prend au minimum deux arguments : le nom de la variable et sa valeur.")
@hook("cmd_hook", "listalias")
def cmd_listalias(msg):
@ -66,9 +66,9 @@ def cmd_listalias(msg):
res.append("Alias créés par %s : %s" % (user, ", ".join(als)))
else:
res.append("%s n'a pas encore créé d'alias" % user)
return Response(msg.sender, " ; ".join(res), channel=msg.channel)
return Response(" ; ".join(res), channel=msg.channel)
else:
return Response(msg.sender, "Alias connus : %s." % ", ".join(DATAS.getNode("aliases").index.keys()), channel=msg.channel)
return Response("Alias connus : %s." % ", ".join(DATAS.getNode("aliases").index.keys()), channel=msg.channel)
@hook("cmd_hook", "listvars")
def cmd_listvars(msg):
@ -80,9 +80,9 @@ def cmd_listvars(msg):
res.append("Variables créées par %s : %s" % (user, ", ".join(als)))
else:
res.append("%s n'a pas encore créé de variable" % user)
return Response(msg.sender, " ; ".join(res), channel=msg.channel)
return Response(" ; ".join(res), channel=msg.channel)
else:
return Response(msg.sender, "Variables connues : %s." % ", ".join(DATAS.getNode("variables").index.keys()), channel=msg.channel)
return Response("Variables connues : %s." % ", ".join(DATAS.getNode("variables").index.keys()), channel=msg.channel)
@hook("cmd_hook", "alias")
def cmd_alias(msg):
@ -92,15 +92,15 @@ def cmd_alias(msg):
if alias[0] == "!":
alias = alias[1:]
if alias in DATAS.getNode("aliases").index:
res.append(Response(msg.sender, "!%s correspond à %s" % (alias,
res.append(Response("!%s correspond à %s" % (alias,
DATAS.getNode("aliases").index[alias]["origin"]),
channel=msg.channel))
else:
res.append(Response(msg.sender, "!%s n'est pas un alias" % alias,
res.append(Response("!%s n'est pas un alias" % alias,
channel=msg.channel))
return res
else:
return Response(msg.sender, "!alias prend en argument l'alias à étendre.",
return Response("!alias prend en argument l'alias à étendre.",
channel=msg.channel)
@hook("cmd_hook", "unalias")
@ -113,14 +113,14 @@ def cmd_unalias(msg):
if alias in DATAS.getNode("aliases").index:
if DATAS.getNode("aliases").index[alias]["creator"] == msg.nick or msg.is_owner:
DATAS.getNode("aliases").delChild(DATAS.getNode("aliases").index[alias])
res.append(Response(msg.sender, "%s a bien été supprimé" % alias, channel=msg.channel))
res.append(Response("%s a bien été supprimé" % alias, channel=msg.channel))
else:
res.append(Response(msg.sender, "Vous n'êtes pas le createur de l'alias %s." % alias, channel=msg.channel))
res.append(Response("Vous n'êtes pas le createur de l'alias %s." % alias, channel=msg.channel))
else:
res.append(Response(msg.sender, "%s n'est pas un alias" % alias, channel=msg.channel))
res.append(Response("%s n'est pas un alias" % alias, channel=msg.channel))
return res
else:
return Response(msg.sender, "!unalias prend en argument l'alias à supprimer.", channel=msg.channel)
return Response("!unalias prend en argument l'alias à supprimer.", channel=msg.channel)
def replace_variables(cnt, msg=None):
cnt = cnt.split(' ')
@ -177,14 +177,14 @@ def parseask(msg):
if re.match(".*(set|cr[ée]{2}|nouvel(le)?) alias.*", msg.text) is not None:
result = re.match(".*alias !?([^ ]+) (pour|=|:) (.+)$", msg.text)
if result.group(1) in DATAS.getNode("aliases").index or result.group(3).find("alias") >= 0:
return Response(msg.sender, "Cet alias est déjà défini.")
raise IRCException("cet alias est déjà défini.")
else:
alias = ModuleState("alias")
alias["alias"] = result.group(1)
alias["origin"] = result.group(3)
alias["creator"] = msg.nick
DATAS.getNode("aliases").addChild(alias)
res = Response(msg.sender, "Nouvel alias %s défini avec succès." % result.group(1))
res = Response("Nouvel alias %s défini avec succès." % result.group(1))
save()
return res
return None

View File

@ -50,7 +50,7 @@ def cmd_anniv(msg):
if (tyd.day == datetime.today().day and
tyd.month == datetime.today().month):
return Response(msg.sender, countdown_format(
return Response(countdown_format(
DATAS.index[name].getDate("born"), "",
"C'est aujourd'hui l'anniversaire de %s !"
" Il a %s. Joyeux anniversaire :)" % (name, "%s")),
@ -59,12 +59,12 @@ def cmd_anniv(msg):
if tyd < datetime.today():
tyd = datetime(date.today().year + 1, tyd.month, tyd.day)
return Response(msg.sender, countdown_format(tyd,
return Response(countdown_format(tyd,
"Il reste %s avant l'anniversaire de %s !" % ("%s",
name), ""),
msg.channel)
else:
return Response(msg.sender, "désolé, je ne connais pas la date d'anniversaire"
return Response("désolé, je ne connais pas la date d'anniversaire"
" de %s. Quand est-il né ?" % name,
msg.channel, msg.nick)
@ -75,12 +75,12 @@ def cmd_age(msg):
name = matches[0]
d = DATAS.index[name].getDate("born")
return Response(msg.sender, countdown_format(d,
return Response(countdown_format(d,
"%s va naître dans %s." % (name, "%s"),
"%s a %s." % (name, "%s")),
msg.channel)
else:
return Response(msg.sender, "désolé, je ne connais pas l'âge de %s."
return Response("désolé, je ne connais pas l'âge de %s."
" Quand est-il né ?" % name, msg.channel, msg.nick)
return True
@ -91,8 +91,7 @@ def parseask(msg):
try:
extDate = extractDate(msg.text)
if extDate is None or extDate.year > datetime.now().year:
return Response(msg.sender,
"la date de naissance ne paraît pas valide...",
return Response("la date de naissance ne paraît pas valide...",
msg.channel,
msg.nick)
else:
@ -107,8 +106,7 @@ def parseask(msg):
ms.setAttribute("born", extDate)
DATAS.addChild(ms)
save()
return Response(msg.sender,
"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")),
msg.channel,
msg.nick)

View File

@ -19,18 +19,17 @@ def load(context):
def bonneannee():
txt = "Bonne année %d !" % datetime.today().year
print (txt)
send_response("localhost:2771", Response(None, txt, "#epitagueule"))
send_response("localhost:2771", Response(None, txt, "#yaka"))
send_response("localhost:2771", Response(None, txt, "#epita2014"))
send_response("localhost:2771", Response(None, txt, "#ykar"))
send_response("localhost:2771", Response(None, txt, "#42sh"))
send_response("localhost:2771", Response(None, txt, "#nemubot"))
send_response("localhost:2771", Response(txt, "#epitagueule"))
send_response("localhost:2771", Response(txt, "#yaka"))
send_response("localhost:2771", Response(txt, "#epita2014"))
send_response("localhost:2771", Response(txt, "#ykar"))
send_response("localhost:2771", Response(txt, "#42sh"))
send_response("localhost:2771", Response(txt, "#nemubot"))
@hook("cmd_hook", "newyear")
@hook("cmd_hook", str(yrn), yrn)
def cmd_newyear(msg, yr):
return Response(msg.sender,
countdown_format(datetime(yr, 1, 1, 0, 0, 1),
return Response(countdown_format(datetime(yr, 1, 1, 0, 0, 1),
"Il reste %s avant la nouvelle année.",
"Nous faisons déjà la fête depuis %s !"),
channel=msg.channel)
@ -42,8 +41,7 @@ def cmd_timetoyear(msg, cur):
if yr == cur:
return None
return Response(msg.sender,
countdown_format(datetime(yr, 1, 1, 0, 0, 1),
return Response(countdown_format(datetime(yr, 1, 1, 0, 0, 1),
"Il reste %s avant %d." % ("%s", yr),
"Le premier janvier %d est passé depuis %s !" % (yr, "%s")),
channel=msg.channel)

View File

@ -48,7 +48,7 @@ def cmd_book(msg):
book = get_book(" ".join(msg.cmds[1:]))
if book is None:
raise IRCException("unable to find book named like this")
res = Response(msg.sender, channel=msg.channel)
res = Response(channel=msg.channel)
res.append_message("%s, writed by %s: %s" % (book.getNode("title").getContent(),
book.getNode("authors").getNode("author").getNode("name").getContent(),
web.striphtml(book.getNode("description").getContent())
@ -61,7 +61,7 @@ def cmd_books(msg):
raise IRCException("please give me a title to search")
title = " ".join(msg.cmds[1:])
res = Response(msg.sender, channel=msg.channel,
res = Response(channel=msg.channel,
title="%s" % (title), count=" (%d more books)")
books = search_books(title)
@ -75,4 +75,4 @@ def cmd_author(msg):
raise IRCException("please give me an author to search")
ath = search_author(" ".join(msg.cmds[1:]))
return Response(msg.sender, [b.getNode("title").getContent() for b in ath.getNode("books").getNodes("book")], channel=msg.channel, title=ath.getNode("name").getContent())
return Response([b.getNode("title").getContent() for b in ath.getNode("books").getNodes("book")], channel=msg.channel, title=ath.getNode("name").getContent())

View File

@ -47,7 +47,7 @@ def cmd_conjug(msg):
conjug = get_conjug(verb, tens)
if len(conjug) > 0:
return Response(msg.sender, conjug, channel=msg.channel,
return Response(conjug, channel=msg.channel,
title="Conjugaison de %s" % verb)
else:
raise IRCException("aucune conjugaison de '%s' n'a été trouvé" % verb)

View File

@ -26,13 +26,12 @@ def reload():
@hook("cmd_hook", "define")
def define(msg):
if len(msg.cmds) <= 1:
return Response(msg.sender,
"Indicate a term to define",
return Response("Indicate a term to define",
msg.channel, nick=msg.nick)
s = DDGSearch.DDGSearch(' '.join(msg.cmds[1:]))
res = Response(msg.sender, channel=msg.channel)
res = Response(channel=msg.channel)
res.append_message(s.definition)
@ -41,13 +40,12 @@ def define(msg):
@hook("cmd_hook", "search")
def search(msg):
if len(msg.cmds) <= 1:
return Response(msg.sender,
"Indicate a term to search",
return Response("Indicate a term to search",
msg.channel, nick=msg.nick)
s = DDGSearch.DDGSearch(' '.join(msg.cmds[1:]))
res = Response(msg.sender, channel=msg.channel, nomore="No more results",
res = Response(channel=msg.channel, nomore="No more results",
count=" (%d more results)")
res.append_message(s.redirect)
@ -64,13 +62,12 @@ def search(msg):
@hook("cmd_hook", "urbandictionnary")
def udsearch(msg):
if len(msg.cmds) <= 1:
return Response(msg.sender,
"Indicate a term to search",
return Response("Indicate a term to search",
msg.channel, nick=msg.nick)
s = UrbanDictionnary.UrbanDictionnary(' '.join(msg.cmds[1:]))
res = Response(msg.sender, channel=msg.channel, nomore="No more results",
res = Response(channel=msg.channel, nomore="No more results",
count=" (%d more definitions)")
for d in s.definitions:
@ -82,18 +79,17 @@ def udsearch(msg):
@hook("cmd_hook", "calculate")
def calculate(msg):
if len(msg.cmds) <= 1:
return Response(msg.sender,
"Indicate a calcul to compute",
return Response("Indicate a calcul to compute",
msg.channel, nick=msg.nick)
s = WFASearch.WFASearch(' '.join(msg.cmds[1:]))
if s.success:
res = Response(msg.sender, channel=msg.channel, nomore="No more results")
res = Response(channel=msg.channel, nomore="No more results")
for result in s.nextRes:
res.append_message(result)
if (len(res.messages) > 0):
res.messages.pop(0)
return res
else:
return Response(msg.sender, s.error, msg.channel)
return Response(s.error, msg.channel)

View File

@ -36,7 +36,7 @@ def load(context):
def fini(d, strend):
send_response(strend["server"], Response(strend["sender"], "%s arrivé à échéance." % strend["name"], channel=strend["channel"], nick=strend["proprio"]))
send_response(strend["server"], Response("%s arrivé à échéance." % strend["name"], channel=strend["channel"], nick=strend["proprio"]))
DATAS.delChild(DATAS.index[strend["name"]])
save()
@ -44,8 +44,7 @@ def fini(d, strend):
def cmd_gouter(msg):
ndate = datetime.today()
ndate = datetime(ndate.year, ndate.month, ndate.day, 16, 42)
return Response(msg.sender,
countdown_format(ndate,
return Response(countdown_format(ndate,
"Le goûter aura lieu dans %s, préparez vos biscuits !",
"Nous avons %s de retard pour le goûter :("),
channel=msg.channel)
@ -54,8 +53,7 @@ def cmd_gouter(msg):
def cmd_we(msg):
ndate = datetime.today() + timedelta(5 - datetime.today().weekday())
ndate = datetime(ndate.year, ndate.month, ndate.day, 0, 0, 1)
return Response(msg.sender,
countdown_format(ndate,
return Response(countdown_format(ndate,
"Il reste %s avant le week-end, courage ;)",
"Youhou, on est en week-end depuis %s."),
channel=msg.channel)
@ -129,11 +127,11 @@ def start_countdown(msg):
save()
if "end" in strnd:
return Response(msg.sender, "%s commencé le %s et se terminera le %s." %
return Response("%s commencé le %s et se terminera le %s." %
(msg.cmds[1], msg.tags["time"].strftime("%A %d %B %Y à %H:%M:%S"),
strnd.getDate("end").strftime("%A %d %B %Y à %H:%M:%S")))
else:
return Response(msg.sender, "%s commencé le %s"% (msg.cmds[1],
return Response("%s commencé le %s"% (msg.cmds[1],
msg.tags["time"].strftime("%A %d %B %Y à %H:%M:%S")))
@hook("cmd_hook", "end")
@ -148,12 +146,12 @@ def end_countdown(msg):
del_event(DATAS.index[msg.cmds[1]]["id"])
DATAS.delChild(DATAS.index[msg.cmds[1]])
save()
return Response(msg.sender, "%s a duré %s." % (msg.cmds[1], duration),
return Response("%s a duré %s." % (msg.cmds[1], duration),
channel=msg.channel, nick=msg.nick)
else:
raise IRCException("Vous ne pouvez pas terminer le compteur %s, créé par %s." % (msg.cmds[1], DATAS.index[msg.cmds[1]]["proprio"]))
else:
return Response(msg.sender, "%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)
@hook("cmd_hook", "eventslist")
def liste(msg):
@ -166,14 +164,14 @@ def liste(msg):
res.append("Compteurs créés par %s : %s" % (user, ", ".join(cmptr)))
else:
res.append("%s n'a pas créé de compteur" % user)
return Response(msg.sender, " ; ".join(res), channel=msg.channel)
return Response(" ; ".join(res), channel=msg.channel)
else:
return Response(msg.sender, "Compteurs connus : %s." % ", ".join(DATAS.index.keys()), channel=msg.channel)
return Response("Compteurs connus : %s." % ", ".join(DATAS.index.keys()), channel=msg.channel)
@hook("cmd_default")
def parseanswer(msg):
if msg.cmds[0] in DATAS.index:
res = Response(msg.sender, channel=msg.channel)
res = Response(channel=msg.channel)
# Avoid message starting by ! which can be interpreted as command by other bots
if msg.cmds[0][0] == "!":
@ -228,8 +226,7 @@ def parseask(msg):
evt["msg_before"] = msg_before
DATAS.addChild(evt)
save()
return Response(msg.sender,
"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)
elif texts is not None and texts.group (2) is not None:
@ -242,7 +239,7 @@ def parseask(msg):
evt["msg_before"] = texts.group (2)
DATAS.addChild(evt)
save()
return Response(msg.sender, "Nouvelle commande !%s ajoutée avec succès." % name.group(1))
return Response("Nouvelle commande !%s ajoutée avec succès." % name.group(1))
else:
raise IRCException("Veuillez indiquez les messages d'attente et d'après événement entre guillemets.")

View File

@ -72,7 +72,7 @@ def cmd_github(msg):
repos = info_repos(" ".join(msg.cmds[1:]))
res = Response(msg.sender, channel=msg.channel, nomore="No more repository", count=" (%d more repo)")
res = Response(channel=msg.channel, nomore="No more repository", count=" (%d more repo)")
for repo in repos["items"]:
homepage = ""
@ -87,7 +87,7 @@ def cmd_github(msg):
if len(msg.cmds) < 2:
raise IRCException("indicate a user name to search")
res = Response(msg.sender, channel=msg.channel, nomore="No more user")
res = Response(channel=msg.channel, nomore="No more user")
user = info_user(" ".join(msg.cmds[1:]))
@ -126,7 +126,7 @@ def cmd_github(msg):
repo = " ".join(msg.cmds[1:])
count = " (%d more issues)" if issue is None else None
res = Response(msg.sender, channel=msg.channel, nomore="No more issue", count=count)
res = Response(channel=msg.channel, nomore="No more issue", count=count)
issues = info_issue(repo, issue)
@ -159,7 +159,7 @@ def cmd_github(msg):
repo = " ".join(msg.cmds[1:])
count = " (%d more commits)" if commit is None else None
res = Response(msg.sender, channel=msg.channel, nomore="No more commit", count=count)
res = Response(channel=msg.channel, nomore="No more commit", count=count)
commits = info_commit(repo, commit)

View File

@ -84,7 +84,7 @@ def cmd_imdb(msg):
else:
data = get_movie(title=title)
res = Response(msg.sender, channel=msg.channel,
res = Response(channel=msg.channel,
title="%s (%s)" % (data['Title'], data['Year']),
nomore="No more information, more at http://www.imdb.com/title/%s" % data['imdbID'])
@ -105,4 +105,4 @@ def cmd_search(msg):
for m in data['Search']:
movies.append("\x02%s\x0F (%s of %s)" % (m['Title'], m['Type'], m['Year']))
return Response(msg.sender, movies, title="Titles found", channel=msg.channel)
return Response(movies, title="Titles found", channel=msg.channel)

View File

@ -32,7 +32,7 @@ def cmd_man(msg):
args.append(msg.cmds[1])
os.unsetenv("LANG")
res = Response(msg.sender, channel=msg.channel)
res = Response(channel=msg.channel)
with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
for line in proc.stdout.read().split(b"\n"):
(line, n) = RGXP_s.subn(b'', line)
@ -50,7 +50,7 @@ def cmd_man(msg):
def cmd_whatis(msg):
args = ["whatis", " ".join(msg.cmds[1:])]
res = Response(msg.sender, channel=msg.channel)
res = Response(channel=msg.channel)
with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
for line in proc.stdout.read().split(b"\n"):
(line, n) = RGXP_s.subn(b'', line)

View File

@ -43,7 +43,7 @@ def cmd_geocode(msg):
raise IRCException("indicate a name")
locname = ' '.join(msg.cmds[1:])
res = Response(msg.sender, channel=msg.channel, nick=msg.nick, nomore="No more geocode", count=" (%s more geocode)")
res = Response(channel=msg.channel, nick=msg.nick, nomore="No more geocode", count=" (%s more geocode)")
for loc in geocode(locname):
res.append_message("%s is at %s,%s (%s precision)" % (where(loc), loc["latLng"]["lat"], loc["latLng"]["lng"], loc["geocodeQuality"].lower()))
return res

View File

@ -76,8 +76,7 @@ def cmd_mediawiki(msg):
if len(msg.cmds) < 3:
raise IRCException("indicate a domain and a term to search")
return Response(msg.sender,
get_page(msg.cmds[1], " ".join(msg.cmds[2:])),
return Response(get_page(msg.cmds[1], " ".join(msg.cmds[2:])),
channel=msg.receivers)
@ -86,7 +85,7 @@ def cmd_wikipedia(msg):
if len(msg.cmds) < 3:
raise IRCException("indicate a lang and a term to search")
return Response(msg.sender,
get_page(msg.cmds[1] + ".wikipedia.org", " ".join(msg.cmds[2:])),
channel=msg.receivers,
line_treat=lambda line: irc_format(parse_wikitext(site, line, ssl)))
return Response(irc_format(parse_wikitext(get_page(msg.cmds[1] + ".wikipedia.org", " ".join(msg.cmds[2:])))),
# get_page(msg.cmds[1] + ".wikipedia.org", " ".join(msg.cmds[2:])),
# line_treat=lambda line: irc_format(parse_wikitext(site, line, ssl)),
channel=msg.receivers)

View File

@ -32,7 +32,7 @@ def cmd_w3m(msg):
if len(msg.cmds) > 1:
args = ["w3m", "-T", "text/html", "-dump"]
args.append(msg.cmds[1])
res = Response(msg.sender, channel=msg.channel)
res = Response(channel=msg.channel)
with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
for line in proc.stdout.read().split(b"\n"):
res.append_message(line.decode())
@ -48,7 +48,7 @@ def cmd_curl(msg):
try:
req = web.getURLContent(" ".join(msg.cmds[1:]))
if req is not None:
res = Response(msg.sender, channel=msg.channel)
res = Response(channel=msg.channel)
for m in req.split("\n"):
res.append_message(m)
return res
@ -88,7 +88,7 @@ def cmd_curly(msg):
finally:
conn.close()
return Response(msg.sender, "Entêtes de la page %s : HTTP/%s, statut : %d %s ; headers : %s" % (url, res.version, res.status, res.reason, ", ".join(["\x03\x02" + h + "\x03\x02: " + v for h, v in res.getheaders()])), channel=msg.channel)
return Response("Entêtes de la page %s : HTTP/%s, statut : %d %s ; headers : %s" % (url, res.version, res.status, res.reason, ", ".join(["\x03\x02" + h + "\x03\x02: " + v for h, v in res.getheaders()])), channel=msg.channel)
@hook("cmd_hook", "traceurl")
def cmd_traceurl(msg):
@ -96,7 +96,7 @@ def cmd_traceurl(msg):
res = list()
for url in msg.cmds[1:]:
trace = traceURL(url)
res.append(Response(msg.sender, trace, channel=msg.channel, title="TraceURL"))
res.append(Response(trace, channel=msg.channel, title="TraceURL"))
return res
else:
raise IRCException("Indiquer a URL to trace!")
@ -170,7 +170,7 @@ def cmd_whois(msg):
whois = js["WhoisRecord"]
res = Response(msg.sender, channel=msg.channel, nomore="No more whois information")
res = Response(channel=msg.channel, nomore="No more whois information")
res.append_message("%s: %s%s%s%s\x03\x02registered by\x03\x02 %s, \x03\x02administrated by\x03\x02 %s, \x03\x02managed by\x03\x02 %s" % (whois["domainName"],
whois["status"] + " " if "status" in whois else "",
@ -196,14 +196,14 @@ def cmd_isup(msg):
raw = urllib.request.urlopen(req, timeout=10)
isup = json.loads(raw.read().decode())
if "status_code" in isup and isup["status_code"] == 1:
res.append(Response(msg.sender, "%s est accessible (temps de reponse : %ss)" % (isup["domain"], isup["response_time"]), channel=msg.channel))
res.append(Response("%s est accessible (temps de reponse : %ss)" % (isup["domain"], isup["response_time"]), channel=msg.channel))
else:
res.append(Response(msg.sender, "%s n'est pas accessible :(" % (isup["domain"]), channel=msg.channel))
res.append(Response("%s n'est pas accessible :(" % (isup["domain"]), channel=msg.channel))
else:
res.append(Response(msg.sender, "%s n'est pas une URL valide" % url, channel=msg.channel))
res.append(Response("%s n'est pas une URL valide" % url, channel=msg.channel))
return res
else:
return Response(msg.sender, "Indiquer une URL à vérifier !", channel=msg.channel)
return Response("Indiquer une URL à vérifier !", channel=msg.channel)
def traceURL(url, timeout=5, stack=None):
"""Follow redirections and return the redirections stack"""
@ -277,7 +277,7 @@ def cmd_w3c(msg):
validator = json.loads(raw.read().decode())
res = Response(msg.sender, channel=msg.channel, nomore="No more error")
res = Response(channel=msg.channel, nomore="No more error")
res.append_message("%s: status: %s, %s warning(s), %s error(s)" % (validator["url"], headers["X-W3C-Validator-Status"], headers["X-W3C-Validator-Warnings"], headers["X-W3C-Validator-Errors"]))

View File

@ -24,17 +24,16 @@ def extractInformation(msg, transport, line, station=None):
times = ratp.getNextStopsAtStation(transport, line, station)
if len(times) > 0:
(time, direction, stationname) = times[0]
return Response(msg.sender, message=["\x03\x02"+time+"\x03\x02 direction "+direction for time, direction, stationname in times], title="Prochains passages du %s ligne %s à l'arrêt %s" %
return Response(message=["\x03\x02"+time+"\x03\x02 direction "+direction for time, direction, stationname in times], title="Prochains passages du %s ligne %s à l'arrêt %s" %
(transport, line, stationname), channel=msg.channel)
else:
return Response(msg.sender, "La station `%s' ne semble pas exister sur le %s ligne %s."
% (station, transport, line), msg.channel)
raise IRCException("La station `%s' ne semble pas exister sur le %s ligne %s."
% (station, transport, line))
else:
stations = ratp.getAllStations(transport, line)
if len(stations) > 0:
return Response(msg.sender, [s for s in stations], title="Stations", channel=msg.channel)
else:
return Response(msg.sender, "Aucune station trouvée.", msg.channel)
if len(stations) == 0:
raise IRCException("aucune station trouvée.")
return Response([s for s in stations], title="Stations", channel=msg.channel)
def ask_ratp(msg):
"""Hook entry from !ratp"""
@ -44,5 +43,5 @@ def ask_ratp(msg):
elif len(msg.cmds) == 3:
return extractInformation(msg, msg.cmds[1], msg.cmds[2])
else:
return Response(msg.sender, "Mauvais usage, merci de spécifier un type de transport et une ligne, ou de consulter l'aide du module.", msg.channel, msg.nick)
raise IRCException("Mauvais usage, merci de spécifier un type de transport et une ligne, ou de consulter l'aide du module.")
return False

View File

@ -42,15 +42,15 @@ def cmd_subreddit(msg):
sbr = json.loads(raw.read().decode())
if "title" in sbr["data"]:
res = Response(msg.sender, channel=msg.channel, nomore="No more information")
res = Response(channel=msg.channel, nomore="No more information")
res.append_message(("[NSFW] " if sbr["data"]["over18"] else "") + sbr["data"]["url"] + " " + sbr["data"]["title"] + ": " + sbr["data"]["public_description" if sbr["data"]["public_description"] != "" else "description"].replace("\n", " ") + " %s subscriber(s)" % sbr["data"]["subscribers"])
if sbr["data"]["public_description"] != "":
res.append_message(sbr["data"]["description"].replace("\n", " "))
all_res.append(res)
else:
all_res.append(Response(msg.sender, "/%s/%s doesn't exist" % (where, sub.group(2)), channel=msg.channel))
all_res.append(Response("/%s/%s doesn't exist" % (where, sub.group(2)), channel=msg.channel))
else:
all_res.append(Response(msg.sender, "%s is not a valid subreddit" % osub, channel=msg.channel, nick=msg.nick))
all_res.append(Response("%s is not a valid subreddit" % osub, channel=msg.channel, nick=msg.nick))
return all_res

View File

@ -11,6 +11,6 @@ nemubotversion = 3.4
@hook("cmd_hook", "choice")
def cmd_choice(msg):
if len(msg.cmds) > 1:
return Response(msg.sender, random.choice(msg.cmds[1:]), channel=msg.channel, nick=msg.nick)
return Response(random.choice(msg.cmds[1:]), channel=msg.channel, nick=msg.nick)
else:
raise IRCException("indicate some terms to pick!")

View File

@ -23,7 +23,7 @@ def cmd_tcode(msg):
url = "http://www.tcodesearch.com/tcodes/search?q=%s" % urllib.parse.quote(msg.cmds[1])
page = web.getURLContent(url)
res = Response(msg.sender, channel=msg.channel,
res = Response(channel=msg.channel,
nomore="No more transaction code", count=" (%d more tcodes)")
if page is not None:

View File

@ -30,8 +30,7 @@ def cmd_sleep(msg):
for i in range(0,6):
f.append(f[i] - timedelta(hours=1,minutes=30))
g.append(f[i+1].strftime("%H:%M"))
return Response(msg.sender,
"You should try to fall asleep at one of the following"
return Response("You should try to fall asleep at one of the following"
" times: %s" % ', '.join(g), channel=msg.channel)
# Just get awake times
@ -41,7 +40,6 @@ def cmd_sleep(msg):
for i in range(0,6):
f.append(f[i] + timedelta(hours=1,minutes=30))
g.append(f[i+1].strftime("%H:%M"))
return Response(msg.sender,
"If you head to bed right now, you should try to wake"
return Response("If you head to bed right now, you should try to wake"
" up at one of the following times: %s" %
', '.join(g), channel=msg.channel)

View File

@ -69,9 +69,9 @@ def cmd_sms(msg):
fails.append( "%s: %s" % (u, test) )
if len(fails) > 0:
return Response(msg.sender, "quelque chose ne s'est pas bien passé durant l'envoi du SMS : " + ", ".join(fails), msg.channel, msg.nick)
return Response("quelque chose ne s'est pas bien passé durant l'envoi du SMS : " + ", ".join(fails), msg.channel, msg.nick)
else:
return Response(msg.sender, "le SMS a bien été envoyé", msg.channel, msg.nick)
return Response("le SMS a bien été envoyé", msg.channel, msg.nick)
apiuser_ask = re.compile(r"(utilisateur|user|numéro|numero|compte|abonne|abone|abonné|account)\s+(est|is)\s+(?P<user>[0-9]{7,})", re.IGNORECASE)
apikey_ask = re.compile(r"(clef|key|password|mot de passe?)\s+(?:est|is)?\s+(?P<key>[a-zA-Z0-9]{10,})", re.IGNORECASE)
@ -90,7 +90,7 @@ def parseask(msg):
test = send_sms("nemubot", apiuser, apikey,
"Vous avez enregistré vos codes d'authentification dans nemubot, félicitation !")
if test is not None:
return Response(msg.sender, "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:
DATAS.index[msg.nick]["user"] = apiuser
@ -103,5 +103,5 @@ def parseask(msg):
ms.setAttribute("lastuse", 0)
DATAS.addChild(ms)
save()
return Response(msg.sender, "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)

View File

@ -33,7 +33,7 @@ def cmd_spell(msg):
try:
r = check_spell(word, lang)
except AspellError:
return Response(msg.sender, "Je n'ai pas le dictionnaire `%s' :(" % lang, msg.channel, msg.nick)
return Response("Je n'ai pas le dictionnaire `%s' :(" % lang, msg.channel, msg.nick)
if r == True:
add_score(msg.nick, "correct")
strRes.append("l'orthographe de `%s' est correcte" % word)
@ -43,7 +43,7 @@ def cmd_spell(msg):
else:
add_score(msg.nick, "bad")
strRes.append("aucune suggestion pour `%s'" % word)
return Response(msg.sender, strRes, channel=msg.channel, nick=msg.nick)
return Response(strRes, channel=msg.channel, nick=msg.nick)
def add_score(nick, t):
global DATAS
@ -66,13 +66,13 @@ def cmd_score(msg):
if len(msg.cmds) > 1:
for cmd in msg.cmds[1:]:
if cmd in DATAS.index:
res.append(Response(msg.sender, "%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, DATAS.index[cmd].getInt(a)) for a in DATAS.index[cmd].attributes.keys() if a != "name"])), channel=msg.channel))
else:
unknown.append(cmd)
else:
return Response(msg.sender, "De qui veux-tu voir les scores ?", channel=msg.channel, nick=msg.nick)
return Response("De qui veux-tu voir les scores ?", channel=msg.channel, nick=msg.nick)
if len(unknown) > 0:
res.append(Response(msg.sender, "%s inconnus" % ", ".join(unknown), channel=msg.channel))
res.append(Response("%s inconnus" % ", ".join(unknown), channel=msg.channel))
return res

View File

@ -35,7 +35,7 @@ def go(what, msg):
if what == "synonymes":
if len(synos) > 0:
res = Response(msg.sender, best, channel=msg.channel,
res = Response(best, channel=msg.channel,
title="Synonymes de %s" % word)
res.append_message(synos)
return res
@ -44,7 +44,7 @@ def go(what, msg):
elif what == "antonymes":
if len(anton) > 0:
res = Response(msg.sender, anton, channel=msg.channel,
res = Response(anton, channel=msg.channel,
title="Antonymes de %s" % word)
return res
else:

View File

@ -68,7 +68,7 @@ def cmd_translate(msg):
raise IRCException(wres["Note"])
else:
res = Response(msg.sender, channel=msg.channel,
res = Response(channel=msg.channel,
count=" (%d more meanings)",
nomore="No more translation")
for k in sorted(wres.keys()):

View File

@ -55,8 +55,7 @@ def print_station_status(msg, station):
"""Send message with information about the given station"""
(available, free) = station_status(station)
if available is not None and free is not None:
return Response(msg.sender,
"à la station %s : %d vélib et %d points d'attache"
return Response("à la station %s : %d vélib et %d points d'attache"
" disponibles." % (station, available, free),
channel=msg.channel, nick=msg.nick)
raise IRCException("station %s inconnue." % station)

View File

@ -70,8 +70,7 @@ def del_site(msg):
del_event(site["_evt_id"])
DATAS.delChild(site)
save()
return Response(msg.sender,
"je ne surveille désormais plus cette URL.",
return Response("je ne surveille désormais plus cette URL.",
channel=msg.channel, nick=msg.nick)
raise IRCException("je ne surveillais pas cette URL !")
@ -107,12 +106,12 @@ def add_site(msg, diffType="diff"):
DATAS.index[url].addChild(alert)
save()
return Response(msg.sender, channel=msg.channel, nick=msg.nick,
return Response(channel=msg.channel, nick=msg.nick,
message="ce site est maintenant sous ma surveillance.")
def format_response(site, link='%s', title='%s', categ='%s', content='%s'):
for a in site.getNodes("alert"):
send_response(a["server"], Response(a["sender"], a["message"].format(url=site["url"], link=link, title=title, categ=categ, content=content),
send_response(a["server"], Response(a["message"].format(url=site["url"], link=link, title=title, categ=categ, content=content),
channel=a["channel"], server=a["server"]))
def alert_change(content, site):

View File

@ -144,13 +144,13 @@ def cmd_coordinates(msg):
raise IRCException("%s n'est pas une ville connue" % msg.cmds[1])
coords = DATAS.index[j]
return Response(msg.sender, "Les coordonnées de %s sont %s,%s" % (msg.cmds[1], coords["lat"], coords["long"]), channel=msg.channel)
return Response("Les coordonnées de %s sont %s,%s" % (msg.cmds[1], coords["lat"], coords["long"]), channel=msg.channel)
def cmd_alert(msg):
loc, coords, specific = treat_coord(msg)
wth = get_json_weather(coords)
res = Response(msg.sender, channel=msg.channel, nomore="No more weather alert", count=" (%d more alerts)")
res = Response(channel=msg.channel, nomore="No more weather alert", count=" (%d more alerts)")
if "alerts" in wth:
for alert in wth["alerts"]:
@ -162,7 +162,7 @@ def cmd_weather(msg):
loc, coords, specific = treat_coord(msg)
wth = get_json_weather(coords)
res = Response(msg.sender, channel=msg.channel, nomore="No more weather information")
res = Response(channel=msg.channel, nomore="No more weather information")
if "alerts" in wth:
alert_msgs = list()
@ -228,6 +228,5 @@ def parseask(msg):
ms.setAttribute("long", gps_long)
DATAS.addChild(ms)
save()
return Response(msg.sender,
"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)

View File

@ -79,7 +79,7 @@ def current_match_new_action(match_str, osef):
msg += " ; à la " + txt_event(events[0])
for n in DATAS.getChilds():
send_response(n["server"], Response(n["sender"], msg, channel=n["channel"]))
send_response(n["server"], Response(msg, channel=n["channel"]))
def is_int(s):
try:
@ -179,7 +179,7 @@ def get_matches(url):
@hook("cmd_hook", "worldcup")
def cmd_worldcup(msg):
res = Response(msg.sender, channel=msg.channel, nomore="No more match to display", count=" (%d more matches)")
res = Response(channel=msg.channel, nomore="No more match to display", count=" (%d more matches)")
nb = len(msg.cmds)
url = None

View File

@ -20,7 +20,7 @@ def gen_response(res, msg, srv):
if res is None:
raise IRCException("la situation est embarassante, il semblerait que YCC soit down :(")
elif isinstance(res, str):
return Response(msg.sender, "URL pour %s : %s" % (srv, res), msg.channel)
return Response("URL pour %s : %s" % (srv, res), msg.channel)
else:
raise IRCException("mauvaise URL : %s" % srv)

View File

@ -23,9 +23,9 @@ import sys
logger = logging.getLogger("nemubot.response")
class Response:
def __init__(self, sender, message=None, channel=None, nick=None, server=None,
nomore="No more message", title=None, more="(suite) ", count=None,
ctcp=False, shown_first_count=-1):
def __init__(self, message=None, channel=None, nick=None, server=None,
nomore="No more message", title=None, more="(suite) ",
count=None, ctcp=False, shown_first_count=-1):
self.nomore = nomore
self.more = more
self.rawtitle = title
@ -37,29 +37,22 @@ class Response:
self.append_message(message, shown_first_count=shown_first_count)
self.elt = 0 # Next element to display
self.sender = None
self.channel = channel
self.nick = nick
self.set_sender(sender)
self.count = count
@property
def receivers(self):
if type(self.channel) is list:
if self.channel is None:
if self.nick is not None:
return [ self.nick ]
return [ self.sender.split("!")[0] ]
elif isinstance(self.channel, list):
return self.channel
else:
return [ self.channel ]
@property
def content(self):
#FIXME: error when messages in self.messages are list!
try:
if self.title is not None:
return self.title + ", ".join(self.messages)
else:
return ", ".join(self.messages)
except:
return ""
def set_sender(self, sender):
if sender is None or sender.find("!") < 0:
if sender is not None:

View File

@ -56,8 +56,7 @@ class IRCServer(SocketServer):
def _ctcp_clientinfo(msg):
"""Response to CLIENTINFO CTCP message"""
return _ctcp_response(msg.sender,
" ".join(self.ctcp_capabilities.keys()))
return _ctcp_response(" ".join(self.ctcp_capabilities.keys()))
def _ctcp_dcc(msg):
"""Response to DCC CTCP message"""
@ -66,7 +65,7 @@ class IRCServer(SocketServer):
port = int(msg.cmds[4])
conn = DCC(srv, msg.sender)
except:
return _ctcp_response(msg.sender, "ERRMSG invalid parameters provided as DCC CTCP request")
return _ctcp_response("ERRMSG invalid parameters provided as DCC CTCP request")
self.logger.info("Receive DCC connection request from %s to %s:%d", conn.sender, ip, port)
@ -75,25 +74,25 @@ class IRCServer(SocketServer):
conn.send_dcc("Hello %s!" % conn.nick)
else:
self.logger.error("DCC: unable to connect to %s:%d", ip, port)
return _ctcp_response(msg.sender, "ERRMSG unable to connect to %s:%d" % (ip, port))
return _ctcp_response("ERRMSG unable to connect to %s:%d" % (ip, port))
self.ctcp_capabilities["ACTION"] = lambda msg: print ("ACTION receive: %s" % msg.text)
self.ctcp_capabilities["CLIENTINFO"] = _ctcp_clientinfo
#self.ctcp_capabilities["DCC"] = _ctcp_dcc
self.ctcp_capabilities["FINGER"] = lambda msg: _ctcp_response(
msg.sender, "VERSION nemubot v%s" % bot.__version__)
"VERSION nemubot v%s" % bot.__version__)
self.ctcp_capabilities["NEMUBOT"] = lambda msg: _ctcp_response(
msg.sender, "NEMUBOT %s" % bot.__version__)
"NEMUBOT %s" % bot.__version__)
self.ctcp_capabilities["PING"] = lambda msg: _ctcp_response(
msg.sender, "PING %s" % " ".join(msg.cmds[1:]))
"PING %s" % " ".join(msg.cmds[1:]))
self.ctcp_capabilities["SOURCE"] = lambda msg: _ctcp_response(
msg.sender, "SOURCE https://github.com/nemunaire/nemubot")
"SOURCE https://github.com/nemunaire/nemubot")
self.ctcp_capabilities["TIME"] = lambda msg: _ctcp_response(
msg.sender, "TIME %s" % (datetime.now()))
"TIME %s" % (datetime.now()))
self.ctcp_capabilities["USERINFO"] = lambda msg: _ctcp_response(
msg.sender, "USERINFO %s" % self.realname)
"USERINFO %s" % self.realname)
self.ctcp_capabilities["VERSION"] = lambda msg: _ctcp_response(
msg.sender, "VERSION nemubot v%s" % bot.__version__)
"VERSION nemubot v%s" % bot.__version__)
self.logger.debug("CTCP capabilities setup: %s", ", ".join(self.ctcp_capabilities))
@ -187,15 +186,11 @@ class IRCServer(SocketServer):
return False
def send_response(self, res):
if type(res.channel) != list:
res.channel = [ res.channel ]
for channel in res.channel:
for channel in res.receivers:
if channel is not None and channel != self.nick:
self.write("%s %s :%s" % ("PRIVMSG", channel, res.get_message()))
else:
channel = res.sender.split("!")[0]
self.write("%s %s :%s" % ("NOTICE" if res.is_ctcp else "PRIVMSG", channel, res.get_message()))
else:
raise Exception("Trying to send a message to an undefined channel: %s" % channel)
def _close(self):
if self.socket is not None: self.write("QUIT")
@ -212,12 +207,19 @@ class IRCServer(SocketServer):
mes = msg.to_message()
mes.raw = msg.raw
if mes.cmd == "PRIVMSG" and mes.is_ctcp:
if hasattr(mes, "receivers"):
# Private message: prepare response
for i in range(len(mes.receivers)):
if mes.receivers[i] == self.nick:
mes.receivers[i] = mes.nick
if (mes.cmd == "PRIVMSG" or mes.cmd == "NOTICE") and mes.is_ctcp:
if mes.cmds[0] in self.ctcp_capabilities:
res = self.ctcp_capabilities[mes.cmds[0]](mes)
else:
res = _ctcp_response(mes.sender, "ERRMSG Unknown or unimplemented CTCP request")
res = _ctcp_response("ERRMSG Unknown or unimplemented CTCP request")
if res is not None:
res.set_sender(mes.sender)
self.send_response(res)
else:
@ -226,8 +228,8 @@ class IRCServer(SocketServer):
from response import Response
def _ctcp_response(sndr, msg):
return Response(sndr, msg, ctcp=True)
def _ctcp_response(msg):
return Response(msg, ctcp=True)
mgx = re.compile(b'''^(?:@(?P<tags>[^ ]+)\ )?