X-Git-Url: http://gitweb.pimeys.fr/?a=blobdiff_plain;f=basile.py;h=a21e79256f732535a79d1f2dc1c04663c4b812dc;hb=12d90abb13b7b999b2dda6475f0ba0f2e544d603;hp=4ee806783efa2306f1f0afc738f7c3ad7e3bdc46;hpb=4d6cedfb164059e9c5c607db4752533ae7333b44;p=bots%2Fbasile.git diff --git a/basile.py b/basile.py index 4ee8067..a21e792 100755 --- a/basile.py +++ b/basile.py @@ -25,10 +25,13 @@ from commands import getstatusoutput as ex import config #: Module responsable du dialogue avec la NoteKfet2015 import nk +#: Module de réponse aux questions de base +import isit +#: Module définissant les erreurs +import errors # la partie qui réfère au fichier lui-même est mieux ici # sinon on réfère la config et pas le fichier lui-même -import os config.thisfile = os.path.realpath(__file__) def get_config_logfile(serveur): @@ -52,151 +55,28 @@ def log(serveur, channel, auteur=None, message=None): f.write((chain + u"\n").encode("utf-8")) f.close() if config.debug_stdout: - print chain + print chain.encode("utf-8") def ignore_event(serv, ev): """Retourne ``True`` si il faut ignorer cet évènement.""" - for (blackmask, exceptmask) in config.blacklisted_masks: + for (blackmask, exceptlist) in config.blacklisted_masks: usermask = ev.source() - if exceptmask is None: - exceptit = False - else: - exceptit = bool(irclib.mask_matches(usermask, exceptmask)) blackit = bool(irclib.mask_matches(usermask, blackmask)) - return blackit and not exceptit - -def regex_join(liste, avant=u".*(?:^| )", apres=u"(?:$|\.| |,|;).*"): - """Fabrique une regexp à partir d'une liste d'éléments à matcher.""" - return avant + u"(" + u"|".join(liste) + u")" + apres - -def is_something(chain, regexp=None, matches=[], avant=u".*(?:^| )", apres=u"(?:$|\.| |,|;).*", - case_sensitive=False): - """Vérifie si chain contient un des éléments de ``matches``. - Si ``regexp`` est fournie, c'est simplement elle qui est testée""" - if case_sensitive: - chain = chain.lower() - if regexp == None: - regexp = regex_join(matches, avant, apres) - regexp = re.compile(regexp) - o = regexp.match(chain) - return o - -def regexp_compile(): - """Compilation des regexp à partir de la conf. - Place les résultats dans le namespace de ``config``""" - config.insult_regexp = regex_join(config.insultes, avant=u".*(?:^| |')") - config.insult_regexp_compiled = re.compile(config.insult_regexp) - - config.not_insult_regexp = u".*pas %s%s" % (config.amplifier_regexp, config.insult_regexp) - config.not_insult_regexp_compiled = re.compile(config.not_insult_regexp) - - config.compliment_regexp = regex_join(config.compliment_triggers, avant=u".*(?:^| |')") - config.compliment_regexp_compiled = re.compile(config.compliment_regexp) - - config.perdu_regexp = regex_join(config.perdu) - config.perdu_regexp_compiled = re.compile(config.perdu_regexp) - - config.tag_regexp = regex_join(config.tag_triggers) - config.tag_regexp_compiled = re.compile(config.tag_regexp) - - config.gros_regexp = regex_join(config.gros) - config.gros_regexp_compiled = re.compile(config.gros_regexp) - - config.tesla_regexp = regex_join(config.tesla_triggers, avant=u"^", apres="$") - config.tesla_regexp_compiled = re.compile(config.tesla_regexp) - - config.merci_regexp = regex_join(config.merci_triggers) - config.merci_regexp_compiled = re.compile(config.merci_regexp) - - config.tamere_regexp = regex_join(config.tamere_triggers) - config.tamere_regexp_compiled = re.compile(config.tamere_regexp) - - config.bonjour_regexp = regex_join(config.bonjour_triggers, avant=u"^") - config.bonjour_regexp_compiled = re.compile(config.bonjour_regexp) - - config.bonne_nuit_regexp = regex_join(config.bonne_nuit_triggers, avant=u"^") - config.bonne_nuit_regexp_compiled = re.compile(config.bonne_nuit_regexp) - - config.pan_regexp = regex_join(config.pan_triggers, avant=".*", apres=".*") - config.pan_regexp_compiled = re.compile(config.pan_regexp) - - -regexp_compile() -def is_insult(chain, debug=True): - """Vérifie si ``chain`` contient une insulte.""" - return is_something(chain, config.insult_regexp_compiled) -def is_not_insult(chain): - """Vérifie si ``chain`` contient une insulte à la forme négative.""" - return is_something(chain, config.not_insult_regexp_compiled) -def is_compliment(chain, debug=True): - """Vérifie si ``chain`` contient un compliment.""" - return is_something(chain, config.compliment_regexp_compiled) -def is_perdu(chain): - """Vérifie si ``chain`` contient une raison de perdre.""" - return is_something(chain, config.perdu_regexp_compiled) -def is_tag(chain): - """Vérifie si ``chain`` demande de fermer sa gueule.""" - return is_something(chain, config.tag_regexp_compiled) -def is_gros(chain): - """Vérifie si ``chain`` traite de gros.""" - return is_something(chain, config.gros_regexp_compiled) -def is_tesla(chain): - """Vérifie si ``chain`` est un ping.""" - return is_something(chain, config.tesla_regexp_compiled) -def is_merci(chain): - """Vérifie si ``chain`` contient un remerciement.""" - return is_something(chain, config.merci_regexp_compiled) -def is_tamere(chain): - """Vérifie si ``chain`` traite ma mère.""" - return is_something(chain, config.tamere_regexp_compiled) -def is_bad_action_trigger(chain,pseudo): - """Vérifie si ``chain`` est une action méchante. - On a besoin d'une regexp dynamique à cause du pseudo qui peut changer.""" - return is_something(chain, matches=config.bad_action_triggers, avant=u"^", - apres="(?: [a-z]*ment)? %s($|\.| |,|;).*" % (pseudo)) -def is_good_action_trigger(chain,pseudo): - """Vérifie si ``chain`` est une action gentille. - On a besoin d'une regexp dynamique à cause du pseudo qui peut changer.""" - return is_something(chain, matches=config.good_action_triggers, avant=u"^", - apres="(?: [a-z]*ment)? %s($|\.| |,|;).*" % (pseudo)) -def is_bonjour(chain): - """Vérifie si ``chain`` contient un bonjour.""" - return is_something(chain, config.bonjour_regexp_compiled) -def is_bonne_nuit(chain): - """Vérifie si ``chain`` contient un bonne nuit.""" - return is_something(chain, config.bonne_nuit_regexp_compiled) -def is_pan(chain): - """Vérifie si ``chain`` contient un pan.""" - return is_something(chain, config.pan_regexp_compiled) - -def is_time(conf): - """Vérifie si l'heure actuelle est entre les deux heures ``conf[0]`` et ``conf[1]``""" - _, _, _, h, m, s, _, _, _ = time.localtime() - return (conf[0], 0, 0) < (h, m, s) < (conf[1], 0, 0) -def is_day(): - """Vérifie si on est le jour.""" - return is_time(config.daytime) -def is_night(): - """Vérifie si on est la nuit.""" - return is_time(config.nighttime) - - -class UnicodeBotError(Exception): - """Erreur levée si quelqu'un fait du caca avec son encodage.""" - pass + exceptit = any([bool(irclib.mask_matches(usermask, exceptmask)) for exceptmask in exceptlist]) + if exceptit: # Il est exempté + return False + else: + if blackit: # Il n'est pas exempté et matche la blacklist + return True -class CrashError(Exception): - """Pour pouvoir faire crasher Basile, parce que ça a l'air drôle.""" - def __init__(self, msg=""): - Exception.__init__(self, msg) def bot_unicode(chain): """Essaye de décoder ``chain`` en UTF-8. - Lève une py:class:`UnicodeBotError` en cas d'échec.""" + Lève une py:class:`errors.UnicodeBotError` en cas d'échec.""" try: return chain.decode("utf8") except UnicodeDecodeError as exc: - raise UnicodeBotError + raise errors.UnicodeBotError class Basile(ircbot.SingleServerIRCBot): @@ -297,7 +177,7 @@ class Basile(ircbot.SingleServerIRCBot): def execute_reload(self, auteur=None): """Recharge la config.""" reload(config) - regexp_compile() + isit.regexp_compile() if auteur in [None, "SIGHUP"]: towrite = "Config reloaded" + " (SIGHUP received)" * (auteur == "SIGHUP") for to in config.report_bugs_to: @@ -307,10 +187,10 @@ class Basile(ircbot.SingleServerIRCBot): else: return True, u"Config reloaded" - def crash(self, chan="nowhere", who="nobody"): + def crash(self, who="nobody", chan="nowhere"): """Fait crasher le bot.""" where = "en privé" if chan == "priv" else "sur le chan %s" % chan - raise CrashError("Crash demandé par %s %s" % (who, where)) + raise errors.CrashError((u"Crash demandé par %s %s" % (who, where)).encode("utf-8")) ACTIONS = { "reload" : execute_reload, @@ -347,11 +227,13 @@ class Basile(ircbot.SingleServerIRCBot): def on_privmsg(self, serv, ev): """À la réception d'un message en privé.""" + if ignore_event(serv, ev): + return message = ev.arguments()[0] auteur = irclib.nm_to_n(ev.source()) try: message = bot_unicode(message) - except UnicodeBotError: + except errors.UnicodeBotError: if config.utf8_trigger: serv.privmsg(auteur, random.choice(config.utf8_fail_answers).encode("utf8")) return @@ -481,7 +363,7 @@ class Basile(ircbot.SingleServerIRCBot): elif cmd == u"crash": if auteur in self.overops: log(self.serveur, "priv", auteur, " ".join(message) + "[successful]") - self.crash("priv", auteur) + self.crash(auteur, "priv") else: notunderstood = True elif cmd == u"reload": @@ -535,7 +417,7 @@ class Basile(ircbot.SingleServerIRCBot): notunderstood = True elif cmd == u"say": if auteur in self.overops and len(message) > 2: - serv.privmsg(message[1], " ".join(message[2:])) + serv.privmsg(message[1].encode("utf-8"), (u" ".join(message[2:])).encode("utf-8")) log(self.serveur, "priv", auteur, " ".join(message)) elif len(message) <= 2: serv.privmsg(auteur, "Syntaxe : SAY ") @@ -551,7 +433,7 @@ class Basile(ircbot.SingleServerIRCBot): notunderstood = True elif cmd == u"kick": if auteur in self.overops and len(message) > 2: - serv.kick(message[1], message[2], " ".join(message[3:])) + serv.kick(message[1].encode("utf-8"), message[2].encode("utf-8"), " ".join(message[3:]).encode("utf-8")) log(self.serveur, "priv", auteur, " ".join(message)) elif len(message) <= 2: serv.privmsg(auteur, "Syntaxe : KICK []") @@ -591,12 +473,14 @@ class Basile(ircbot.SingleServerIRCBot): def on_pubmsg(self, serv, ev): """À la réception d'un message sur un channel.""" + if ignore_event(serv, ev): + return auteur = irclib.nm_to_n(ev.source()) canal = ev.target() message = ev.arguments()[0] try: message = bot_unicode(message) - except UnicodeBotError: + except errors.UnicodeBotError: if config.utf8_trigger and not canal in self.quiet_channels: serv.privmsg(canal, (u"%s: %s"% ( auteur, random.choice(config.utf8_fail_answers))).encode("utf8")) return @@ -619,7 +503,7 @@ class Basile(ircbot.SingleServerIRCBot): self.execute_something("reload", {"auteur" : auteur}, place=canal, auteur=auteur) elif cmd == u"crash": if auteur in self.overops: - self.crash(auteur, message) + self.crash(auteur, canal) elif cmd in [u"part", u"leave", u"dégage", u"va-t-en", u"tut'tiresailleurs,c'estmesgalets"]: if auteur in self.ops and (not (canal in self.stay_channels) or auteur in self.overops): @@ -675,18 +559,18 @@ class Basile(ircbot.SingleServerIRCBot): else: serv.privmsg(canal, "%s: Je ne connais pas votre pseudo note." % (auteur)) log(self.serveur, canal, auteur, message + "[unknown]") - elif (re.match("!?(pain au chocolat|chocolatine)", message.lower()) + elif (re.match("(pain au chocolat|chocolatine)", message.lower()) and not canal in self.quiet_channels): serv.action(canal, "sert un pain au chocolat à %s" % (auteur)) - elif re.match("!?manzana",message.lower()) and not canal in self.quiet_channels: + elif re.match("manzana",message.lower()) and not canal in self.quiet_channels: if auteur in config.manzana: serv.action(canal, "sert une bouteille de manzana à %s" % (auteur)) elif auteur in config.manzana_bis: serv.action(canal, "sert un grand verre de jus de pomme à %s : tout le monde sait qu'il ne boit pas." % (auteur)) else: serv.action(canal, "sert un verre de manzana à %s" % (auteur)) - if is_insult(message) and not canal in self.quiet_channels: - if is_not_insult(message): + if isit.is_insult(message) and not canal in self.quiet_channels: + if isit.is_not_insult(message): answer = random.choice(config.compliment_answers) for ligne in answer.split("\n"): serv.privmsg(canal, "%s: %s" % (auteur, ligne.encode("utf8"))) @@ -694,16 +578,16 @@ class Basile(ircbot.SingleServerIRCBot): answer = random.choice(config.insultes_answers) for ligne in answer.split("\n"): serv.privmsg(canal, "%s: %s" % (auteur, ligne.encode("utf8"))) - elif is_compliment(message) and not canal in self.quiet_channels: + elif isit.is_compliment(message) and not canal in self.quiet_channels: answer = random.choice(config.compliment_answers) for ligne in answer.split("\n"): serv.privmsg(canal, "%s: %s" % (auteur,ligne.encode("utf8"))) - gros_match = is_gros(message) + gros_match = isit.is_gros(message) if gros_match and not canal in self.quiet_channels: taille = get_filesize() answer = u"Mais non, je ne suis pas %s, %sKo tout au plus…" % (gros_match.groups()[0], taille) serv.privmsg(canal, "%s: %s"%(auteur, answer.encode("utf8"))) - if is_tesla(message) and not canal in self.quiet_channels: + if isit.is_tesla(message) and not canal in self.quiet_channels: l1, l2 = config.tesla_answers, config.tesla_actions n1, n2 = len(l1), len(l2) i = random.randrange(n1 + n2) @@ -711,11 +595,11 @@ class Basile(ircbot.SingleServerIRCBot): serv.action(canal, l2[i - n1].encode("utf8")) else: serv.privmsg(canal, "%s: %s" % (auteur, l1[i].encode("utf8"))) - if is_tamere(message) and not canal in self.quiet_channels: + if isit.is_tamere(message) and not canal in self.quiet_channels: answer = random.choice(config.tamere_answers) for ligne in answer.split("\n"): serv.privmsg(canal, "%s: %s"%(auteur, ligne.encode("utf8"))) - if is_tag(message) and not canal in self.quiet_channels: + if isit.is_tag(message) and not canal in self.quiet_channels: if auteur in self.ops: action = random.choice(config.tag_actions) serv.action(canal, action.encode("utf8")) @@ -724,7 +608,7 @@ class Basile(ircbot.SingleServerIRCBot): answer = random.choice(config.tag_answers) for ligne in answer.split("\n"): serv.privmsg(canal, "%s: %s" % (auteur, ligne.encode("utf8"))) - if is_merci(message): + if isit.is_merci(message): answer = random.choice(config.merci_answers) for ligne in answer.split("\n"): serv.privmsg(canal, "%s: %s"%(auteur, ligne.encode("utf8"))) @@ -758,18 +642,18 @@ class Basile(ircbot.SingleServerIRCBot): for j in mess]) out = int(translate(out)) serv.privmsg(canal,"%s: %s !" % (auteur, translate(str(out + 1)).encode("utf8"))) - if is_bonjour(message) and not canal in self.quiet_channels: - if is_night(): + if isit.is_bonjour(message) and not canal in self.quiet_channels: + if isit.is_night(): answer = random.choice(config.night_answers) - elif is_day(): + elif isit.is_day(): answer = random.choice(config.bonjour_answers) else: answer = random.choice(config.bonsoir_answers) serv.privmsg(canal, answer.format(auteur).encode("utf8")) - if is_bonne_nuit(message) and not canal in self.quiet_channels: + if isit.is_bonne_nuit(message) and not canal in self.quiet_channels: answer = random.choice(config.bonne_nuit_answers) serv.privmsg(canal, answer.format(auteur).encode("utf8")) - if is_pan(message) and not canal in self.quiet_channels: + if isit.is_pan(message) and not canal in self.quiet_channels: serv.privmsg(canal, "%s: ce n'est pas sur moi qu'il faut tirer, même si je sais que j'attire l'œil !" % (auteur)) else: if message in [u"!pain au chocolat", u"!chocolatine"] and not canal in self.quiet_channels: @@ -792,7 +676,7 @@ class Basile(ircbot.SingleServerIRCBot): ).format(mypseudo).lower(), message.strip().lower()): answer = random.choice(config.bonjour_answers) serv.privmsg(canal, answer.format(auteur).encode("utf8")) - if (is_perdu(message) and not canal in self.quiet_channels): + if (isit.is_perdu(message) and not canal in self.quiet_channels): # proba de perdre sur trigger : # avant 30min (enfin, config) : 0 # ensuite, +25%/30min, linéairement @@ -804,18 +688,20 @@ class Basile(ircbot.SingleServerIRCBot): def on_action(self, serv, ev): """À la réception d'une action.""" + if ignore_event(serv, ev): + return action = ev.arguments()[0] auteur = irclib.nm_to_n(ev.source()) channel = ev.target() try: action = bot_unicode(action) - except UnicodeBotError: + except errors.UnicodeBotError: if config.utf8_trigger and not channel in self.quiet_channels: serv.privmsg(channel, (u"%s: %s"%(auteur,random.choice(config.utf8_fail_answers))).encode("utf8")) return mypseudo = self.nick - if is_bad_action_trigger(action, mypseudo) and not channel in self.quiet_channels: + if isit.is_bad_action_trigger(action, mypseudo) and not channel in self.quiet_channels: l1, l2 = config.bad_action_answers, config.bad_action_actions n1, n2 = len(l1), len(l2) i = random.randrange(n1 + n2) @@ -823,7 +709,7 @@ class Basile(ircbot.SingleServerIRCBot): serv.action(channel, l2[i - n1].format(auteur).encode("utf8")) else: serv.privmsg(channel, l1[i].format(auteur).encode("utf8")) - if is_good_action_trigger(action, mypseudo) and not channel in self.quiet_channels: + if isit.is_good_action_trigger(action, mypseudo) and not channel in self.quiet_channels: l1, l2 = config.good_action_answers, config.good_action_actions n1, n2 = len(l1), len(l2) i = random.randrange(n1 + n2) @@ -839,7 +725,7 @@ class Basile(ircbot.SingleServerIRCBot): victime = ev.arguments()[0] raison = ev.arguments()[1] if victime == self.nick: - log(self.serveur, "%s kické de %s par %s (raison : %s)" % (victime, channel, auteur, raison)) + log(self.serveur, u"%s kické de %s par %s (raison : %s)" % (victime, channel.decode("utf-8"), auteur, raison)) time.sleep(2) serv.join(channel) l1, l2 = config.kick_answers, config.kick_actions