示例#1
0
 def test_response_serialization(self):
     response = TextMessage(text="Hello, world!")
     model = ChatMessage()
     model.response_dict = response
     assert isinstance(model.response, MessageElement)
     assert isinstance(model.serialized_response, dict)
     assert model.serialized_response[
         '__type__'] == response.__module__ + "." + response.__class__.__name__
示例#2
0
 def test_logging_service(self, monkeypatch):
     monkeypatch.setattr("botshot.tasks.run_async", run_sync)
     current_state_name = 'default.root'
     message = ChatMessage()
     message.type = ChatMessage.MESSAGE
     message.text = "Hello, world!"
     message.id = 105
     logging_service = AsyncLoggingService([TestMessageLogger()])
     logging_service.log_user_message_start(message, current_state_name)
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
示例#4
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)
示例#5
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)
示例#6
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 = []
示例#7
0
    def accept_scheduled(self, conversation_id, user_id, payload):
        with transaction.atomic():
            conversation = ChatConversation.objects.select_for_update().get(pk=conversation_id)
            if user_id is not None:
                user = ChatUser.objects.get(pk=user_id)
            else:  # generic postback for conversation, not for a specific member
                user = None  # TODO: if there's just one user, set this to the user

            message = ChatMessage()
            message.conversation = conversation
            message.user = user
            message.type = ChatMessage.SCHEDULE
            message.is_user = True
            message.time = timezone.now()
            message.entities = payload
            self._process(message)
示例#8
0
    def accept_inactive(self, conversation_id, user_id, payload, counter):
        with transaction.atomic():
            conversation = ChatConversation.objects.select_for_update().get(pk=conversation_id)
            user = ChatUser.objects.get(pk=user_id)

            # TODO: this might break for more users or with special messages
            if conversation.context_dict != counter:  # user was active
                return

            message = ChatMessage()
            message.conversation = conversation
            message.user = user
            message.type = ChatMessage.SCHEDULE
            message.is_user = True
            message.time = timezone.now()
            message.entities = payload
            self._process(message)
示例#9
0
def webchat(request):
    if request.method == 'POST':
        if not request.POST.get('message'):
            print("Error, message not set in POST")
            return HttpResponse(400)

        if 'webchat_id' not in request.session:
            webchat_id = WebchatInterface.make_webchat_id()
            request.session['webchat_id'] = webchat_id

        interface = WebchatInterface()
        is_ok = interface.webhook(request)
        return JsonResponse({'ok': True}) if is_ok else HttpResponse(400)

    if 'webchat_id' in request.session:
        messages = _get_webchat_id_messages(request.session['webchat_id'])
    else:
        messages = []
        welcome_msg = settings.BOT_CONFIG.get(
            'WEBCHAT_WELCOME_MESSAGE',
            'Hi there, this is the default greeting message!'
        )
        if welcome_msg:
            default_message = ChatMessage()
            default_message.type = ChatMessage.MESSAGE
            default_message.text = welcome_msg
            default_message.time = datetime.now()
            default_message.is_user = False
            messages.append(default_message)

    context = {
        'messages': messages,
        'form': MessageForm,
        'timestamp': datetime.now().timestamp(),
        'user_img': settings.BOT_CONFIG.get('WEBCHAT_USER_IMAGE', 'images/icon_user.png'),
        'bot_img': settings.BOT_CONFIG.get('WEBCHAT_BOT_IMAGE', 'images/icon_robot.png')
    }
    return render(request, 'botshot/webchat/index.html', context)
示例#10
0
    def send(self, conversation, responses, reply_to=None):
        """
        Send responses to a conversation.

        :param conversation: a ChatConversation object
        :param responses: the messages we're sending, Iterable of MessageElement objects
        :param reply_to: (optional) message that we're replying to (used for example in Telegram)
        """
        logging.info("Sending bot responses: %s", responses)
        conversation.interface.send_responses(conversation, reply_to, responses)

        for response in responses:
            message = ChatMessage()
            message.conversation = conversation
            message.user = reply_to.user if reply_to else None
            message.type = ChatMessage.MESSAGE
            message.text = response.get_text()
            message.time = timezone.now()
            message.is_user = False
            message.response_dict = todict(response)
            message.save()