From 3c325ca9e0bfcab4c96bd150d2617afc0cf5fd04 Mon Sep 17 00:00:00 2001 From: louis chauvet Date: Sat, 1 Sep 2018 17:39:14 +0200 Subject: [PATCH] Add fpi command to search in pi with regex --- modules/pi.py | 37 +++++++++++++++++++++++++++++++++++-- traductions.py | 3 +++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/modules/pi.py b/modules/pi.py index d8ac276..65f0e78 100644 --- a/modules/pi.py +++ b/modules/pi.py @@ -1,4 +1,6 @@ import os +import re + import traductions as tr @@ -15,7 +17,7 @@ class MainClass: try: start = int(args[0]) except ValueError: - await msg.channel.send(tr.tr[self.guild.config["lang"]]["Errors"]["TooBigNumberPiError"]) + await msg.channel.send(tr.tr[self.guild.config["lang"]]["errors"]["TooBigNumberPiError"]) with open(self.pi_file) as pi_file: pi_file.read(start) txt = pi_file.read(2000) @@ -23,11 +25,42 @@ class MainClass: await msg.channel.send(txt) async def pi_search(self, msg, command, args): - pass + if len(args) == 0: + await msg.channel.send(tr.tr[self.guild.config["lang"]]["errors"]["NotEnoughParamError"]) + return + try: + to_search = re.compile(args[0]) + if "*" in args[0] or "+" in args[0]: + await msg.channel.send(tr.tr[self.guild.config["lang"]]["errors"]["ForbiddenRegexError"]) + return + elif len(args[0]) > 50: + await msg.channel.send(tr.tr[self.guild.config["lang"]]["errors"]["RegexTooLongError"]) + except re.error: + await msg.channel.send(tr.tr[self.guild.config["lang"]]["errors"]["RegexError"]) + return + with open(self.pi_file) as pi_file: + pi = pi_file.readline() + results = to_search.finditer(pi) + texts = [] + for result in results: + texts.append( + "Une occurence de votre recherche a été trouvée à la {debut}ème place: `{before}`{find}`{after}`".format( + debut=result.start(0), + before=pi[result.start(0) - 10:result.start(0)], + find=pi[result.start(0):result.end(0)], + after=pi[result.end(0):result.end(0) + 10] + )) + if texts: + for text in texts[:10]: + await msg.channel.send(text) + else: + await msg.channel.send("Pas de résultats") async def on_message(self, msg): if msg.content.startswith(self.guild.config["prefix"]): command, *args = msg.content.lstrip(self.guild.config["prefix"]).split(" ") if command == "pi": await self.pi(msg, command, args) + elif command == "fpi": + await self.pi_search(msg, command, args) return diff --git a/traductions.py b/traductions.py index 8fdd558..2fc3c03 100644 --- a/traductions.py +++ b/traductions.py @@ -147,6 +147,9 @@ tr = { "du bot.", "CommandNotFoundError": "La commande {command} n'existe pas.", "TooBigNumberPiError": "Vous devez spécifier un nombre inferieur a 10000.", + "RegexError": "La regex que vous avez utilisé n'est pas valide.", + "ForbiddenRegexError": "Vous n'avez pas le droit d'utiliser les caractères `*` et `+` dans une regex.", + "RegexTooLongError": "La regex ne doit pas faire plus e 50 caractères", }, }, }