async def test_matrix_nio_backend_send_message_error(self):
     backend = matrix_nio.MatrixNioBackend(self.bot_config)
     test_server = "test.matrix.org"
     test_user = f"@test_user:{test_server}"
     event_id = "1234567890"
     room_id = "test_room"
     backend.client = nio.AsyncClient(test_server,
                                      user=test_user,
                                      device_id="test_device")
     backend.client.rooms = {
         "test_room": "Test Room",
         "other_test_room": "Test Room"
     }
     backend.client.room_send = mock.Mock(
         return_value=aiounittest.futurized(
             ErrorResponse.from_dict({
                 "errcode": "ERROR_SENDING_MESSAGE",
                 "error": "Error sending message",
                 "retry_after_ms": 10000
             })))
     message_text = "Test message"
     test_message = Message(
         message_text,
         matrix_nio.MatrixNioPerson("an_id",
                                    client=backend.client,
                                    emails=["*****@*****.**"],
                                    full_name=""))
     test_message.to = matrix_nio.MatrixNioRoom("test_room",
                                                client=backend.client,
                                                title="A title")
     test_message.to.room = "test_room"
     with self.assertRaises(ValueError):
         result = await backend._send_message(test_message)
     backend.client.room_send.assert_called_once()
 async def test_matrix_nio_backend_send_message(self):
     backend = matrix_nio.MatrixNioBackend(self.bot_config)
     test_server = "test.matrix.org"
     test_user = f"@test_user:{test_server}"
     event_id = "1234567890"
     room_id = "test_room"
     backend.client = nio.AsyncClient(test_server,
                                      user=test_user,
                                      device_id="test_device")
     backend.client.rooms = {
         "test_room": "Test Room",
         "other_test_room": "Test Room"
     }
     backend.client.room_send = mock.Mock(
         return_value=aiounittest.futurized(
             RoomSendResponse.from_dict({"event_id": event_id}, room_id)))
     message_text = "Test message"
     test_message = Message(
         message_text,
         matrix_nio.MatrixNioPerson("an_id",
                                    client=backend.client,
                                    emails=["*****@*****.**"],
                                    full_name=""))
     test_message.to = matrix_nio.MatrixNioRoom("test_room",
                                                client=backend.client,
                                                title="A title")
     test_message.to.room = "test_room"
     result = await backend._send_message(test_message)
     self.assertIsInstance(result, RoomSendResponse)
     self.assertEqual(result.room_id, room_id)
     self.assertEqual(result.event_id, event_id)
     # TODO: Add assert called once with
     backend.client.room_send.assert_called_once()
Ejemplo n.º 3
0
 def callback_message(msg):
     frm = bot.build_identifier(msg.frm.person)
     frm.bot_id = bot_id
     if room_id is not None or room_name is not None:
         frm.room = DummyRoom(room_id, room_name)
     if approver_is_admin and "yes" in msg.body:
         frm._email = admin_default_email
     else:
         frm._email = from_email
         frm._nick = from_nick
     msg = Message(body=msg.body,
                   frm=frm,
                   to=msg.to,
                   parent=msg.parent,
                   extras={
                       'conversation':
                       DummyConversation({
                           'id': 1,
                           'serviceUrl': 'http://localhost',
                           'channelData': {
                               'team': {
                                   'id': 1
                               },
                               'tenant': {
                                   'id': 1
                               }
                           }
                       })
                   })
     ErrBot.callback_message(bot, msg)
Ejemplo n.º 4
0
    def execute(self, flow: Flow):
        """
        This is where the flow execution happens from one of the thread of the pool.
        """
        while True:
            autosteps = flow.next_autosteps()
            steps = flow.next_steps()

            if not steps:
                log.debug("Flow ended correctly.Nothing left to do.")
                with self._lock:
                    self.in_flight.remove(flow)
                break

            if not autosteps and flow.current_step.hints:
                possible_next_steps = [
                    f'You are in the flow **{flow.name}**, you can continue with:\n\n'
                ]
                for step in steps:
                    cmd = step.command
                    cmd_fnc = self._bot.all_commands[cmd]
                    reg_cmd = cmd_fnc._err_re_command
                    syntax_args = cmd_fnc._err_command_syntax
                    reg_prefixed = cmd_fnc._err_command_prefix_required if reg_cmd else True
                    syntax = self._bot.prefix if reg_prefixed else ''
                    if not reg_cmd:
                        syntax += cmd.replace('_', ' ')
                    if syntax_args:
                        syntax += syntax_args
                    possible_next_steps.append(f'- {syntax}')
                self._bot.send(flow.requestor, '\n'.join(possible_next_steps))
                break

            log.debug('Steps triggered automatically %s.',
                      ', '.join(str(node) for node in autosteps))
            log.debug('All possible next steps: %s.',
                      ', '.join(str(node) for node in steps))

            for autostep in autosteps:
                log.debug("Proceeding automatically with step %s", autostep)
                if autostep == FLOW_END:
                    log.debug('This flow ENDED.')
                    with self._lock:
                        self.in_flight.remove(flow)
                    return
                try:
                    msg = Message(frm=flow.requestor, flow=flow)
                    result = self._bot.commands[autostep.command](msg, None)
                    log.debug('Step result %s: %s', flow.requestor, result)

                except Exception as e:
                    log.exception('%s errored at %s', flow, autostep)
                    self._bot.send(flow.requestor,
                                   f'{flow} errored at {autostep} with "{e}"')
                flow.advance(
                    autostep
                )  # TODO: this is only true for a single step, make it forkable.
        log.debug('Flow execution suspended/ended normally.')
Ejemplo n.º 5
0
 def check_requester_flag(self, message: Message, requester: str):
     if requester is not None:
         if hasattr(message.frm, "bot_id") and message.frm.bot_id is not None \
                 and message.frm.bot_id == self._bot.bot_config.ACCESS_FORM_BOT_INFO.get('bot_id'):
             previous_channel_id = message.frm.room.id
             message.frm = self.build_identifier(requester)
             message.frm._channelid = previous_channel_id
         else:
             raise Exception("You cannot use the requester flag.")
 def test_matrix_nio_backend_prefix_groupchat_reply(self):
     backend = matrix_nio.MatrixNioBackend(self.bot_config)
     backend.client = nio.AsyncClient("test.matrix.org",
                                      user="******",
                                      device_id="test_device")
     full_name = "Charles de Gaulle"
     person = matrix_nio.MatrixNioPerson("an_id", backend.client, full_name,
                                         ["*****@*****.**"])
     message = Message("A message")
     message_body = f"@{person.fullname} {message.body}"
     backend.prefix_groupchat_reply(message, person)
     self.assertEqual(message.body, message_body)
 def test_matrix_nio_backend_is_not_from_self(self):
     backend = matrix_nio.MatrixNioBackend(self.bot_config)
     test_user_id = "test_user"
     backend.client = nio.AsyncClient("test.matrix.org",
                                      user=test_user_id,
                                      device_id="test_device")
     message_text = "Test message"
     response_text = "A response"
     test_message = Message(
         message_text,
         matrix_nio.MatrixNioPerson("another_test_user_id",
                                    client=backend.client,
                                    emails=["*****@*****.**"],
                                    full_name=""))
     self.assertFalse(backend.is_from_self(test_message))
Ejemplo n.º 8
0
    def execute(self, flow: Flow):
        """
        This is where the flow execution happens from one of the thread of the pool.
        """
        while True:
            autosteps = flow.next_autosteps()
            steps = flow.next_steps()

            if not steps:
                log.debug("Flow ended correctly.Nothing left to do.")
                with self._lock:
                    self.in_flight.remove(flow)
                break

            if not autosteps:
                possible_next_steps = ["You are in the flow **%s**, you can continue with:\n\n" % flow.name]
                for step in steps:
                    cmd = step.command
                    syntax = self._bot.all_commands[cmd]._err_command_syntax
                    syntax = '' if syntax is None else syntax

                    possible_next_steps.append("- %s%s %s" % (self._bot.prefix, cmd.replace('_', ' '), syntax))
                self._bot.send(flow.requestor, "\n".join(possible_next_steps))
                break

            log.debug("Steps triggered automatically %s", ', '.join(str(node) for node in autosteps))
            log.debug("All possible next steps: %s", ', '.join(str(node) for node in steps))

            for autostep in autosteps:
                log.debug("Proceeding automatically with step %s", autostep)
                if autostep == FLOW_END:
                    log.debug('This flow ENDED.')
                    with self._lock:
                        self.in_flight.remove(flow)
                    return
                try:
                    msg = Message(frm=flow.requestor, flow=flow)
                    result = self._bot.commands[autostep.command](msg, None)
                    log.debug('Step result %s: %s', flow.requestor, result)

                except Exception as e:
                    log.exception('%s errored at %s', flow, autostep)
                    self._bot.send(flow.requestor,
                                   '%s errored at %s with "%s"' % (flow, autostep, e))
                flow.advance(autostep)  # TODO: this is only true for a single step, make it forkable.
        log.debug("Flow exectution suspended/ended normally.")
 def test_matrix_nio_backend_build_reply(self):
     backend = matrix_nio.MatrixNioBackend(self.bot_config)
     backend.client = nio.AsyncClient("test.matrix.org",
                                      user="******",
                                      device_id="test_device")
     message_text = "Test message"
     response_text = "A response"
     test_message = Message(
         message_text,
         matrix_nio.MatrixNioPerson("an_id",
                                    client=backend.client,
                                    emails=["*****@*****.**"],
                                    full_name=""))
     response = backend.build_reply(test_message, response_text)
     self.assertIsInstance(response, Message)
     self.assertEqual(response.to, test_message.frm)
     self.assertEqual(response.body, f"{message_text}\n{response_text}")