From b0df6b077ba93eebfe0202d0ef17ebb649f8845c Mon Sep 17 00:00:00 2001 From: hadware Date: Tue, 29 May 2018 21:22:37 +0200 Subject: [PATCH] =?UTF-8?q?Corrections=20dans=20les=20requ=C3=AAtes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocobot.py | 15 +++++- tools/coco/__init__.py | 1 + tools/coco/client.py | 5 +- tools/processors/messages.py | 93 +++++++++++++++++++++++++++++++++--- 4 files changed, 105 insertions(+), 9 deletions(-) diff --git a/cocobot.py b/cocobot.py index 5249998..03a10f1 100755 --- a/cocobot.py +++ b/cocobot.py @@ -4,8 +4,10 @@ import argparse import asyncio import logging +from tools.coco from tools.base import CoboBot from tools.processors import MessageDispatcher, CommandsDispatcherProcessor, ConnectionDispatcher +from tools.processors.messages import * # setting up argument parser parser = argparse.ArgumentParser(description='Le lou bot') @@ -15,9 +17,18 @@ parser.add_argument('--domain', type=str, help='domain to connect to', default=" parser.add_argument('--port', type=int, help='port on which to connect the socket', default=80) parser.add_argument('--method', type=str, help='http or https', default="https") +# setting up coco client +cococlient = CocoClient() # setting up the various dispatchers -coco_commands = CommandsDispatcherProcessor([], "coco", default_response="de?") +connect_cmd = CocoConnectCommand(cococlient) +msg_cmd = CocoMsgCommand(cococlient) +list_cmd = CocoListCommand(cococlient) +switch_cmd = CocoSwitchCommand(cococlient) +help_cmd = BotHelp([connect_cmd, msg_cmd, list_cmd, switch_cmd]) + +coco_commands = CommandsDispatcherProcessor([connect_cmd, msg_cmd, list_cmd, switch_cmd, help_cmd], + "coco", default_response="de?") root_messages_dispatcher = MessageDispatcher([coco_commands]) @@ -29,7 +40,7 @@ if __name__ == "__main__": cocobot = CoboBot(args.cookie, args.channel, args.domain, args.port, args.method, root_messages_dispatcher, connections_dispatcher) - asyncio.get_event_loop().run_until_complete(pikabot.listen()) + asyncio.get_event_loop().run_until_complete(cocobot.listen()) diff --git a/tools/coco/__init__.py b/tools/coco/__init__.py index e69de29..3311f7b 100644 --- a/tools/coco/__init__.py +++ b/tools/coco/__init__.py @@ -0,0 +1 @@ +from .client import CocoClient \ No newline at end of file diff --git a/tools/coco/client.py b/tools/coco/client.py index bdd419d..d795a9f 100644 --- a/tools/coco/client.py +++ b/tools/coco/client.py @@ -28,7 +28,7 @@ class Interlocutor: def to_botmessage(self): sex_indic = "un homme" if self.is_male else "une femme" - return BotMessage("%s est %s de %i ans" %(self.nick, sex_indic, self.age)) + return BotMessage("Conversation avec %s, %s de %i ans" %(self.nick, sex_indic, self.age)) def __eq__(self, other): return other.nick == self.nick @@ -47,6 +47,7 @@ class CocoClient: self.user_id = None # type:str self.user_pass = None # type:str self.nick = None # type:str + self.is_connected = False def _format_history(self, interlocutor: Interlocutor): if interlocutor in self.histories: @@ -61,6 +62,7 @@ class CocoClient: user = Interlocutor.from_string(user_code) self.interlocutors.add(user) self.histories[user].append((user.nick, msg)) + logging.info("Msg from %s : %s" % (user.nick, msg)) if user == self.current_interlocutor: out.append(Message("💬 %s: %s" % (user.nick, msg))) @@ -78,6 +80,7 @@ class CocoClient: post_login_req = PostLoginRequest(self.user_id, self.user_pass) post_login_req.retrieve() logging.info("Post login successful") + self.is_connected = True def pulse(self) -> List[AbstractResponse]: pulse_req = PulseRequest(self.user_id, self.user_pass) diff --git a/tools/processors/messages.py b/tools/processors/messages.py index 12b1892..59905f3 100755 --- a/tools/processors/messages.py +++ b/tools/processors/messages.py @@ -1,4 +1,5 @@ -from tools.commons import Message +from tools.coco.client import CocoClient +from tools.commons import Message, BotMessage from .commons import * @@ -6,28 +7,108 @@ class DispatcherBotProcessor(MessageProcessor): """A processor that matches a context, then forwards the message to a list of sub-processors. This enables the botprocessor-matching mechanism to behave kinda like a decision tree""" - def __init__(self, processors_list : List[MessageProcessor]): + def __init__(self, processors_list: List[MessageProcessor]): self.dispatcher = MessageDispatcher(processors_list) - def process(self, text : str, sender_id : str, users_list : UserList): + def process(self, text: str, sender_id: str, users_list: UserList): return self.dispatcher.dispatch(text, sender_id, users_list) class CommandsDispatcherProcessor(DispatcherBotProcessor): """Reacts to commands of the form '/botname command' or 'botname, command' """ - def __init__(self, processors_list: List[MessageProcessor], trigger_word: str = None, default_response :str = None): + def __init__(self, processors_list: List[MessageProcessor], trigger_word: str = None, default_response: str = None): super().__init__(processors_list) self.trigger = trigger_word self.default_response = default_response if default_response is not None else "Commande non reconnue, pd" - def match(self, text : str, sender_id : str, users_list : UserList): + def match(self, text: str, sender_id: str, users_list: UserList): trigger = self.trigger.upper() if self.trigger is not None else users_list.my_name.upper() return text.upper().startswith(trigger + ",") \ or text.upper().startswith("/" + trigger) - def process(self, text : str, sender_id : str, users_list : UserList): + def process(self, text: str, sender_id : str, users_list: UserList): without_cmd = text[len(users_list.my_name)+1:] response = super().process(without_cmd, sender_id, users_list) return Message(self.default_response) if response is None else response + +class BaseCocobotCommand(MessageProcessor): + + HELP_STR = None + _cmd_suffix = "" + + def __init__(self, cococlient: CocoClient): + self.cococlient = cococlient + + def match(self, text : str, sender_id : str, users_list : UserList): + return text.lower().startswith(self._cmd_suffix) + + +class CocoConnectCommand(BaseCocobotCommand): + HELP_STR = "/coconnect pseudo age code_postal" + _cmd_suffix = "nnect" + + def process(self, text : str, sender_id : str, users_list : UserList): + text = text[len(self._cmd_suffix):].strip() + try: + nick, age, zip_code = text.split() + except ValueError: + return Message("Pas le bon nombre d'arguments, pd") + + if not nick.isalnum(): + return Message("Le pseudo doit être alphanumérique, pd") + + if len(age) != 2 or not age.isnumeric(): + return Message("L'âge c'est avec DEUX chiffres (déso bulbi)") + + if len(zip_code) != 5 or not zip_code.isnumeric(): + return Message("Le code postal c'est 5 chiffres, pd") + + return self.cococlient.connect(nick, int(age), True, zip_code) + + +class CocoMsgCommand(BaseCocobotCommand): + HELP_STR = "/cocospeak message" + _cmd_suffix = "speak" + + def process(self, text : str, sender_id : str, users_list : UserList): + text = text[len(self._cmd_suffix):].strip() + return self.cococlient.send_msg(text) + + +class CocoSwitchCommand(BaseCocobotCommand): + HELP_STR = "/cocoswitch [pseudo de l'interlocuteur]" + _cmd_suffix = "switch" + + def process(self, text : str, sender_id : str, users_list : UserList): + text = text[len(self._cmd_suffix):].strip() + if text: + return self.cococlient.switch_conv(text) + else: + return self.cococlient.switch_conv() + + +class CocoListCommand(BaseCocobotCommand): + HELP_STR = "/cocolist" + _cmd_suffix = "list" + + def process(self, text : str, sender_id : str, users_list : UserList): + return self.cococlient.list_convs() + + +class BotHelp(MessageProcessor): + """Displays the help string for all processors in the list that have a helpt string""" + + def __init__(self, processors_list: List[BaseCocobotCommand]): + all_help_strs = [proc.HELP_STR + for proc in processors_list if proc.HELP_STR is not None] + self.help_str = ", ".join(all_help_strs) + + def match(self, text : str, sender_id : str, users_list : UserList): + return text.lower().startswith("help") + + def process(self, text : str, sender_id : str, users_list : UserList): + return BotMessage(self.help_str) + +