Exemplo n.º 1
0
    def exit_callback(self):
        # Don't send prompt if there's nowhere to send.
        if not getattr(coordinator, 'master', None):
            raise Exception(self._("Web WeChat logged your account out before master channel is ready."))
        self.logger.debug('Calling exit callback...')
        if self._stop_polling_event.is_set():
            return
        msg = EFBMsg()
        chat = EFBChat(self).system()
        chat.chat_type = ChatType.System
        chat.chat_name = self._("EWS User Auth")
        msg.chat = msg.author = chat
        msg.deliver_to = coordinator.master
        msg.text = self._("WeChat server has logged you out. Please log in again when you are ready.")
        msg.uid = f"__reauth__.{int(time.time())}"
        msg.type = MsgType.Text
        on_log_out = self.flag("on_log_out")
        on_log_out = on_log_out if on_log_out in ("command", "idle", "reauth") else "command"
        if on_log_out == "command":
            msg.type = MsgType.Text
            msg.commands = EFBMsgCommands(
                [EFBMsgCommand(name=self._("Log in again"), callable_name="reauth", kwargs={"command": True})])
        elif on_log_out == "reauth":
            if self.flag("qr_reload") == "console_qr_code":
                msg.text += "\n" + self._("Please check your log to continue.")
            self.reauth()

        coordinator.send_message(msg)
Exemplo n.º 2
0
    def exit_callback(self):
        self.logger.debug('Calling exit callback...')
        if self._stop_polling_event.is_set():
            return
        msg = EFBMsg()
        chat = EFBChat(self).system()
        chat.chat_type = ChatType.System
        chat.chat_name = self._("EWS User Auth")
        msg.chat = msg.author = chat
        msg.deliver_to = coordinator.master
        msg.text = self._(
            "WeChat server has logged you out. Please log in again when you are ready."
        )
        msg.uid = "__reauth__.%s" % int(time.time())
        msg.type = MsgType.Text
        on_log_out = self.flag("on_log_out")
        on_log_out = on_log_out if on_log_out in ("command", "idle",
                                                  "reauth") else "command"
        if on_log_out == "command":
            msg.type = MsgType.Text
            msg.commands = EFBMsgCommands([
                EFBMsgCommand(name=self._("Log in again"),
                              callable_name="reauth",
                              kwargs={"command": True})
            ])
        elif on_log_out == "reauth":
            if self.flag("qr_reload") == "console_qr_code":
                msg.text += "\n" + self._("Please check your log to continue.")
            self.reauth()

        coordinator.send_message(msg)
Exemplo n.º 3
0
def test_pickle_commands_attribute():
    commands = EFBMsgCommands([
        EFBMsgCommand(name="Command 1", callable_name="command_1",
                      args=(1, 2, 3), kwargs={"four": 4, "five": 5}),
        EFBMsgCommand(name="Command 2", callable_name="command_2",
                      args=("1", "2", "3"), kwargs={"four": "4", "five": "5"})
    ])
    commands_dup = pickle.loads(pickle.dumps(commands))
    for cmd in range(len(commands.commands)):
        for attr in ("name", "callable_name", "args", "kwargs"):
            assert getattr(commands.commands[cmd], attr) == \
                   getattr(commands_dup.commands[cmd], attr)
Exemplo n.º 4
0
def test_verify_message_command(base_message):
    msg = base_message

    msg.type = MsgType.Text
    command = EFBMsgCommand(name="Command 1", callable_name="command_1")

    msg.commands = EFBMsgCommands([command])
    msg.verify()

    with pytest.raises(ValueError):
        # noinspection PyTypeChecker
        EFBMsgCommand("name", "callable_name", args="args", kwargs="kwargs")  # type: ignore
Exemplo n.º 5
0
 def send_msg_to_master(self, context):
     self.logger.debug(repr(context))
     msg = EFBMsg()
     msg.chat = msg.author = self.chat_manager.build_efb_chat_as_system_user(context)
     msg.deliver_to = coordinator.master
     msg.type = MsgType.Text
     msg.uid = "__{context[uid_prefix]}__.{uni_id}".format(context=context,
                                                           uni_id=str(int(time.time())))
     if 'message' in context:
         msg.text = context['message']
     if 'commands' in context:
         msg.commands = EFBMsgCommands(context['commands'])
     coordinator.send_message(msg)
Exemplo n.º 6
0
 def wechat_friend_msg(self, msg: wxpy.Message) -> EFBMsg:
     efb_msg = EFBMsg()
     gender = {1: self._("M"), 2: self._("F")}.get(msg.card.sex, msg.card.sex)
     txt = (self._("Card: {user.nick_name}\n"
                   "From: {user.province}, {user.city}\n"
                   "Bio: {user.signature}\n"
                   "Gender: {gender}"))
     txt = txt.format(user=msg.card, gender=gender)
     efb_msg.text = txt
     efb_msg.type = MsgType.Text
     efb_msg.commands = EFBMsgCommands([
         EFBMsgCommand(
             name=self._("Accept friend request"),
             callable_name="accept_friend",
             kwargs={"username": msg.card.user_name}
         )
     ])
     return efb_msg
Exemplo n.º 7
0
def test_verify_message_command():
    msg = EFBMsg()
    msg.deliver_to = coordinator.master

    msg.author = patch_chat_0
    msg.chat = patch_chat_1
    msg.text = "Message"
    msg.verify()

    msg.type = MsgType.Text
    msg.attributes = None
    msg.commands = EFBMsgCommands(
        [EFBMsgCommand(name="Command 1", callable_name="command_1")])

    msg.commands.commands[0].verify = mock.Mock()

    msg.verify()

    msg.commands.commands[0].verify.assert_called_once()
Exemplo n.º 8
0
 def handle_group_request(context):
     self.logger.debug(repr(context))
     context['group_name'] = self._('[Request]') + self.get_group_info(context['group_id'])['group_name']
     context['group_id_orig'] = context['group_id']
     context['group_id'] = str(context['group_id']) + "_notification"
     context['message_type'] = 'group'
     context['event_description'] = '\u2139 New Group Join Request'
     original_group = self.get_group_info(context['group_id'], False)
     group_name = context['group_id']
     if original_group is not None and 'group_name' in original_group:
         group_name = original_group['group_name']
     msg = EFBMsg()
     msg.uid = 'group' + '_' + str(context['group_id'])
     msg.author = self.chat_manager.build_efb_chat_as_system_user(context)
     msg.chat = self.chat_manager.build_efb_chat_as_group(context)
     msg.deliver_to = coordinator.master
     msg.type = MsgType.Text
     name = ""
     if not self.get_friend_remark(context['user_id']):
         name = "{}({})[{}] ".format(
             self.get_stranger_info(context['user_id'])['nickname'], self.get_friend_remark(context['user_id']),
             context['user_id'])
     else:
         name = "{}[{}] ".format(self.get_stranger_info(context['user_id'])['nickname'], context['user_id'])
     msg.text = "{} wants to join the group {}({}). \nHere is the comment: {}".format(
         name, group_name, context['group_id_orig'], context['comment']
     )
     msg.commands = EFBMsgCommands([EFBMsgCommand(
         name=self._("Accept"),
         callable_name="process_group_request",
         kwargs={'result': 'accept',
                 'flag': context['flag'],
                 'sub_type': context['sub_type']}
     ), EFBMsgCommand(
         name=self._("Decline"),
         callable_name="process_group_request",
         kwargs={'result': 'decline',
                 'flag': context['flag'],
                 'sub_type': context['sub_type']}
     )])
     coordinator.send_message(msg)
Exemplo n.º 9
0
    def qq_contact_wrapper(self, data) -> EFBMsg:
        efb_msg = EFBMsg()
        efb_msg.type = MsgType.Text
        uid = data['id']
        user_data = self.inst.get_stranger_info(user_id=uid)
        txt = "Friend Request Received\n"
        "UID: {user[user_id]}\n"
        "Nickname: {user[nickname]}\n"
        "Age: {user[age]}\n"
        "Gender: {user[sex]}"

        txt = txt.format(user=user_data)
        efb_msg.text = txt
        efb_msg.type = MsgType.Text
        efb_msg.commands = EFBMsgCommands([
            EFBMsgCommand(
                name="Send friend request",
                callable_name="add_friend",  # todo Add add_friend() to handle friend request
                kwargs={"uid": uid}
            )
        ])
        return efb_msg
Exemplo n.º 10
0
    def test_chain_verify(self):
        patch_chat_0 = self.chat.copy()
        patch_chat_1 = self.chat.copy()
        patch_chat_0.verify = mock.Mock()
        patch_chat_1.verify = mock.Mock()

        msg = EFBMsg()
        msg.deliver_to = self.channel

        with self.subTest("Different author and chat"):
            msg.author = patch_chat_0
            msg.chat = patch_chat_1
            msg.text = "Message"
            msg.verify()

            patch_chat_0.verify.assert_called_once()
            patch_chat_1.verify.assert_called_once()

        patch_chat_0.verify.reset_mock()

        with self.subTest("Same author and chat"):
            msg.author = patch_chat_0
            msg.chat = patch_chat_0
            msg.text = "Message"
            msg.verify()

            patch_chat_0.verify.assert_called_once()

        with self.subTest("Link message"):
            msg.type = MsgType.Link
            msg.attributes = EFBMsgLinkAttribute(title='Title', url='URL')
            msg.attributes.verify = mock.Mock()
            msg.verify()

            msg.attributes.verify.assert_called_once()

        with self.subTest("Location message"):
            msg.type = MsgType.Location
            msg.attributes = EFBMsgLocationAttribute(latitude=0.0,
                                                     longitude=0.0)
            msg.attributes.verify = mock.Mock()
            msg.verify()

            msg.attributes.verify.assert_called_once()

        with self.subTest("Status message"):
            msg.type = MsgType.Status
            msg.attributes = EFBMsgStatusAttribute(
                status_type=EFBMsgStatusAttribute.Types.TYPING)
            msg.attributes.verify = mock.Mock()
            msg.verify()

            msg.attributes.verify.assert_called_once()

        with self.subTest("Message Command"):
            msg.type = MsgType.Text
            msg.attributes = None
            msg.commands = EFBMsgCommands(
                [EFBMsgCommand(name="Command 1", callable_name="command_1")])

            msg.commands.commands[0].verify = mock.Mock()

            msg.verify()

            msg.commands.commands[0].verify.assert_called_once()