Exemple #1
0
 def telegramize(self) -> Optional[InputMediaUploadedPhoto]:
     if self.valid is None:
         raise RuntimeError(
             'Validate() must be called before telegramize()')
     if self.uploaded_file:
         return InputMediaUploadedPhoto(self.uploaded_file)
     return None
Exemple #2
0
    async def upload_file_direct(self, file: bytes, mime_type: str = None,
                                 attributes: List[TypeDocumentAttribute] = None,
                                 file_name: str = None, max_image_size: float = 10 * 1000 ** 2,
                                 ) -> Union[InputMediaUploadedDocument, InputMediaUploadedPhoto]:
        file_handle = await super().upload_file(file, file_name=file_name, use_cache=False)

        if (mime_type == "image/png" or mime_type == "image/jpeg") and len(file) < max_image_size:
            return InputMediaUploadedPhoto(file_handle)
        else:
            attributes = attributes or []
            attr_dict = {type(attr): attr for attr in attributes}

            return InputMediaUploadedDocument(
                file=file_handle,
                mime_type=mime_type or "application/octet-stream",
                attributes=list(attr_dict.values()))
Exemple #3
0
async def _(event):
    if event.fwd_from:
        return
    if not event.is_reply:
        await event.edit("Reply to a message to broadcast.")
        return
    channels = get_all_channels()
    error_count = 0
    sent_count = 0
    await event.edit("`Sending....`")
    if event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        if previous_message.sticker or previous_message.poll:
            await event.edit("Reply .forward for stickers and polls.")
            return
        if previous_message.gif or previous_message.audio or previous_message.voice or previous_message.video or previous_message.video_note or previous_message.contact or previous_message.game or previous_message.geo or previous_message.invoice:  # Written by @HeisenbergTheDanger
            await event.edit("Not supported. Try .forward")
            return
        if previous_message.document:
            return
            data = await client.download_file(previous_message.document, bytes)
            print(data[:16])
        elif not previous_message.web_preview and previous_message.photo:
            file = await borg.download_file(previous_message.media)
            uploaded_doc = await borg.upload_file(file, file_name="img.png")
            raw_text = previous_message.text
            for channel in channels:
                try:
                    if previous_message.photo:
                        await borg.send_file(
                            int(channel.chat_id),
                            InputMediaUploadedPhoto(file=uploaded_doc),
                            force_document=False,
                            caption=raw_text,
                            link_preview=False)

                    sent_count += 1
                    await event.edit(
                        f"Sent : {sent_count}\nError : {error_count}\nTotal : {len(channels)}"
                    )
                except Exception as error:
                    try:
                        await borg.send_message(
                            logs_id, f"Error in sending at {chat_id}.")
                        await borg.send_message(logs_id,
                                                "Error! " + str(error))
                        if error == "The message cannot be empty unless a file is provided":
                            event.edit(
                                "For sending files, upload in Saved Messages and reply .forward to in."
                            )
                            return
                    except BaseException:
                        pass
                    error_count += 1
                    await event.edit(
                        f"Sent : {sent_count}\nError : {error_count}\nTotal : {len(channels)}"
                    )
                    if error_count >= 10 and sent_count == 0:
                        await event.edit * ("`Stopped for too many errors.`")
                        return
            await event.edit(
                f"{sent_count} messages sent with {error_count} errors.")
            if error_count > 0:
                try:
                    await borg.send_message(logs_id, f"{error_count} Errors")
                except BaseException:
                    pass
        else:
            raw_text = previous_message.text
            for channel in channels:
                try:
                    await borg.send_message(int(channel.chat_id),
                                            raw_text,
                                            link_preview=False)
                    sent_count += 1
                    await event.edit(
                        f"Sent : {sent_count}\nError : {error_count}\nTotal : {len(channels)}"
                    )
                except Exception as error:
                    try:
                        await borg.send_message(
                            logs_id, f"Error in sending at {channel.chat_id}.")
                        await borg.send_message(logs_id,
                                                "Error! " + str(error))
                        if error == "The message cannot be empty unless a file is provided":
                            event.edit(
                                "For sending files, upload in Saved Messages and reply .forward to in."
                            )
                            return
                    except BaseException:
                        pass
                    error_count += 1
                    await event.edit(
                        f"Sent : {sent_count}\nError : {error_count}\nTotal : {len(channels)}"
                    )
                    if error_count >= 10 and sent_count == 0:
                        await event.edit * ("Stopped for too many errors.")
                        return
            await event.edit(
                f"{sent_count} messages sent with {error_count} errors.")
            if error_count > 0:
                try:
                    await borg.send_message(logs_id, f"{error_count} Errors")
                except BaseException:
                    await event.edit(
                        "`Set up log channel for checking errors.`")
Exemple #4
0
async def _(event):
    if event.fwd_from:
        return
    mssg = await eor(event, "`...`")
    if not event.is_reply:
        await mssg.edit("Reply to a message to start fban....")
        return
    channels = get_all_channels()
    error_count = 0
    sent_count = 0
    await mssg.edit("Fbanning....")
    if event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        if previous_message.sticker or previous_message.poll:
            await mssg.edit("**ERROR !** \nOnly Text Message is supported for fban.")
            return
        if (
            previous_message.gif
            or previous_message.audio
            or previous_message.voice
            or previous_message.video
            or previous_message.video_note
            or previous_message.contact
            or previous_message.game
            or previous_message.geo
            or previous_message.invoice
        ):  # Written by @HeisenbergTheDanger
            await mssg.edit("**ERROR !** \nOnly Text Message is supported for fban.")
            return
        if not previous_message.web_preview and previous_message.photo:
            file = await borg.download_file(previous_message.media)
            uploaded_doc = await borg.upload_file(file, file_name="img.png")
            raw_text = previous_message.text
            for channel in channels:
                try:
                    if previous_message.photo:
                        await borg.send_file(
                            int(channel.chat_id),
                            InputMediaUploadedPhoto(file=uploaded_doc),
                            force_document=False,
                            caption=raw_text,
                            link_preview=False,
                        )

                    sent_count += 1
                    await mssg.edit(
                        f"Fbanned : {sent_count}\nError : {error_count}\nTotal : {len(channels)}",
                    )
                except Exception as error:
                    try:
                        await borg.send_message(
                            logs_id, f"Error in Fbanning at {chat_id}."
                        )
                        await borg.send_message(logs_id, "Error! " + str(error))
                        if (
                            error
                            == "The message cannot be empty unless a file is provided"
                        ):
                            mssg.edit(
                                "**ERROR !** \nOnly Text Message is supported for fban."
                            )
                            return
                    except BaseException:
                        pass
                    error_count += 1
                    await mssg.edit(
                        f"Fbanned : {sent_count}\nError : {error_count}\nTotal : {len(channels)}",
                    )
            await mssg.edit(f"{sent_count} fbans with {error_count} errors.")
            if error_count > 0:
                try:
                    await borg.send_message(logs_id, f"{error_count} Errors")
                except BaseException:
                    pass
        else:
            raw_text = previous_message.text
            for channel in channels:
                try:
                    await borg.send_message(
                        int(channel.chat_id), raw_text, link_preview=False
                    )
                    sent_count += 1
                    await mssg.edit(
                        f"Fbanned : {sent_count}\nError : {error_count}\nTotal : {len(channels)}",
                    )
                except Exception as error:
                    try:
                        await borg.send_message(
                            logs_id, f"Error in Fbanning at {channel.chat_id}."
                        )
                        await borg.send_message(logs_id, "Error! " + str(error))
                        if (
                            error
                            == "The message cannot be empty unless a file is provided"
                        ):
                            mssg.edit(
                                "**ERROR !** \nOnly Text Message is supported for fban."
                            )
                            return
                    except BaseException:
                        pass
                    error_count += 1
                    await mssg.edit(
                        f"Fbanned : {sent_count}\nError : {error_count}\nTotal : {len(channels)}",
                    )
            await mssg.edit(f"{sent_count} fbans with {error_count} errors.")
            if error_count > 0:
                try:
                    await borg.send_message(logs_id, f"{error_count} Errors")
                except BaseException:
                    await mssg.edit("Set up heroku var `FBAN_LOGGER_GROUP` for checking errors.")# Written by @HeisenbergTheDanger
    async def _handle_matrix_file(
            self,
            sender_id: TelegramID,
            event_id: EventID,
            space: TelegramID,
            client: 'MautrixTelegramClient',
            content: MediaMessageEventContent,
            reply_to: TelegramID,
            caption: TextMessageEventContent = None) -> None:
        mime = content.info.mimetype
        w, h = content.info.width, content.info.height
        file_name = content["net.maunium.telegram.internal.filename"]
        max_image_size = config["bridge.image_as_file_size"] * 1000**2

        if config["bridge.parallel_file_transfer"] and content.url:
            file_handle, file_size = await parallel_transfer_to_telegram(
                client, self.main_intent, content.url, sender_id)
        else:
            if content.file:
                if not decrypt_attachment:
                    self.log.warning(
                        f"Can't bridge encrypted media event {event_id}:"
                        " matrix-nio not installed")
                    return
                file = await self.main_intent.download_media(content.file.url)
                file = decrypt_attachment(file, content.file.key.key,
                                          content.file.hashes.get("sha256"),
                                          content.file.iv)
            else:
                file = await self.main_intent.download_media(content.url)

            if content.msgtype == MessageType.STICKER:
                if mime != "image/gif":
                    mime, file, w, h = util.convert_image(file,
                                                          source_mime=mime,
                                                          target_type="webp")
                else:
                    # Remove sticker description
                    file_name = "sticker.gif"

            file_handle = await client.upload_file(file)
            file_size = len(file)

        file_handle.name = file_name

        attributes = [DocumentAttributeFilename(file_name=file_name)]
        if w and h:
            attributes.append(DocumentAttributeImageSize(w, h))

        if (mime == "image/png"
                or mime == "image/jpeg") and file_size < max_image_size:
            media = InputMediaUploadedPhoto(file_handle)
        else:
            media = InputMediaUploadedDocument(file=file_handle,
                                               attributes=attributes,
                                               mime_type=mime
                                               or "application/octet-stream")

        caption, entities = self._matrix_event_to_entities(
            caption) if caption else (None, None)

        async with self.send_lock(sender_id):
            if await self._matrix_document_edit(client, content, space,
                                                caption, media, event_id):
                return
            try:
                response = await client.send_media(self.peer,
                                                   media,
                                                   reply_to=reply_to,
                                                   caption=caption,
                                                   entities=entities)
            except (PhotoInvalidDimensionsError, PhotoSaveFileInvalidError,
                    PhotoExtInvalidError):
                media = InputMediaUploadedDocument(file=media.file,
                                                   mime_type=mime,
                                                   attributes=attributes)
                response = await client.send_media(self.peer,
                                                   media,
                                                   reply_to=reply_to,
                                                   caption=caption,
                                                   entities=entities)
            self._add_telegram_message_to_db(event_id, space, 0, response)
        await self._send_delivery_receipt(event_id)
Exemple #6
0
 def send_photo_file(self, input_file, input_peer, caption=''):
     """Sends a previously uploaded input_file
        (which should be a photo) to an input_peer"""
     self.send_media_file(
         InputMediaUploadedPhoto(input_file, caption), input_peer)
Exemple #7
0
 def send_photo_file(self, input_file, entity, caption=''):
     """Sends a previously uploaded input_file
        (which should be a photo) to the given entity (or input peer)"""
     self.send_media_file(InputMediaUploadedPhoto(input_file, caption),
                          entity)