Ejemplo n.º 1
0
    def __init__(self):

        self.message = ChatMessage()
        self.sender = ChatUser()
        self.conversation = ChatConversation()
        self.conversation.conversation_id = 1
        self.conversation.save()
        self.chat_manager = ChatManager()
        self.context = Context.load({})
        self.logging_service = Mock()

        self.sent = []
        self.schedules = []
        self.inactive_callbacks = []
Ejemplo n.º 2
0
    def accept_with_entities(self, raw_message, entities):
        with transaction.atomic():
            try:
                conversation = ChatConversation.objects.select_for_update(
                ).get(interface_name=raw_message.interface.name,
                      raw_conversation_id=raw_message.raw_conversation_id)
            except ObjectDoesNotExist:
                conversation = ChatConversation()
                conversation.interface_name = raw_message.interface.name
                conversation.raw_conversation_id = raw_message.raw_conversation_id
                conversation.meta = raw_message.conversation_meta
                raw_message.interface.fill_conversation_details(conversation)
                # Save and read instance from database to acquire lock
                conversation.save()
                logging.info("Created new conversation: %s",
                             conversation.__dict__)
                conversation = ChatConversation.objects.select_for_update(
                ).get(pk=conversation.conversation_id)

            conversation.last_message_time = timezone.now()

            try:
                user = ChatUser.objects.get(
                    raw_user_id=raw_message.raw_user_id)
            except ObjectDoesNotExist:
                user = ChatUser()
                user.raw_user_id = raw_message.raw_user_id
                logging.info("Created new user: %s", user.__dict__)
                # Save user before filling details so that image field can be saved
                user.save()
                user.conversations.add(
                    conversation)  # save metadata before filling details
                conversation.save()

                # TODO: also update details of existing users every once in a while
                raw_message.interface.fill_user_details(user)
                user.save()

            message = ChatMessage()
            message.conversation = conversation
            message.user = user
            message.type = raw_message.type
            message.text = raw_message.text
            message.time = make_aware(
                datetime.fromtimestamp(raw_message.timestamp))
            message.is_user = True
            message.entities = entities

            self._process(message)
Ejemplo n.º 3
0
 def setUp(self, monkeypatch):
     self.message = ChatMessage()
     self.message.type = ChatMessage.MESSAGE
     self.message.text = "Hello, world!"
     self.message.conversation = ChatConversation()
     self.message.time = time.time()
     self.message.user = ChatUser()
     self.message.is_user = True
     self.message.message_id = 105
     self.dialog = MessageProcessor(chat_manager=None, message=self.message)
def message():
    message = ChatMessage()
    message.type = ChatMessage.MESSAGE
    message.text = "Hello, world!"
    message.conversation = ChatConversation()
    message.time = time.time()
    message.user = ChatUser()
    message.is_user = True
    message.message_id = 105
    message.entities = {}
    return message
Ejemplo n.º 5
0
def conversation():
    user = ChatUser()
    user.user_id = -1
    user.save()

    conversation = ChatConversation()
    conversation.interface_name = 'test'
    conversation.conversation_id = -1
    conversation.save()
    yield conversation
Ejemplo n.º 6
0
    def test_user_details(self, interface, monkeypatch):
        user = ChatUser()
        conversation = ChatConversation()
        conversation.meta = {"page_id": self.page['PAGE_ID']}
        user.save()
        conversation.save()
        user.conversations.add(conversation)
        user.save()
        conversation.save()

        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json = lambda: {"first_name": "foo", "last_name": "bar"}
        monkeypatch.setattr("requests.get", lambda x: mock_response)
        interface.fill_user_details(user)
        assert user.first_name == 'foo' and user.last_name == 'bar'
Ejemplo n.º 7
0
class MockDialog:

    def __init__(self):

        self.message = ChatMessage()
        self.sender = ChatUser()
        self.conversation = ChatConversation()
        self.conversation.conversation_id = 1
        self.conversation.save()
        self.chat_manager = ChatManager()
        self.context = Context.load({})
        self.logging_service = Mock()

        self.sent = []
        self.schedules = []
        self.inactive_callbacks = []

    def inactive(self, payload, seconds=None):
        self.inactive_callbacks.append((payload, seconds))

    def schedule(self, payload, at=None, seconds=None):
        if not at and not seconds:
            raise ValueError('Specify either "at" or "seconds" parameter')
        time_formatted = "at {}".format(at) if at else "in {} seconds".format(seconds)
        logging.info('Scheduling callback %s with payload "%s"', time_formatted, payload)
        self.schedules.append((payload, at, seconds))
        return Mock()

    def send(self, responses):
        if not responses:
            return
        if not isinstance(responses, list) and not isinstance(responses, tuple):
            responses = [responses]

        self.sent += responses

    def has_text(self, text, regex=True):
        for msg in self.sent:
            if regex:
                if isinstance(msg, str) and re.match(text, msg):
                    return True
                if isinstance(msg, TextMessage) and re.match(text, msg.text):
                    return True
            if not regex:
                if msg == text or (isinstance(msg, TextMessage) and msg.text == text):
                    return True
        return False

    def has_only(self, text):
        return len(self.sent) == 1 and self.has_text(text)

    def has_template(self, template):
        for msg in self.sent:
            if isinstance(msg, template):
                return True
        return False

    def is_state_scheduled(self, state, times=1):
        for payload, at, seconds in self.schedules:
            if payload.get("_state") == state:
                times -= 1
        return times == 0