def onMessageUnsent(self, mid=None, author_id=None, thread_id=None, thread_type=None, ts=None, msg=None):
     chat = self.chat_manager.get_thread(thread_id)
     author = chat.get_member(author_id)
     if mid in self.message_mappings:
         for i in range(self.message_mappings[mid]):
             coordinator.send_status(
                 MessageRemoval(source_channel=self.channel,
                                destination_channel=coordinator.master,
                                message=EFBMessage(chat=chat, author=author, uid=f"{mid}.{i}"))
             )
     else:
         coordinator.send_status(
             MessageRemoval(source_channel=self.channel,
                            destination_channel=coordinator.master,
                            message=EFBMessage(chat=chat, author=author, uid=mid))
         )
Exemplo n.º 2
0
 def send_message_recall_status(self):
     slave = next(iter(coordinator.slaves.values()))
     alice = slave.get_chat('alice')
     msg = Message(
         deliver_to=slave,
         chat=alice,
         author=alice.self,
         uid="1"
     )
     status = MessageRemoval(self, slave, msg)
     return coordinator.send_status(status)
Exemplo n.º 3
0
def test_pickle_message_removal(slave_channel, master_channel):
    msg = Message()
    msg.chat = slave_channel.alice
    msg.uid = "uid"
    msg_removal = MessageRemoval(source_channel=master_channel,
                                 destination_channel=slave_channel,
                                 message=msg)
    msg_removal_dup = pickle.loads(pickle.dumps(msg_removal))

    # Assume Message is picklable
    for i in ("source_channel", "destination_channel"):
        assert getattr(msg_removal, i) == getattr(msg_removal_dup, i)
Exemplo n.º 4
0
 def wechat_system_msg(self, msg: wxpy.Message) -> Optional[Message]:
     if msg.recalled_message_id:
         recall_id = str(msg.recalled_message_id)
         # check conversion table first
         if recall_id in self.recall_msg_id_conversion:
             # prevent feedback of messages deleted by master channel.
             del self.recall_msg_id_conversion[recall_id]
             return None
             # val = self.recall_msg_id_conversion.pop(recall_id)
             # val[1] -= 1
             # if val[1] > 0:  # not all associated messages are recalled.
             #     return None
             # else:
             #     efb_msg.uid = val[0]
         else:
             # Format message IDs as JSON of List[List[str]].
             chat, author = self.get_chat_and_author(msg)
             efb_msg = Message(
                 chat=chat, author=author,
                 uid=MessageID(json.dumps([[recall_id]]))
             )
         coordinator.send_status(MessageRemoval(source_channel=self.channel,
                                                destination_channel=coordinator.master,
                                                message=efb_msg))
         return None
     chat, _ = self.get_chat_and_author(msg)
     try:
         author = chat.get_member(SystemChatMember.SYSTEM_ID)
     except KeyError:
         author = chat.add_system_member()
     if any(i in msg.text for i in self.NEW_CHAT_PATTERNS):
         coordinator.send_status(ChatUpdates(
             channel=self.channel,
             new_chats=(chat.uid,)
         ))
     elif any(i in msg.text for i in self.CHAT_AND_MEMBER_UPDATE_PATTERNS):
         # TODO: detect actual member changes from message text
         coordinator.send_status(ChatUpdates(
             channel=self.channel,
             modified_chats=(chat.uid,)
         ))
     return Message(
         text=msg.text,
         type=MsgType.Text,
         chat=chat,
         author=author,
     )
Exemplo n.º 5
0
 def delete_message(self, update: Update, context: CallbackContext):
     """Remove an arbitrary message from its remote chat.
     Triggered by command ``/rm``.
     """
     message: Message = update.message
     if message.reply_to_message is None:
         return self.bot.reply_error(
             update,
             self.
             _("Reply /rm to a message to remove it from its remote chat."))
     reply: Message = message.reply_to_message
     msg_log = self.db.get_msg_log(master_msg_id=utils.message_id_to_str(
         chat_id=reply.chat_id, message_id=reply.message_id))
     if not msg_log or msg_log.slave_member_uid == self.db.FAIL_FLAG:
         return self.bot.reply_error(
             update,
             self.
             _("This message is not found in ETM database. You cannot remove it from its remote chat."
               ))
     try:
         etm_msg: ETMMsg = msg_log.build_etm_msg(self.chat_manager)
     except UnpicklingError:
         return self.bot.reply_error(
             update,
             self.
             _("This message is not found in ETM database. You cannot remove it from its remote chat."
               ))
     dest_channel = coordinator.slaves.get(etm_msg.chat.module_id, None)
     if dest_channel is None:
         return self.bot.reply_error(
             update,
             self.
             _("Module of this message ({module_id}) could not be found, or is not a slave channel."
               ).format(module_id=etm_msg.chat.module_id))
     # noinspection PyBroadException
     try:
         coordinator.send_status(
             MessageRemoval(source_channel=self.channel,
                            destination_channel=dest_channel,
                            message=etm_msg))
     except EFBException as e:
         self.logger.exception(
             "Failed to remove message from remote chat. Message: %s; Error: %s",
             etm_msg, e)
         return reply.reply_text(
             self.
             _("Failed to remove this message from remote chat.\n\n{error!s}"
               ).format(error=e))
     except Exception as e:
         self.logger.exception(
             "Failed to remove message from remote chat. Message: %s; Error: %s",
             etm_msg, e)
         return reply.reply_text(
             self.
             _("Failed to remove this message from remote chat.\n\n{error!r}"
               ).format(error=e))
     if not self.channel.flag('prevent_message_removal'):
         try:
             reply.delete()
         except telegram.TelegramError:
             reply.reply_text(self._("Message is removed in remote chat."))
     else:
         reply.reply_text(self._("Message is removed in remote chat."))
Exemplo n.º 6
0
    def process_telegram_message(self,
                                 update: Update,
                                 context: CallbackContext,
                                 destination: EFBChannelChatIDStr,
                                 quote: bool = False):
        """
        Process messages came from Telegram.

        Args:
            update: Telegram message update
            context: PTB update context
            destination: Destination of the message specified.
            quote: If the message shall quote another one
        """

        # Message ID for logging
        message_id = utils.message_id_to_str(update=update)

        message: Message = update.effective_message

        edited = bool(update.edited_message or update.edited_channel_post)
        self.logger.debug('[%s] Message is edited: %s, %s', message_id, edited,
                          message.edit_date)

        channel, uid, gid = utils.chat_id_str_to_id(destination)
        if channel not in coordinator.slaves:
            return self.bot.reply_error(
                update,
                self._("Internal error: Slave channel “{0}” not found.").
                format(channel))

        m = ETMMsg()
        log_message = True
        try:
            m.uid = MessageID(message_id)
            # Store Telegram message type
            m.type_telegram = mtype = get_msg_type(message)

            if self.TYPE_DICT.get(mtype, None):
                m.type = self.TYPE_DICT[mtype]
                self.logger.debug("[%s] EFB message type: %s", message_id,
                                  mtype)
            else:
                self.logger.info(
                    "[%s] Message type %s is not supported by ETM", message_id,
                    mtype)
                raise EFBMessageTypeNotSupported(
                    self.
                    _("{type_name} messages are not supported by EFB Telegram Master channel."
                      ).format(type_name=mtype.name))

            m.put_telegram_file(message)
            # Chat and author related stuff
            m.chat = self.chat_manager.get_chat(channel, uid, build_dummy=True)
            m.author = m.chat.self or m.chat.add_self()

            m.deliver_to = coordinator.slaves[channel]

            if quote:
                self.attach_target_message(message, m, channel)
            # Type specific stuff
            self.logger.debug("[%s] Message type from Telegram: %s",
                              message_id, mtype)

            if m.type not in coordinator.slaves[
                    channel].supported_message_types:
                self.logger.info(
                    "[%s] Message type %s is not supported by channel %s",
                    message_id, m.type.name, channel)
                raise EFBMessageTypeNotSupported(
                    self.
                    _("{type_name} messages are not supported by slave channel {channel_name}."
                      ).format(type_name=m.type.name,
                               channel_name=coordinator.slaves[channel].
                               channel_name))

            # Parse message text and caption to markdown
            msg_md_text = message.text and message.text_markdown
            if msg_md_text and msg_md_text == escape_markdown(message.text):
                msg_md_text = message.text
            msg_md_text = msg_md_text or ""

            msg_md_caption = message.caption and message.caption_markdown
            if msg_md_caption and msg_md_caption == escape_markdown(
                    message.caption):
                msg_md_caption = message.caption
            msg_md_caption = msg_md_caption or ""

            # Flag for edited message
            if edited:
                m.edit = True
                text = msg_md_text or msg_md_caption
                msg_log = self.db.get_msg_log(
                    master_msg_id=utils.message_id_to_str(update=update))
                if not msg_log or msg_log.slave_message_id == self.db.FAIL_FLAG:
                    raise EFBMessageNotFound()
                m.uid = msg_log.slave_message_id
                if text.startswith(self.DELETE_FLAG):
                    coordinator.send_status(
                        MessageRemoval(
                            source_channel=self.channel,
                            destination_channel=coordinator.slaves[channel],
                            message=m))
                    if not self.channel.flag('prevent_message_removal'):
                        try:
                            message.delete()
                        except telegram.TelegramError:
                            message.reply_text(
                                self._("Message is removed in remote chat."))
                    else:
                        message.reply_text(
                            self._("Message is removed in remote chat."))
                    log_message = False
                    return
                self.logger.debug('[%s] Message is edited (%s)', m.uid, m.edit)
                if m.file_unique_id and m.file_unique_id != msg_log.file_unique_id:
                    self.logger.debug(
                        "[%s] Message media is edited (%s -> %s)", m.uid,
                        msg_log.file_unique_id, m.file_unique_id)
                    m.edit_media = True

            # Enclose message as an Message object by message type.
            if mtype is TGMsgType.Text:
                m.text = msg_md_text
            elif mtype is TGMsgType.Photo:
                m.text = msg_md_caption
                m.mime = "image/jpeg"
                self._check_file_download(message.photo[-1])
            elif mtype in (TGMsgType.Sticker, TGMsgType.AnimatedSticker):
                # Convert WebP to the more common PNG
                m.text = ""
                self._check_file_download(message.sticker)
            elif mtype is TGMsgType.Animation:
                m.text = msg_md_caption
                self.logger.debug(
                    "[%s] Telegram message is a \"Telegram GIF\".", message_id)
                m.filename = getattr(message.document, "file_name",
                                     None) or None
                if m.filename and not m.filename.lower().endswith(".gif"):
                    m.filename += ".gif"
                m.mime = message.document.mime_type or m.mime
            elif mtype is TGMsgType.Document:
                m.text = msg_md_caption
                self.logger.debug("[%s] Telegram message type is document.",
                                  message_id)
                m.filename = getattr(message.document, "file_name",
                                     None) or None
                m.mime = message.document.mime_type
                self._check_file_download(message.document)
            elif mtype is TGMsgType.Video:
                m.text = msg_md_caption
                m.mime = message.video.mime_type
                self._check_file_download(message.video)
            elif mtype is TGMsgType.VideoNote:
                m.text = msg_md_caption
                self._check_file_download(message.video)
            elif mtype is TGMsgType.Audio:
                m.text = "%s - %s\n%s" % (message.audio.title,
                                          message.audio.performer,
                                          msg_md_caption)
                m.mime = message.audio.mime_type
                self._check_file_download(message.audio)
            elif mtype is TGMsgType.Voice:
                m.text = msg_md_caption
                m.mime = message.voice.mime_type
                self._check_file_download(message.voice)
            elif mtype is TGMsgType.Location:
                # TRANSLATORS: Message body text for location messages.
                m.text = self._("Location")
                m.attributes = LocationAttribute(message.location.latitude,
                                                 message.location.longitude)
            elif mtype is TGMsgType.Venue:
                m.text = f"📍 {message.location.title}\n{message.location.adderss}"
                m.attributes = LocationAttribute(
                    message.venue.location.latitude,
                    message.venue.location.longitude)
            elif mtype is TGMsgType.Contact:
                contact: telegram.Contact = message.contact
                m.text = self._(
                    "Shared a contact: {first_name} {last_name}\n{phone_number}"
                ).format(first_name=contact.first_name,
                         last_name=contact.last_name,
                         phone_number=contact.phone_number)
            elif mtype is TGMsgType.Dice:
                # Per docs, message.dice must be one of [1, 2, 3, 4, 5, 6],
                # DICE_CHAR is of length 7, so should be safe.
                m.text = f"{self.DICE_CHAR[message.dice.value]} ({message.dice.value})"
            else:
                raise EFBMessageTypeNotSupported(
                    self._("Message type {0} is not supported.").format(
                        mtype.name))

            slave_msg = coordinator.send_message(m)
            if slave_msg and slave_msg.uid:
                m.uid = slave_msg.uid
            else:
                m.uid = None
        except EFBChatNotFound as e:
            self.bot.reply_error(update, e.args[0]
                                 or self._("Chat is not found."))
        except EFBMessageTypeNotSupported as e:
            self.bot.reply_error(
                update, e.args[0] or self._("Message type is not supported."))
        except EFBOperationNotSupported as e:
            self.bot.reply_error(
                update,
                self._("Message editing is not supported.\n\n{exception!s}".
                       format(exception=e)))
        except EFBException as e:
            self.bot.reply_error(
                update,
                self._("Message is not sent.\n\n{exception!s}".format(
                    exception=e)))
            self.logger.exception(
                "Message is not sent. (update: %s, exception: %s)", update, e)
        except Exception as e:
            self.bot.reply_error(
                update,
                self._("Message is not sent.\n\n{exception!r}".format(
                    exception=e)))
            self.logger.exception(
                "Message is not sent. (update: %s, exception: %s)", update, e)
        finally:
            if log_message:
                self.db.add_or_update_message_log(m, update.effective_message)
                if m.file:
                    m.file.close()