Browse Source

Corrections dans les requêtes

master
hadware 8 years ago
parent
commit
b0df6b077b
  1. 15
      cocobot.py
  2. 1
      tools/coco/__init__.py
  3. 5
      tools/coco/client.py
  4. 83
      tools/processors/messages.py

15
cocobot.py

@ -4,8 +4,10 @@ import argparse
import asyncio import asyncio
import logging import logging
from tools.coco
from tools.base import CoboBot from tools.base import CoboBot
from tools.processors import MessageDispatcher, CommandsDispatcherProcessor, ConnectionDispatcher from tools.processors import MessageDispatcher, CommandsDispatcherProcessor, ConnectionDispatcher
from tools.processors.messages import *
# setting up argument parser # setting up argument parser
parser = argparse.ArgumentParser(description='Le lou bot') 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('--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") parser.add_argument('--method', type=str, help='http or https', default="https")
# setting up coco client
cococlient = CocoClient()
# setting up the various dispatchers # 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]) 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, cocobot = CoboBot(args.cookie, args.channel, args.domain, args.port, args.method,
root_messages_dispatcher, connections_dispatcher) root_messages_dispatcher, connections_dispatcher)
asyncio.get_event_loop().run_until_complete(pikabot.listen()) asyncio.get_event_loop().run_until_complete(cocobot.listen())

1
tools/coco/__init__.py

@ -0,0 +1 @@
from .client import CocoClient

5
tools/coco/client.py

@ -28,7 +28,7 @@ class Interlocutor:
def to_botmessage(self): def to_botmessage(self):
sex_indic = "un homme" if self.is_male else "une femme" 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): def __eq__(self, other):
return other.nick == self.nick return other.nick == self.nick
@ -47,6 +47,7 @@ class CocoClient:
self.user_id = None # type:str self.user_id = None # type:str
self.user_pass = None # type:str self.user_pass = None # type:str
self.nick = None # type:str self.nick = None # type:str
self.is_connected = False
def _format_history(self, interlocutor: Interlocutor): def _format_history(self, interlocutor: Interlocutor):
if interlocutor in self.histories: if interlocutor in self.histories:
@ -61,6 +62,7 @@ class CocoClient:
user = Interlocutor.from_string(user_code) user = Interlocutor.from_string(user_code)
self.interlocutors.add(user) self.interlocutors.add(user)
self.histories[user].append((user.nick, msg)) self.histories[user].append((user.nick, msg))
logging.info("Msg from %s : %s" % (user.nick, msg))
if user == self.current_interlocutor: if user == self.current_interlocutor:
out.append(Message("💬 %s: %s" % (user.nick, msg))) 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 = PostLoginRequest(self.user_id, self.user_pass)
post_login_req.retrieve() post_login_req.retrieve()
logging.info("Post login successful") logging.info("Post login successful")
self.is_connected = True
def pulse(self) -> List[AbstractResponse]: def pulse(self) -> List[AbstractResponse]:
pulse_req = PulseRequest(self.user_id, self.user_pass) pulse_req = PulseRequest(self.user_id, self.user_pass)

83
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 * from .commons import *
@ -31,3 +32,83 @@ class CommandsDispatcherProcessor(DispatcherBotProcessor):
response = super().process(without_cmd, sender_id, users_list) response = super().process(without_cmd, sender_id, users_list)
return Message(self.default_response) if response is None else response 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)

Loading…
Cancel
Save